AEAD fix ciphertext-extension forgery with padding

This commit is contained in:
sam.hadow committed 2026-10-18 17:56:14 +02:00
1 parent b7647c4794
commit 20e7fe5814
2 files changed
+118 -50

No files matched your search

+108 -50
View File
@@ -1,11 +1,16 @@
use crate::keccak::shake256; use crate::keccak::shake256;
/// Rate (bytes absorbed/emitted per step).
const RATE_SIZE: usize = 16; const RATE_SIZE: usize = 16;
/// Capacity (bytes never directly exposed or influenced by input).
const CAPACITY_SIZE: usize = 64; const CAPACITY_SIZE: usize = 64;
/// Full AEAD state: rate || capacity = 80 bytes.
const STATE_SIZE: usize = RATE_SIZE + CAPACITY_SIZE; const STATE_SIZE: usize = RATE_SIZE + CAPACITY_SIZE;
const CHUNK_SIZE: usize = 16; const CHUNK_SIZE: usize = RATE_SIZE;
const MIN_KEY_SIZE: usize = 16; const MIN_KEY_SIZE: usize = 16;
const MAX_KEY_SIZE: usize = 64; const MAX_KEY_SIZE: usize = 64;
/// First padding byte (`10*` padding, applied to the final chunk of both the associated data and the message, even when that chunk is empty).
const PAD_BYTE: u8 = 0x80;
#[derive(Debug, Clone, PartialEq, Eq)] #[derive(Debug, Clone, PartialEq, Eq)]
pub struct EncryptionResult { pub struct EncryptionResult {
@@ -22,6 +27,10 @@ pub struct DecryptionResult {
#[derive(Debug, Clone)] #[derive(Debug, Clone)]
pub struct KeccakAead { pub struct KeccakAead {
state: [u8; STATE_SIZE], state: [u8; STATE_SIZE],
/// Ciphertext bytes of the message chunk currently being filled (`pending[..pos]`). They become the rate of the next SHAKE256 input.
pending: [u8; CHUNK_SIZE],
/// Number of bytes of the current message chunk already processed.
pos: usize,
} }
impl KeccakAead { impl KeccakAead {
@@ -36,6 +45,11 @@ impl KeccakAead {
} }
/// Initialize the AEAD state. /// Initialize the AEAD state.
///
/// ```text
/// state = SHAKE256(iv || key || nonce, 80)
/// state[16 .. 16 + key.len()] ^= key
/// ```
pub fn new(iv: &[u8], key: &[u8], nonce: &[u8]) -> Self { pub fn new(iv: &[u8], key: &[u8], nonce: &[u8]) -> Self {
Self::assert_valid_key_size(key); Self::assert_valid_key_size(key);
@@ -54,75 +68,104 @@ impl KeccakAead {
state[RATE_SIZE + i] ^= byte; state[RATE_SIZE + i] ^= byte;
} }
Self { state } Self {
state,
pending: [0u8; CHUNK_SIZE],
pos: 0,
}
} }
/// Process associated data. /// Process associated data.
/// Data is processed in 16-byte chunks. ///
/// Must be called exactly once, with the complete associated data, before any message processing.
///
/// Data is absorbed in 16-byte chunks: each chunk is XORed into the rate (`state[0..16]`), the capacity (`state[16..80]`) is carried over, and the whole 80-byte block is passed through SHAKE256.
///
/// The final chunk is always padded with `10*` (0x80 XORed in right after the last data byte, remaining rate bytes left as the current state). If the length is a multiple of 16, or the data is empty, this results in one extra block that carries only the padding. This makes the encoding of the associated data injective with respect to its length.
///
/// Finally, a domain-separation bit is XORed into the last capacity byte.
pub fn associated_data_processing(&mut self, associated_data: &[u8]) { pub fn associated_data_processing(&mut self, associated_data: &[u8]) {
for chunk in associated_data.chunks(CHUNK_SIZE) { let mut chunks = associated_data.chunks_exact(CHUNK_SIZE);
let mut input = [0u8; STATE_SIZE];
// r = chunk XOR state[0..16] for chunk in &mut chunks {
let mut input = self.state;
// rate = chunk XOR state[0..16], capacity = state[16..80]
for (i, &byte) in chunk.iter().enumerate() { for (i, &byte) in chunk.iter().enumerate() {
input[i] = byte ^ self.state[i]; input[i] ^= byte;
} }
// c = state[16..48]
input[RATE_SIZE..STATE_SIZE].copy_from_slice(&self.state[RATE_SIZE..STATE_SIZE]);
self.state = shake256_state(&input); self.state = shake256_state(&input);
} }
// Final (possibly empty) chunk, always padded.
let remainder = chunks.remainder();
let mut input = self.state;
for (i, &byte) in remainder.iter().enumerate() {
input[i] ^= byte;
}
// remainder.len() < CHUNK_SIZE, so this index is always in the rate.
input[remainder.len()] ^= PAD_BYTE;
self.state = shake256_state(&input);
// Domain separation between associated data and message.
self.state[STATE_SIZE - 1] ^= 1; self.state[STATE_SIZE - 1] ^= 1;
} }
/// Encrypt plaintext. /// Absorb the completed message chunk (`pending`) into the state.
/// Returns the ciphertext split logically into 16-byte chunks, then concatenated. ///
/// The rate of the SHAKE256 input is the ciphertext chunk, the capacity is carried over.
#[inline]
fn absorb_pending_chunk(&mut self) {
let mut input = self.state;
input[..CHUNK_SIZE].copy_from_slice(&self.pending);
self.state = shake256_state(&input);
self.pos = 0;
}
/// Encrypt plaintext (streaming).
///
/// May be called repeatedly with pieces of any size; the result is the same as a single call with the concatenated plaintext. Each ciphertext byte is `plaintext XOR state[pos]`, and the ciphertext chunk becomes the rate of the next SHAKE256 input once 16 bytes have been processed. Ciphertext length always equals plaintext length.
///
/// The final (possibly empty) chunk is padded with `10*` by `finalize`, so a message that is a multiple of 16 bytes (or empty) triggers one extra padding-only block there.
pub fn plaintext_processing(&mut self, plaintext: &[u8]) -> Vec<u8> { pub fn plaintext_processing(&mut self, plaintext: &[u8]) -> Vec<u8> {
let mut ciphertext = Vec::with_capacity(plaintext.len()); let mut ciphertext = Vec::with_capacity(plaintext.len());
for chunk in plaintext.chunks(CHUNK_SIZE) { for &byte in plaintext {
let mut input = [0u8; STATE_SIZE]; let c = byte ^ self.state[self.pos];
// r = chunk XOR state[0..16] ciphertext.push(c);
for (i, &byte) in chunk.iter().enumerate() { self.pending[self.pos] = c;
ciphertext.push(byte ^ self.state[i]); self.pos += 1;
if self.pos == CHUNK_SIZE {
self.absorb_pending_chunk();
} }
// input = r || c
//
// The rate portion must be the generated ciphertext.
let start = ciphertext.len() - chunk.len();
input[..chunk.len()].copy_from_slice(&ciphertext[start..]);
input[RATE_SIZE..STATE_SIZE].copy_from_slice(&self.state[RATE_SIZE..STATE_SIZE]);
self.state = shake256_state(&input);
} }
ciphertext ciphertext
} }
/// Decrypt ciphertext. /// Decrypt ciphertext (streaming).
///
/// Mirrors `plaintext_processing`: may be called repeatedly with pieces of any size. The received ciphertext becomes the rate of each SHAKE256 input, and the final chunk is padded in `finalize` exactly as during encryption.
pub fn ciphertext_processing(&mut self, ciphertext: &[u8]) -> Vec<u8> { pub fn ciphertext_processing(&mut self, ciphertext: &[u8]) -> Vec<u8> {
let mut plaintext = Vec::with_capacity(ciphertext.len()); let mut plaintext = Vec::with_capacity(ciphertext.len());
for chunk in ciphertext.chunks(CHUNK_SIZE) { for &c in ciphertext {
let mut input = [0u8; STATE_SIZE]; plaintext.push(c ^ self.state[self.pos]);
// plaintext = ciphertext XOR state[0..16] self.pending[self.pos] = c;
for (i, &byte) in chunk.iter().enumerate() { self.pos += 1;
plaintext.push(byte ^ self.state[i]);
if self.pos == CHUNK_SIZE {
self.absorb_pending_chunk();
} }
// input = ciphertext || c
input[..chunk.len()].copy_from_slice(chunk);
input[RATE_SIZE..STATE_SIZE].copy_from_slice(&self.state[RATE_SIZE..STATE_SIZE]);
self.state = shake256_state(&input);
} }
plaintext plaintext
@@ -130,17 +173,30 @@ impl KeccakAead {
/// Finalize and generate the authentication tag. /// Finalize and generate the authentication tag.
/// The tag has the same length as the key. /// The tag has the same length as the key.
///
/// First pads the final (possibly empty) message chunk with `10*`, then mixes in the key and squeezes the tag. Must be called exactly once, after all message data has been processed.
pub fn finalize(&mut self, key: &[u8]) -> Vec<u8> { pub fn finalize(&mut self, key: &[u8]) -> Vec<u8> {
Self::assert_valid_key_size(key); Self::assert_valid_key_size(key);
// Construct padded key: // Pad the final message chunk: rate = ciphertext[..pos] || state[pos..16]
// with 0x80 XORed in at `pos` (pos < CHUNK_SIZE always holds here).
let mut input = self.state;
input[..self.pos].copy_from_slice(&self.pending[..self.pos]);
input[self.pos] ^= PAD_BYTE;
self.state = shake256_state(&input);
self.pos = 0;
// Construct the padded key (right-aligned in the 64-byte capacity):
// padded_key = 0^(64 - key.len()) || key
let mut padded_key = [0u8; CAPACITY_SIZE]; let mut padded_key = [0u8; CAPACITY_SIZE];
let padding_len = CAPACITY_SIZE - key.len(); let padding_len = CAPACITY_SIZE - key.len();
padded_key[padding_len..].copy_from_slice(key); padded_key[padding_len..].copy_from_slice(key);
// XOR padded key into c. // XOR padded key into the capacity, c = state[16..80].
for (state_byte, &key_byte) in self.state[RATE_SIZE..STATE_SIZE] for (state_byte, &key_byte) in self.state[RATE_SIZE..STATE_SIZE]
.iter_mut() .iter_mut()
.zip(padded_key.iter()) .zip(padded_key.iter())
@@ -148,10 +204,10 @@ impl KeccakAead {
*state_byte ^= key_byte; *state_byte ^= key_byte;
} }
// SHAKE256(state, 48) // SHAKE256(state, 80)
let output = shake256(&self.state, STATE_SIZE); let output = shake256(&self.state, STATE_SIZE);
// Take the last `key.len()` bytes from the output. // Take the last `key.len()` bytes from the output and XOR with the key.
let tag_start = STATE_SIZE - key.len(); let tag_start = STATE_SIZE - key.len();
key.iter() key.iter()
@@ -162,10 +218,12 @@ impl KeccakAead {
/// Encrypt: /// Encrypt:
/// ///
/// sponge = KeccakAead(iv, key, nonce) /// ```text
/// sponge.associated_data_processing(ad) /// sponge = KeccakAead(iv, key, nonce)
/// ciphertext = sponge.plaintext_processing(plaintext) /// sponge.associated_data_processing(ad)
/// tag = sponge.finalize(key) /// ciphertext = sponge.plaintext_processing(plaintext)
/// tag = sponge.finalize(key)
/// ```
pub fn encrypt( pub fn encrypt(
key: &[u8], key: &[u8],
plaintext: &[u8], plaintext: &[u8],
@@ -204,7 +262,7 @@ impl KeccakAead {
} }
} }
/// SHAKE256 wrapper returning exactly a 48-byte AEAD state. /// SHAKE256 wrapper returning exactly an 80-byte AEAD state.
#[inline] #[inline]
fn shake256_state(state: &[u8; STATE_SIZE]) -> [u8; STATE_SIZE] { fn shake256_state(state: &[u8; STATE_SIZE]) -> [u8; STATE_SIZE] {
let output = shake256(state, STATE_SIZE); let output = shake256(state, STATE_SIZE);
+10
View File
@@ -92,6 +92,16 @@ fn tag_changes_when_ciphertext_changes() {
assert_ne!(decrypted.tag, encrypted.tag); assert_ne!(decrypted.tag, encrypted.tag);
} }
#[test]
fn rejects_zero_extended_ciphertext() {
let (key, iv, nonce) = ([0x42u8; 32], [0x11u8; 16], [0x22u8; 16]);
let enc = KeccakAead::encrypt(&key, b"hello", &iv, b"ad", &nonce);
let mut forged = enc.cipher.clone();
forged.push(0x00);
let dec = KeccakAead::decrypt(&key, &forged, &iv, b"ad", &nonce);
assert_ne!(dec.tag, enc.tag);
}
#[test] #[test]
#[should_panic(expected = "key must be between 16 and 64 bytes")] #[should_panic(expected = "key must be between 16 and 64 bytes")]
fn rejects_short_key() { fn rejects_short_key() {