bitwarden_crypto/
aes.rs

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
//! # AES operations
//!
//! Contains low level AES operations used by the rest of the library.
//!
//! In most cases you should use the [EncString][crate::EncString] with
//! [KeyEncryptable][crate::KeyEncryptable] & [KeyDecryptable][crate::KeyDecryptable] instead.

use aes::cipher::{
    block_padding::Pkcs7,
    typenum::{U16, U32},
    BlockDecryptMut, BlockEncryptMut, KeyIvInit,
};
use generic_array::GenericArray;
use hmac::Mac;
use subtle::ConstantTimeEq;

use crate::{
    error::{CryptoError, Result},
    util::{PbkdfSha256Hmac, PBKDF_SHA256_HMAC_OUT_SIZE},
};

/// Decrypt using AES-256 in CBC mode.
///
/// Behaves similar to [decrypt_aes256_hmac], but does not validate the MAC.
pub(crate) fn decrypt_aes256(
    iv: &[u8; 16],
    data: Vec<u8>,
    key: &GenericArray<u8, U32>,
) -> Result<Vec<u8>> {
    // Decrypt data
    let iv = GenericArray::from_slice(iv);
    let mut data = data;
    let decrypted_key_slice = cbc::Decryptor::<aes::Aes256>::new(key, iv)
        .decrypt_padded_mut::<Pkcs7>(&mut data)
        .map_err(|_| CryptoError::KeyDecrypt)?;

    // Data is decrypted in place and returns a subslice of the original Vec, to avoid cloning it,
    // we truncate to the subslice length
    let decrypted_len = decrypted_key_slice.len();
    data.truncate(decrypted_len);

    Ok(data)
}

/// Decrypt using AES-256 in CBC mode with MAC.
///
/// Behaves similar to [decrypt_aes256], but also validates the MAC.
pub(crate) fn decrypt_aes256_hmac(
    iv: &[u8; 16],
    mac: &[u8; 32],
    data: Vec<u8>,
    mac_key: &GenericArray<u8, U32>,
    key: &GenericArray<u8, U32>,
) -> Result<Vec<u8>> {
    let res = generate_mac(mac_key, iv, &data)?;
    if res.ct_ne(mac).into() {
        return Err(CryptoError::InvalidMac);
    }
    decrypt_aes256(iv, data, key)
}

/// Encrypt using AES-256 in CBC mode.
///
/// Behaves similar to [encrypt_aes256_hmac], but does't generate a MAC.
///
/// ## Returns
///
/// A AesCbc256_B64 EncString
#[allow(unused)]
pub(crate) fn encrypt_aes256(data_dec: &[u8], key: &GenericArray<u8, U32>) -> ([u8; 16], Vec<u8>) {
    let rng = rand::thread_rng();
    let (iv, data) = encrypt_aes256_internal(rng, data_dec, key);

    (iv, data)
}

/// Encrypt using AES-256 in CBC mode with MAC.
///
/// Behaves similar to [encrypt_aes256], but also generate a MAC.
///
/// ## Returns
///
/// A AesCbc256_HmacSha256_B64 EncString
pub(crate) fn encrypt_aes256_hmac(
    data_dec: &[u8],
    mac_key: &GenericArray<u8, U32>,
    key: &GenericArray<u8, U32>,
) -> Result<([u8; 16], [u8; 32], Vec<u8>)> {
    let rng = rand::thread_rng();
    let (iv, data) = encrypt_aes256_internal(rng, data_dec, key);
    let mac = generate_mac(mac_key, &iv, &data)?;

    Ok((iv, mac, data))
}

/// Encrypt using AES-256 in CBC mode.
///
/// Used internally by:
/// - [encrypt_aes256]
/// - [encrypt_aes256_hmac]
fn encrypt_aes256_internal(
    mut rng: impl rand::RngCore,
    data_dec: &[u8],
    key: &GenericArray<u8, U32>,
) -> ([u8; 16], Vec<u8>) {
    let mut iv = [0u8; 16];
    rng.fill_bytes(&mut iv);
    let data = cbc::Encryptor::<aes::Aes256>::new(key, &iv.into())
        .encrypt_padded_vec_mut::<Pkcs7>(data_dec);

    (iv, data)
}

/// Decrypt using AES-128 in CBC mode.
///
/// Behaves similar to [decrypt_aes128_hmac], but does not validate the MAC.
fn decrypt_aes128(iv: &[u8; 16], data: Vec<u8>, key: &GenericArray<u8, U16>) -> Result<Vec<u8>> {
    // Decrypt data
    let iv = GenericArray::from_slice(iv);
    let mut data = data;
    let decrypted_key_slice = cbc::Decryptor::<aes::Aes128>::new(key, iv)
        .decrypt_padded_mut::<Pkcs7>(&mut data)
        .map_err(|_| CryptoError::KeyDecrypt)?;

    // Data is decrypted in place and returns a subslice of the original Vec, to avoid cloning it,
    // we truncate to the subslice length
    let decrypted_len = decrypted_key_slice.len();
    data.truncate(decrypted_len);

    Ok(data)
}

