Skip to content

Instantly share code, notes, and snippets.

@akwasiio
Created February 23, 2024 19:26
Show Gist options
  • Save akwasiio/437c314c87e734e0e0124e981ac4ba2d to your computer and use it in GitHub Desktop.
Save akwasiio/437c314c87e734e0e0124e981ac4ba2d to your computer and use it in GitHub Desktop.
Rust code for encrypting & decrypting plaintext using cbc
pub fn cbc_decryption(key_stream: &[u8], cipher: &[u8], init_vector: &[u8]) -> Vec<u8> {
let mut res = Vec::new();
let chunked: Vec<&[u8]> = cipher.chunks(16).collect();
chunked
.iter()
.enumerate()
.for_each(|(index, cipher_chunk)| {
let last = if index == 0 {
init_vector
} else {
chunked[index - 1]
};
let decrypted = decrypt_aes_ecb(key_stream, cipher_chunk);
let xor = fixed_xor(&decrypted, last);
res.push(xor);
});
// let padding_len = *res.last().unwrap().last().unwrap() as usize;
res.into_iter()
.flatten()
// .take(cipher.len() - padding_len)
.collect()
}
pub fn cbc_encryption(key_stream: &[u8], plain_text: &[u8], init_vector: &[u8]) -> Vec<u8> {
let mut cipher = Vec::new();
let init_vector = init_vector.to_vec();
let padded = pkcs7_padding(plain_text, 16);
padded.chunks(16).for_each(|chunk| {
let last_cipher = cipher.last().unwrap_or(&init_vector);
let xor_res = fixed_xor(last_cipher, chunk);
let encrypted = encrypt_aes_ecb(key_stream, &xor_res);
cipher.push(encrypted);
});
cipher.into_iter().flatten().collect()
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment