use crate::result::{ZipError, ZipResult};
use aes::cipher::{BlockCipherEncrypt, KeyInit};
use core::{any, fmt};
const AES_BLOCK_SIZE: usize = 16;
const BATCH_BLOCKS: usize = 32;
#[derive(Debug)]
pub struct Aes128;
#[derive(Debug)]
pub struct Aes192;
#[derive(Debug)]
pub struct Aes256;
pub trait AesKind {
type Key: AsRef<[u8]>;
type Cipher: KeyInit + zeroize::ZeroizeOnDrop;
}
impl AesKind for Aes128 {
type Key = [u8; 16];
type Cipher = aes::Aes128;
}
impl AesKind for Aes192 {
type Key = [u8; 24];
type Cipher = aes::Aes192;
}
impl AesKind for Aes256 {
type Key = [u8; 32];
type Cipher = aes::Aes256;
}
pub struct AesCtrZipKeyStream<C: AesKind> {
counter: u128,
cipher: C::Cipher,
buffer: [u8; AES_BLOCK_SIZE],
pos: usize,
}
impl<C> fmt::Debug for AesCtrZipKeyStream<C>
where
C: AesKind,
{
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(
f,
"AesCtrZipKeyStream<{}>(counter: {})",
any::type_name::<C>(),
self.counter
)
}
}
impl<C: AesKind> Drop for AesCtrZipKeyStream<C> {
fn drop(&mut self) {
use zeroize::Zeroize;
self.buffer.zeroize();
self.counter.zeroize();
}
}
impl<C> AesCtrZipKeyStream<C>
where
C: AesKind,
C::Cipher: KeyInit,
{
pub fn new(key: &[u8]) -> ZipResult<AesCtrZipKeyStream<C>> {
Ok(AesCtrZipKeyStream {
counter: 1,
cipher: C::Cipher::new_from_slice(key).map_err(|_| ZipError::InvalidPassword)?,
buffer: [0u8; AES_BLOCK_SIZE],
pos: AES_BLOCK_SIZE,
})
}
}
impl<C> AesCipher for AesCtrZipKeyStream<C>
where
C: AesKind,
C::Cipher: BlockCipherEncrypt,
{
#[inline]
fn crypt_in_place(&mut self, mut target: &mut [u8]) {
while !target.is_empty() {
if self.pos == AES_BLOCK_SIZE && target.len() >= AES_BLOCK_SIZE {
let blocks = (target.len() / AES_BLOCK_SIZE).min(BATCH_BLOCKS);
let mut keystream: [aes::cipher::Block<C::Cipher>; BATCH_BLOCKS] =
Default::default();
for block in &mut keystream[..blocks] {
block.copy_from_slice(&self.counter.to_le_bytes());
self.counter += 1;
}
self.cipher.encrypt_blocks(&mut keystream[..blocks]);
let (whole, rest) =
core::mem::take(&mut target).split_at_mut(blocks * AES_BLOCK_SIZE);
for (chunk, block) in whole
.as_chunks_mut::<AES_BLOCK_SIZE>()
.0
.iter_mut()
.zip(&keystream)
{
xor(chunk, block);
}
for block in &mut keystream[..blocks] {
zeroize::Zeroize::zeroize(block.as_mut_slice());
}
target = rest;
continue;
}
if self.pos == AES_BLOCK_SIZE {
self.buffer = self.counter.to_le_bytes();
#[allow(deprecated)]
self.cipher
.encrypt_block(aes::cipher::Block::<C::Cipher>::from_mut_slice(
&mut self.buffer,
));
self.counter += 1;
self.pos = 0;
}
let target_len = target.len().min(AES_BLOCK_SIZE - self.pos);
xor(
&mut target[0..target_len],
&self.buffer[self.pos..(self.pos + target_len)],
);
target = &mut target[target_len..];
self.pos += target_len;
}
}
}
pub trait AesCipher {
fn crypt_in_place(&mut self, target: &mut [u8]);
}
#[inline]
fn xor(dest: &mut [u8], src: &[u8]) {
debug_assert_eq!(
dest.len(),
src.len(),
"XOR operation requires destination and source slices to have equal length"
);
for (lhs, rhs) in dest.iter_mut().zip(src.iter()) {
*lhs ^= *rhs;
}
}
#[cfg(test)]
mod tests {
use super::{Aes128, Aes192, Aes256, AesCipher, AesCtrZipKeyStream, AesKind};
use aes::cipher::{BlockCipherEncrypt, KeyInit};
fn roundtrip<Aes>(key: &[u8], ciphertext: &[u8], expected_plaintext: &[u8])
where
Aes: AesKind,
Aes::Cipher: KeyInit + BlockCipherEncrypt,
{
let mut key_stream = AesCtrZipKeyStream::<Aes>::new(key).unwrap();
let mut plaintext = ciphertext.to_vec().into_boxed_slice();
key_stream.crypt_in_place(&mut plaintext);
assert_eq!(*plaintext, *expected_plaintext);
let mut key_stream = AesCtrZipKeyStream::<Aes>::new(key).unwrap();
key_stream.crypt_in_place(&mut plaintext);
assert_eq!(*plaintext, *ciphertext);
}
fn keystream_block_by_block<Aes>(key: &[u8], len: usize) -> Vec<u8>
where
Aes: AesKind,
Aes::Cipher: KeyInit + BlockCipherEncrypt,
{
let cipher = Aes::Cipher::new_from_slice(key).unwrap();
let mut out = Vec::with_capacity(len + 16);
let mut counter = 1u128;
while out.len() < len {
let mut block = aes::cipher::Block::<Aes::Cipher>::default();
block.copy_from_slice(&counter.to_le_bytes());
cipher.encrypt_block(&mut block);
out.extend_from_slice(&block);
counter += 1;
}
out.truncate(len);
out
}
fn batched_matches_block_by_block<Aes>(key: &[u8])
where
Aes: AesKind,
Aes::Cipher: KeyInit + BlockCipherEncrypt,
{
const LEN: usize = 3 * 512 + 37;
let expected = keystream_block_by_block::<Aes>(key, LEN);
let splits: &[&[usize]] = &[
&[LEN],
&[1, LEN - 1],
&[15, 1, 16, 17, LEN - 49],
&[16; 4],
&[511, 1, 513, 7, 9],
&[5, 512, 3, 512, 5],
];
for split in splits {
let mut stream = AesCtrZipKeyStream::<Aes>::new(key).unwrap();
let mut data = vec![0u8; LEN];
let mut at = 0;
for &part in split.iter().chain(core::iter::once(&LEN)) {
let end = (at + part).min(LEN);
stream.crypt_in_place(&mut data[at..end]);
at = end;
}
assert_eq!(data, expected, "split {split:?}");
}
}
#[test]
fn batched_keystream_matches_block_by_block() {
batched_matches_block_by_block::<Aes128>(&[0x11; 16]);
batched_matches_block_by_block::<Aes192>(&[0x22; 24]);
batched_matches_block_by_block::<Aes256>(&[0x33; 32]);
}
#[test]
fn new_with_wrong_key_size() {
AesCtrZipKeyStream::<Aes128>::new(&[1, 2, 3, 4, 5])
.expect_err("Wrong key size should fail");
}
#[test]
fn crypt_aes_256_0_byte() {
let ciphertext = [];
let expected_plaintext = &[];
let key = [
0x0b, 0xec, 0x2e, 0xf2, 0x46, 0xf0, 0x7e, 0x35, 0x16, 0x54, 0xe0, 0x98, 0x10, 0xb3,
0x18, 0x55, 0x24, 0xa3, 0x9e, 0x0e, 0x40, 0xe7, 0x92, 0xad, 0xb2, 0x8a, 0x48, 0xf4,
0x5c, 0xd0, 0xc0, 0x54,
];
roundtrip::<Aes256>(&key, &ciphertext, expected_plaintext);
}
#[test]
fn crypt_aes_128_5_byte() {
let ciphertext = [0x98, 0xa9, 0x8c, 0x26, 0x0e];
let expected_plaintext = b"asdf\n";
let key = [
0xe0, 0x25, 0x7b, 0x57, 0x97, 0x6a, 0xa4, 0x23, 0xab, 0x94, 0xaa, 0x44, 0xfd, 0x47,
0x4f, 0xa5,
];
roundtrip::<Aes128>(&key, &ciphertext, expected_plaintext);
}
#[test]
fn crypt_aes_192_5_byte() {
let ciphertext = [0x36, 0x55, 0x5c, 0x61, 0x3c];
let expected_plaintext = b"asdf\n";
let key = [
0xe4, 0x4a, 0x88, 0x52, 0x8f, 0xf7, 0x0b, 0x81, 0x7b, 0x75, 0xf1, 0x74, 0x21, 0x37,
0x8c, 0x90, 0xad, 0xbe, 0x4a, 0x65, 0xa8, 0x96, 0x0e, 0xcc,
];
roundtrip::<Aes192>(&key, &ciphertext, expected_plaintext);
}
#[test]
fn crypt_aes_256_5_byte() {
let ciphertext = [0xc2, 0x47, 0xc0, 0xdc, 0x56];
let expected_plaintext = b"asdf\n";
let key = [
0x79, 0x5e, 0x17, 0xf2, 0xc6, 0x3d, 0x28, 0x9b, 0x4b, 0x4b, 0xbb, 0xa9, 0xba, 0xc9,
0xa5, 0xee, 0x3a, 0x4f, 0x0f, 0x4b, 0x29, 0xbd, 0xe9, 0xb8, 0x41, 0x9c, 0x41, 0xa5,
0x15, 0xb2, 0x86, 0xab,
];
roundtrip::<Aes256>(&key, &ciphertext, expected_plaintext);
}
#[test]
fn crypt_aes_128_40_byte() {
let ciphertext = [
0xcf, 0x72, 0x6b, 0xa1, 0xb2, 0x0f, 0xdf, 0xaa, 0x10, 0xad, 0x9c, 0x7f, 0x6d, 0x1c,
0x8d, 0xb5, 0x16, 0x7e, 0xbb, 0x11, 0x69, 0x52, 0x8c, 0x89, 0x80, 0x32, 0xaa, 0x76,
0xa6, 0x18, 0x31, 0x98, 0xee, 0xdd, 0x22, 0x68, 0xb7, 0xe6, 0x77, 0xd2,
];
let expected_plaintext = b"Lorem ipsum dolor sit amet, consectetur\n";
let key = [
0x43, 0x2b, 0x6d, 0xbe, 0x05, 0x76, 0x6c, 0x9e, 0xde, 0xca, 0x3b, 0xf8, 0xaf, 0x5d,
0x81, 0xb6,
];
roundtrip::<Aes128>(&key, &ciphertext, expected_plaintext);
}
#[test]
fn crypt_aes_192_40_byte() {
let ciphertext = [
0xa6, 0xfc, 0x52, 0x79, 0x2c, 0x6c, 0xfe, 0x68, 0xb1, 0xa8, 0xb3, 0x07, 0x52, 0x8b,
0x82, 0xa6, 0x87, 0x9c, 0x72, 0x42, 0x3a, 0xf8, 0xc6, 0xa9, 0xc9, 0xfb, 0x61, 0x19,
0x37, 0xb9, 0x56, 0x62, 0xf4, 0xfc, 0x5e, 0x7a, 0xdd, 0x55, 0x0a, 0x48,
];
let expected_plaintext = b"Lorem ipsum dolor sit amet, consectetur\n";
let key = [
0xac, 0x92, 0x41, 0xba, 0xde, 0xd9, 0x02, 0xfe, 0x40, 0x92, 0x20, 0xf6, 0x56, 0x03,
0xfe, 0xae, 0x1b, 0xba, 0x01, 0x97, 0x97, 0x79, 0xbb, 0xa6,
];
roundtrip::<Aes192>(&key, &ciphertext, expected_plaintext);
}
#[test]
fn crypt_aes_256_40_byte() {
let ciphertext = [
0xa9, 0x99, 0xbd, 0xea, 0x82, 0x9b, 0x8f, 0x2f, 0xb7, 0x52, 0x2f, 0x6b, 0xd8, 0xf6,
0xab, 0x0e, 0x24, 0x51, 0x9e, 0x18, 0x0f, 0xc0, 0x8f, 0x54, 0x15, 0x80, 0xae, 0xbc,
0xa0, 0x5c, 0x8a, 0x11, 0x8d, 0x14, 0x7e, 0xc5, 0xb4, 0xae, 0xd3, 0x37,
];
let expected_plaintext = b"Lorem ipsum dolor sit amet, consectetur\n";
let key = [
0x64, 0x7c, 0x7a, 0xde, 0xf0, 0xf2, 0x61, 0x49, 0x1c, 0xf1, 0xf1, 0xe3, 0x37, 0xfc,
0xe1, 0x4d, 0x4a, 0x77, 0xd4, 0xeb, 0x9e, 0x3d, 0x75, 0xce, 0x9a, 0x3e, 0x10, 0x50,
0xc2, 0x07, 0x36, 0xb6,
];
roundtrip::<Aes256>(&key, &ciphertext, expected_plaintext);
}
#[test]
fn test_aes_ctr_keystream_zeroize_on_drop() {
let key = [0x42u8; 16];
let mut stream = AesCtrZipKeyStream::<Aes128>::new(&key).unwrap();
let mut data = [0u8; 16];
stream.crypt_in_place(&mut data);
assert_ne!(data, [0u8; 16]);
drop(stream);
}
}