276 lines
9.0 KiB
Rust
276 lines
9.0 KiB
Rust
use crate::keccak::shake256;
|
|
|
|
/// Rate (bytes absorbed/emitted per step).
|
|
const RATE_SIZE: usize = 16;
|
|
/// Capacity (bytes never directly exposed or influenced by input).
|
|
const CAPACITY_SIZE: usize = 64;
|
|
/// Full AEAD state: rate || capacity = 80 bytes.
|
|
const STATE_SIZE: usize = RATE_SIZE + CAPACITY_SIZE;
|
|
const CHUNK_SIZE: usize = RATE_SIZE;
|
|
const MIN_KEY_SIZE: usize = 16;
|
|
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)]
|
|
pub struct EncryptionResult {
|
|
pub cipher: Vec<u8>,
|
|
pub tag: Vec<u8>,
|
|
}
|
|
|
|
#[derive(Debug, Clone, PartialEq, Eq)]
|
|
pub struct DecryptionResult {
|
|
pub plaintext: Vec<u8>,
|
|
pub tag: Vec<u8>,
|
|
}
|
|
|
|
#[derive(Debug, Clone)]
|
|
pub struct KeccakAead {
|
|
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 {
|
|
#[inline]
|
|
fn assert_valid_key_size(key: &[u8]) {
|
|
assert!(
|
|
(MIN_KEY_SIZE..=MAX_KEY_SIZE).contains(&key.len()),
|
|
"key must be between {} and {} bytes",
|
|
MIN_KEY_SIZE,
|
|
MAX_KEY_SIZE
|
|
);
|
|
}
|
|
|
|
/// 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 {
|
|
Self::assert_valid_key_size(key);
|
|
|
|
let mut input = Vec::with_capacity(iv.len() + key.len() + nonce.len());
|
|
|
|
input.extend_from_slice(iv);
|
|
input.extend_from_slice(key);
|
|
input.extend_from_slice(nonce);
|
|
|
|
let squeezed = shake256(&input, STATE_SIZE);
|
|
|
|
let mut state = [0u8; STATE_SIZE];
|
|
state.copy_from_slice(&squeezed);
|
|
|
|
for (i, &byte) in key.iter().enumerate() {
|
|
state[RATE_SIZE + i] ^= byte;
|
|
}
|
|
|
|
Self {
|
|
state,
|
|
pending: [0u8; CHUNK_SIZE],
|
|
pos: 0,
|
|
}
|
|
}
|
|
|
|
/// Process associated data.
|
|
///
|
|
/// 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]) {
|
|
let mut chunks = associated_data.chunks_exact(CHUNK_SIZE);
|
|
|
|
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() {
|
|
input[i] ^= byte;
|
|
}
|
|
|
|
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;
|
|
}
|
|
|
|
/// Absorb the completed message chunk (`pending`) into the state.
|
|
///
|
|
/// 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> {
|
|
let mut ciphertext = Vec::with_capacity(plaintext.len());
|
|
|
|
for &byte in plaintext {
|
|
let c = byte ^ self.state[self.pos];
|
|
|
|
ciphertext.push(c);
|
|
self.pending[self.pos] = c;
|
|
self.pos += 1;
|
|
|
|
if self.pos == CHUNK_SIZE {
|
|
self.absorb_pending_chunk();
|
|
}
|
|
}
|
|
|
|
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> {
|
|
let mut plaintext = Vec::with_capacity(ciphertext.len());
|
|
|
|
for &c in ciphertext {
|
|
plaintext.push(c ^ self.state[self.pos]);
|
|
|
|
self.pending[self.pos] = c;
|
|
self.pos += 1;
|
|
|
|
if self.pos == CHUNK_SIZE {
|
|
self.absorb_pending_chunk();
|
|
}
|
|
}
|
|
|
|
plaintext
|
|
}
|
|
|
|
/// Finalize and generate the authentication tag.
|
|
/// 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> {
|
|
Self::assert_valid_key_size(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 padding_len = CAPACITY_SIZE - key.len();
|
|
|
|
padded_key[padding_len..].copy_from_slice(key);
|
|
|
|
// XOR padded key into the capacity, c = state[16..80].
|
|
for (state_byte, &key_byte) in self.state[RATE_SIZE..STATE_SIZE]
|
|
.iter_mut()
|
|
.zip(padded_key.iter())
|
|
{
|
|
*state_byte ^= key_byte;
|
|
}
|
|
|
|
// SHAKE256(state, 80)
|
|
let output = shake256(&self.state, STATE_SIZE);
|
|
|
|
// Take the last `key.len()` bytes from the output and XOR with the key.
|
|
let tag_start = STATE_SIZE - key.len();
|
|
|
|
key.iter()
|
|
.zip(&output[tag_start..])
|
|
.map(|(&key_byte, &output_byte)| key_byte ^ output_byte)
|
|
.collect()
|
|
}
|
|
|
|
/// Encrypt:
|
|
///
|
|
/// ```text
|
|
/// sponge = KeccakAead(iv, key, nonce)
|
|
/// sponge.associated_data_processing(ad)
|
|
/// ciphertext = sponge.plaintext_processing(plaintext)
|
|
/// tag = sponge.finalize(key)
|
|
/// ```
|
|
pub fn encrypt(
|
|
key: &[u8],
|
|
plaintext: &[u8],
|
|
iv: &[u8],
|
|
associated_data: &[u8],
|
|
nonce: &[u8],
|
|
) -> EncryptionResult {
|
|
let mut sponge = Self::new(iv, key, nonce);
|
|
|
|
sponge.associated_data_processing(associated_data);
|
|
|
|
let cipher = sponge.plaintext_processing(plaintext);
|
|
|
|
let tag = sponge.finalize(key);
|
|
|
|
EncryptionResult { cipher, tag }
|
|
}
|
|
|
|
/// Decrypt.
|
|
pub fn decrypt(
|
|
key: &[u8],
|
|
ciphertext: &[u8],
|
|
iv: &[u8],
|
|
associated_data: &[u8],
|
|
nonce: &[u8],
|
|
) -> DecryptionResult {
|
|
let mut sponge = Self::new(iv, key, nonce);
|
|
|
|
sponge.associated_data_processing(associated_data);
|
|
|
|
let plaintext = sponge.ciphertext_processing(ciphertext);
|
|
|
|
let tag = sponge.finalize(key);
|
|
|
|
DecryptionResult { plaintext, tag }
|
|
}
|
|
}
|
|
|
|
/// SHAKE256 wrapper returning exactly an 80-byte AEAD state.
|
|
#[inline]
|
|
fn shake256_state(state: &[u8; STATE_SIZE]) -> [u8; STATE_SIZE] {
|
|
let output = shake256(state, STATE_SIZE);
|
|
|
|
let mut result = [0u8; STATE_SIZE];
|
|
|
|
result.copy_from_slice(&output);
|
|
|
|
result
|
|
}
|