diff --git a/ascon/src/aead.rs b/ascon/src/aead.rs index 81c6dd6..e78caa9 100644 --- a/ascon/src/aead.rs +++ b/ascon/src/aead.rs @@ -1,6 +1,6 @@ //! Authenticated Encryption with Associated Data. -use crate::{Ascon, Key, KEY_SIZE, RATE, S_SIZE}; +use crate::{Ascon, Key, Nonce, KEY_SIZE, RATE, S_SIZE}; use alloc::{vec, vec::Vec}; /// Ascon(a,b) `b`-parameter. @@ -23,7 +23,7 @@ pub enum DecryptFail { } /// AEAD encryption. -pub fn encrypt(key: &Key, iv: &[u8], message: &[u8], aad: &[u8]) -> (Vec, Tag) { +pub fn encrypt(key: &Key, nonce: &Nonce, message: &[u8], aad: &[u8]) -> (Vec, Tag) { let s = aad.len() / RATE + 1; let t = message.len() / RATE + 1; let l = message.len() % RATE; @@ -42,7 +42,7 @@ pub fn encrypt(key: &Key, iv: &[u8], message: &[u8], aad: &[u8]) -> (Vec, Ta mm[message.len()] = 0x80; // init - let mut ss = Ascon::new(key, iv); + let mut ss = Ascon::new(key, nonce); // aad if !aad.is_empty() { @@ -78,7 +78,7 @@ pub fn encrypt(key: &Key, iv: &[u8], message: &[u8], aad: &[u8]) -> (Vec, Ta /// AEAD decryption. pub fn decrypt( key: &Key, - iv: &[u8], + nonce: &Nonce, ciphertext: &[u8], aad: &[u8], tag: &[u8], @@ -99,7 +99,7 @@ pub fn decrypt( aa[aad.len()] = 0x80; // init - let mut ss = Ascon::new(key, iv); + let mut ss = Ascon::new(key, nonce); // aad if !aad.is_empty() { diff --git a/ascon/src/lib.rs b/ascon/src/lib.rs index 3840a1f..04a099a 100644 --- a/ascon/src/lib.rs +++ b/ascon/src/lib.rs @@ -25,6 +25,9 @@ use core::convert::TryInto; /// Size of an Ascon key in bytes. const KEY_SIZE: usize = 16; +/// Size of an Ascon nonce in bytes. +const NONCE_SIZE: usize = 16; + /// State size in bits. const S_BITS: usize = 320; @@ -37,6 +40,9 @@ const RATE: usize = 128 / 8; /// Ascon permutation key. pub type Key = [u8; KEY_SIZE]; +/// Ascon nonce. +pub type Nonce = [u8; NONCE_SIZE]; + /// Ascon permutation state. type State = [u8; S_SIZE]; @@ -48,23 +54,22 @@ pub struct Ascon { impl Ascon { /// Initialize Ascon permutation. - // TODO(tarcieri): validate length of key and nonce - pub fn new(key: &Key, nonce: &[u8]) -> Self { + pub fn new(key: &Key, nonce: &Nonce) -> Self { let mut state = [0; S_SIZE]; state[0] = KEY_SIZE as u8 * 8; state[1] = RATE as u8 * 8; state[2] = A as u8; state[3] = B as u8; - let mut pos = S_SIZE - 2 * KEY_SIZE; - state[pos..pos + key.len()].copy_from_slice(key); - pos += KEY_SIZE; - state[pos..pos + nonce.len()].copy_from_slice(nonce); + let pos = S_SIZE - KEY_SIZE - NONCE_SIZE; + let (k, n) = state[pos..].split_at_mut(KEY_SIZE); + k.copy_from_slice(key); + n.copy_from_slice(nonce); permutation(&mut state, 12 - A, A); for (i, &b) in key.iter().enumerate() { - state[pos + i] ^= b; + state[pos + KEY_SIZE + i] ^= b; } Self { key: *key, state }