byte_aes/
lib.rs

1//! # Byte-AES
2//!
3//! ### Developer: Omkarium
4//!
5//! `byte-aes` is a simple wrapper around the popular `aes` crate. The goal is to perform Encrypt and Decrypt operations
6//! using the **Advanced Encryption Standard 256 bit** Algorithm conveninent to use instead of use Low level functions of the `aes` crate
7
8// Bringing all of these items into scope so they can be used in the individual modules without declaring full path
9use aes::{
10    cipher::{crypto_common::generic_array::GenericArray, typenum::U16},
11    Block,
12};
13
14pub mod cryptor;
15
16pub use cryptor::Aes256Cryptor;
17
18// This function is for internal use
19// It takes those structs which implement the OMFE trait. In this case, the Encryptor and Decryptor structs are implementing it.
20// It takes raw_bytes and splits them into chunks of 16 bytes. If any chunk is having less than 16 bytes, this function resize that particular chunk to a
21// capacity of 16 bytes filled with data specified by Pkcs7Padding algorithm
22
23fn split_into_16byte_blocks(mut origin: Vec<u8>, is_decrypt: bool) -> Vec<Vec<u8>> {
24    let round = origin.len() % 16;
25    if round == 0 && !is_decrypt {
26        let extra = [16u8; 16];
27        origin.extend_from_slice(&extra[..]);
28    } else if !is_decrypt {
29        let required_padding = 16 - round;
30        let extra = vec![required_padding as u8; required_padding];
31        origin.extend_from_slice(&extra[..]);
32    }
33    origin.chunks(16).map(|v| v.to_vec()).collect()
34}
35
36// This function gets us a GenericArray key and blocks(data)
37// We need a Box here in the return type because the GenericArray type is not sized because its some kind of linked list
38// and we cannot return a type whose size is not known during compilation
39
40fn get_generic_array(item: Vec<u8>, is_decrypt: bool) -> Vec<Block> {
41    // Once the Encrypted or Decrypted Bytes are provided via self we split then into a a Vec<Vec<u8> where the inner Vec is always 16 bytes long
42    let blocks = split_into_16byte_blocks(item, is_decrypt);
43
44    // We can't use the Vec<u8> to directly decrypt, so we need to use the GenericArray struct provided by the aes crate
45
46    // Same logic as the above, but the data we are planning to encrypt shall be 16 byte long blocks. Hence the U16 type.
47    let generic_block = blocks
48        .into_iter()
49        .map(|v| GenericArray::<u8, U16>::from_slice(&v[..]).to_owned())
50        .collect();
51
52    // deferencing the Generic block from the Vec as a single Unit
53    //let deref_generic_block = generic_block.as_mut_slice();
54    generic_block
55}
56
57/// This is my create
58#[cfg(test)]
59mod tests {
60    use crate::Aes256Cryptor;
61
62    #[test]
63    fn test_with_strings() {
64        let my_32byte_key = "Thisi$MyKeyT0Encryp!thislastTime".to_owned();
65        let original_text = "I am Omkaram Venkatesh and 
66        this is my plain text and some random chars 223@#$^$%*%^(!#@%$~@#$[]]'///\\drewe. Lets see if this gets encrypted now)".to_string();
67
68        let cryptor = Aes256Cryptor::try_from(&my_32byte_key).unwrap();
69        let encrypted_bytes: Vec<u8> = cryptor.encrypt(&original_text as &str);
70
71        let decrypted_text: String =
72            String::from_utf8_lossy(&cryptor.decrypt(encrypted_bytes).unwrap_or_default())
73                .to_string();
74
75        assert_eq!(original_text, decrypted_text);
76    }
77
78    #[test]
79    fn test_with_bytes() {
80        let key = "c4ca4238a0b923820dcc509a6f75849b";
81        let cryptor = Aes256Cryptor::try_from(key).unwrap();
82        let buf: [u8; 4] = [1, 0, 0, 1];
83        let encrypt_buf = cryptor.encrypt(buf);
84
85        let clear_buf = cryptor.decrypt(encrypt_buf);
86        let clear_buf = clear_buf.as_ref().map(|v| &v[..]).map_err(|_| ());
87        assert_eq!(Ok(&buf[..]), clear_buf);
88
89        let buf: [u8; 16] = [1, 0, 0, 1, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 13];
90        let encrypt_buf = cryptor.encrypt(buf);
91
92        let clear_buf = cryptor.decrypt(encrypt_buf);
93        let clear_buf = clear_buf.as_ref().map(|v| &v[..]).map_err(|_| ());
94        assert_eq!(Ok(&buf[..]), clear_buf);
95
96        let buf = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 200]; // invalid data for decrypting
97        let clear_buf = cryptor.decrypt(buf);
98        assert!(clear_buf.is_err());
99    }
100}