Skip to main content

bitwarden_crypto_primitives/rustcrypto/
xaes_256_gcm.rs

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