crypto_dispatch/algorithms/
aes256_gcm_siv.rs1use zeroize::Zeroizing;
6
7use crate::traits::{AeadCipherAlgorithm, AeadParams};
8use crate::AlgorithmError;
9use crypto_core::AeadAlgorithm;
10
11pub struct Aes256GcmSivAlgo;
13
14impl AeadCipherAlgorithm for Aes256GcmSivAlgo {
15 const ALG: AeadAlgorithm = AeadAlgorithm::Aes256GcmSiv;
16
17 fn encrypt(params: &AeadParams<'_>, plaintext: &[u8]) -> Result<Vec<u8>, AlgorithmError> {
18 #[cfg(any(feature = "native", all(feature = "wasm", target_arch = "wasm32")))]
19 {
20 let key = crypto_aes256_gcm_siv::Aes256GcmSivKey::from_slice(params.key)?;
21 let nonce = crypto_aes256_gcm_siv::Aes256GcmSivNonce::from_slice(params.nonce)?;
22 let request = crypto_aes256_gcm_siv::EncryptRequest {
23 key: &key,
24 nonce,
25 aad: params.aad,
26 plaintext,
27 };
28 let sealed = crypto_aes256_gcm_siv::encrypt(&request)?;
29 Ok(sealed.into_vec())
30 }
31
32 #[cfg(not(any(feature = "native", all(feature = "wasm", target_arch = "wasm32"))))]
33 {
34 let _ = (params, plaintext);
35 Err(AlgorithmError::UnsupportedAeadAlgorithm(Self::ALG))
36 }
37 }
38
39 fn decrypt(
40 params: &AeadParams<'_>,
41 ciphertext_with_tag: &[u8],
42 ) -> Result<Zeroizing<Vec<u8>>, AlgorithmError> {
43 #[cfg(any(feature = "native", all(feature = "wasm", target_arch = "wasm32")))]
44 {
45 let key = crypto_aes256_gcm_siv::Aes256GcmSivKey::from_slice(params.key)?;
46 let nonce = crypto_aes256_gcm_siv::Aes256GcmSivNonce::from_slice(params.nonce)?;
47 let ciphertext =
48 crypto_aes256_gcm_siv::CiphertextWithTag::from_vec(ciphertext_with_tag.to_vec())?;
49 let request = crypto_aes256_gcm_siv::DecryptRequest {
50 key: &key,
51 nonce,
52 aad: params.aad,
53 ciphertext: &ciphertext,
54 };
55 let plaintext = crypto_aes256_gcm_siv::decrypt(&request)?;
56 Ok(Zeroizing::new(plaintext))
57 }
58
59 #[cfg(not(any(feature = "native", all(feature = "wasm", target_arch = "wasm32"))))]
60 {
61 let _ = (params, ciphertext_with_tag);
62 Err(AlgorithmError::UnsupportedAeadAlgorithm(Self::ALG))
63 }
64 }
65}