use aes::{Aes256, cipher::KeyInit};
use aes::cipher::{
BlockEncrypt,
BlockDecrypt,
crypto_common::generic_array::GenericArray,
typenum::{U32, U16, B0, B1, UInt, UTerm}
};
pub mod encrypt;
pub mod decrypt;
pub use self::encrypt::Encryptor;
pub use self::decrypt::Decryptor;
fn split_into_16byte_blocks(item: &impl OMFE) -> Vec<Vec<u8>> {
let mut blocks = Vec::new();
for chunk in item.get_raw_bytes().chunks(16) {
let mut chunk = chunk.to_vec();
let capacity = chunk.capacity();
if capacity < 16 {
let pad_length = capacity + (16 - capacity % 16) % 16;
chunk.resize(pad_length, 0);
}
blocks.push(chunk);
}
blocks
}
fn get_generic_array<'a>(item: &impl OMFE, key: &String) -> Box<(GenericArray<u8, UInt<UInt<UInt<UInt<UInt<UInt<UTerm, B1>, B0>, B0>, B0>, B0>, B0>>, Vec<GenericArray<u8, UInt<UInt<UInt<UInt<UInt<UTerm, B1>, B0>, B0>, B0>, B0>>>)> {
let blocks = split_into_16byte_blocks(item);
let key = GenericArray::<u8, U32>::from_slice(key.as_bytes());
let mut generic_block = Vec::new();
for each_block in blocks.as_slice() {
let data = GenericArray::<u8, U16>::from_slice(each_block);
generic_block.push(*data);
}
let deref_generic_block = generic_block.as_mut_slice();
Box::new((key.to_owned(),deref_generic_block.to_owned()))
}
pub trait OMFE {
fn get_raw_bytes(&self) -> Vec<u8>;
}
#[cfg(test)]
mod tests {
use crate::{encrypt::Encryptor, decrypt::Decryptor};
#[test]
fn it_works() {
let my_32byte_key = "Thisi$MyKeyT0Encryp!thislastTime".to_owned();
let original_text = "I am Omkaram Venkatesh and
this is my plain text and some random chars 223@#$^$%*%^(!#@%$~@#$[]]'///\\drewe. Lets see if this gets encrypted now)".to_string();
let mut encrypt_obj: Encryptor = Encryptor::from(&original_text);
let encrypted_bytes: Vec<u8> = encrypt_obj.encrypt_with(&my_32byte_key);
let mut decrypted_obj: Decryptor = Decryptor::from(&encrypted_bytes);
let decrypted_text: String = decrypted_obj.decrypt_with(&my_32byte_key);
assert_eq!(original_text, decrypted_text);
}
}