How to decrypt a message using Aes128Cbc Rust

1.2k views Asked by At

I am having a few issues trying to decrypt a message that I have saved to a text file. When trying to decrypt the message I get the error - "thread 'main' panicked at 'called Result::unwrap() on an Err value: BlockModeError'". Which really doesn't give me much to play with. And I can't find anything online about other people having issues. I am using this crate block-modes. And this is the example they use to use block-modes docs

use block_modes::block_padding::Pkcs7;

type Aes128Cbc = Cbc<Aes128, Pkcs7>;

pub struct FileHandler{
    file: File,
    file_path: String,
    encyption_key: [u8; 16],
}

impl FileHandler{
    pub fn new() -> FileHandler{
        let mut temp_dir = PathBuf::from(UserDirs::new().unwrap().document_dir().unwrap());
        temp_dir.push("storage.txt"); // Creating Path for docs folder
        let temp_file: File;

        match OpenOptions::new().append(true).read(true).open(&temp_dir){
            Ok(result) => {temp_file = result},
            Err(_) => { temp_file = File::create(&temp_dir).expect(&format!("Could not create file! - {}", temp_dir.to_str().unwrap())); }
        } // Opening the file in read and append

        FileHandler {
            file: temp_file,
            file_path: String::from(temp_dir.to_str().unwrap()),
            encyption_key: [0u8; 16],
        } // returning the FileHandler object
    }

    fn write(&mut self, string: &str, url_key: &Url){  

        let mut iv_buffer = [0u8; 16];

        let cypher = Aes128Cbc::new_from_slices(&self.encyption_key, &iv_buffer).unwrap(); // creates the cyoher object
        for letter in cypher.encrypt_vec(string.as_bytes()){
            self.file.write_all(&[letter]).expect("Failed to write to file!"); // loops through each encrypted letter and writes it
        }
    }

    pub fn read_details(&mut self) -> Option<(String, String)> {

        let mut iv_buffer = [0u8; 16];

        let metadata = fs::metadata(&self.file_path).unwrap();
        let mut buffer = vec![0; metadata.len() as usize]; // making a buffer that will fit the contents of the file
        self.file.read(&mut buffer).expect("buffer overflow"); // reading to the buffer

        let cypher = Aes128Cbc::new_from_slices(&self.encyption_key, &iv_buffer).unwrap(); // creating cypher object
            
        let temp = cypher.decrypt_vec(&mut buffer).unwrap(); // Where the error occurs

        None
    }
}

Any help at all will be hugely appreciated as I have been stumped on this for a while.

0

There are 0 answers