tiny_crypto/sym/
mod.rs

1//! Symmetric Ciphers
2//! 
3
4/// The trait for symmetric cipher.
5pub trait Cipher {
6    type KeyBytes;
7
8    fn from_key_array(key: &Self::KeyBytes) -> Self;
9    fn encrypt_with_iv(&self, iv: &Self::KeyBytes, input: &[u8]) -> Vec<u8>;
10    fn decrypt_with_iv(&self, iv: &Self::KeyBytes, input: &[u8]) -> Vec<u8>;
11}
12
13mod aes;
14pub use aes::Aes;
15/// The type of AES with 128 key bits.
16pub type Aes128 = aes::Aes<{128 / 8}>;
17/// The type of AES with 192 key bits.
18pub type Aes192 = aes::Aes<{192 / 8}>;
19/// The type of AES with 256 key bits.
20pub type Aes256 = aes::Aes<{256 / 8}>;
21
22#[cfg(test)]
23mod tests {
24    use super::*;
25    use rstest::*;
26
27    #[rstest]
28    #[case(Aes128::from_key_array(b"This is the key!"))]
29    #[case(Aes192::from_key_array(b"This is the key!This is "))]
30    #[case(Aes256::from_key_array(b"This is the key!This is the key!"))]
31    fn encrypt_and_decrypt<const N: usize, T: Cipher<KeyBytes=[u8; N]>>(#[case] cipher: T) {
32        let plain = b"This is the plain text";
33        let iv = [0x88u8; N];
34        let data = cipher.encrypt_with_iv(&iv, plain);
35        let out = cipher.decrypt_with_iv(&iv, &data);
36        assert_eq!(out, plain);
37    }
38}