Skip to main content

bitwarden_crypto_primitives/
xchacha20_poly1305.rs

1//! XChaCha20-Poly1305.
2
3use crate::{Error, backend};
4
5/// Key length in bytes.
6pub const KEY_LEN: usize = 32;
7/// Nonce length in bytes.
8pub const NONCE_LEN: usize = 24;
9/// Authentication tag length in bytes.
10pub const TAG_LEN: usize = 16;
11
12/// Encrypts `plaintext` and authenticates it with `aad`. Returns `ciphertext || tag`.
13///
14/// The caller must never reuse a nonce under the same key.
15pub fn encrypt(
16    key: &[u8; KEY_LEN],
17    nonce: &[u8; NONCE_LEN],
18    aad: &[u8],
19    plaintext: &[u8],
20) -> Vec<u8> {
21    backend::xchacha20_poly1305::encrypt(key, nonce, aad, plaintext)
22}
23
24/// Verifies and decrypts `ciphertext || tag`.
25pub fn decrypt(
26    key: &[u8; KEY_LEN],
27    nonce: &[u8; NONCE_LEN],
28    aad: &[u8],
29    ciphertext: &[u8],
30) -> Result<Vec<u8>, Error> {
31    backend::xchacha20_poly1305::decrypt(key, nonce, aad, ciphertext)
32}
33
34#[cfg(test)]
35mod tests {
36    use super::*;
37    use crate::test_vectors::{array, bytes};
38
39    const KEY: &str = "0707070707070707070707070707070707070707070707070707070707070707";
40    const NONCE: &str = "090909090909090909090909090909090909090909090909";
41
42    #[test]
43    fn roundtrip() {
44        let ct = encrypt(&array(KEY), &array(NONCE), b"aad", b"plaintext");
45        assert_eq!(ct.len(), b"plaintext".len() + TAG_LEN);
46        assert_eq!(
47            decrypt(&array(KEY), &array(NONCE), b"aad", &ct),
48            Ok(b"plaintext".to_vec())
49        );
50    }
51
52    #[test]
53    fn rejects_tampering() {
54        let mut ct = encrypt(&array(KEY), &array(NONCE), b"aad", b"plaintext");
55        assert_eq!(
56            decrypt(&array(KEY), &array(NONCE), b"other", &ct),
57            Err(Error::DecryptionFailed)
58        );
59
60        ct[0] ^= 1;
61        assert_eq!(
62            decrypt(&array(KEY), &array(NONCE), b"aad", &ct),
63            Err(Error::DecryptionFailed)
64        );
65        assert_eq!(
66            decrypt(&array(KEY), &array(NONCE), b"aad", &ct[..4]),
67            Err(Error::DecryptionFailed)
68        );
69    }
70
71    /// Edge cases under fixed key and nonce: empty plaintext with AAD (tag only), a plaintext one
72    /// byte past a block without AAD, and a multi-block plaintext with AAD.
73    #[test]
74    fn known_answers() {
75        const KEY_42: &str = "4242424242424242424242424242424242424242424242424242424242424242";
76        const NONCE_24: &str = "242424242424242424242424242424242424242424242424";
77
78        // (aad, plaintext, ciphertext || tag), all hex
79        let cases = [
80            ("616164", "", "bb3d3db24cbd51fdd25cb14e51c03ed8"),
81            (
82                "",
83                "1111111111111111111111111111111111",
84                "b44fc6747f355db7b33e2e2b1f991cdb23a66e8baea84463df6b29df542779ce\
85                1d",
86            ),
87            (
88                "616164",
89                "54686520717569636b2062726f776e20666f78206a756d7073206f7665722074\
90                6865206c617a7920646f67",
91                "f136b2451f5125c5c90f5d4861ff63ea549ef69a166a19ed5241893b0e62fbb9\
92                7cf4a8b455e122bc18dad68ba7eb2a903d166f31fa83074b716ac9",
93            ),
94        ];
95        let (key, nonce) = (array::<KEY_LEN>(KEY_42), array::<NONCE_LEN>(NONCE_24));
96        for (aad, plaintext, expected) in cases {
97            let (aad, plaintext) = (bytes(aad), bytes(plaintext));
98            let ciphertext = encrypt(&key, &nonce, &aad, &plaintext);
99            assert_eq!(hex::encode(&ciphertext), expected);
100            assert_eq!(decrypt(&key, &nonce, &aad, &ciphertext), Ok(plaintext));
101        }
102    }
103}