use aes::{Aes128, Aes256};
use cipher::KeyIvInit;
use eme2::{Eme2, Error};
type Aes128Eme2 = Eme2<Aes128>;
type Aes256Eme2 = Eme2<Aes256>;
fn test_roundtrip(len: usize) {
let key = [0x42; 64];
let tweak = [0x11; 16];
let mut plaintext = vec![0u8; len];
for (i, val) in plaintext.iter_mut().enumerate() {
*val = (i % 256) as u8;
}
let mut buf = plaintext.clone();
let cipher = Aes256Eme2::new(&key.into(), &tweak.into());
cipher.encrypt(&mut buf).expect("encryption succeeded");
assert_ne!(buf, plaintext);
assert_eq!(buf.len(), plaintext.len());
cipher.decrypt(&mut buf).expect("decryption succeeded");
assert_eq!(buf, plaintext);
}
#[test]
fn test_exact_block() {
test_roundtrip(16);
}
#[test]
fn test_multiple_blocks() {
test_roundtrip(32);
test_roundtrip(48);
test_roundtrip(64);
test_roundtrip(1024);
}
#[test]
fn test_partial_blocks() {
test_roundtrip(17);
test_roundtrip(31);
test_roundtrip(33);
test_roundtrip(127);
test_roundtrip(1025);
}
#[test]
fn test_data_too_short() {
let key = [0x42; 64];
let tweak = [0x11; 16];
let cipher = Aes256Eme2::new(&key.into(), &tweak.into());
let mut buf = vec![0u8; 15];
let err = cipher
.encrypt(&mut buf)
.expect_err("should return error for short data");
assert_eq!(err, Error::DataTooShort);
}
#[test]
fn test_sprp_avalanche_effect() {
let key = [0x42; 64];
let tweak = [0x11; 16];
let cipher = Aes256Eme2::new(&key.into(), &tweak.into());
let plaintext = b"This is a message that spans multiple blocks for SPRP test!!";
let mut buf1 = plaintext.to_vec();
cipher.encrypt(&mut buf1).expect("encryption succeeded");
let mut buf2 = buf1.clone();
buf2[25] ^= 0x01;
cipher.decrypt(&mut buf1).expect("decryption succeeded");
cipher.decrypt(&mut buf2).expect("decryption succeeded");
assert_eq!(&buf1[..], &plaintext[..]);
let diff_count = buf1.iter().zip(buf2.iter()).filter(|(a, b)| a != b).count();
assert!(
diff_count > plaintext.len() / 2,
"SPRP property failed, diff_count: {}",
diff_count
);
}
#[test]
fn test_tweak_separation() {
let key = [0x42; 64];
let tweak1 = [0x11; 16];
let tweak2 = [0x22; 16];
let plaintext = vec![0xAB; 64];
let mut buf1 = plaintext.clone();
let mut buf2 = plaintext.clone();
let cipher1 = Aes256Eme2::new(&key.into(), &tweak1.into());
let cipher2 = Aes256Eme2::new(&key.into(), &tweak2.into());
cipher1.encrypt(&mut buf1).expect("encryption succeeded");
cipher2.encrypt(&mut buf2).expect("encryption succeeded");
assert_ne!(buf1, buf2);
}
#[test]
fn test_aes128_compatibility() {
let key = [0x42; 48];
let tweak = [0x11; 16];
let cipher = Aes128Eme2::new(&key.into(), &tweak.into());
let mut buf = vec![0x00; 32];
cipher.encrypt(&mut buf).expect("encryption succeeded");
assert_ne!(buf, vec![0x00; 32]);
cipher.decrypt(&mut buf).expect("decryption succeeded");
assert_eq!(buf, vec![0x00; 32]);
}