bitwarden_crypto_primitives/rustcrypto/
xchacha20_poly1305.rs1use chacha20poly1305::{KeyInit, XChaCha20Poly1305, aead::AeadInOut};
2
3use crate::{
4 Error,
5 xchacha20_poly1305::{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 XChaCha20Poly1305::new(key.into())
16 .encrypt_in_place(nonce.into(), aad, &mut buffer)
17 .expect("XChaCha20-Poly1305 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 XChaCha20Poly1305::new(key.into())
29 .decrypt_in_place(nonce.into(), aad, &mut buffer)
30 .map_err(|_| Error::DecryptionFailed)?;
31 Ok(buffer)
32}