aes_candidates.rs
benches/crypto/cases/src/aes_candidates.rs
1//! AES-only candidates and matched varying-record controls.2use cdk_rsx_crypto_bench_api::{Case, Operation, Params, Pattern};3use cdk_rsx_crypto_symmetric as s;4use core::hint::black_box;56#[derive(Clone, Copy)]7enum Algorithm {8 Gcm128,9 Gcm256,10 Siv128,11 Siv256,12}1314enum Cipher {15 G128(s::Aes128Gcm),16 G256(s::Aes256Gcm),17 S128(s::Aes128GcmSiv),18 S256(s::Aes256GcmSiv),19 G128Candidate(s::Aes128GcmPrepared64),20 G256Candidate(s::Aes256GcmPrepared64),21 S128Candidate(s::Aes128GcmSivBatched),22 S256Candidate(s::Aes256GcmSivBatched),23}24impl Cipher {25 fn new(algorithm: Algorithm, candidate: bool, key: &[u8; 32]) -> Self {26 match (algorithm, candidate) {27 (Algorithm::Gcm128, false) => {28 Self::G128(s::Aes128Gcm::new(key[..16].try_into().unwrap()))29 }30 (Algorithm::Gcm256, false) => Self::G256(s::Aes256Gcm::new(key)),31 (Algorithm::Siv128, false) => {32 Self::S128(s::Aes128GcmSiv::new(key[..16].try_into().unwrap()))33 }34 (Algorithm::Siv256, false) => Self::S256(s::Aes256GcmSiv::new(key)),35 (Algorithm::Gcm128, true) => {36 Self::G128Candidate(s::Aes128GcmPrepared64::new(key[..16].try_into().unwrap()))37 }38 (Algorithm::Gcm256, true) => Self::G256Candidate(s::Aes256GcmPrepared64::new(key)),39 (Algorithm::Siv128, true) => {40 Self::S128Candidate(s::Aes128GcmSivBatched::new(key[..16].try_into().unwrap()))41 }42 (Algorithm::Siv256, true) => Self::S256Candidate(s::Aes256GcmSivBatched::new(key)),43 }44 }45 fn seal(&self, nonce: &[u8; 12], aad: &[u8], body: &mut [u8]) -> Result<[u8; 16], s::Error> {46 match self {47 Self::G128(c) => c.seal(nonce, aad, body),48 Self::G256(c) => c.seal(nonce, aad, body),49 Self::S128(c) => c.seal(nonce, aad, body),50 Self::S256(c) => c.seal(nonce, aad, body),51 Self::G128Candidate(c) => c.seal(nonce, aad, body),52 Self::G256Candidate(c) => c.seal(nonce, aad, body),53 Self::S128Candidate(c) => c.seal(nonce, aad, body),54 Self::S256Candidate(c) => c.seal(nonce, aad, body),55 }56 }57 fn open(58 &self,59 nonce: &[u8; 12],60 aad: &[u8],61 body: &mut [u8],62 tag: &[u8; 16],63 ) -> Result<(), s::Error> {64 match self {65 Self::G128(c) => c.open(nonce, aad, body, tag),66 Self::G256(c) => c.open(nonce, aad, body, tag),67 Self::S128(c) => c.open(nonce, aad, body, tag),68 Self::S256(c) => c.open(nonce, aad, body, tag),69 Self::G128Candidate(c) => c.open(nonce, aad, body, tag),70 Self::G256Candidate(c) => c.open(nonce, aad, body, tag),71 Self::S128Candidate(c) => c.open(nonce, aad, body, tag),72 Self::S256Candidate(c) => c.open(nonce, aad, body, tag),73 }74 }75}7677fn bytes(mut seed: u64, len: usize) -> Vec<u8> {78 (0..len)79 .map(|_| {80 seed ^= seed << 13;81 seed ^= seed >> 7;82 seed ^= seed << 17;83 seed as u884 })85 .collect()86}8788// 100/500 records and any u64 driver iteration need at most 73 bits. Nonces89// remain distinct across records and measured/warmup cohorts under one key.90fn record_nonce(iteration: u64, count: usize, index: usize) -> [u8; 12] {91 (iteration as u128 * count as u128 + index as u128).to_be_bytes()[4..]92 .try_into()93 .unwrap()94}9596struct Item {97 key: [u8; 32],98 nonce: [u8; 12],99 aad: [u8; 32],100 plain: Vec<u8>,101 ciphertext: Vec<u8>,102 body: Vec<u8>,103 expected: Vec<u8>,104 tag: [u8; 16],105 expected_tag: [u8; 16],106 output_tag: [u8; 16],107 success: bool,108 expected_success: bool,109 prepared: Option<Box<Cipher>>,110}111struct Fixture {112 items: Vec<Item>,113 common: Option<Box<Cipher>>,114 algorithm: Algorithm,115 candidate: bool,116 fresh: bool,117 open: bool,118 records: bool,119 ran: bool,120}121122fn prepare(123 p: &Params,124 algorithm: Algorithm,125 candidate: bool,126 fresh: bool,127 open: bool,128 records: bool,129) -> Result<Box<dyn Operation>, String> {130 if p.batch == 0131 || p.batch > 500132 || p.message_len > 1024 * 1024133 || p.message_len134 .checked_mul(p.batch)135 .is_none_or(|n| n > 8 * 1024 * 1024)136 {137 return Err("AES fixture exceeds bounded bytes or batch 1..=500".into());138 }139 let mut items = Vec::with_capacity(p.batch);140 let mut common = None;141 for index in 0..p.batch {142 let seed = p143 .seed144 .wrapping_add(if p.distinct { index as u64 } else { 0 });145 let key = bytes(seed ^ 0x834df3871, 32).try_into().unwrap();146 let record_seed = if records {147 p.seed.wrapping_add(index as u64 + 1)148 } else {149 seed150 };151 let nonce = if records {152 record_nonce(0, p.batch, index)153 } else {154 bytes(record_seed ^ 0xf138daf27, 12).try_into().unwrap()155 };156 let aad: [u8; 32] = bytes(record_seed ^ 0xc9a781e, 32).try_into().unwrap();157 let plain = bytes(record_seed, p.message_len);158 let mut ciphertext = plain.clone();159 let expected_tag = Cipher::new(algorithm, false, &key)160 .seal(&nonce, &aad, &mut ciphertext)161 .unwrap();162 let valid = match p.pattern {163 Pattern::Valid => true,164 Pattern::Invalid => false,165 Pattern::Mixed => index % 2 == 0,166 };167 let expected_success = !open || valid;168 let expected = if open {169 if valid {170 plain.clone()171 } else {172 vec![0; plain.len()]173 }174 } else {175 ciphertext.clone()176 };177 let mut tag = expected_tag;178 if open && !valid {179 tag[if index % 2 == 0 { 0 } else { 15 }] ^= 1;180 }181 let prepared = if fresh {182 None183 } else if p.distinct {184 Some(Box::new(Cipher::new(algorithm, candidate, &key)))185 } else {186 if index == 0 {187 common = Some(Box::new(Cipher::new(algorithm, candidate, &key)));188 }189 None190 };191 items.push(Item {192 key,193 nonce,194 aad,195 plain: plain.clone(),196 ciphertext,197 body: plain,198 expected,199 tag,200 expected_tag,201 output_tag: [0; 16],202 success: false,203 expected_success,204 prepared,205 });206 }207 Ok(Box::new(Fixture {208 items,209 common,210 algorithm,211 candidate,212 fresh,213 open,214 records,215 ran: false,216 }))217}218219impl Operation for Fixture {220 fn operations_per_run(&self) -> usize {221 self.items.len()222 }223 fn run(&mut self, iteration: u64) -> u64 {224 let mut checksum = 0u64;225 let count = self.items.len();226 for (index, item) in self.items.iter_mut().enumerate() {227 if self.records {228 item.nonce = record_nonce(iteration, count, index);229 }230 item.body.copy_from_slice(black_box(if self.open {231 &item.ciphertext232 } else {233 &item.plain234 }));235 let key = black_box(&item.key);236 let nonce = black_box(&item.nonce);237 let aad = black_box(&item.aad);238 let temporary;239 let cipher = if self.fresh {240 temporary = Cipher::new(self.algorithm, self.candidate, key);241 &temporary242 } else {243 self.common244 .as_deref()245 .or(item.prepared.as_deref())246 .expect("prepared")247 };248 if self.open {249 item.success = cipher250 .open(nonce, aad, &mut item.body, black_box(&item.tag))251 .is_ok();252 } else {253 item.output_tag = cipher.seal(nonce, aad, &mut item.body).expect("bounded");254 item.success = true;255 }256 black_box(item.body.as_slice());257 black_box(item.output_tag);258 black_box(item.success);259 checksum = checksum.rotate_left(7)260 ^ u64::from_le_bytes(item.output_tag[..8].try_into().unwrap())261 ^ item.success as u64;262 if let Some(byte) = item.body.first() {263 checksum ^= *byte as u64;264 }265 }266 self.ran = true;267 checksum268 }269 fn check(&mut self) -> Result<(), String> {270 if !self.ran {271 return Err("AES fixture has not run".into());272 }273 for (index, item) in self.items.iter_mut().enumerate() {274 if self.records {275 item.expected.copy_from_slice(&item.plain);276 item.expected_tag = Cipher::new(self.algorithm, false, &item.key)277 .seal(&item.nonce, &item.aad, &mut item.expected)278 .unwrap();279 }280 if item.body != item.expected281 || item.success != item.expected_success282 || (!self.open && item.output_tag != item.expected_tag)283 {284 return Err(format!("AES complete output mismatch at record {index}"));285 }286 }287 Ok(())288 }289}290291pub fn cases() -> Vec<Case> {292 // Fixed-tuple candidates match the existing symmetric cases' inputs and293 // restore/preparation boundary. Records always vary input/AAD/nonce;294 // distinct=false shares one key, distinct=true prepares a key per record.295 macro_rules! c {296 ($id:literal, $algorithm:ident, $fresh:expr, $open:expr) => {297 Case { id: $id, description: "Explicit AES software-hash/batched-derivation candidate; matches fixed-tuple upstream cases", prepare: |p| prepare(p, Algorithm::$algorithm, true, $fresh, $open, false) }298 };299 }300 macro_rules! r {301 ($id:literal, $algorithm:ident, $candidate:expr) => {302 Case { id: $id, description: "Varying input/AAD and advancing record nonces; distinct=false one prepared key, true key per record", prepare: |p| prepare(p, Algorithm::$algorithm, $candidate, false, false, true) }303 };304 }305 let mut cases = vec![306 c!("aes128gcm-seal-prepared64-fresh", Gcm128, true, false),307 c!("aes128gcm-seal-prepared64-prepared", Gcm128, false, false),308 c!("aes128gcm-open-prepared64-fresh", Gcm128, true, true),309 c!("aes128gcm-open-prepared64-prepared", Gcm128, false, true),310 c!("aes256gcm-seal-prepared64-fresh", Gcm256, true, false),311 c!("aes256gcm-seal-prepared64-prepared", Gcm256, false, false),312 c!("aes256gcm-open-prepared64-fresh", Gcm256, true, true),313 c!("aes256gcm-open-prepared64-prepared", Gcm256, false, true),314 c!("aes128gcmsiv-seal-batched-fresh", Siv128, true, false),315 c!("aes128gcmsiv-seal-batched-prepared", Siv128, false, false),316 c!("aes128gcmsiv-open-batched-fresh", Siv128, true, true),317 c!("aes128gcmsiv-open-batched-prepared", Siv128, false, true),318 c!("aes256gcmsiv-seal-batched-fresh", Siv256, true, false),319 c!("aes256gcmsiv-seal-batched-prepared", Siv256, false, false),320 c!("aes256gcmsiv-open-batched-fresh", Siv256, true, true),321 c!("aes256gcmsiv-open-batched-prepared", Siv256, false, true),322 r!("aes128gcm-seal-reference-records", Gcm128, false),323 r!("aes128gcm-seal-prepared64-records", Gcm128, true),324 r!("aes256gcm-seal-reference-records", Gcm256, false),325 r!("aes256gcm-seal-prepared64-records", Gcm256, true),326 r!("aes128gcmsiv-seal-reference-records", Siv128, false),327 r!("aes128gcmsiv-seal-batched-records", Siv128, true),328 r!("aes256gcmsiv-seal-reference-records", Siv256, false),329 r!("aes256gcmsiv-seal-batched-records", Siv256, true),330 ];331 cases.extend(hash_cases());332 cases333}334335enum HashKey {336 GHash(s::GHashPrepared64),337 Polyval(s::PolyvalPrepared64),338}339impl HashKey {340 fn new(ghash: bool, key: &[u8; 16]) -> Self {341 if ghash {342 Self::GHash(s::GHashPrepared64::new(key))343 } else {344 Self::Polyval(s::PolyvalPrepared64::new(key))345 }346 }347 fn tag(&self, blocks: &[[u8; 16]]) -> [u8; 16] {348 match self {349 Self::GHash(key) => key.hash_blocks(blocks),350 Self::Polyval(key) => key.hash_blocks(blocks),351 }352 }353}354struct HashItem {355 key: [u8; 16],356 blocks: Vec<[u8; 16]>,357 prepared: Option<HashKey>,358 expected: [u8; 16],359 output: [u8; 16],360}361struct HashFixture {362 items: Vec<HashItem>,363 ghash: bool,364 fresh: bool,365 ran: bool,366}367impl Operation for HashFixture {368 fn operations_per_run(&self) -> usize {369 self.items.len()370 }371 fn run(&mut self, _: u64) -> u64 {372 let mut checksum = 0u64;373 for item in &mut self.items {374 item.output = if self.fresh {375 HashKey::new(self.ghash, black_box(&item.key)).tag(black_box(&item.blocks))376 } else {377 item.prepared.as_ref().unwrap().tag(black_box(&item.blocks))378 };379 black_box(item.output);380 checksum =381 checksum.rotate_left(7) ^ u64::from_le_bytes(item.output[..8].try_into().unwrap());382 }383 self.ran = true;384 checksum385 }386 fn check(&mut self) -> Result<(), String> {387 if !self.ran {388 return Err("AES hash fixture has not run".into());389 }390 if self.items.iter().any(|item| item.output != item.expected) {391 return Err("AES prepared hash mismatch".into());392 }393 Ok(())394 }395}396fn prepare_hash(p: &Params, ghash: bool, fresh: bool) -> Result<Box<dyn Operation>, String> {397 if p.batch == 0398 || p.batch > 500399 || p.message_len == 0400 || p.message_len % 16 != 0401 || p.message_len > 1024 * 1024402 || p.message_len403 .checked_mul(p.batch)404 .is_none_or(|n| n > 8 * 1024 * 1024)405 {406 return Err(407 "AES hash fixture needs bounded complete 16-byte blocks and batch 1..=500".into(),408 );409 }410 let items = (0..p.batch)411 .map(|index| {412 let seed = p413 .seed414 .wrapping_add(if p.distinct { index as u64 } else { 0 });415 let key: [u8; 16] = bytes(seed ^ 0x834df3871, 16).try_into().unwrap();416 let blocks: Vec<[u8; 16]> = bytes(seed, p.message_len)417 .chunks_exact(16)418 .map(|b| b.try_into().unwrap())419 .collect();420 let expected = if ghash {421 s::ghash(&key, &blocks)422 } else {423 s::polyval(&key, &blocks)424 };425 HashItem {426 key,427 blocks,428 expected,429 output: [0; 16],430 prepared: if fresh {431 None432 } else {433 Some(HashKey::new(ghash, &key))434 },435 }436 })437 .collect();438 Ok(Box::new(HashFixture {439 items,440 ghash,441 fresh,442 ran: false,443 }))444}445fn hash_cases() -> Vec<Case> {446 vec![447 Case {448 id: "ghash-blocks-prepared64-fresh",449 description: "Raw GHASH constant-time prepared64 arithmetic including key decomposition",450 prepare: |p| prepare_hash(p, true, true),451 },452 Case {453 id: "ghash-blocks-prepared64-prepared",454 description: "Raw GHASH constant-time prepared64 arithmetic with retained key decomposition",455 prepare: |p| prepare_hash(p, true, false),456 },457 Case {458 id: "polyval-blocks-prepared64-fresh",459 description: "Raw POLYVAL constant-time prepared64 arithmetic including key decomposition",460 prepare: |p| prepare_hash(p, false, true),461 },462 Case {463 id: "polyval-blocks-prepared64-prepared",464 description: "Raw POLYVAL constant-time prepared64 arithmetic with retained key decomposition",465 prepare: |p| prepare_hash(p, false, false),466 },467 ]468}469470#[cfg(test)]471mod tests {472 use super::*;473474 #[test]475 fn aes_candidates_execute_exact_100_record_calls_at_primary_sizes() {476 for case in cases() {477 for message_len in [32, 128, 512, 2048] {478 for distinct in [false, true] {479 for pattern in [Pattern::Valid, Pattern::Invalid, Pattern::Mixed] {480 let mut fixture = (case.prepare)(&Params {481 message_len,482 batch: 100,483 seed: 31,484 pattern,485 distinct,486 })487 .unwrap();488 assert_eq!(fixture.operations_per_run(), 100);489 // One invocation performs exactly 100 logical records;490 // warm and measured cohorts use monotonically increasing491 // nonces in the explicit varying-record populations.492 for iteration in [0, 1] {493 fixture.run(iteration);494 fixture.check().unwrap_or_else(|e| {495 panic!("{} len{message_len} distinct{distinct}: {e}", case.id)496 });497 }498 }499 }500 }501 }502 }503504 #[test]505 fn records_have_distinct_inputs_and_nonces_independent_of_key_population() {506 for distinct in [false, true] {507 let params = Params {508 message_len: 32,509 batch: 100,510 seed: 31,511 pattern: Pattern::Valid,512 distinct,513 };514 let mut previous_key = None;515 let mut nonces = std::collections::BTreeSet::new();516 for index in 0..params.batch {517 let seed = params.seed + if distinct { index as u64 } else { 0 };518 let key = bytes(seed ^ 0x834df3871, 32);519 if let Some(old) = previous_key {520 assert_eq!(key == old, !distinct);521 }522 previous_key = Some(key);523 for iteration in [0, 1, u64::MAX] {524 assert!(nonces.insert(record_nonce(iteration, params.batch, index)));525 }526 }527 }528 }529}