|
| 1 | +#![cfg(feature = "alloc")] // TODO: remove after migration to the new `aead` crate |
| 2 | +use ascon_aead::{ |
| 3 | + AsconAead128, |
| 4 | + aead::{Aead, KeyInit, Nonce, Payload, dev::blobby}, |
| 5 | +}; |
| 6 | + |
| 7 | +fn run_pass_test<C: Aead>( |
| 8 | + cipher: &C, |
| 9 | + nonce: &Nonce<C>, |
| 10 | + aad: &[u8], |
| 11 | + pt: &[u8], |
| 12 | + ct: &[u8], |
| 13 | +) -> Result<(), &'static str> { |
| 14 | + let res = cipher |
| 15 | + .encrypt(nonce, Payload { aad, msg: pt }) |
| 16 | + .map_err(|_| "encryption failure")?; |
| 17 | + if res != ct { |
| 18 | + return Err("encrypted data is different from target ciphertext"); |
| 19 | + } |
| 20 | + |
| 21 | + let res = cipher |
| 22 | + .decrypt(nonce, Payload { aad, msg: ct }) |
| 23 | + .map_err(|_| "decryption failure")?; |
| 24 | + if res != pt { |
| 25 | + return Err("decrypted data is different from target plaintext"); |
| 26 | + } |
| 27 | + |
| 28 | + Ok(()) |
| 29 | +} |
| 30 | + |
| 31 | +#[macro_export] |
| 32 | +macro_rules! new_pass_test { |
| 33 | + ($name:ident, $test_name:expr, $cipher:ty $(,)?) => { |
| 34 | + #[test] |
| 35 | + fn $name() { |
| 36 | + use blobby::Blob5Iterator; |
| 37 | + use $crate::KeyInit; |
| 38 | + |
| 39 | + let data = include_bytes!(concat!("data/", $test_name, ".blb")); |
| 40 | + for (i, row) in Blob5Iterator::new(data).unwrap().enumerate() { |
| 41 | + let [key, nonce, aad, pt, ct] = row.unwrap(); |
| 42 | + let key = key.try_into().expect("wrong key size"); |
| 43 | + let nonce = nonce.try_into().expect("wrong nonce size"); |
| 44 | + let cipher = <$cipher as KeyInit>::new(key); |
| 45 | + let res = run_pass_test(&cipher, nonce, aad, pt, ct); |
| 46 | + if let Err(reason) = res { |
| 47 | + panic!( |
| 48 | + "\n\ |
| 49 | + Failed (pass) test #{i}\n\ |
| 50 | + reason:\t{reason:?}\n\ |
| 51 | + key:\t{key:?}\n\ |
| 52 | + nonce:\t{nonce:?}\n\ |
| 53 | + aad:\t{aad:?}\n\ |
| 54 | + plaintext:\t{pt:?}\n\ |
| 55 | + ciphertext:\t{ct:?}\n" |
| 56 | + ); |
| 57 | + } |
| 58 | + } |
| 59 | + } |
| 60 | + }; |
| 61 | +} |
| 62 | + |
| 63 | +// Test vectors are taken from the reference Ascon implementation: |
| 64 | +// https://github.com/ascon/ascon-c/blob/fdfca408/crypto_aead/asconaead128/LWC_AEAD_KAT_128_128.txt |
| 65 | +new_pass_test!(ascon_aead_kats, "kats", AsconAead128); |
0 commit comments