Implement challenge 18 CTR cipher mode.

This commit is contained in:
2022-07-09 11:54:55 -04:00
parent 1304ff2144
commit e70c6c470c
3 changed files with 31 additions and 28 deletions

View File

@@ -1,37 +1,29 @@
use crate::bytes::Bytes;
// use crate::cbc;
// use openssl::symm;
use crate::cbc;
use openssl::symm;
fn _xor(a: &[u8], b: &[u8]) -> Vec<u8> {
fn xor(a: &Vec<u8>, b: &Vec<u8>) -> Vec<u8> {
Iterator::zip(a.iter(), b.iter())
.map(|z| *(z.0) ^ *(z.1))
.collect()
}
pub fn _encrypt(Bytes(_key): &Bytes, Bytes(_data): &Bytes) -> Bytes {
// let block_size = 16;
let result: Vec<u8> = vec![];
// let mut prev_cipher: Vec<u8> = iv.to_vec(); // first xor input is IV
// for data in data.chunks(block_size) {
// let xored = xor(&prev_cipher, data);
// let mut cipher = cbc::enrypt_aes_128_ecb_block(key, &xored);
// prev_cipher = cipher.to_vec(); // cipher is input for next xor
// result.append(&mut cipher);
// }
Bytes(result)
pub fn encrypt(key: &Bytes, nonce: u64, data: &Bytes) -> Bytes {
decrypt(key, nonce, data)
}
pub fn decrypt(Bytes(_key): &Bytes, Bytes(_data): &Bytes) -> Bytes {
// XXX: does not handle padding for last block
// let cipher_type = symm::Cipher::aes_128_ecb();
// let block_size = cipher_type.block_size();
let result: Vec<u8> = vec![];
// let mut prev_cipher: Vec<u8> = iv.to_vec(); // first xor input is IV
// for cipher in data.chunks(block_size) {
// let xored = cbc::decrypt_aes_128_ecb_block(key, &cipher);
// let data = xor(&xored, &prev_cipher);
// result.extend(data.to_vec());
// prev_cipher = cipher.to_vec();
// }
pub fn decrypt(Bytes(key): &Bytes, nonce: u64, Bytes(data): &Bytes) -> Bytes {
let mut counter: u64 = 0;
let cipher_type = symm::Cipher::aes_128_ecb();
let block_size = cipher_type.block_size();
let mut result: Vec<u8> = vec![];
for cipher in data.chunks(block_size) {
let mut keyinput = nonce.to_le_bytes().to_vec();
keyinput.append(&mut counter.to_le_bytes().to_vec());
let keystream = cbc::enrypt_aes_128_ecb_block(key, &keyinput);
let mut data = xor(&keystream, &cipher.to_vec());
result.append(&mut data);
counter += 1;
}
Bytes(result)
}