libes/enc/
aes256gcm.rs

1use super::generics::Encryption;
2use crate::EciesError;
3use aes_gcm::aead::{Aead, Payload};
4use aes_gcm::KeyInit;
5
6#[cfg(feature = "ECIES-MAC")]
7use crate::markers::{EciesMacDecryptionSupport, EciesMacEncryptionSupport};
8#[cfg(feature = "ECIES-MAC")]
9impl EciesMacEncryptionSupport for Aes256Gcm {}
10#[cfg(feature = "ECIES-MAC")]
11impl EciesMacDecryptionSupport for Aes256Gcm {}
12
13#[cfg(feature = "ECIES-AEAD")]
14use crate::markers::{EciesAeadDecryptionSupport, EciesAeadEncryptionSupport};
15#[cfg(feature = "ECIES-AEAD")]
16impl EciesAeadEncryptionSupport for Aes256Gcm {}
17#[cfg(feature = "ECIES-AEAD")]
18impl EciesAeadDecryptionSupport for Aes256Gcm {}
19
20#[cfg(feature = "ECIES-SYN")]
21use crate::markers::{EciesSynDecryptionSupport, EciesSynEncryptionSupport};
22#[cfg(feature = "ECIES-SYN")]
23impl EciesSynEncryptionSupport for Aes256Gcm {}
24#[cfg(feature = "ECIES-SYN")]
25impl EciesSynDecryptionSupport for Aes256Gcm {}
26
27/// Marker for using the `AES256-GCM` algorithm for encryption
28///
29/// AES256-GCM is provided by [aes-gcm](https://crates.io/crates/aes-gcm)
30pub struct Aes256Gcm;
31
32impl Encryption for Aes256Gcm {
33    const ENCRYPTION_KEY_LEN: usize = 32;
34    const ENCRYPTION_NONCE_LEN: usize = 12;
35
36    fn encrypt(key: &[u8], nonce: &[u8], plaintext: &[u8]) -> Result<Vec<u8>, EciesError> {
37        let enc = aes_gcm::Aes256Gcm::new_from_slice(key).map_err(|_| EciesError::BadData)?;
38
39        enc.encrypt(
40            nonce.into(),
41            Payload {
42                msg: plaintext,
43                aad: b"",
44            },
45        )
46        .map_err(|_| EciesError::EncryptionError)
47    }
48
49    fn decrypt(key: &[u8], nonce: &[u8], ciphertext: &[u8]) -> Result<Vec<u8>, EciesError> {
50        let dec = aes_gcm::Aes256Gcm::new_from_slice(key).map_err(|_| EciesError::BadData)?;
51
52        dec.decrypt(
53            nonce.into(),
54            Payload {
55                msg: ciphertext,
56                aad: b"",
57            },
58        )
59        .map_err(|_| EciesError::DecryptionError)
60    }
61}