tiny_crypto/sym/
aes.rs

1/// The AES cipher
2pub struct Aes<const BYTES: usize> {
3    cipher: libaes::Cipher,
4}
5
6impl<const BYTES: usize> super::Cipher for Aes<BYTES> {
7    type KeyBytes = [u8; BYTES];
8
9    fn from_key_array(key: &Self::KeyBytes) -> Self {
10        Self { cipher: new_libaes_cipher(BYTES * 8, key) }
11    }
12
13    fn encrypt_with_iv(&self, iv: &Self::KeyBytes, input: &[u8]) -> Vec<u8> {
14        self.cipher.cbc_encrypt(iv, input)
15    }
16    fn decrypt_with_iv(&self, iv: &Self::KeyBytes, input: &[u8]) -> Vec<u8> {
17        self.cipher.cbc_decrypt(iv, input)
18    }
19}
20
21fn new_libaes_cipher(bits: usize, key: &[u8]) -> libaes::Cipher {
22    match bits {
23        128 => libaes::Cipher::new_128(key.try_into().unwrap()),
24        192 => libaes::Cipher::new_192(key.try_into().unwrap()),
25        256 => libaes::Cipher::new_256(key.try_into().unwrap()),
26        _ => unreachable!()
27    }
28}