aws_lc_rs/aead/
poly1305.rs1use super::{Tag, TAG_LEN};
9use crate::aws_lc::{CRYPTO_poly1305_finish, CRYPTO_poly1305_init, CRYPTO_poly1305_update};
10use crate::cipher::block::BLOCK_LEN;
11use core::mem::MaybeUninit;
12
13pub(super) struct Key {
15 pub(super) key_and_nonce: [u8; KEY_LEN],
16}
17
18const KEY_LEN: usize = 2 * BLOCK_LEN;
19
20impl Key {
21 #[inline]
22 #[allow(dead_code)]
23 pub(super) fn new(key_and_nonce: [u8; KEY_LEN]) -> Self {
24 Self { key_and_nonce }
25 }
26}
27
28pub struct Context {
29 state: poly1305_state,
30}
31
32#[repr(C, align(64))]
37#[allow(non_camel_case_types)]
38struct poly1305_state(aws_lc::poly1305_state);
39
40impl Context {
41 #[inline]
42 pub(super) fn from_key(Key { key_and_nonce }: Key) -> Self {
43 unsafe {
44 let mut state = MaybeUninit::<poly1305_state>::uninit();
45 CRYPTO_poly1305_init(state.as_mut_ptr().cast(), key_and_nonce.as_ptr());
46 Self {
47 state: state.assume_init(),
48 }
49 }
50 }
51
52 #[inline]
53 pub fn update(&mut self, input: &[u8]) {
54 unsafe {
55 CRYPTO_poly1305_update(
56 self.state.0.as_mut_ptr().cast(),
57 input.as_ptr(),
58 input.len(),
59 );
60 }
61 }
62
63 #[inline]
64 pub(super) fn finish(mut self) -> Tag {
65 unsafe {
66 let mut tag = MaybeUninit::<[u8; TAG_LEN]>::uninit();
67 CRYPTO_poly1305_finish(self.state.0.as_mut_ptr().cast(), tag.as_mut_ptr().cast());
68 crate::fips::set_fips_service_status_unapproved();
69 Tag(tag.assume_init(), TAG_LEN)
70 }
71 }
72}
73
74#[inline]
79pub(super) fn sign(key: Key, input: &[u8]) -> Tag {
80 let mut ctx = Context::from_key(key);
81 ctx.update(input);
82 ctx.finish()
83}
84
85#[cfg(test)]
86mod tests {
87 use super::*;
88 use crate::{test, test_file};
89
90 #[test]
92 pub fn test_poly1305() {
93 test::run(
94 test_file!("data/poly1305_test.txt"),
95 |section, test_case| {
96 assert_eq!(section, "");
97 let key = test_case.consume_bytes("Key");
98 let key: &[u8; BLOCK_LEN * 2] = key.as_slice().try_into().unwrap();
99 let input = test_case.consume_bytes("Input");
100 let expected_mac = test_case.consume_bytes("MAC");
101 let key = Key::new(*key);
102 let Tag(actual_mac, _) = sign(key, &input);
103 assert_eq!(expected_mac, actual_mac.as_ref());
104
105 Ok(())
106 },
107 );
108 }
109}