Skip to main content

bitwarden_crypto_primitives/
aes_cbc.rs

1//! AES-256-CBC.
2//!
3//! Unauthenticated: always pair with a MAC (encrypt-then-MAC).
4
5use crate::{Error, backend};
6
7/// Key length in bytes.
8pub const KEY_LEN: usize = 32;
9/// IV length in bytes.
10pub const IV_LEN: usize = 16;
11/// Block length in bytes.
12pub const BLOCK_LEN: usize = 16;
13
14/// Encrypts `plaintext` with PKCS#7 padding.
15pub fn encrypt_pkcs7(key: &[u8; KEY_LEN], iv: &[u8; IV_LEN], plaintext: &[u8]) -> Vec<u8> {
16    backend::aes_cbc::encrypt_pkcs7(key, iv, plaintext)
17}
18
19/// Decrypts `ciphertext` and strips PKCS#7 padding.
20pub fn decrypt_pkcs7(
21    key: &[u8; KEY_LEN],
22    iv: &[u8; IV_LEN],
23    ciphertext: &[u8],
24) -> Result<Vec<u8>, Error> {
25    backend::aes_cbc::decrypt_pkcs7(key, iv, ciphertext)
26}
27
28/// Unpadded, block-at-a-time CBC encryption for streaming. The caller must perform padding.
29pub struct Encryptor(backend::aes_cbc::Encryptor);
30
31impl Encryptor {
32    /// Starts a CBC chain.
33    pub fn new(key: &[u8; KEY_LEN], iv: &[u8; IV_LEN]) -> Self {
34        Self(backend::aes_cbc::Encryptor::new(key, iv))
35    }
36
37    /// Encrypts the next block in place.
38    pub fn encrypt_block(&mut self, block: &mut [u8; BLOCK_LEN]) {
39        self.0.encrypt_block(block);
40    }
41}
42
43/// Unpadded, block-at-a-time CBC decryption for streaming. The caller must remove padding.
44pub struct Decryptor(backend::aes_cbc::Decryptor);
45
46impl Decryptor {
47    /// Starts a CBC chain.
48    pub fn new(key: &[u8; KEY_LEN], iv: &[u8; IV_LEN]) -> Self {
49        Self(backend::aes_cbc::Decryptor::new(key, iv))
50    }
51
52    /// Decrypts the next block in place.
53    pub fn decrypt_block(&mut self, block: &mut [u8; BLOCK_LEN]) {
54        self.0.decrypt_block(block);
55    }
56}
57
58#[cfg(test)]
59mod tests {
60    use super::*;
61    use crate::test_vectors::{array, bytes};
62
63    // NIST SP 800-38A F.2.5 (CBC-AES256.Encrypt), first two blocks.
64    const KEY: &str = "603deb1015ca71be2b73aef0857d77811f352c073b6108d72d9810a30914dff4";
65    const IV: &str = "000102030405060708090a0b0c0d0e0f";
66    const PT: &str = "6bc1bee22e409f96e93d7e117393172aae2d8a571e03ac9c9eb76fac45af8e51";
67    const CT: &str = "f58c4c04d6e5f1ba779eabfb5f7bfbd69cfc4e967edb808d679f777bc6702c7d";
68
69    #[test]
70    fn streaming_known_answer() {
71        let (key, iv) = (array::<KEY_LEN>(KEY), array::<IV_LEN>(IV));
72        let pt = bytes(PT);
73
74        let mut enc = Encryptor::new(&key, &iv);
75        let mut out = Vec::new();
76        for chunk in pt.chunks_exact(BLOCK_LEN) {
77            let mut block: [u8; BLOCK_LEN] = chunk.try_into().expect("block");
78            enc.encrypt_block(&mut block);
79            out.extend_from_slice(&block);
80        }
81        assert_eq!(hex::encode(&out), CT);
82
83        let mut dec = Decryptor::new(&key, &iv);
84        let mut back = Vec::new();
85        for chunk in out.chunks_exact(BLOCK_LEN) {
86            let mut block: [u8; BLOCK_LEN] = chunk.try_into().expect("block");
87            dec.decrypt_block(&mut block);
88            back.extend_from_slice(&block);
89        }
90        assert_eq!(back, pt);
91    }
92
93    #[test]
94    fn padded_roundtrip_matches_streaming() {
95        let (key, iv) = (array::<KEY_LEN>(KEY), array::<IV_LEN>(IV));
96        let pt = bytes(PT);
97
98        let ct = encrypt_pkcs7(&key, &iv, &pt);
99        // Two data blocks plus one full padding block.
100        assert_eq!(ct.len(), 3 * BLOCK_LEN);
101        assert_eq!(hex::encode(&ct[..2 * BLOCK_LEN]), CT);
102        assert_eq!(decrypt_pkcs7(&key, &iv, &ct), Ok(pt));
103    }
104
105    #[test]
106    fn rejects_bad_length() {
107        let (key, iv) = (array::<KEY_LEN>(KEY), array::<IV_LEN>(IV));
108        assert_eq!(
109            decrypt_pkcs7(&key, &iv, &bytes("000000000000000000000000000000")),
110            Err(Error::DecryptionFailed)
111        );
112    }
113
114    /// PKCS#7 edge cases: empty input pads to a full block, a block-aligned input gains a whole
115    /// padding block, and one byte more shares the first ciphertext block with it.
116    #[test]
117    fn known_answers_padding() {
118        const KEY_42: &str = "4242424242424242424242424242424242424242424242424242424242424242";
119        const IV_24: &str = "24242424242424242424242424242424";
120
121        // (plaintext, ciphertext)
122        let cases = [
123            ("", "f14adffc8869f2eb0df4e65f69723de2"),
124            (
125                "11111111111111111111111111111111",
126                "7d2f24631d29ffe73a37092c736b54e049282da0cce3e6a9ea19ee2d77dfef42",
127            ),
128            (
129                "1111111111111111111111111111111111",
130                "7d2f24631d29ffe73a37092c736b54e044226c47a0f59fe109bf2cf59c633d36",
131            ),
132        ];
133        let (key, iv) = (array::<KEY_LEN>(KEY_42), array::<IV_LEN>(IV_24));
134        for (plaintext, expected) in cases {
135            let plaintext = bytes(plaintext);
136            let ciphertext = encrypt_pkcs7(&key, &iv, &plaintext);
137            assert_eq!(hex::encode(&ciphertext), expected);
138            assert_eq!(decrypt_pkcs7(&key, &iv, &ciphertext), Ok(plaintext));
139        }
140    }
141}