include_crypt_crypto/
aes.rs

1use crate::key::EncryptionKey;
2use aes::{
3    cipher::{NewStreamCipher, StreamCipher},
4    Aes256,
5};
6use cfb_mode::{cipher::stream::InvalidKeyNonceLength, Cfb};
7
8/// Default key length (AES-256)
9pub const AES_KEY_LEN: usize = 32;
10
11/// Nonce length (AES-256)
12pub const AES_NONCE_LEN: usize = 16;
13
14/// Encrypts the specified data with the AES CFB cipher.
15///
16/// # Parameters
17///
18/// - `data`: The plaintext data buffer. After this function has been called, it
19///   will store the encrypted data.
20/// - `key`: The encryption key. It must be exactly 32 bytes.
21/// - `nonce`: The unique nonce. It must be exactly 16 bytes.
22///
23/// # Returns
24///
25/// If the data could be successfully encrypted `Ok(())` will be returned. If
26/// the key or nonce are invalid, `Err(InvalidKeyNonceLength)` will be returned.
27#[inline(always)]
28pub fn aes_encrypt<K: AsRef<EncryptionKey>>(data: &mut [u8], key: K, nonce: K) -> Result<(), InvalidKeyNonceLength> {
29    Cfb::<Aes256>::new_var(key.as_ref(), nonce.as_ref()).map(|mut aes| aes.encrypt(data))
30}
31
32/// Decrypts the specified data with the AES CFB cipher.
33///
34/// # Parameters
35///
36/// - `data`: The encrypted data buffer. After this function has been called, it
37///   will store the decrypted data.
38/// - `key`: The decryption key. It must be exactly 32 bytes.
39/// - `nonce`: The unique nonce. It must be exactly 16 bytes.
40///
41/// # Returns
42///
43/// If the data could be successfully decrypted `Ok(())` will be returned. If
44/// the key or nonce are invalid, `Err(InvalidKeyNonceLength)` will be returned.
45#[inline(always)]
46pub fn aes_decrypt<K: AsRef<EncryptionKey>>(data: &mut [u8], key: K, nonce: K) -> Result<(), InvalidKeyNonceLength> {
47    Cfb::<Aes256>::new_var(key.as_ref(), nonce.as_ref()).map(|mut aes| aes.decrypt(data))
48}
49
50#[cfg(test)]
51mod tests {
52    use super::*;
53    use crate::key::EncryptionKey;
54
55    #[test]
56    fn test_aes() {
57        let mut data = Vec::from("The quick brown fox jumps over the lazy dog.".as_bytes());
58        let key = EncryptionKey::random(AES_KEY_LEN);
59        let nonce = EncryptionKey::random(AES_NONCE_LEN);
60
61        assert_eq!(aes_encrypt(data.as_mut_slice(), &key, &nonce).is_ok(), true);
62        assert_eq!(aes_decrypt(data.as_mut_slice(), &key, &nonce).is_ok(), true);
63
64        assert_eq!(data, "The quick brown fox jumps over the lazy dog.".as_bytes());
65    }
66}