//! AEZ *\[sic!\]* v5 encryption implemented in Rust. //! //! # ☣️ Cryptographic hazmat ☣️ //! //! This crate is not battle tested, nor is it audited. Its usage for critical systems is strongly //! discouraged. It mainly exists as a learning exercise. //! //! # AEZ encryption //! //! [AEZ](https://www.cs.ucdavis.edu/~rogaway/aez/index.html) is an authenticated encryption //! scheme. It works in two steps: //! //! * First, a known authentication block (a fixed number of zeroes) is appended to the message. //! * Second, the message is enciphered with an arbitrary-length blockcipher. //! //! The blockcipher is tweaked with the key, the nonce and additional data. //! //! The [paper](https://www.cs.ucdavis.edu/~rogaway/aez/aez.pdf) explains the security concepts of //! AEZ in more detail. //! //! # AEZ encryption (for laypeople) //! //! The security property of encryption schemes says that an adversary without key must not learn //! the content of a message, but the adversary might still be able to modify the message. For //! example, in AES-CTR, flipping a bit in the ciphertext means that the same bit will be flipped //! in the plaintext once the message is decrypted. //! //! Authenticated encryption solves this problem by including a mechanism to detect changes. This //! can be done for example by including a MAC, or using a mode like GCM (Galois counter mode). In //! many cases, not only the integrity of the ciphertext can be verified, but additional data can //! be provided during encryption and decryption which will also be included in the integrity //! check. This results in an *authenticated encryption with associated data* scheme, AEAD for //! short. //! //! AEZ employs a nifty technique in order to realize an AEAD scheme: The core of AEZ is an //! enciphering scheme, which in addition to "hiding" its input is also very "unpredictable", //! similar to a hash function. That means that if a ciphertext is changed slightly (by flipping a //! bit), the resulting plaintext will be unpredictably and completely different. //! //! With this property, authenticated encryption can be realized implicitly: The message is padded //! with a known string before enciphering it. If, after deciphering, this known string is not //! present, the message has been tampered with. Since the enciphering scheme is parametrized by //! the key, a nonce and arbitrary additional data, we can verify the integrity of associated data //! as well. //! //! # Other implementations //! //! As this library is a learning exercise, if you want to use AEZ in practice, it is suggested to //! use the [`aez`](https://crates.io/crates/aez) crate which provides bindings to the C reference //! implementation of AEZ. //! //! `zears` differs from `aez` in that ... //! //! * it works on platforms without hardware AES support, using the "soft" backend of //! [`aes`](https://crates.io/crates/aes). //! * it does not inherit the limitations of the reference implementation in regards to nonce //! length, authentication tag length, or the maximum of one associated data item. //! //! `zears` is tested with test vectors generated from the reference implementation using [Nick //! Mathewson's tool](https://github.com/nmathewson/aez_test_vectors). //! //! # Example usage //! //! The core of this crate is the [Aez] struct, which provides the high-level API. There is usually //! not a lot more that you need: //! //! ``` //! # use zears::*; //! let aez = Aez::new(b"my secret key!"); //! let cipher = aez.encrypt(b"nonce", &[b"associated data"], 16, b"message"); //! let plaintext = aez.decrypt(b"nonce", &[b"associated data"], 16, &cipher); //! assert_eq!(plaintext.unwrap(), b"message"); //! //! // Flipping a bit leads to decryption failure //! let mut cipher = aez.encrypt(b"nonce", &[], 16, b"message"); //! cipher[0] ^= 0x02; //! let plaintext = aez.decrypt(b"nonce", &[], 16, &cipher); //! assert!(plaintext.is_none()); //! //! // Similarly, modifying the associated data leads to failure //! let cipher = aez.encrypt(b"nonce", &[b"foo"], 16, b"message"); //! let plaintext = aez.decrypt(b"nonce", &[b"bar"], 16, &cipher); //! assert!(plaintext.is_none()); //! ``` use std::iter; use constant_time_eq::constant_time_eq; mod block; #[cfg(test)] mod testvectors; use block::Block; type Key = [u8; 48]; type Tweak<'a> = &'a [&'a [u8]]; /// AEZ encryption scheme. pub struct Aez { key: Key, } impl Aez { /// Create a new AEZ instance. /// /// The key is expanded using Blake2b, according to the AEZ specification. /// /// If you provide a key of the correct length (48 bytes), no expansion is done and the key is /// taken as-is. pub fn new(key: &[u8]) -> Self { Aez { key: extract(key) } } /// Encrypt the given data. /// /// Parameters: /// /// * `nonce` -- the nonce to use. Each nonce should only be used once, as re-using the nonce /// (without chaning the key) will lead to the same ciphertext being produced, potentially /// making it re-identifiable. /// * `associated_data` -- additional data to be included in the integrity check. Note that /// this data will *not* be contained in the ciphertext, but it must be provided on /// decryption. /// * `tau` -- number of *bytes* (not bits) to use for integrity checking. A value of `tau = /// 16` gives 128 bits of security. Passing a value of 0 is valid and leads to no integrity /// checking. /// * `data` -- actual data to encrypt. Can be empty, in which case the returned ciphertext /// provides a "hash" that verifies the integrity of the associated data will be /// /// Returns the ciphertext, which will be of length `data.len() + tau`. pub fn encrypt( &self, nonce: &[u8], associated_data: &[&[u8]], tau: u32, data: &[u8], ) -> Vec { encrypt(&self.key, nonce, associated_data, tau, data) } /// Decrypts the given ciphertext. /// /// Parameters: /// /// * `nonce`, `associated_data` and `tau` are as for [`Aez::encrypt`]. /// * `data` -- the ciphertext to decrypt. /// /// Returns the decrypted content. If the authentication check fails, returns `None` instead. /// The returned vector has length `data.len() - tau`. pub fn decrypt( &self, nonce: &[u8], associated_data: &[&[u8]], tau: u32, data: &[u8], ) -> Option> { decrypt(&self.key, nonce, associated_data, tau, data) } } fn aesenc(mut block: Block, key: &Block) -> block::Block { aes::hazmat::cipher_round((&mut block.0).into(), &key.0.into()); block } fn aes4(keys: &[&Block; 5], block: &Block) -> Block { aesenc( aesenc(aesenc(aesenc(*block ^ *keys[0], keys[1]), keys[2]), keys[3]), keys[4], ) } fn aes10(keys: &[&Block; 11], block: &Block) -> Block { aesenc( aesenc( aesenc( aesenc( aesenc( aesenc( aesenc( aesenc( aesenc(aesenc(*block ^ *keys[0], keys[1]), keys[2]), keys[3], ), keys[4], ), keys[5], ), keys[6], ), keys[7], ), keys[8], ), keys[9], ), keys[10], ) } fn extract(key: &[u8]) -> [u8; 48] { if key.len() == 48 { key.try_into().unwrap() } else { use blake2::Digest; type Blake2b384 = blake2::Blake2b; let mut hasher = Blake2b384::new(); hasher.update(key); hasher.finalize().into() } } fn encrypt(key: &Key, nonce: &[u8], ad: &[&[u8]], tau: u32, message: &[u8]) -> Vec { let auth_message = message .iter() .copied() .chain(iter::repeat_n(0, tau as usize)) .collect::>(); // We treat tau as bytes, but according to the spec, tau is actually in bits. let tau_block = Block::from_int(tau * 8); let mut tweaks = vec![&tau_block.0, nonce]; tweaks.extend(ad); if message.is_empty() { aez_prf(key, &tweaks, tau) } else { encipher(key, &tweaks, &auth_message) } } fn decrypt(key: &Key, nonce: &[u8], ad: &[&[u8]], tau: u32, ciphertext: &[u8]) -> Option> { if ciphertext.len() < tau as usize { return None; } let tau_block = Block::from_int(tau * 8); let mut tweaks = vec![&tau_block.0, nonce]; tweaks.extend(ad); if ciphertext.len() == tau as usize { if constant_time_eq(&ciphertext, &aez_prf(key, &tweaks, tau)) { return Some(Vec::new()); } else { return None; } } let x = decipher(key, &tweaks, ciphertext); let (m, auth) = x.split_at(ciphertext.len() - tau as usize); assert!(auth.len() == tau as usize); if constant_time_eq(&auth, &vec![0; tau as usize]) { Some(Vec::from(m)) } else { None } } fn encipher(key: &Key, tweaks: Tweak, message: &[u8]) -> Vec { if message.len() < 256 / 8 { encipher_aez_tiny(key, tweaks, message) } else { encipher_aez_core(key, tweaks, message) } } fn encipher_aez_tiny(key: &Key, tweaks: Tweak, message: &[u8]) -> Vec { let mu = message.len() * 8; assert!(mu < 256); let n = mu / 2; let delta = aez_hash(key, tweaks); let round_count = match mu { 8 => 24u32, 16 => 16, _ if mu < 128 => 10, _ => 8, }; let (mut left, mut right); // We might end up having to split at a nibble, so manually adjust for that if n % 8 == 0 { left = Block::from_slice(&message[..n / 8]); right = Block::from_slice(&message[n / 8..]); } else { assert!(n % 8 == 4); left = Block::from_slice(&message[..n / 8 + 1]).clip(n); right = Block::from_slice(&message[n / 8..]) << 4; }; let i = if mu >= 128 { 6 } else { 7 }; for j in 0..round_count { let right_ = (left ^ e(0, i, key, delta ^ right.pad(n) ^ Block::from_int(j))).clip(n); (left, right) = (right, right_); } let mut ciphertext = Vec::new(); if n % 8 == 0 { ciphertext.extend_from_slice(&right.0[..n / 8]); ciphertext.extend_from_slice(&left.0[..n / 8]); } else { ciphertext.extend_from_slice(&right.0[..n / 8 + 1]); for byte in &left.0[..n / 8 + 1] { *ciphertext.last_mut().unwrap() |= byte >> 4; ciphertext.push((byte & 0x0f) << 4); } ciphertext.pop(); } if mu < 128 { let mut c = Block::from_slice(&ciphertext); c = c ^ (e(0, 3, key, delta ^ (c | Block::ONE)) & Block::ONE); ciphertext = Vec::from(&c.0[..mu / 8]); } assert!(ciphertext.len() == message.len()); ciphertext } fn encipher_aez_core(key: &Key, tweaks: Tweak, message: &[u8]) -> Vec { assert!(message.len() >= 32); let delta = aez_hash(key, tweaks); let (block_pairs, m_u, m_v, m_x, m_y, d) = split_blocks(message); let len_v = d.saturating_sub(128); let mut ws = Vec::new(); let mut xs = Vec::new(); for (i, (mi, mi_)) in block_pairs.iter().enumerate() { let i = (i + 1) as i32; let w = *mi ^ e(1, i, key, *mi_); let x = *mi_ ^ e(0, 0, key, w); ws.push(w); xs.push(x); } let mut x = Block::NULL; for xi in &xs { x = x ^ *xi; } match d { 0 => (), _ if d <= 127 => { x = x ^ e(0, 4, key, m_u.pad(d.into())); } _ => { x = x ^ e(0, 4, key, m_u); x = x ^ e(0, 5, key, m_v.pad(len_v.into())); } } let s_x = m_x ^ delta ^ x ^ e(0, 1, key, m_y); let s_y = m_y ^ e(-1, 1, key, s_x); let s = s_x ^ s_y; let mut cipher_pairs = Vec::new(); let mut y = Block::NULL; for (i, (wi, xi)) in ws.iter().zip(xs.iter()).enumerate() { let i = (i + 1) as i32; let s_ = e(2, i, key, s); let yi = *wi ^ s_; let zi = *xi ^ s_; let ci_ = yi ^ e(0, 0, key, zi); let ci = zi ^ e(1, i, key, ci_); cipher_pairs.push((ci, ci_)); y = y ^ yi; } let mut c_u = Block::default(); let mut c_v = Block::default(); match d { 0 => (), _ if d <= 127 => { c_u = (m_u ^ e(-1, 4, key, s)).clip(d.into()); y = y ^ e(0, 4, key, c_u.pad(d.into())); } _ => { c_u = m_u ^ e(-1, 4, key, s); c_v = (m_v ^ e(-1, 5, key, s)).clip(len_v.into()); y = y ^ e(0, 4, key, c_u); y = y ^ e(0, 5, key, c_v.pad(len_v.into())); } } let c_y = s_x ^ e(-1, 2, key, s_y); let c_x = s_y ^ delta ^ y ^ e(0, 2, key, c_y); let mut ciphertext = Vec::new(); for (ci, ci_) in cipher_pairs { ciphertext.extend_from_slice(&ci.0); ciphertext.extend_from_slice(&ci_.0); } ciphertext.extend_from_slice(&c_u.0[..128.min(d) as usize / 8]); ciphertext.extend_from_slice(&c_v.0[..len_v as usize / 8]); ciphertext.extend_from_slice(&c_x.0); ciphertext.extend_from_slice(&c_y.0); assert!(ciphertext.len() == message.len()); ciphertext } fn decipher(key: &Key, tweaks: Tweak, message: &[u8]) -> Vec { if message.len() < 256 / 8 { decipher_aez_tiny(key, tweaks, message) } else { decipher_aez_core(key, tweaks, message) } } fn decipher_aez_tiny(key: &Key, tweaks: Tweak, message: &[u8]) -> Vec { let mu = message.len() * 8; assert!(mu < 256); let n = mu / 2; let delta = aez_hash(key, tweaks); let round_count = match mu { 8 => 24u32, 16 => 16, _ if mu < 128 => 10, _ => 8, }; let mut message = Vec::from(message); if mu < 128 { let mut c = Block::from_slice(&message); c = c ^ (e(0, 3, key, delta ^ (c | Block::ONE)) & Block::ONE); message.clear(); message.extend(&c.0[..mu / 8]); } let (mut left, mut right); // We might end up having to split at a nibble, so manually adjust for that if n % 8 == 0 { left = Block::from_slice(&message[..n / 8]); right = Block::from_slice(&message[n / 8..]); } else { left = Block::from_slice(&message[..n / 8 + 1]).clip(n); right = Block::from_slice(&message[n / 8..]) << 4; }; let i = if mu >= 128 { 6 } else { 7 }; for j in (0..round_count).rev() { let right_ = (left ^ e(0, i, key, delta ^ right.pad(n) ^ Block::from_int(j))).clip(n); (left, right) = (right, right_); } let mut ciphertext = Vec::new(); if n % 8 == 0 { ciphertext.extend_from_slice(&right.0[..n / 8]); ciphertext.extend_from_slice(&left.0[..n / 8]); } else { ciphertext.extend_from_slice(&right.0[..n / 8 + 1]); for byte in &left.0[..n / 8 + 1] { *ciphertext.last_mut().unwrap() |= byte >> 4; ciphertext.push((byte & 0x0f) << 4); } ciphertext.pop(); } assert!(ciphertext.len() == message.len()); ciphertext } fn decipher_aez_core(key: &Key, tweaks: Tweak, cipher: &[u8]) -> Vec { assert!(cipher.len() >= 32); let delta = aez_hash(key, tweaks); let (block_pairs, c_u, c_v, c_x, c_y, d) = split_blocks(cipher); let len_v = d.saturating_sub(128); let mut ws = Vec::new(); let mut ys = Vec::new(); for (i, (ci, ci_)) in block_pairs.iter().enumerate() { let i = (i + 1) as i32; let w = *ci ^ e(1, i, key, *ci_); let y = *ci_ ^ e(0, 0, key, w); ws.push(w); ys.push(y); } let mut y = Block::NULL; for yi in &ys { y = y ^ *yi; } match d { 0 => (), _ if d <= 127 => { y = y ^ e(0, 4, key, c_u.pad(d.into())); } _ => { y = y ^ e(0, 4, key, c_u); y = y ^ e(0, 5, key, c_v.pad(len_v.into())); } } let s_x = c_x ^ delta ^ y ^ e(0, 2, key, c_y); let s_y = c_y ^ e(-1, 2, key, s_x); let s = s_x ^ s_y; let mut plain_pairs = Vec::new(); let mut x = Block::NULL; for (i, (wi, yi)) in ws.iter().zip(ys.iter()).enumerate() { let i = (i + 1) as i32; let s_ = e(2, i, key, s); let xi = *wi ^ s_; let zi = *yi ^ s_; let mi_ = xi ^ e(0, 0, key, zi); let mi = zi ^ e(1, i, key, mi_); plain_pairs.push((mi, mi_)); x = x ^ xi; } let mut m_u = Block::default(); let mut m_v = Block::default(); match d { 0 => (), _ if d <= 127 => { m_u = (c_u ^ e(-1, 4, key, s)).clip(d.into()); x = x ^ e(0, 4, key, m_u.pad(d.into())); } _ => { m_u = c_u ^ e(-1, 4, key, s); m_v = (c_v ^ e(-1, 5, key, s)).clip(len_v.into()); x = x ^ e(0, 4, key, m_u); x = x ^ e(0, 5, key, m_v.pad(len_v.into())); } } let m_y = s_x ^ e(-1, 1, key, s_y); let m_x = s_y ^ delta ^ x ^ e(0, 1, key, m_y); let mut message = Vec::new(); for (mi, mi_) in plain_pairs { message.extend_from_slice(&mi.0); message.extend_from_slice(&mi_.0); } message.extend_from_slice(&m_u.0[..128.min(d) as usize / 8]); message.extend_from_slice(&m_v.0[..len_v as usize / 8]); message.extend_from_slice(&m_x.0); message.extend_from_slice(&m_y.0); message } fn split_blocks(mut message: &[u8]) -> (Vec<(Block, Block)>, Block, Block, Block, Block, u8) { let num_blocks = (message.len() - 16 - 16) / 32; let mut blocks = Vec::new(); for _ in 0..num_blocks { let a = Block::from_slice(&message[..16]); let b = Block::from_slice(&message[16..32]); blocks.push((a, b)); message = &message[32..]; } let m_uv = &message[..message.len() - 32]; let d = m_uv.len() * 8; assert!(d < 256); message = &message[m_uv.len()..]; assert!(message.len() == 32); let m_u; let m_v; if d <= 127 { m_u = Block::from_slice(m_uv); m_v = Block::default(); } else { m_u = Block::from_slice(&m_uv[..16]); m_v = Block::from_slice(&m_uv[16..]); } let m_x = Block::from_slice(&message[..16]); let m_y = Block::from_slice(&message[16..]); (blocks, m_u, m_v, m_x, m_y, d as u8) } fn pad_to_blocks(value: &[u8]) -> Vec { let mut blocks = Vec::new(); for chunk in value.chunks(16) { if chunk.len() == 16 { blocks.push(Block::from_slice(chunk)); } else { blocks.push(Block::from_slice(chunk).pad(chunk.len() * 8)); } } blocks } fn aez_hash(key: &Key, tweaks: Tweak) -> Block { let mut hash = Block::NULL; for (i, tweak) in tweaks.iter().enumerate() { // Adjust for zero-based vs one-based indexing let j = i + 2 + 1; // This is somewhat implicit in the AEZ spec, but basically for an empty string we still // set l = 1 and then xor E_K^{j, 0}(10*). We could modify the last if branch to cover this // as well, but then we need to fiddle with getting an empty chunk from an empty iterator. if tweak.is_empty() { hash = hash ^ e(j.try_into().unwrap(), 0, key, Block::ONE); } else if tweak.len() % 16 == 0 { for (l, chunk) in tweak.chunks(16).enumerate() { hash = hash ^ e( j.try_into().unwrap(), (l + 1).try_into().unwrap(), key, Block::from_slice(chunk), ); } } else { let blocks = pad_to_blocks(tweak); for (l, chunk) in blocks.iter().enumerate() { hash = hash ^ e( j.try_into().unwrap(), if l == blocks.len() - 1 { 0 } else { (l + 1).try_into().unwrap() }, key, *chunk, ); } } } hash } fn aez_prf(key: &Key, tweaks: Tweak, tau: u32) -> Vec { let mut result = Vec::new(); let mut index = 0u128; let delta = aez_hash(key, tweaks); while result.len() < tau as usize { let block = e(-1, 3, key, delta ^ Block::from_int(index)); result.extend_from_slice(&block.0[..16.min(tau as usize - result.len())]); index += 1; } result } fn e(j: i32, i: i32, key: &Key, block: Block) -> Block { let (key_i, key_j, key_l) = split_key(key); if j == -1 { let k = [ &Block::NULL, &key_i, &key_j, &key_l, &key_i, &key_j, &key_l, &key_i, &key_j, &key_l, &key_i, ]; let delta = key_l * i.try_into().expect("i was negative"); aes10(&k, &(block ^ delta)) } else { let k = [&Block::NULL, &key_j, &key_i, &key_l, &Block::NULL]; let exponent = if i % 8 == 0 { i / 8 } else { i / 8 + 1 }; let j: u32 = j.try_into().expect("j was negative"); let i: u32 = i.try_into().expect("i was negative"); let delta = (key_j * j) ^ (key_i * (1 << exponent)) ^ (key_l * (i % 8)); aes4(&k, &(block ^ delta)) } } fn split_key(key: &Key) -> (Block, Block, Block) { ( Block::from_slice(&key[..16]), Block::from_slice(&key[16..32]), Block::from_slice(&key[32..]), ) } #[cfg(test)] mod test { use super::*; #[test] fn test_extract() { for (a, b) in testvectors::EXTRACT_VECTORS { let a = hex::decode(a).unwrap(); let b = hex::decode(b).unwrap(); assert_eq!(extract(&a), b.as_slice()); } } #[test] fn test_e() { for (k, j, i, a, b) in testvectors::E_VECTORS { let name = format!("e({j}, {i}, {k}, {a})"); let k = hex::decode(k).unwrap(); let k = k.as_slice().try_into().unwrap(); let a = hex::decode(a).unwrap(); let a = Block::from_slice(&a); let b = hex::decode(b).unwrap(); assert_eq!(&e(*j, *i, k, a).0, b.as_slice(), "{name}"); } } #[test] fn test_aez_hash() { for (k, tau, tw, v) in testvectors::HASH_VECTORS { let name = format!("aez_hash({k}, {tau}, {tw:?})"); let k = hex::decode(k).unwrap(); let k = k.as_slice().try_into().unwrap(); let v = hex::decode(v).unwrap(); let mut tweaks = vec![Vec::from(Block::from_int(*tau).0)]; for t in *tw { tweaks.push(hex::decode(t).unwrap()); } let tweaks = tweaks.iter().map(Vec::as_slice).collect::>(); assert_eq!(&aez_hash(&k, &tweaks).0, v.as_slice(), "{name}"); } } #[test] fn test_encrypt() { let mut failed = 0; let mut succ = 0; for (k, n, ads, tau, m, c) in testvectors::ENCRYPT_VECTORS { let name = format!("encrypt({k}, {n}, {ads:?}, {tau}, {m})"); let k = hex::decode(k).unwrap(); let k = k.as_slice().try_into().unwrap(); let n = hex::decode(n).unwrap(); let mut ad = Vec::new(); for i in *ads { ad.push(hex::decode(i).unwrap()); } let ad = ad.iter().map(Vec::as_slice).collect::>(); let m = hex::decode(m).unwrap(); let c = hex::decode(c).unwrap(); if &encrypt(&k, &n, &ad, *tau, &m) == &c { println!("+ {name}"); succ += 1; } else { println!("- {name}"); failed += 1; } } println!("{succ} succeeded, {failed} failed"); assert_eq!(failed, 0); } #[test] fn test_decrypt() { let mut failed = 0; let mut succ = 0; for (k, n, ads, tau, m, c) in testvectors::ENCRYPT_VECTORS { let name = format!("decrypt({k}, {n}, {ads:?}, {tau}, {c})"); let k = hex::decode(k).unwrap(); let k = k.as_slice().try_into().unwrap(); let n = hex::decode(n).unwrap(); let mut ad = Vec::new(); for i in *ads { ad.push(hex::decode(i).unwrap()); } let ad = ad.iter().map(Vec::as_slice).collect::>(); let m = hex::decode(m).unwrap(); let c = hex::decode(c).unwrap(); if decrypt(&k, &n, &ad, *tau, &c) == Some(m) { println!("+ {name}"); succ += 1; } else { println!("- {name}"); failed += 1; } } println!("{succ} succeeded, {failed} failed"); assert_eq!(failed, 0); } #[test] fn test_encrypt_decrypt() { let aez = Aez::new(b"foobar"); let cipher = aez.encrypt(&[0], &[b"foobar"], 16, b"hi"); let plain = aez.decrypt(&[0], &[b"foobar"], 16, &cipher).unwrap(); assert_eq!(plain, b"hi"); } #[test] fn test_encrypt_decrypt_long() { let message = b"ene mene miste es rappelt in der kiste ene mene meck und du bist weg"; let aez = Aez::new(b"foobar"); let cipher = aez.encrypt(&[0], &[b"foobar"], 16, message); let plain = aez.decrypt(&[0], &[b"foobar"], 16, &cipher).unwrap(); assert_eq!(plain, message); } }