/// Decrypt using AES-128 in CBC mode with MAC.
///
/// Behaves similar to [decrypt_aes128], but also validates the MAC.
pub(crate) fn decrypt_aes128_hmac(
    iv: &[u8; 16],
    mac: &[u8; 32],
    data: Vec<u8>,
    mac_key: &GenericArray<u8, U16>,
    key: &GenericArray<u8, U16>,
) -> Result<Vec<u8>> {
    let res = generate_mac(mac_key, iv, &data)?;
    if res.ct_ne(mac).into() {
        return Err(CryptoError::InvalidMac);
    }
    decrypt_aes128(iv, data, key)
}

/// Generate a MAC using HMAC-SHA256.
fn generate_mac(mac_key: &[u8], iv: &[u8], data: &[u8]) -> Result<[u8; 32]> {
    let mut hmac =
        PbkdfSha256Hmac::new_from_slice(mac_key).expect("hmac new_from_slice should not fail");
    hmac.update(iv);
    hmac.update(data);
    let mac: [u8; PBKDF_SHA256_HMAC_OUT_SIZE] = (*hmac.finalize().into_bytes())
        .try_into()
        .map_err(|_| CryptoError::InvalidMac)?;

    Ok(mac)
}

#[cfg(test)]
mod tests {
    use base64::{engine::general_purpose::STANDARD, Engine};
    use generic_array::{sequence::GenericSequence, ArrayLength};
    use rand::SeedableRng;

    use super::*;

    /// Helper function for generating a `GenericArray` of size 32 with each element being
    /// a multiple of a given increment, starting from a given offset.
    fn generate_generic_array<N: ArrayLength<u8>>(
        offset: u8,
        increment: u8,
    ) -> GenericArray<u8, N> {
        GenericArray::generate(|i| offset + i as u8 * increment)
    }

    /// Helper function for generating a vector of a given size with each element being
    /// a multiple of a given increment, starting from a given offset.
    fn generate_vec(length: usize, offset: u8, increment: u8) -> Vec<u8> {
        (0..length).map(|i| offset + i as u8 * increment).collect()
    }

    #[test]
    fn test_encrypt_aes256_internal() {
        let key = generate_generic_array(0, 1);

        let rng = rand_chacha::ChaCha8Rng::from_seed([0u8; 32]);
        let result = encrypt_aes256_internal(rng, "EncryptMe!".as_bytes(), &key);
        assert_eq!(
            result,
            (
                [62, 0, 239, 47, 137, 95, 64, 214, 127, 91, 184, 232, 31, 9, 165, 161],
                vec![214, 76, 187, 97, 58, 146, 212, 140, 95, 164, 177, 204, 179, 133, 172, 148]
            )
        );
    }

    #[test]
    fn test_generate_mac() {
        let mac_key = generate_vec(16, 0, 16);

        let iv = generate_vec(16, 0, 16);
        let data = generate_vec(16, 0, 16);

        let result = generate_mac(&mac_key, &iv, &data);

        assert!(result.is_ok());
        let mac = result.unwrap();
        assert_eq!(mac.len(), 32);
    }

    #[test]
    fn test_decrypt_aes128() {
        let iv = generate_vec(16, 0, 1);
        let iv: &[u8; 16] = iv.as_slice().try_into().unwrap();
        let key = generate_generic_array(0, 1);

        let data = STANDARD.decode("dC0X+2IjFbeL4WLLg2jX7Q==").unwrap();

        let decrypted = decrypt_aes128(iv, data, &key).unwrap();

        assert_eq!(String::from_utf8(decrypted).unwrap(), "EncryptMe!");
    }

    #[test]
    fn test_decrypt_aes256() {
        let iv = generate_vec(16, 0, 1);
        let iv: &[u8; 16] = iv.as_slice().try_into().unwrap();
        let key = generate_generic_array(0, 1);
        let data = STANDARD.decode("ByUF8vhyX4ddU9gcooznwA==").unwrap();

        let decrypted = decrypt_aes256(iv, data, &key).unwrap();

        assert_eq!(String::from_utf8(decrypted).unwrap(), "EncryptMe!");
    }

    #[test]
    fn test_encrypt_decrypt_aes256() {
        let key = generate_generic_array(0, 1);
        let data = "EncryptMe!";

        let (iv, encrypted) = encrypt_aes256(data.as_bytes(), &key);
        let decrypted = decrypt_aes256(&iv, encrypted, &key).unwrap();

        assert_eq!(String::from_utf8(decrypted).unwrap(), "EncryptMe!");
    }
}