bitwarden_crypto_primitives/
xaes_256_gcm.rs1use crate::{Error, backend};
4
5pub const KEY_LEN: usize = 32;
7pub const NONCE_LEN: usize = 24;
9pub const TAG_LEN: usize = 16;
11
12pub fn encrypt(
16 key: &[u8; KEY_LEN],
17 nonce: &[u8; NONCE_LEN],
18 aad: &[u8],
19 plaintext: &[u8],
20) -> Vec<u8> {
21 backend::xaes_256_gcm::encrypt(key, nonce, aad, plaintext)
22}
23
24pub 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::xaes_256_gcm::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 #[test]
72 fn known_answer() {
73 let ct = encrypt(
75 &array("0101010101010101010101010101010101010101010101010101010101010101"),
76 b"ABCDEFGHIJKLMNOPQRSTUVWX",
77 b"",
78 b"XAES-256-GCM",
79 );
80 assert_eq!(
81 hex::encode(ct),
82 "ce546ef63c9cc60765923609b33a9a1974e96e52daf2fcf7075e2271"
83 );
84 }
85
86 #[test]
89 fn known_answers() {
90 const KEY_42: &str = "4242424242424242424242424242424242424242424242424242424242424242";
91 const NONCE_24: &str = "242424242424242424242424242424242424242424242424";
92
93 let cases = [
95 ("616164", "", "18ef199c103f13f2e1ce85cf374b9997"),
96 (
97 "",
98 "1111111111111111111111111111111111",
99 "ad5c0f01a138cecf2105b59c272f9c753a9e5deb768d43176de5ad57ce51818a\
100 93",
101 ),
102 (
103 "616164",
104 "54686520717569636b2062726f776e20666f78206a756d7073206f7665722074\
105 6865206c617a7920646f67",
106 "e8257b30c15cb6bd5b34c6ff5949e3444d3eb310e11eef91efd172b8bf2d73f6\
107 e8987bd472107d0c660e4ad8ab245fa9f6dca83a0ebfd854a7eb43",
108 ),
109 ];
110 let (key, nonce) = (array::<KEY_LEN>(KEY_42), array::<NONCE_LEN>(NONCE_24));
111 for (aad, plaintext, expected) in cases {
112 let (aad, plaintext) = (bytes(aad), bytes(plaintext));
113 let ciphertext = encrypt(&key, &nonce, &aad, &plaintext);
114 assert_eq!(hex::encode(&ciphertext), expected);
115 assert_eq!(decrypt(&key, &nonce, &aad, &ciphertext), Ok(plaintext));
116 }
117 }
118}