1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
use crate::Aes256;
use crate::KeyInit;
use crate::BlockEncrypt;
use crate::get_generic_array;
use crate::OMFE;

/// Initialize the Struct with text as `String` type using the from() method and perform encryption operations
pub struct Encryptor {
    raw_bytes: Vec<u8>
}

impl From<&str> for Encryptor {
    fn from(value: &str) -> Self {
        Self { raw_bytes: value.as_bytes().to_owned() }
    }
}

impl From<String> for Encryptor {
    fn from(value: String) -> Self {
        Self { raw_bytes: value.as_bytes().to_owned() }
    }
}

impl<'a, T> From<&'a [T]> for Encryptor 
where Vec<u8>: From<&'a [T]> {
    fn from(value: &'a [T]) -> Self {
        Self { raw_bytes: value.into() }
    }
}

impl Encryptor {
    /// Takes a Key of 32 bytes in length to Encrypt the text initialized with the Encryptor::from() associated function
    /// 
    /// # Examples
    /// 
    /// ```
    /// use byte_aes::encrypt::Encryptor;
    /// 
    /// let my_32byte_key = "Thisi$MyKeyT0Encryp!thislastTime".to_owned();
    /// let original_text: String = "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 original_bytes: &[u8] = original_text.as_bytes();
    /// 
    /// // You can encrypt your data by providing a slice
    /// let mut encrypt_obj: Encryptor = Encryptor::from(original_text.as_str());
    /// 
    /// // You can encrypt your data by providing a String
    /// let mut encrypt_obj: Encryptor = Encryptor::from(original_text.as_str());
    /// 
    /// // You can encrypt your data by providing raw bytes
    /// let mut encrypt_obj: Encryptor = Encryptor::from(original_bytes);
    /// let encrypted_bytes: Vec<u8> = encrypt_obj.encrypt_with(&my_32byte_key);
    /// 
    /// ````
    /// 
    /// The output from the variable 'encrypted_bytes' would return a `Vec<u8>`
    pub fn encrypt_with(&mut self, key: &String) -> Vec<u8> {

        // I am deferencing the Box returned from the get_generic_array below
        let (key, mut deref_generic_block) = *get_generic_array(self, key);

        let aes_object = Aes256::new(&key);

        // Encrypt the single unit at once (This Unit will contain all the blocks)
        aes_object.encrypt_blocks(deref_generic_block.as_mut_slice());
        
        // Stich back the encrypted blocks
        deref_generic_block.concat().into_iter().collect::<Vec<u8>>()
    }
}

impl OMFE for Encryptor {
    fn get_raw_bytes(&self) -> Vec<u8> {
        self.raw_bytes.to_owned()
    }
}