Skip to main content

bitwarden_crypto_primitives/rustcrypto/
aes_gcm.rs

1use aes_gcm::{Aes256Gcm, KeyInit, aead::AeadInOut};
2
3use crate::{
4    Error,
5    aes_gcm::{KEY_LEN, NONCE_LEN},
6};
7
8pub(crate) fn encrypt(
9    key: &[u8; KEY_LEN],
10    nonce: &[u8; NONCE_LEN],
11    aad: &[u8],
12    plaintext: &[u8],
13) -> Vec<u8> {
14    let mut buffer = plaintext.to_vec();
15    Aes256Gcm::new(key.into())
16        .encrypt_in_place(nonce.into(), aad, &mut buffer)
17        .expect("AES-GCM encryption of in-memory data does not fail");
18    buffer
19}
20
21pub(crate) fn decrypt(
22    key: &[u8; KEY_LEN],
23    nonce: &[u8; NONCE_LEN],
24    aad: &[u8],
25    ciphertext: &[u8],
26) -> Result<Vec<u8>, Error> {
27    let mut buffer = ciphertext.to_vec();
28    Aes256Gcm::new(key.into())
29        .decrypt_in_place(nonce.into(), aad, &mut buffer)
30        .map_err(|_| Error::DecryptionFailed)?;
31    Ok(buffer)
32}