qualia_core_db/crypto/network/
aead.rs1use aead::{AeadInOut, KeyInit};
4use chacha20poly1305::{ChaCha20Poly1305, Key, Nonce, Tag};
5
6use super::errors::CryptoError;
7use super::types::{AEAD_KEY_LEN, AEAD_NONCE_LEN, AEAD_TAG_LEN};
8
9pub fn encrypt_in_place(
11 key: &[u8; AEAD_KEY_LEN],
12 nonce: &[u8; AEAD_NONCE_LEN],
13 aad: &[u8],
14 buffer: &mut [u8],
15 tag_out: &mut [u8; AEAD_TAG_LEN],
16) -> Result<(), CryptoError> {
17 let cipher = ChaCha20Poly1305::new(
18 &Key::try_from(key.as_slice()).map_err(|_| CryptoError::CryptoFailure)?,
19 );
20 let tag = cipher
21 .encrypt_inout_detached(
22 &Nonce::try_from(nonce.as_slice()).map_err(|_| CryptoError::CryptoFailure)?,
23 aad,
24 buffer.into(),
25 )
26 .map_err(|_| CryptoError::CryptoFailure)?;
27 tag_out.copy_from_slice(tag.as_slice());
28 Ok(())
29}
30
31pub fn decrypt_in_place(
33 key: &[u8; AEAD_KEY_LEN],
34 nonce: &[u8; AEAD_NONCE_LEN],
35 aad: &[u8],
36 buffer: &mut [u8],
37 tag: &[u8; AEAD_TAG_LEN],
38) -> Result<(), CryptoError> {
39 let cipher = ChaCha20Poly1305::new(
40 &Key::try_from(key.as_slice()).map_err(|_| CryptoError::CryptoFailure)?,
41 );
42 let tag = Tag::try_from(tag.as_slice()).map_err(|_| CryptoError::CryptoFailure)?;
43 cipher
44 .decrypt_inout_detached(
45 &Nonce::try_from(nonce.as_slice()).map_err(|_| CryptoError::CryptoFailure)?,
46 aad,
47 buffer.into(),
48 &tag,
49 )
50 .map_err(|_| CryptoError::CryptoFailure)
51}
52
53#[cfg(test)]
54mod tests {
55 use super::*;
56
57 #[test]
58 fn round_trip_and_aad_mismatch() {
59 let key = [7u8; 32];
60 let nonce = [9u8; 12];
61 let mut buf = *b"hello-qdnf";
62 let mut tag = [0u8; 16];
63 encrypt_in_place(&key, &nonce, b"aad", &mut buf, &mut tag).unwrap();
64 let mut good = buf;
65 decrypt_in_place(&key, &nonce, b"aad", &mut good, &tag).unwrap();
66 assert_eq!(&good, b"hello-qdnf");
67 let mut bad = buf;
68 assert!(decrypt_in_place(&key, &nonce, b"nope", &mut bad, &tag).is_err());
69 }
70}