From 8a94ded36f13b075adbdaa329b9efe075824aaeb Mon Sep 17 00:00:00 2001 From: officialfrancismendoza Date: Wed, 11 Nov 2026 10:26:27 +0700 Subject: [PATCH 01/10] Initial add for AES-XTS (#184) --- alpha_0.1.4_release_notes.md | 3 + cli/src/main.rs | 90 +++ cli/src/xts_cmd.rs | 130 +++ cli/tests/aes_xts_cli_tests.rs | 199 +++++ crypto/aes/Cargo.toml | 4 + crypto/aes/benches/aes_xts_benches.rs | 110 +++ crypto/aes/src/lib.rs | 9 +- crypto/aes/src/xts.rs | 91 +++ crypto/aes/tests/xts_acvp_tests.rs | 747 ++++++++++++++++++ crypto/aes/tests/xts_tests.rs | 481 +++++++++++ crypto/aes/tests/xts_wycheproof.rs | 121 +++ crypto/cipher/Cargo.toml | 4 + crypto/cipher/src/modes/mod.rs | 9 +- .../cipher/src/modes/possible_enhancements.md | 1 - crypto/cipher/src/modes/xts.rs | 514 ++++++++++++ crypto/cipher/tests/modes/xts_tests.rs | 228 ++++++ 16 files changed, 2736 insertions(+), 5 deletions(-) create mode 100644 cli/src/xts_cmd.rs create mode 100644 cli/tests/aes_xts_cli_tests.rs create mode 100644 crypto/aes/benches/aes_xts_benches.rs create mode 100644 crypto/aes/src/xts.rs create mode 100644 crypto/aes/tests/xts_acvp_tests.rs create mode 100644 crypto/aes/tests/xts_tests.rs create mode 100644 crypto/aes/tests/xts_wycheproof.rs create mode 100644 crypto/cipher/src/modes/xts.rs create mode 100644 crypto/cipher/tests/modes/xts_tests.rs diff --git a/alpha_0.1.4_release_notes.md b/alpha_0.1.4_release_notes.md index 5fcb82b06..61ebc28dd 100644 --- a/alpha_0.1.4_release_notes.md +++ b/alpha_0.1.4_release_notes.md @@ -17,6 +17,9 @@ * CHACHA20 -- ChaCha20, Poly1305 and ChaCha20-Poly1305 (RFC 8439). * AES Key Wrap -- AES_KW and AES_KWP (NIST SP 800-38F; RFC 3394 / RFC 5649) over any 128-bit block permutation, with the `KeyWrapper` / `KeyUnwrapper` core traits and the `aes*-kw` / `aes*-kwp` CLI commands. +* AES-XTS -- XTS-AES-128 and XTS-AES-256 (NIST SP 800-38E; IEEE Std 1619-2007) for storage, as `XTS_AES_128` / + `XTS_AES_256` over `bouncycastle_cipher::modes::XTSKey`, with the data-unit length `N` checked at compile time; + the `aes128-xts` / `aes256-xts` CLI commands. * ECDSA -- FIPS 186-5 signatures over P-256, P-384, P-521, secp256k1, brainpoolP256r1, brainpoolP384r1 and brainpoolP512r1, with the RFC 6979 deterministic variant, through the `SigningKey` / `DeterministicSigningKey` / `VerifyingKey` core roles; the `ecdsa-*` CLI commands. diff --git a/cli/src/main.rs b/cli/src/main.rs index 8730759dd..6b832b0da 100644 --- a/cli/src/main.rs +++ b/cli/src/main.rs @@ -23,6 +23,7 @@ mod sha2_cmd; mod sha3_cmd; mod sm2_cmd; mod sm3_cmd; +mod xts_cmd; use crate::ecdsa_cmd::ECDSAAction; use crate::hkdf_cmd::HKDFVariant; @@ -2567,6 +2568,85 @@ enum Subcommands { x: bool, }, + /// XTS-AES-128 (NIST SP 800-38E; IEEE Std 1619-2007), for storage: streams stdin to stdout one + /// data unit at a time. + /// + /// The input is a sequence of data units of `--data-unit-len` bytes -- 512, 1024, 2048 or 4096, + /// the usual sector sizes -- and must be a whole number of them; the output is exactly as long + /// as the input, with nothing prepended. The first data unit is processed under `--tweak` and + /// each one after it under the tweak before it plus one, read as a 128-bit little-endian + /// integer. For sectors numbered from n, `--tweak` is n in 16 little-endian bytes: sector 1 is + /// 01000000000000000000000000000000. `decrypt` needs the same `--tweak` and `--data-unit-len`. + /// + /// The key is 32 bytes, Key_1 | Key_2: two AES-128 keys, the first for the data and the second + /// for the tweak, which must differ (FIPS 140-3 IG C.I) and should be generated independently. + /// + /// WARNING: XTS provides confidentiality only, and is for data at rest, not in transit. Nothing + /// detects a modified ciphertext, which decrypts to unpredictable data rather than to an error, + /// or an old one, which decrypts to the old data, and the same data under the same key and + /// tweak always encrypts the same way. Give every data unit under a key its own tweak. + /// + /// Note: in production uses, secrets should not be passed on the command-line because they get + /// logged in shell history. Use the file-based input instead. + AES128_XTS { + #[arg(short, long)] + direction: CipherDirection, + + /// The 32-byte XTS key, Key_1 | Key_2, in hex. + /// The `key_file` option is preferred to avoid leaving key material in command history. + #[arg(long)] + key: Option, + + /// A file containing the 32-byte XTS key (raw bytes; hex with --hex-input). + /// If both key and key_file options are provided, the file will be used. + #[arg(short, long)] + key_file: Option, + + /// The 16-byte tweak of the first data unit, in hex. See above. + #[arg(long)] + tweak: String, + + /// The length of a data unit in bytes: 512, 1024, 2048 or 4096. + #[arg(long)] + data_unit_len: usize, + + #[arg(short)] + /// Output in hex format. + x: bool, + }, + + /// XTS-AES-256 (NIST SP 800-38E; IEEE Std 1619-2007), for storage: streams stdin to stdout one + /// data unit at a time. + /// + /// See `aes128-xts` for the data units, the tweak and the warnings; only the key differs: 64 + /// bytes, Key_1 | Key_2, two AES-256 keys. + AES256_XTS { + #[arg(short, long)] + direction: CipherDirection, + + /// The 64-byte XTS key, Key_1 | Key_2, in hex. + /// The `key_file` option is preferred to avoid leaving key material in command history. + #[arg(long)] + key: Option, + + /// A file containing the 64-byte XTS key (raw bytes; hex with --hex-input). + /// If both key and key_file options are provided, the file will be used. + #[arg(short, long)] + key_file: Option, + + /// The 16-byte tweak of the first data unit, in hex. See `aes128-xts`. + #[arg(long)] + tweak: String, + + /// The length of a data unit in bytes: 512, 1024, 2048 or 4096. + #[arg(long)] + data_unit_len: usize, + + #[arg(short)] + /// Output in hex format. + x: bool, + }, + /// Camellia-128 Key Wrap (RFC 3657 `id-camellia128-wrap`; NIST SP 800-38F Sec 6.2 over the /// Camellia permutation): `-d encrypt` wraps stdin to stdout, `-d decrypt` unwraps it. /// @@ -5682,6 +5762,16 @@ fn run() { Some(Subcommands::AES256_KWP { direction, key, key_file, x }) => { kw_cmd::kwp_cmd::(direction, key, key_file, *x, "AES-256"); } + Some(Subcommands::AES128_XTS { direction, key, key_file, tweak, data_unit_len, x }) => { + xts_cmd::xts_cmd::( + direction, key, key_file, tweak, *data_unit_len, *x, "XTS-AES-128", + ); + } + Some(Subcommands::AES256_XTS { direction, key, key_file, tweak, data_unit_len, x }) => { + xts_cmd::xts_cmd::( + direction, key, key_file, tweak, *data_unit_len, *x, "XTS-AES-256", + ); + } Some(Subcommands::CAMELLIA128_KW { direction, key, key_file, x }) => { kw_cmd::kw_cmd::(direction, key, key_file, *x, "Camellia-128"); } diff --git a/cli/src/xts_cmd.rs b/cli/src/xts_cmd.rs new file mode 100644 index 000000000..9a49fd386 --- /dev/null +++ b/cli/src/xts_cmd.rs @@ -0,0 +1,130 @@ +//! XTS-AES encryption and decryption of stdin to stdout, one data unit at a time: the +//! `aes128-xts` and `aes256-xts` commands, one generic function that `main` instantiates per key +//! length. +//! +//! The input is a sequence of data units of `--data-unit-len` bytes, and must be a whole number of +//! them: an XTS key protects data units of one fixed length (NIST SP 800-38E Sec 4), and the +//! library fixes that length in the key's type, so the command offers the usual sector sizes and +//! instantiates a key type for the one chosen. The first data unit is processed under `--tweak` and +//! each later one under the tweak before it plus one, as a 128-bit little-endian integer -- the +//! consecutive sequence numbers of consecutive sectors, as NIST's ACVP tests number the data units +//! of a longer payload. Nothing is prepended or appended: the output is exactly as long as the +//! input. +//! +//! # Warning +//! +//! XTS provides confidentiality only, and only for data at rest; see the subcommand help. + +use crate::helpers::block_mode_helpers::{CipherDirection, load_key_object}; +use crate::helpers::{ + decode_hex_arg, flush_stdout, read_stdin_chunk, write_bytes_or_hex, write_stdout, +}; +use bouncycastle::cipher::modes::{XTS_TWEAK_LEN, XTSKey}; +use bouncycastle::core::hazmat::BlockPermutation; +use bouncycastle::core::symmetric_key::FromKeyMaterial; +use std::process::exit; + +/// XTS over the permutation `P` with a `KEY_LEN`-byte key, `Key_1 | Key_2`; `alg` names the +/// algorithm in messages. Exits with an error for a `data_unit_len` it does not offer. +pub(crate) fn xts_cmd( + action: &CipherDirection, + key: &Option, + key_file: &Option, + tweak: &str, + data_unit_len: usize, + output_hex: bool, + alg: &str, +) where + P: BlockPermutation<16>, + XTSKey: FromKeyMaterial, + XTSKey: FromKeyMaterial, + XTSKey: FromKeyMaterial, + XTSKey: FromKeyMaterial, +{ + let tweak = load_tweak(tweak); + match data_unit_len { + 512 => run::(action, key, key_file, &tweak, output_hex, alg), + 1024 => run::(action, key, key_file, &tweak, output_hex, alg), + 2048 => run::(action, key, key_file, &tweak, output_hex, alg), + 4096 => run::(action, key, key_file, &tweak, output_hex, alg), + other => { + eprintln!("Error: --data-unit-len must be 512, 1024, 2048 or 4096 bytes, not {other}."); + exit(-1); + } + } +} + +/// `--tweak`: exactly 16 bytes of hex, the 128-bit tweak of the first data unit. +fn load_tweak(tweak: &str) -> [u8; XTS_TWEAK_LEN] { + let bytes = decode_hex_arg(tweak, "tweak"); + bytes.as_slice().try_into().unwrap_or_else(|_| { + eprintln!("Error: the tweak is {} bytes; XTS takes exactly {XTS_TWEAK_LEN}.", bytes.len()); + exit(-1) + }) +} + +/// Processes stdin a data unit at a time under consecutive tweaks from `first_tweak`. +fn run( + action: &CipherDirection, + key: &Option, + key_file: &Option, + first_tweak: &[u8; XTS_TWEAK_LEN], + output_hex: bool, + alg: &str, +) where + P: BlockPermutation<16>, + XTSKey: FromKeyMaterial, +{ + let key = load_key_object::, KEY_LEN>(key, key_file, alg); + let mut sequence_number = u128::from_le_bytes(*first_tweak); + let mut data_unit = [0u8; N]; + let mut units = 0u64; + loop { + let filled = fill(&mut data_unit); + if filled == 0 { + break; + } + if filled < N { + // The whole data units before it are already written; flush them so that the error + // follows the output rather than landing inside it. + flush_stdout(); + eprintln!( + "\nError: input to {alg} must be a whole number of {N}-byte data units \ + (data contained {filled} trailing byte(s))." + ); + exit(-1); + } + if units > 0 { + // Fail rather than wrap round to a tweak an earlier data unit may have used. + sequence_number = sequence_number.checked_add(1).unwrap_or_else(|| { + flush_stdout(); + eprintln!("\nError: the tweak cannot go past 2^128 - 1."); + exit(-1) + }); + } + let tweak = sequence_number.to_le_bytes(); + match action { + CipherDirection::Encrypt => key.encrypt_inplace(&tweak, &mut data_unit), + CipherDirection::Decrypt => key.decrypt_inplace(&tweak, &mut data_unit), + }; + write_bytes_or_hex(&data_unit, output_hex); + units += 1; + } + if output_hex { + write_stdout(b"\n"); + } + flush_stdout(); +} + +/// Reads stdin into `buf` until it is full or the input ends, and returns how much was read. +fn fill(buf: &mut [u8]) -> usize { + let mut filled = 0; + while filled < buf.len() { + let n = read_stdin_chunk(&mut buf[filled..]); + if n == 0 { + break; + } + filled += n; + } + filled +} diff --git a/cli/tests/aes_xts_cli_tests.rs b/cli/tests/aes_xts_cli_tests.rs new file mode 100644 index 000000000..d9b7d783e --- /dev/null +++ b/cli/tests/aes_xts_cli_tests.rs @@ -0,0 +1,199 @@ +//! Tests for the `aes128-xts` and `aes256-xts` subcommands: the library's answer at every offered +//! data-unit length, and an OpenSSL known answer, through the command; consecutive tweaks across +//! data units, including a carry; the refusals of partial data units, a wrapping tweak and bad +//! arguments; and the help listing. + +mod common; +use bouncycastle::aes::{XTS_AES_128, XTS_AES_256}; +use common::{ + KEY32, key_object, listed_in_help, pseudo_random, run, run_err_silent, run_ok, unhex, +}; + +/// `Key_1 | Key_2` for XTS-AES-256: counting bytes, whose halves differ. XTS-AES-128 takes +/// [`KEY32`]. +const KEY64: &str = "000102030405060708090a0b0c0d0e0f101112131415161718191a1b1c1d1e1f\ + 202122232425262728292a2b2c2d2e2f303132333435363738393a3b3c3d3e3f"; + +const TWEAK: &str = "f0e1d2c3b4a5968778695a4b3c2d1e0f"; + +/// The library's answer for `data` as consecutive `N`-byte data units from the tweak `first`. +fn library_128(key: &str, first: &str, data: &[u8], encrypt: bool) -> Vec { + let key: XTS_AES_128 = key_object::<32, _>(key); + let first = u128::from_le_bytes(unhex(first).try_into().unwrap()); + let mut out = data.to_vec(); + for (n, unit) in (first..).zip(out.as_chunks_mut::().0) { + if encrypt { + key.encrypt_inplace(&n.to_le_bytes(), unit); + } else { + key.decrypt_inplace(&n.to_le_bytes(), unit); + } + } + out +} + +/// As [`library_128`], for XTS-AES-256. +fn library_256(key: &str, first: &str, data: &[u8], encrypt: bool) -> Vec { + let key: XTS_AES_256 = key_object::<64, _>(key); + let first = u128::from_le_bytes(unhex(first).try_into().unwrap()); + let mut out = data.to_vec(); + for (n, unit) in (first..).zip(out.as_chunks_mut::().0) { + if encrypt { + key.encrypt_inplace(&n.to_le_bytes(), unit); + } else { + key.decrypt_inplace(&n.to_le_bytes(), unit); + } + } + out +} + +/// The arguments of `cmd` in `direction` under `key`, from `tweak`, in `len`-byte data units. +fn xts(cmd: &str, direction: &str, key: &str, tweak: &str, len: usize) -> Vec { + let len = len.to_string(); + [cmd, "-d", direction, "--key", key, "--tweak", tweak, "--data-unit-len", &len] + .iter() + .map(|s| s.to_string()) + .collect() +} + +fn args(v: &[String]) -> Vec<&str> { + v.iter().map(String::as_str).collect() +} + +/// Three data units through `cmd`, both directions, against the library's `expected`. +fn agrees(cmd: &str, key: &str, len: usize, data: &[u8], expected: &[u8]) { + let ct = run_ok(&args(&xts(cmd, "encrypt", key, TWEAK, len)), data); + assert_eq!(ct, expected, "{cmd} at {len}: encrypt"); + let mut hex_args = xts(cmd, "encrypt", key, TWEAK, len); + hex_args.push("-x".to_string()); + let hex = run_ok(&args(&hex_args), data); + assert_eq!(unhex(String::from_utf8_lossy(&hex).trim()), expected, "{cmd} at {len}: -x"); + let pt = run_ok(&args(&xts(cmd, "decrypt", key, TWEAK, len)), &ct); + assert_eq!(pt, data, "{cmd} at {len}: decrypt"); +} + +#[test] +fn the_commands_agree_with_the_library_at_every_data_unit_length() { + for len in [512, 1024, 2048, 4096] { + let data = pseudo_random(3 * len, len as u32); + let expected = match len { + 512 => library_128::<512>(KEY32, TWEAK, &data, true), + 1024 => library_128::<1024>(KEY32, TWEAK, &data, true), + 2048 => library_128::<2048>(KEY32, TWEAK, &data, true), + _ => library_128::<4096>(KEY32, TWEAK, &data, true), + }; + agrees("aes128-xts", KEY32, len, &data, &expected); + } + for len in [512, 4096] { + let data = pseudo_random(3 * len, len as u32 + 1); + let expected = match len { + 512 => library_256::<512>(KEY64, TWEAK, &data, true), + _ => library_256::<4096>(KEY64, TWEAK, &data, true), + }; + agrees("aes256-xts", KEY64, len, &data, &expected); + assert_eq!( + match len { + 512 => library_256::<512>(KEY64, TWEAK, &expected, false), + _ => library_256::<4096>(KEY64, TWEAK, &expected, false), + }, + data + ); + } +} + +/// A 512-byte data unit whose byte k is k mod 251, under the key 01 02 .. and `TWEAK`, against +/// OpenSSL 3.5.0: the first block and the last 32 bytes of the known answers in +/// `crypto/aes/tests/xts_tests.rs`, through the commands. +#[test] +fn an_openssl_known_answer_through_the_commands() { + let pt: Vec = (0..512).map(|k| (k % 251) as u8).collect(); + let key_128: String = (1..=32u8).map(|b| format!("{b:02x}")).collect(); + let key_256: String = (1..=64u8).map(|b| format!("{b:02x}")).collect(); + + let ct = run_ok(&args(&xts("aes128-xts", "encrypt", &key_128, TWEAK, 512)), &pt); + assert_eq!(ct[..16], unhex("b9606f8b4bcb9a6990a511c8e0b07aa6")); + assert_eq!( + ct[480..], + unhex("f47d6467859b134958f1504d4f19524687d16d4fe39d8f3c3c812695dcfbd91e") + ); + assert_eq!(run_ok(&args(&xts("aes128-xts", "decrypt", &key_128, TWEAK, 512)), &ct), pt); + + let ct = run_ok(&args(&xts("aes256-xts", "encrypt", &key_256, TWEAK, 512)), &pt); + assert_eq!(ct[..16], unhex("965c8f85ac79930ac1e8b46eb069dbe9")); + assert_eq!( + ct[480..], + unhex("61102f0e9dbdcdd4821d60f2b3ea839cff6330cee358a6b8e3d8376df070295e") + ); + assert_eq!(run_ok(&args(&xts("aes256-xts", "decrypt", &key_256, TWEAK, 512)), &ct), pt); +} + +/// The second data unit is processed under the first one's tweak plus one, as a little-endian +/// integer: from 255 (`ff 00 ..`) to 256 (`00 01 00 ..`), a carry into the second byte. +#[test] +fn consecutive_data_units_take_consecutive_tweaks() { + let data = pseudo_random(2 * 512, 7); + let both = run_ok( + &args(&xts("aes128-xts", "encrypt", KEY32, "ff000000000000000000000000000000", 512)), + &data, + ); + let second = run_ok( + &args(&xts("aes128-xts", "encrypt", KEY32, "00010000000000000000000000000000", 512)), + &data[512..], + ); + assert_eq!(both[512..], second[..]); + assert_eq!(both, library_128::<512>(KEY32, "ff000000000000000000000000000000", &data, true)); +} + +/// Input that is not a whole number of data units is refused; the whole ones before the +/// remainder have already been written, as the command streams. +#[test] +fn the_input_must_be_a_whole_number_of_data_units() { + let out = run(&args(&xts("aes128-xts", "encrypt", KEY32, TWEAK, 512)), &[0x42; 512 + 100]); + assert!(!out.status.success()); + assert_eq!(out.stdout.len(), 512, "the first data unit is written before the refusal"); + let err = String::from_utf8_lossy(&out.stderr); + assert!(err.contains("whole number of 512-byte data units"), "stderr: {err}"); + assert!(err.contains("100 trailing byte(s)"), "stderr: {err}"); + + let err = run_err_silent(&args(&xts("aes256-xts", "decrypt", KEY64, TWEAK, 4096)), &[1; 15]); + assert!(err.contains("whole number of 4096-byte data units"), "stderr: {err}"); + + // No input is no data units: nothing to do, and nothing written. + assert!(run_ok(&args(&xts("aes128-xts", "encrypt", KEY32, TWEAK, 512)), &[]).is_empty()); +} + +/// The tweak is not allowed to wrap from 2^128 - 1 to 0, where it could repeat one in use. +#[test] +fn the_tweak_does_not_wrap() { + let out = run( + &args(&xts("aes128-xts", "encrypt", KEY32, "ffffffffffffffffffffffffffffffff", 512)), + &[0x42; 2 * 512], + ); + assert!(!out.status.success()); + assert_eq!(out.stdout.len(), 512, "the first data unit is written before the refusal"); + assert!(String::from_utf8_lossy(&out.stderr).contains("cannot go past 2^128 - 1")); +} + +/// A wrong key length, equal key halves, a malformed tweak and an unsupported data-unit length +/// are all refused before anything is written. +#[test] +fn bad_arguments_are_refused() { + let short_key = &KEY32[..62]; + let equal_halves = "00112233445566778899aabbccddeeff00112233445566778899aabbccddeeff"; + let cases: [(&str, &str, &str, usize, &str); 6] = [ + ("aes128-xts", short_key, TWEAK, 512, "needs a 32-byte key"), + ("aes256-xts", KEY32, TWEAK, 512, "needs a 64-byte key"), + ("aes128-xts", equal_halves, TWEAK, 512, "Key_1 != Key_2"), + ("aes128-xts", KEY32, &TWEAK[..30], 512, "the tweak is 15 bytes"), + ("aes128-xts", KEY32, "not hex", 512, "`--tweak` must be hex"), + ("aes256-xts", KEY64, TWEAK, 1000, "--data-unit-len must be 512, 1024, 2048 or 4096"), + ]; + for (cmd, key, tweak, len, msg) in cases { + let err = run_err_silent(&args(&xts(cmd, "encrypt", key, tweak, len)), &[0x42; 512]); + assert!(err.contains(msg), "{cmd} {key} {tweak} {len}: stderr was: {err}"); + } +} + +#[test] +fn the_commands_are_listed_in_help() { + listed_in_help(&["aes128-xts", "aes256-xts"]); +} diff --git a/crypto/aes/Cargo.toml b/crypto/aes/Cargo.toml index 893378e7f..017491797 100644 --- a/crypto/aes/Cargo.toml +++ b/crypto/aes/Cargo.toml @@ -26,3 +26,7 @@ harness = false [[bench]] name = "aes_gcm_packet_benches" harness = false + +[[bench]] +name = "aes_xts_benches" +harness = false diff --git a/crypto/aes/benches/aes_xts_benches.rs b/crypto/aes/benches/aes_xts_benches.rs new file mode 100644 index 000000000..3cb2f0df9 --- /dev/null +++ b/crypto/aes/benches/aes_xts_benches.rs @@ -0,0 +1,110 @@ +//! Criterion benchmarks for XTS-AES: one data unit encrypted and decrypted in place, at both key +//! sizes, for a one-block data unit, a 512-byte and a 4 KiB sector, a 64 KiB data unit, and a +//! 4 KiB one a byte short, whose last two blocks are ciphertext-stolen; and key setup. +//! +//! Given their masks, XTS's blocks are independent, so both directions hand the permutation four +//! blocks at a time and should run at close to ECB's throughput in `aes_modes_benches`. What XTS +//! adds is the encryption of the tweak, once per data unit, and a multiplication by α per block, +//! so the one-block figure is the per-data-unit overhead and the larger ones the per-block cost. +//! Decryption runs the inverse cipher, which is slower than the forward one on the bit-sliced AES. +//! +//! The cipher works in place, so each measurement runs on a fresh copy of the data unit made in +//! criterion's untimed setup (`iter_batched`); the copy is not part of the timing. + +use bouncycastle_aes::hazmat::{AES128Internal, AES256Internal}; +use bouncycastle_aes::{XTS_AES_128, XTS_AES_256}; +use bouncycastle_cipher::modes::XTSKey; +use bouncycastle_core::hazmat::BlockPermutation; +use bouncycastle_core::key_material::{KeyMaterial, KeyType}; +use bouncycastle_core::symmetric_key::FromKeyMaterial; +use criterion::measurement::WallTime; +use criterion::{ + BatchSize, BenchmarkGroup, Criterion, Throughput, criterion_group, criterion_main, +}; +use std::hint::black_box; + +const TWEAK: [u8; 16] = [0x5a; 16]; + +/// `Key_1 | Key_2`, with distinct, non-zero halves. +fn key() -> KeyMaterial { + let bytes: [u8; N] = core::array::from_fn(|i| (i as u8).wrapping_mul(7).wrapping_add(1)); + KeyMaterial::::from_bytes_as_type(&bytes, KeyType::SymmetricCipherKey).unwrap() +} + +/// Encryption and decryption of one `N`-byte data unit, reported as `label`. +fn data_unit( + group: &mut BenchmarkGroup<'_, WallTime>, + label: &str, +) where + P: BlockPermutation<16>, + XTSKey: FromKeyMaterial, +{ + let key = XTSKey::::from_key_material(&key::()).unwrap(); + let plaintext: Box<[u8; N]> = (0..N) + .map(|i| (i as u8).wrapping_mul(31)) + .collect::>() + .into_boxed_slice() + .try_into() + .unwrap(); + let mut ciphertext = plaintext.clone(); + key.encrypt_inplace(&TWEAK, &mut ciphertext); + + group.throughput(Throughput::Bytes(N as u64)); + group.bench_function(format!("encrypt {label}"), |b| { + b.iter_batched( + || plaintext.clone(), + |mut unit| { + key.encrypt_inplace(black_box(&TWEAK), &mut unit); + black_box(&unit); + }, + BatchSize::SmallInput, + ) + }); + group.bench_function(format!("decrypt {label}"), |b| { + b.iter_batched( + || ciphertext.clone(), + |mut unit| { + key.decrypt_inplace(black_box(&TWEAK), &mut unit); + black_box(&unit); + }, + BatchSize::SmallInput, + ) + }); +} + +fn bench_xts_aes_128(c: &mut Criterion) { + let mut group = c.benchmark_group("modes::xts::XTS_AES_128"); + data_unit::(&mut group, "16B (one block)"); + data_unit::(&mut group, "512B sector"); + data_unit::(&mut group, "4KiB sector"); + data_unit::(&mut group, "4095B (ciphertext stealing)"); + data_unit::(&mut group, "64KiB"); + group.finish(); +} + +fn bench_xts_aes_256(c: &mut Criterion) { + let mut group = c.benchmark_group("modes::xts::XTS_AES_256"); + data_unit::(&mut group, "16B (one block)"); + data_unit::(&mut group, "512B sector"); + data_unit::(&mut group, "4KiB sector"); + data_unit::(&mut group, "4095B (ciphertext stealing)"); + data_unit::(&mut group, "64KiB"); + group.finish(); +} + +/// Key setup: splitting `Key_1 | Key_2` and expanding two AES schedules, paid once per key. +fn bench_xts_init(c: &mut Criterion) { + let mut group = c.benchmark_group("modes::xts::init"); + let material_128 = key::<32>(); + let material_256 = key::<64>(); + group.bench_function("XTS_AES_128 from_key_material (two key schedules)", |b| { + b.iter(|| black_box(XTS_AES_128::<4096>::from_key_material(black_box(&material_128)))) + }); + group.bench_function("XTS_AES_256 from_key_material (two key schedules)", |b| { + b.iter(|| black_box(XTS_AES_256::<4096>::from_key_material(black_box(&material_256)))) + }); + group.finish(); +} + +criterion_group!(benches, bench_xts_aes_128, bench_xts_aes_256, bench_xts_init); +criterion_main!(benches); diff --git a/crypto/aes/src/lib.rs b/crypto/aes/src/lib.rs index d475d64a2..24e49d077 100644 --- a/crypto/aes/src/lib.rs +++ b/crypto/aes/src/lib.rs @@ -24,6 +24,7 @@ //! * [`AES_GCM_128`] //! * [`AES_GMAC_128`], a nonce-based MAC rather than a cipher //! * [`AES_KW_128`] and [`AES_KWP_128`], key wraps rather than ciphers +//! * [`XTS_AES_128`], for storage: one data unit at a time, in place, under a tweak //! //! Each mode is used through a mode-bound key object such as [`AES256Key`](AES256Key), //! which validates and expands the material once and hands out the mode's encryptors and @@ -72,9 +73,9 @@ //! The ratios hold for all three key lengths to within a few percent; in absolute terms AES-128 //! single-block encryption is about 240 us per 16 KiB and decryption about 330 us. That multiplier //! is what the modes of operation batch through wherever their blocks are independent: both -//! directions of ECB and CTR (and so GCM's CTR half), and the decryption direction of CBC, CFB and -//! CFB8. CBC and CFB *encryption* cannot, because each forward cipher input depends on the previous -//! output (SP 800-38A Sec 6.2 and 6.3), so those two paths run one block at a time. +//! directions of ECB, CTR (and so GCM's CTR half) and XTS, and the decryption direction of CBC, +//! CFB and CFB8. CBC and CFB *encryption* cannot, because each forward cipher input depends on +//! the previous output (SP 800-38A Sec 6.2 and 6.3), so those two paths run one block at a time. //! //! SHIFTROWS() and MIXCOLUMNS() become masks and rotations in the same representation, and the //! key schedule is stored bit-sliced too, so no transposition happens inside the round loop. The @@ -198,6 +199,7 @@ mod kw; mod round; mod sbox; mod schedule; +mod xts; use bouncycastle_utils::secret::{NoPadding, ZeroizablePrimitive}; @@ -285,3 +287,4 @@ pub use gcm::{AES_GCM_128, AES_GCM_192, AES_GCM_256, GCM_NONCE_LEN}; pub use gmac::{AES_GMAC_128, AES_GMAC_192, AES_GMAC_256}; pub use key::{AES128Key, AES192Key, AES256Key}; pub use kw::{AES_KW_128, AES_KW_192, AES_KW_256, AES_KWP_128, AES_KWP_192, AES_KWP_256}; +pub use xts::{XTS_AES_128, XTS_AES_256}; diff --git a/crypto/aes/src/xts.rs b/crypto/aes/src/xts.rs new file mode 100644 index 000000000..6505134bb --- /dev/null +++ b/crypto/aes/src/xts.rs @@ -0,0 +1,91 @@ +//! Type aliases for XTS-AES (NIST SP 800-38E; IEEE Std 1619-2007). The docs are on +//! [`XTS_AES_128`], which the crate root re-exports. + +use crate::hazmat::{AES128Internal, AES256Internal}; +use bouncycastle_cipher::modes::XTSKey; + +/// XTS-AES-128 (NIST SP 800-38E; IEEE Std 1619-2007) for data units of exactly `DATA_UNIT_LEN` +/// bytes: a 256-bit key `Key_1 | Key_2`, each half an AES-128 key, `Key_1` for the data and +/// `Key_2` for the tweak. +/// +/// It is the key object of [`bouncycastle_cipher::modes::xts`], which describes the tweak and the +/// security considerations; read those before using XTS, which is unauthenticated and meant for +/// storage. The key is built once with [`FromKeyMaterial`] and encrypts and decrypts one data +/// unit at a time, in place: [`encrypt_inplace`](XTSKey::encrypt_inplace) and +/// [`decrypt_inplace`](XTSKey::decrypt_inplace). A data unit is from 16 bytes to 2^20 blocks, +/// and a length outside that range does not compile. SP 800-38E approves XTS with these two key +/// sizes only, so there is no XTS-AES-192. +/// +/// # Usage Examples +/// +/// NIST's ACVP sample vector ACVP-AES-XTS-2.0 tcId 125, a 23-byte data unit -- one block and +/// seven bytes, so the last two blocks are ciphertext-stolen -- under sequence number 202: +/// +/// ``` +/// use bouncycastle_aes::XTS_AES_128; +/// use bouncycastle_core::key_material::{KeyMaterial, KeyType}; +/// use bouncycastle_core::symmetric_key::FromKeyMaterial; +/// +/// let key_bytes = [ +/// 0xc3, 0xd3, 0xdc, 0x0b, 0x7a, 0x34, 0x5c, 0xcf, 0xe4, 0x8b, 0x23, 0x20, 0x75, 0xe4, +/// 0x72, 0x99, 0xeb, 0xf1, 0x1e, 0x5c, 0x40, 0xe1, 0xbf, 0xe4, 0x2a, 0xcf, 0x96, 0xe1, +/// 0x84, 0x0b, 0x73, 0x53, +/// ]; +/// let material = KeyMaterial::<32>::from_bytes_as_type(&key_bytes, KeyType::SymmetricCipherKey) +/// .expect("a 32-byte symmetric cipher key"); +/// let key = XTS_AES_128::<23>::from_key_material(&material).expect("a valid XTS-AES-128 key"); +/// +/// let plaintext = [ +/// 0xea, 0xfd, 0xbd, 0x33, 0x05, 0x11, 0xba, 0xa1, 0xc9, 0x12, 0xea, 0x24, 0xb7, 0xb1, +/// 0x30, 0x35, 0x07, 0xab, 0x3a, 0xab, 0xe6, 0x62, 0x1c, +/// ]; +/// // The tweak is the sequence number as a 128-bit little-endian integer. +/// let tweak = 202u128.to_le_bytes(); +/// +/// let mut data_unit = plaintext; +/// assert_eq!(key.encrypt_inplace(&tweak, &mut data_unit), 23); +/// assert_eq!( +/// data_unit, +/// [ +/// 0xb0, 0xc6, 0x8b, 0x8a, 0x8c, 0x23, 0x0a, 0x35, 0x67, 0x63, 0x38, 0x54, 0x6d, 0x36, +/// 0x1e, 0x15, 0x17, 0x8b, 0x8c, 0xc3, 0x42, 0x6e, 0x31, +/// ] +/// ); +/// key.decrypt_inplace(&tweak, &mut data_unit); +/// assert_eq!(data_unit, plaintext); +/// ``` +/// +/// A run of 4096-byte sectors under a fresh XTS-AES-256 key, each under its own sequence number: +/// +/// ``` +/// use bouncycastle_aes::XTS_AES_256; +/// use bouncycastle_core::symmetric_key::FromKeyMaterial; +/// use bouncycastle_rng::HashDRBG_SHA512; +/// +/// let mut rng = HashDRBG_SHA512::new_from_os(); +/// let key = XTS_AES_256::<4096>::generate(&mut rng).expect("a 256-bit RNG"); +/// +/// let mut disk = vec![0u8; 8 * 4096]; +/// let (sectors, rest) = disk.as_chunks_mut::<4096>(); +/// assert!(rest.is_empty()); +/// for (n, sector) in (100u128..).zip(sectors.iter_mut()) { +/// key.encrypt_inplace(&n.to_le_bytes(), sector); +/// } +/// // Equal plaintext sectors, under different sequence numbers, encrypt differently. +/// assert_ne!(sectors[0], sectors[1]); +/// ``` +/// +/// # Memory Usage +/// +/// A key is two AES schedules: 352 bytes for XTS-AES-128 and 480 for XTS-AES-256. A call works in +/// the caller's buffer; beside the permutation's own frame it keeps the tweak's mask and the +/// masks of the four blocks in flight on the stack. +/// +/// [`FromKeyMaterial`]: bouncycastle_core::symmetric_key::FromKeyMaterial +#[allow(non_camel_case_types)] +pub type XTS_AES_128 = XTSKey; + +/// XTS-AES-256 (NIST SP 800-38E; IEEE Std 1619-2007) for data units of exactly `DATA_UNIT_LEN` +/// bytes: a 512-bit key `Key_1 | Key_2`, each half an AES-256 key. See [`XTS_AES_128`]. +#[allow(non_camel_case_types)] +pub type XTS_AES_256 = XTSKey; diff --git a/crypto/aes/tests/xts_acvp_tests.rs b/crypto/aes/tests/xts_acvp_tests.rs new file mode 100644 index 000000000..2e06f38d2 --- /dev/null +++ b/crypto/aes/tests/xts_acvp_tests.rs @@ -0,0 +1,747 @@ +//! XTS-AES-128 and XTS-AES-256 against NIST's ACVP sample vectors. +//! +//! The vectors are copied from the `internalProjection.json` of `ACVP-AES-XTS-1.0` and +//! `ACVP-AES-XTS-2.0` in NIST's ACVP-Server repository (`gen-val/json-files`, commit `975de31e`), +//! whose expected values come from NIST's reference implementation; each was also reproduced with +//! OpenSSL when it was copied. bc-test-data has no AES-XTS set, so a subset is embedded here: +//! every whole-byte `ACVP-AES-XTS-2.0` vector of at most 128 bytes -- ciphertext stealing with +//! tails of most lengths, both directions and both tweak modes -- and the shortest of 129 to 700 +//! bytes for each key size, direction and tweak mode that has one. (An ACVP data unit can be any +//! number of bits; this API takes whole bytes.) +//! +//! Each vector is checked in both directions, whichever one it was generated for. A vector of +//! tweak mode "number" gives the data unit's sequence number as well as the tweak, and the check +//! confirms that the tweak is the number's 128-bit little-endian encoding before using it. + +use bouncycastle_aes::hazmat::{AES128Internal, AES256Internal}; +use bouncycastle_cipher::modes::XTSKey; +use bouncycastle_core::hazmat::BlockPermutation; +use bouncycastle_core::key_material::{KeyMaterial, KeyType}; +use bouncycastle_core::symmetric_key::FromKeyMaterial; +use bouncycastle_hex as hex; + +/// One ACVP test case, as hex. +struct Vector { + /// The revision, `tgId` and `tcId` it was copied from. + source: &'static str, + key: &'static str, + /// The 128-bit tweak value, `tweakValue`. + tweak: &'static str, + /// `sequenceNumber`, for tweak mode "number". + sequence_number: Option, + pt: &'static str, + ct: &'static str, +} + +/// Checks `v` through `XTSKey` under its `KEY_LEN`-byte key, in both directions. +fn check(v: &Vector) +where + P: BlockPermutation<16>, + XTSKey: FromKeyMaterial, +{ + let material = KeyMaterial::::from_bytes_as_type( + &hex::decode(v.key).unwrap(), + KeyType::SymmetricCipherKey, + ) + .unwrap(); + let key = XTSKey::::from_key_material(&material) + .unwrap_or_else(|e| panic!("{}: the key is refused: {e:?}", v.source)); + + let tweak: [u8; 16] = hex::decode(v.tweak).unwrap().try_into().unwrap(); + if let Some(n) = v.sequence_number { + assert_eq!(n.to_le_bytes(), tweak, "{}: the tweak is the sequence number, LE", v.source); + } + let pt: [u8; N] = hex::decode(v.pt).unwrap().try_into().expect("an N-byte plaintext"); + let ct: [u8; N] = hex::decode(v.ct).unwrap().try_into().expect("an N-byte ciphertext"); + + let mut data_unit = pt; + assert_eq!(key.encrypt_inplace(&tweak, &mut data_unit), N, "{}", v.source); + assert_eq!(data_unit, ct, "{}: encryption", v.source); + + let mut data_unit = ct; + assert_eq!(key.decrypt_inplace(&tweak, &mut data_unit), N, "{}", v.source); + assert_eq!(data_unit, pt, "{}: decryption", v.source); +} + +#[test] +fn acvp_xts_aes_128() { + check::(&V2_TG1_TC4); + check::(&V2_TG3_TC131); + check::(&V2_TG9_TC444); + check::(&V2_TG11_TC535); + check::(&V2_TG3_TC125); + check::(&V2_TG11_TC503); + check::(&V2_TG11_TC516); + check::(&V2_TG3_TC139); + check::(&V2_TG3_TC101); + check::(&V2_TG1_TC13); + check::(&V2_TG1_TC38); + check::(&V2_TG11_TC525); + check::(&V2_TG1_TC36); + check::(&V2_TG11_TC502); + check::(&V2_TG11_TC548); + check::(&V2_TG3_TC144); + check::(&V2_TG9_TC412); + check::(&V2_TG9_TC433); + check::(&V2_TG11_TC508); + check::(&V2_TG9_TC441); + check::(&V2_TG3_TC127); + check::(&V2_TG1_TC18); +} + +#[test] +fn acvp_xts_aes_256() { + check::(&V1_TG11_TC101); + check::(&V1_TG18_TC171); + check::(&V2_TG5_TC233); + check::(&V2_TG7_TC319); + check::(&V2_TG13_TC642); + check::(&V2_TG15_TC719); + check::(&V2_TG15_TC702); + check::(&V2_TG5_TC237); + check::(&V2_TG15_TC737); + check::(&V2_TG13_TC603); + check::(&V2_TG13_TC640); + check::(&V2_TG13_TC649); + check::(&V2_TG5_TC230); + check::(&V2_TG15_TC717); + check::(&V2_TG13_TC641); + check::(&V2_TG13_TC644); + check::(&V2_TG15_TC712); + check::(&V2_TG7_TC305); + check::(&V2_TG13_TC646); +} + +// ---- the vectors ---- + +/// ACVP-AES-XTS-2.0 tgId 1 tcId 4: AES-128, encrypt, tweakMode hex, 16 bytes. +const V2_TG1_TC4: Vector = Vector { + source: "ACVP-AES-XTS-2.0 tgId 1 tcId 4", + key: "8acb99d1d215612314d6b262147343f23f1b1e8f34f1dcbd6d57200fae54e8c4", + tweak: "bf0d3404d7bce2b4132d02e90a256ebf", + sequence_number: None, + pt: "ea29098cb827a1de9d69f5b47a500c34", + ct: "7a4cc60de7997471aab765348f08d935", +}; + +/// ACVP-AES-XTS-2.0 tgId 3 tcId 131: AES-128, encrypt, tweakMode number, 16 bytes. +const V2_TG3_TC131: Vector = Vector { + source: "ACVP-AES-XTS-2.0 tgId 3 tcId 131", + key: "852d1f431ecedb3434b856b664b97a319fb70ae546b0a8b359edcc7b00fa0b45", + tweak: "4d000000000000000000000000000000", + sequence_number: Some(77), + pt: "0625bd766ef28555c68ac0a200347f55", + ct: "3ae27f24b6c9ebf7b13d9709c18d1769", +}; + +/// ACVP-AES-XTS-2.0 tgId 9 tcId 444: AES-128, decrypt, tweakMode hex, 16 bytes. +const V2_TG9_TC444: Vector = Vector { + source: "ACVP-AES-XTS-2.0 tgId 9 tcId 444", + key: "ad17809726942ffde1060dd99de05415906c3ea6647ae52d8dbea10238341580", + tweak: "7daa90322aa35fd658cd72f818159f2b", + sequence_number: None, + pt: "a5fdabb4e63926bf33bebfc73e01c05b", + ct: "dc6929d5f7a1c1bb50f5ad10d0ed94fa", +}; + +/// ACVP-AES-XTS-2.0 tgId 11 tcId 535: AES-128, decrypt, tweakMode number, 16 bytes. +const V2_TG11_TC535: Vector = Vector { + source: "ACVP-AES-XTS-2.0 tgId 11 tcId 535", + key: "6aa59d12e31dc3850e22d0ea0641f47478779bd5b8f0dc4b0a0e49e05e7ac055", + tweak: "a9000000000000000000000000000000", + sequence_number: Some(169), + pt: "8732826aad287e864070694a0af4255a", + ct: "1242abfca4a5041936ea5a55c810c7e2", +}; + +/// ACVP-AES-XTS-2.0 tgId 3 tcId 125: AES-128, encrypt, tweakMode number, 23 bytes (b = 7). +const V2_TG3_TC125: Vector = Vector { + source: "ACVP-AES-XTS-2.0 tgId 3 tcId 125", + key: "c3d3dc0b7a345ccfe48b232075e47299ebf11e5c40e1bfe42acf96e1840b7353", + tweak: "ca000000000000000000000000000000", + sequence_number: Some(202), + pt: "eafdbd330511baa1c912ea24b7b1303507ab3aabe6621c", + ct: "b0c68b8a8c230a35676338546d361e15178b8cc3426e31", +}; + +/// ACVP-AES-XTS-2.0 tgId 11 tcId 503: AES-128, decrypt, tweakMode number, 29 bytes (b = 13). +const V2_TG11_TC503: Vector = Vector { + source: "ACVP-AES-XTS-2.0 tgId 11 tcId 503", + key: "0e00f2017e1fba4bd287e57b95d197e57bd0e7253be250b31380426cdd19dde5", + tweak: "d0000000000000000000000000000000", + sequence_number: Some(208), + pt: "0df94f3f3eb892dbfad8fa149d5e275af6e81e0f9578861668354385a6", + ct: "7b3af90fb25385a545804d183a624931d1b02aeb5654f2070fa55503c5", +}; + +/// ACVP-AES-XTS-2.0 tgId 11 tcId 516: AES-128, decrypt, tweakMode number, 46 bytes (b = 14). +const V2_TG11_TC516: Vector = Vector { + source: "ACVP-AES-XTS-2.0 tgId 11 tcId 516", + key: "8e52f6fd062d7c3dca35e3959e0b1d397af6ceedcc8a833c807a6da14c108e8f", + tweak: "5c000000000000000000000000000000", + sequence_number: Some(92), + pt: "\ + 72bbecdcac5b9913780ac9d439bbdbc46367f61cb3d6f0b0dcb100a2e33a4189ff812cccb7af572d0b183752\ + 9f79", + ct: "\ + 18aea17a4d782407848151529c59fa54a35a413fa9b9352fcd43752a3400bf1c8780ee9860c094bc3577a702\ + ba50", +}; + +/// ACVP-AES-XTS-2.0 tgId 3 tcId 139: AES-128, encrypt, tweakMode number, 48 bytes. +const V2_TG3_TC139: Vector = Vector { + source: "ACVP-AES-XTS-2.0 tgId 3 tcId 139", + key: "b45cf630863a2e65ca84e55e4cdd7d14c3ca25f86a4aed34fd35cee38c859aeb", + tweak: "5f000000000000000000000000000000", + sequence_number: Some(95), + pt: "\ + b6c799f91fc6c3b84092b1993f28f5ca743f7577b69a464d5516f74af26ef87b1e258641a8f2533941dc93b0\ + 97424bf4", + ct: "\ + d892c20885d33a10ad528b4a6022ce5d60b7ce3e77a99bd21bd267d7a6da43123e4ea8f10ebed953c4c735dd\ + 5b1ee7b7", +}; + +/// ACVP-AES-XTS-2.0 tgId 3 tcId 101: AES-128, encrypt, tweakMode number, 56 bytes (b = 8). +const V2_TG3_TC101: Vector = Vector { + source: "ACVP-AES-XTS-2.0 tgId 3 tcId 101", + key: "4d283fa6573813ebbb3e2ecc03013416972c53c40249fbb4fc582e0005fe58bb", + tweak: "f5000000000000000000000000000000", + sequence_number: Some(245), + pt: "\ + 2dc07c5d016cdfaf10dd3698a0583d659e897452b3e314c985401336e824c9f2d6ce254066d2a00b7f06a716\ + 1280f50f8f1725cef02e8a52", + ct: "\ + b80a9187ab9638477dfb6a4c4a759b361cb2b496e9ea882d684cf9d231e43d37e91f5fba1798f84b45ba9c85\ + 61e71be17cbe3465b72ec3b7", +}; + +/// ACVP-AES-XTS-2.0 tgId 1 tcId 13: AES-128, encrypt, tweakMode hex, 62 bytes (b = 14). +const V2_TG1_TC13: Vector = Vector { + source: "ACVP-AES-XTS-2.0 tgId 1 tcId 13", + key: "6fa0ae27860cb658b40a3d95666954442e418ee3e4565657dd08edc69e20e5d2", + tweak: "c7c71ac8a3f858145b9ba0e658491af7", + sequence_number: None, + pt: "\ + 316f416dd8828155aafe1efa50361d48613e073e1b4b66b00d86a908626157d3058dcb83b1b6833580aa2f4a\ + 0663de87115027f5f4eb60fcf2f2235bb801", + ct: "\ + 74fccb3c6fa20bae9d1fba9525519a5aebb0bd4f2803a40c4ec0d80fbe3d5ecf53ea3d8c7456d23b4fd7772c\ + 4bc44b06c0c7a533e53747a4cb94927d4572", +}; + +/// ACVP-AES-XTS-2.0 tgId 1 tcId 38: AES-128, encrypt, tweakMode hex, 64 bytes. +const V2_TG1_TC38: Vector = Vector { + source: "ACVP-AES-XTS-2.0 tgId 1 tcId 38", + key: "4e202f28cdc52b4652cb8a58aa7333ce3a64d343098f278d7e88125b58605d7e", + tweak: "530d55c0b4d4a7c7041a5cc2af8ceae9", + sequence_number: None, + pt: "\ + d01a71806151bb27515e4fdc62264f1675b5220c0bbb03bfa1917989ed7ca5a2a8ec7ffa8aa8835c71deff0c\ + 4ec81ef812ffd8fe02056b5014fb29e5ae2d0650", + ct: "\ + dd50d20ed7b5d4a9083d0b8410aa8392f627a41a765c7436bf3cce3feede6a4e0c2ea4053701f532d43ac7e6\ + 04703f13d7cc2b9258eb1db12ab6e29ba5cd7fd8", +}; + +/// ACVP-AES-XTS-2.0 tgId 11 tcId 525: AES-128, decrypt, tweakMode number, 75 bytes (b = 11). +const V2_TG11_TC525: Vector = Vector { + source: "ACVP-AES-XTS-2.0 tgId 11 tcId 525", + key: "88cfdd08e11ea2981cd342080a7770300effbd1e0b2738562f060bffacbd9af7", + tweak: "d8000000000000000000000000000000", + sequence_number: Some(216), + pt: "\ + 42e0b4f015fdb8e0c9f1339a5ec6c940cb3e4f84088e2d05e966d457e3eb7bd96dce0ff96b4c0e9aeb3cbf00\ + 35c0c66b3b2ba29d0a7ba98c8ef9cdadbc04f558368d2bfed49fc7af696b8b", + ct: "\ + 103672952d6947df8aee1cf3779a536ce5620efe4f9e01fa650b7129fd2c8638c7b9a25de456921dfe0cbc0c\ + 219d61a12f092b33f661b0b29357ebc08645eb46fb3e91d83b827611950460", +}; + +/// ACVP-AES-XTS-2.0 tgId 1 tcId 36: AES-128, encrypt, tweakMode hex, 86 bytes (b = 6). +const V2_TG1_TC36: Vector = Vector { + source: "ACVP-AES-XTS-2.0 tgId 1 tcId 36", + key: "a1e04e9180658a01af0882bf5319a88a097e43aa00c9140abbebade5fe63eea8", + tweak: "4fdb844b178e00df69c41096b076b231", + sequence_number: None, + pt: "\ + 90b44113367f8b928685152b98bccb17a90efa9f1e42e5e3f385100cf71087c4331a7b1f305299031e61ede6\ + ad088fcbf7a4f5852722c30cd37265cf82aaf4736cc2332888c3bb9f9321c2e14eb856595592b6eb83f3", + ct: "\ + 1561acd6c5f0052a9241049416bebf907971c31c6724b2891495b03d93f308a4e37406db648469eff0bd1a4b\ + f0b6ea66781e5b513e942b7d259742c0692b21feb025affeb65230fdaca4f3ad4bba7ef53ff198adfe5b", +}; + +/// ACVP-AES-XTS-2.0 tgId 11 tcId 502: AES-128, decrypt, tweakMode number, 92 bytes (b = 12). +const V2_TG11_TC502: Vector = Vector { + source: "ACVP-AES-XTS-2.0 tgId 11 tcId 502", + key: "0692f81900c50b2171aa24a718b8cc0e29d723c7e9d0b0c7ca490b0abba4eaa7", + tweak: "cc000000000000000000000000000000", + sequence_number: Some(204), + pt: "\ + 7d4230b7fae49be48c71a98bbb2224b44650d0492739a200f0dd1ad71f18636c5cbcf35075f5d16f61a39e69\ + 2e5eaf82cfce4b62245b2289112947380bc64e3c687901dabb2a99973bbdef14549b31f9c43b5d13f03dfc0a\ + fc17c675", + ct: "\ + 8c010cb5f0f4dec68df4b6bffe9d5dbb08fca75bd7fe411248e80dde8c9816286922457674d50bd032fbc52b\ + e2f9b0d72897a2d2cd54c9d177808afbc411c1532099b8ae758653abce74afa1d0b993d3e4d1f04deb37c221\ + d1bafcc7", +}; + +/// ACVP-AES-XTS-2.0 tgId 11 tcId 548: AES-128, decrypt, tweakMode number, 93 bytes (b = 13). +const V2_TG11_TC548: Vector = Vector { + source: "ACVP-AES-XTS-2.0 tgId 11 tcId 548", + key: "d169f425fb98179f9b6a0c72ee490c36f9ba04a5cc59fc71f292e2ebeea3e60d", + tweak: "f5000000000000000000000000000000", + sequence_number: Some(245), + pt: "\ + 32c873f28118bd7141869f15dd1632cb2b9916e508230dd8ede7928b78aaa92d4c7a49492f8d442f881d6b5c\ + b8b439157a1481ca12b14e1732ee1f7b4ae94a599c7662d5b1093aa53a9b0a1185164ff87ed47f2cd35c710a\ + 45e7948af6", + ct: "\ + 2c6926de92a4c7e0b6d91ac808618808c2b0f6133da310f74886c9c378cd79b63215d47751cee7f0ce4149dc\ + 5044f8bc555ab8675a182300e077ad79949621ffb66b0c011ede637b18512c60a4f06ef5005e599acd2f213f\ + 16f255b549", +}; + +/// ACVP-AES-XTS-2.0 tgId 3 tcId 144: AES-128, encrypt, tweakMode number, 94 bytes (b = 14). +const V2_TG3_TC144: Vector = Vector { + source: "ACVP-AES-XTS-2.0 tgId 3 tcId 144", + key: "02f67f1a707e9ccb6208263996a6a3f2ede1d9357cb1d71fe1e9a0930a7838dc", + tweak: "0a000000000000000000000000000000", + sequence_number: Some(10), + pt: "\ + 54bdbf9e132107e5cab8e3cff0f327fa64f235f9bbdb41c194933b7863668446d8172dbea007e422da9410bd\ + 726cb21d6104f98ebe11f3817b5fa6f844e279db76563ca21188fe5d80f30aaf5cbc203a8c805add42fb9c14\ + ba3e469e6565", + ct: "\ + 37ca552b306aa35d80756b6ab82e5cd3fb72df960e939629eaf6c3465515a1093d6c387b7e3b7aaf37554bff\ + c2aceac8b56d58f302e304e2d0db471733cdbb25911b8f405f50bb114dc29da2638b52ab51d45f013298901f\ + 3cf2a3b580f4", +}; + +/// ACVP-AES-XTS-2.0 tgId 9 tcId 412: AES-128, decrypt, tweakMode hex, 94 bytes (b = 14). +const V2_TG9_TC412: Vector = Vector { + source: "ACVP-AES-XTS-2.0 tgId 9 tcId 412", + key: "274976d0a13779af9de7d91b0c3b56b15be1d2b9771a75850eaa595b732c4e97", + tweak: "f2fc1bf4ee74720ecab2a2e114a777ff", + sequence_number: None, + pt: "\ + 55a9ab8095e2025e007c5229ab6c3c6ac2a4a87558a82e54531f383a67260dac51d5a4d1a0165ea9a9325fb5\ + 98415e3ac9bb86e1cf030439de3342dd211311390ee92f482ba03b64610d5d69fbd173356db3b01a6a16d7f6\ + 0f0ccd6b2151", + ct: "\ + 562c4483eaf6a0c4b6920f63fa80b8240d160d623ecd2b6bcd61c642fb3042ac4ad39bc55f63c768441187a3\ + 8642e6d5ec558bb6d8996bf1f1a3e7b15ee4d63d3595a6e155a57998cce6fbaabe1d0eb4132527d26d7842f1\ + b4f06bd9fc93", +}; + +/// ACVP-AES-XTS-2.0 tgId 9 tcId 433: AES-128, decrypt, tweakMode hex, 100 bytes (b = 4). +const V2_TG9_TC433: Vector = Vector { + source: "ACVP-AES-XTS-2.0 tgId 9 tcId 433", + key: "38a415450a8a52b171ac7a571eb9f8abd96ef5d3f59558c296817d018349fea5", + tweak: "6cc3a5fc6c25df36fc5adb6bc4714b2a", + sequence_number: None, + pt: "\ + c96a17bd3e6c0fc9443c9c3e3ddae29b32ca140236e34b1b544c593fa1c82d4d44f644a639a8a9d4a2f0ffcd\ + 338ca2257cadd6415133e491ba116bf7e3d2fc662e3c3cebc7aa8a2722d16cec871af01c3fbe37420438cafd\ + 607a66b5581065819949fc74", + ct: "\ + 31a976845781c861969b91c5e776b7795c5eb4c2177cd3af296cc6d2ece94d037261cdd533540a8d310c4fc9\ + 45812e5d5469ebd04c7006fe7fa9d9610ff96de665d64716d30ce3472f01331d7b525902cdd6cc5acfb2d9b9\ + 77a1e2169c398f642acb1c9e", +}; + +/// ACVP-AES-XTS-2.0 tgId 11 tcId 508: AES-128, decrypt, tweakMode number, 100 bytes (b = 4). +const V2_TG11_TC508: Vector = Vector { + source: "ACVP-AES-XTS-2.0 tgId 11 tcId 508", + key: "c0c85a32988822fd2f146178cf21c0b417c198f35e621835085e182b0fe9a7c8", + tweak: "49000000000000000000000000000000", + sequence_number: Some(73), + pt: "\ + 01c97075dbca87fdd44086eea98060f526fe7962895cf954e33307fb7813b704dedd05bccb2b98449d52557c\ + 0d709fdcbbdbce58d313c9c1fe3263a05118cb5a4c9956023e05e26055f37d90c3a54e59a8d1a47488134b2b\ + 1e97012ce8cadc0d3a0ae2a9", + ct: "\ + b59cf115c0f380ca04a27d29a58157095721a40fbd5f74b1dd1b251952269fac3e07fa272b17d5bcd05653d2\ + 14f6502e776b52ae95e5cfb0c31c2c96af512057749120f5b0cf75a9d03af58c0f38ce0ab1d56a737e133e5e\ + fcaaf6a0c1a5f7c6e3630be3", +}; + +/// ACVP-AES-XTS-2.0 tgId 9 tcId 441: AES-128, decrypt, tweakMode hex, 119 bytes (b = 7). +const V2_TG9_TC441: Vector = Vector { + source: "ACVP-AES-XTS-2.0 tgId 9 tcId 441", + key: "05b104202f78cb71331bfccefb9bce77977f6bfce3d01e4e167f001fe2c82250", + tweak: "eddca8e9cae2487d4fcc200e6491a790", + sequence_number: None, + pt: "\ + cb872fb2d7596de44cb51bd3d6269d58772c09bd3ce0d294d344f39e9353da555f8d8e4433226c12650a231e\ + d7bfe482ee8c1c3a38ab6394541234edd27e54aab13156d5bee738d2c7cd1c2b362040fe2a94e5912459ec4b\ + 33bc40d320e6a002f0ce816dd1d0cf8281b4c2b102b54e53e3dc11c6b9f384", + ct: "\ + 0cee96da18921858d88cbae9315efd4feb02d687e1b37e9c8c1cb248d1a3fded042d2df8ebb97a6d074caf62\ + 6caa6bc8c7d1c2dfb5277e39e6829492ff1fa588ee27949d27c520ade18caf5fec641e21afb267772cec1598\ + ca54bd0c675cf9b6ac9cc78bcc1a7a2f48efcbcbc0498ea48efceef9d55125", +}; + +/// ACVP-AES-XTS-2.0 tgId 3 tcId 127: AES-128, encrypt, tweakMode number, 126 bytes (b = 14). +const V2_TG3_TC127: Vector = Vector { + source: "ACVP-AES-XTS-2.0 tgId 3 tcId 127", + key: "4c819dce0edea0af7ca2cadc18a6d1213d4d7120ffd01e84114fd2d438678cd9", + tweak: "9a000000000000000000000000000000", + sequence_number: Some(154), + pt: "\ + 94bc929bca0e94c32e603538e39d37aa91d00007cc09dfde1d67dca2a2cf0fb1daae7a4f5162f13e553e2ade\ + af3beceef275a3481967870e0be3febc4ce902583ee474d08b291f3418196e5418eac21b24288ca4284e964f\ + 7e067870960a58c39342c9715711177e19cb97afb60615845495c7a4ad959b0755cbe1a3a739", + ct: "\ + 6456c9ebb196d4bb0a5a1e65c2c9cba208a726ac47365bac7a1fc0bd37d93b667b401ae6abc40b7a6d91be06\ + bf60ba51abb2f398ea93f19e60eec3456b74ee996ded4162525aa14a7962e482eaf80edbe75d2d7b1297be9e\ + 83845d288c6c549675c73bb2f9e1a2b54bdedae3297680189d339926e99884f7b653e72482cb", +}; + +/// ACVP-AES-XTS-2.0 tgId 1 tcId 18: AES-128, encrypt, tweakMode hex, 262 bytes (b = 6). +const V2_TG1_TC18: Vector = Vector { + source: "ACVP-AES-XTS-2.0 tgId 1 tcId 18", + key: "a961fa246936e474bd453ad6d21affa859dae7322bcad53030e82d5506610f54", + tweak: "e2bcc8951a6d4ba8001676fd052998da", + sequence_number: None, + pt: "\ + 1910d9ac563533caeef460ef9d7b902d6b7d5f157eb2eb820d50599d01d3681e34d85263486b25b8ef66e416\ + 4de3808a852e286f7f442d6b7321177ced2330d30aaed21e05165c94ecde5aab1e5ea425cc47c031a773cc07\ + f65779a400129649110374f2084cd1465fcfe24c4c23c3edc6188e846d41d77fa0db6ad75cbc64cf2aa6cee2\ + 4b6a3d5bcc2e737ef26ce3612fd66065e2c1f0e0e5c05c46a79e74d34dd4b82f84f3c3277d71465e22bc3ffd\ + 211275d08fb2a4e3d653d50f91bacc128c953a326a0473a5a6f01786a4c734bbd0ee0174b0006888062334f8\ + 996a1794f8ea25567710ec228626d1f83aab060b4c6e79a94fc4fdb1ecb2425627facc78e85232abd280", + ct: "\ + 52c66c83c4701ac5209861cfb07a978115fafbfc66da33b683fd4560d952dac3dd566efae5d8573b5692820d\ + e4999a0210f9ba4efc843d9cd8f91da5ced139e3d6b83fc4656ab80242926cfca430210139b3872e47a00529\ + cf5801f9258f4eec7dc786d816df6f935216678b00af9d775a15a8d0c198366406bc19a3414426457a8b7c3a\ + 77cf5db5f4ccb412524832056dda2e2a17b7da298763752c1765397779e94e306399b6af55ef90ea61f94a02\ + b8f226a57ed869722a24a37625de01ee9c20de72adee49520bb443537c392a8d75d5a5a63477b4fc25376d8c\ + aaffea407af287ff0affb1f63bb569bcbb312ba2e1b7aed532f81e0fd045a4b0849dae7c0266bf91416d", +}; + +/// ACVP-AES-XTS-1.0 tgId 11 tcId 101: AES-256, encrypt, tweakMode hex, 320 bytes. +const V1_TG11_TC101: Vector = Vector { + source: "ACVP-AES-XTS-1.0 tgId 11 tcId 101", + key: "\ + 2ba2f3f25c0819edb749996effc95a8cd5c4c70b353f1bcad9903dea946b8720650863b3fba7eeda72e09ba4\ + 8b1ef7beba8c8464187b408e56ee9a4be38bce52", + tweak: "1366aa5b88c0456680cff819ddf81537", + sequence_number: None, + pt: "\ + ee258cf68714185a28df8675cd71b973db207662be7545f1ffebc8140217baf85669164591d2df30ee43da5e\ + 6c3f7a1e039c629d8424bb046a1ec86644079d033ef3b54890bc103dbefa867979b00fc7520c1b9f1af8eb0b\ + b1a602a20f9d2b75bc540e7c07cc2b1e3c7c96702f6caa6cc0d8046f7d5a574d70bc14bbdb4dba546bb5e624\ + 1cd0a0567c99fa72455cc7c561ddefcaf2962ba3782b4da722a7b737eedcccf7320b4ab0a2f706a8fdd078bd\ + 6337629384a93137ad18306780424d8341f842be192bfcc471747323ced8bca892ceea702af92f319ae6222f\ + d0bb24161ad580ba790b8b4da88d8db3dacb1dd0480022a5586858c2b2bbc9a579a452fe274defeca804a9b5\ + 7343d983bbe1ed638b9cd422b94c640ac129be22c0ff9181104895c72fa96c1c22dcf1bc721aec71de89a40a\ + 266347bd151e951520cb9165", + ct: "\ + 5181e91d815a44163a8ca2f12dd6a5b51a82eeed30c9665d5d8cc7e3e3359e2534461f5b9bee4a9836647dae\ + 81bac117e8c8aebe0a31864e3b9df05f34de5bac15aeb162d8cb77eb2d893de06edfd064e258d36e113226bb\ + 01c26ce532ef82bb2f0506b7797aa5a4b1ccbd0713964ce74868728cc42da69b74914ecd4775e01dad6d5d66\ + cde80f91db57894cc280be52ffe79725afdc7fcd5a4c26fc22bfa2c7bd5f367389e31285dd3137e94885e714\ + f988bef70ec4cf2022c2320fe9e527cbbb8abc0612e1c8fda67d6f208449a23ee2860f31fd7b6f36521537e0\ + f08dddb766314d400d616ea2f6721a70201cf5a85b7a3b69c462057398cebdcce5e7308fb322d2c4ae9bf966\ + 2941f53d787c6e093106cad99554773f9db9a7ce3e6a15eccc1667fa64425357c6fd5b72d086dca76722c312\ + cdc823d08f653a0d1a7a5427", +}; + +/// ACVP-AES-XTS-1.0 tgId 18 tcId 171: AES-256, encrypt, tweakMode number, 559 bytes (b = 15). +const V1_TG18_TC171: Vector = Vector { + source: "ACVP-AES-XTS-1.0 tgId 18 tcId 171", + key: "\ + 4553964ee112435943a1dfddb0db6dfedfbcaae3765036dd86ffb11969d501df2381b7ab692e365fc2e609a8\ + b6556189e592f9443a9114fcffff7d1771063f4c", + tweak: "46000000000000000000000000000000", + sequence_number: Some(70), + pt: "\ + 4a953211645291d801e4758b4d35dc0317231fa9224b7555921bfefa063843377156de935878ac053c1b90af\ + e7a718fdf98350b43db0a328288a891057cdf391945c326533d68667d75d59c6749ee01c2c56c7facad794a3\ + bc1169dfdf836295e2054dc8c34553c17d1a8cd254603a926a6894ba63d596e124f6ab86980481642fae27ae\ + 304a84c1102ad061b9b899689801e361e8924409b37e13480764ec4d7b468aeec9d2944eca7d4da7df4a6037\ + 3eb3ea8452fdaaba9cf081c5994f3f5dd2afab19f0d81b8286365f934de1f93543ac9746c2befc27607bc6e5\ + 551a8429109a88d87fa3e4d6faad424e250a3663d5d6df1d784ff85b872bbdd4ae1630c885849d8344ce0b23\ + ca1096ba1984531d5075fb85e309adae1ecda78bc6aee690675bd3782886d8d05bc32726fd17282eb7848395\ + a7972458fdc60a1c9f67e6f13794d241b20aa2d30aa21d0862ab7429e946f2ad9f1e25399d8583ca5ae37378\ + cb89d172401175a93122b3ccd1c2de809065ff12e0b17b0906125327b4d3f6be6eeeca402b058ee959d25e1a\ + 272b4cf0ad379e50a1e16795c9fd77cefbce7c903ddbf71eb38bb82eb5a1f4474744067de14ff63063339a66\ + 0d7dcbe433438b4d1aa65f2ea82d40a36801843b48741395e1aa12871c97369d0aa04bf32f21303add3dbc5b\ + d9e828f4d612c79ad1a4075870fb05647e688ad7013916d12216b6309c55df50cd8490e70e90efa76e38d620\ + 726d09e552cc8fbd8d8adf6acf3785c5b936d2a7c579c67ae057300d251861", + ct: "\ + 795d9ef272b0b923cdfca4fbc4457ec624875688a120b498ad62b1a337354895165b910ad5f2e119e601acde\ + bc9984b8f7cc0f1e7590144b64a3dd48e7d154df06355905e6ce778dd946c6e4e428c846870b8dfc5bda1f13\ + 675cd69568a81003e7b3802f6b1b447dfc81a24b5bb42a7ab695052e8992695d3da3125412ea58ae90cb4b01\ + 6d2646017dbefaa96f1c45e9fd63958387e0a56f47a86fdd2bdcbf59e3aaf35633186aa99273234a78a80821\ + 4f471eab9012b48c034694ce4d8f00743e7bea666fc7e0c86c29dc888083d1bd9dcdc4dcdb457d032a894460\ + 2e62b50e8f696a329537ed113cdbbcb4c298f31a1a0df8f4d84aca643fb7ba98f430bf226e7587d69e0e8522\ + fc3da498d0eb382aca86741861654954178b20469230d1ea63a9434a4688c36fb83c63833431be2847ddfeec\ + 0b907fb4d4bfe640d5d5e0457a2f3e701cd79b2e6081520fbdbf44c91a57a5179801861550e6a4f90d01b5a6\ + 6b05c73d3af0f990124525f59d6742c54d27841ee0fcf2ff3d57825d4c32ec52cf909c36ab26f60b79650eeb\ + b75b3bcc4f5e55bad56b117224daaf2e2184183016eff3a4e311f90e1b4ba68cde1a3d7ed702c55d38ae5a7b\ + 6f4b5b80b19ed457ec64967d277ebc927404ceb03b909c9fc3a4d2f6d5ea2c13492fb64cbac155923b4f7bd6\ + 6c8774e08cbd23777c48a5bb457b01ddf194feda4e2ca5d1e34ae7d48b94184e42e6028368064e8e0f20fd34\ + 980b5b06748ae66dd9d4634c5174c07deef68b7aa08e22f7fe090f48b05d7d", +}; + +/// ACVP-AES-XTS-2.0 tgId 5 tcId 233: AES-256, encrypt, tweakMode hex, 16 bytes. +const V2_TG5_TC233: Vector = Vector { + source: "ACVP-AES-XTS-2.0 tgId 5 tcId 233", + key: "\ + 9d9674635844373fbac65ea8fefccf4bedb7b1845c89dc1b28b343fdcd5df7af1c0a96edeead069c6666b741\ + 153fa3f367ad7538f9615c348462115fe09da571", + tweak: "eae1092e65f917efaf69e01740494551", + sequence_number: None, + pt: "0873e8a1ef36f962efaae5b9bd617d39", + ct: "6ea0f22583c4c6397adcaf702a08c27d", +}; + +/// ACVP-AES-XTS-2.0 tgId 7 tcId 319: AES-256, encrypt, tweakMode number, 16 bytes. +const V2_TG7_TC319: Vector = Vector { + source: "ACVP-AES-XTS-2.0 tgId 7 tcId 319", + key: "\ + 95f8cac93590607136175e70d8fa55465a1edaa5e128c31f17821fb29cdd5d218d8e637502eec9e88acb1b28\ + 8727561ce79b01bf11efbef86dccb7fe78ea3c52", + tweak: "f9000000000000000000000000000000", + sequence_number: Some(249), + pt: "40e5982e173de25bdeec94a02130ebcf", + ct: "4b9c0a90753d611c4df75991c4d4abc8", +}; + +/// ACVP-AES-XTS-2.0 tgId 13 tcId 642: AES-256, decrypt, tweakMode hex, 16 bytes. +const V2_TG13_TC642: Vector = Vector { + source: "ACVP-AES-XTS-2.0 tgId 13 tcId 642", + key: "\ + 074beb63ea25525f509e04562158a49f1c5de35dd0b32528de9673f9d8b2c1e799c852ee2ce4a5487e49822f\ + e803860ed6eb5cc61ddc965a3a18478f6ed1a8d2", + tweak: "642178ce09bf25ef9bdc12a9043643cd", + sequence_number: None, + pt: "bc564ad27849d52c0fe571248907f6d8", + ct: "ceec59a7677a8a78230139670e604025", +}; + +/// ACVP-AES-XTS-2.0 tgId 15 tcId 719: AES-256, decrypt, tweakMode number, 16 bytes. +const V2_TG15_TC719: Vector = Vector { + source: "ACVP-AES-XTS-2.0 tgId 15 tcId 719", + key: "\ + 530d1742668119cf2be522a070fca1262dc0a85543440998fa1abe81d5f16f522cc220cd9e7cffba88ebb933\ + 2aa42e9a8a6d8a2af9639a73dab5bf663ca1bae5", + tweak: "b7000000000000000000000000000000", + sequence_number: Some(183), + pt: "39a576b8e051682d9bb974522bc8173f", + ct: "184c449f962b94b8eba1b8ddb7e44db9", +}; + +/// ACVP-AES-XTS-2.0 tgId 15 tcId 702: AES-256, decrypt, tweakMode number, 21 bytes (b = 5). +const V2_TG15_TC702: Vector = Vector { + source: "ACVP-AES-XTS-2.0 tgId 15 tcId 702", + key: "\ + 6838b46d0a41d3468520baef2f28dacd770a7f2e2a53328345bcd010d40799bb1e2ed2e127c0cb999f4d4946\ + d1026fa90b9344d11d59223b1adc2dd6db7394ce", + tweak: "2f000000000000000000000000000000", + sequence_number: Some(47), + pt: "dd3870cb70e39e96f1b70404030dabfe2d1a54cc89", + ct: "678cf29fd1e660bcdc9d874c8e4c5f7292ab8368d5", +}; + +/// ACVP-AES-XTS-2.0 tgId 5 tcId 237: AES-256, encrypt, tweakMode hex, 27 bytes (b = 11). +const V2_TG5_TC237: Vector = Vector { + source: "ACVP-AES-XTS-2.0 tgId 5 tcId 237", + key: "\ + dcf8c5f5ac2ff90719df2dcbbee159c53c44e80bcfa95c718c659c4e8f6fc0a4c85a9e3c16527e66bdd924c1\ + 3ec8314987f0f3e89089007b34dc472b95b7e03e", + tweak: "7eb2097b64cc3bccad39608427ecc1a5", + sequence_number: None, + pt: "a06b93f02ae1b52f2d7995d024914dd490320670ad610f5b4bc91e", + ct: "87e96fcd94d73ba5e2cfe45a96be469c2a13ce2f621cd76fc1c875", +}; + +/// ACVP-AES-XTS-2.0 tgId 15 tcId 737: AES-256, decrypt, tweakMode number, 31 bytes (b = 15). +const V2_TG15_TC737: Vector = Vector { + source: "ACVP-AES-XTS-2.0 tgId 15 tcId 737", + key: "\ + a373bfc7b1697d90e3338fa4eda3a6b47333e128afd5ab041deec226c678a02a1595a2c29ffcc534dea529d5\ + e0fc611c77825ae6127a9146365fc3779d5b350c", + tweak: "f6000000000000000000000000000000", + sequence_number: Some(246), + pt: "a6f75098bd821c44d18a6e5870a7133b15800c27d6d2c7450309e80d07d586", + ct: "0870a04fbf1d37cd1af4a2411be163e1655f82fc85a99ab6e462e0d6c9df28", +}; + +/// ACVP-AES-XTS-2.0 tgId 13 tcId 603: AES-256, decrypt, tweakMode hex, 46 bytes (b = 14). +const V2_TG13_TC603: Vector = Vector { + source: "ACVP-AES-XTS-2.0 tgId 13 tcId 603", + key: "\ + fe08576b2820261bb57ee5164416885f9b154ba446ec82e129345825e30721c87a13ac02fde62cd5d7a34433\ + e5eb021be485ea54422113aa0b545154f5fdbef9", + tweak: "89325d57b103c2cdc2bfa2e3327aa6ff", + sequence_number: None, + pt: "\ + c1355ee7100214f1bf77a1d8d1b0c2229ec647806e7d8004cca909350315a03d7d62b84dba97cda22359554b\ + 744b", + ct: "\ + b2ca0147326de586698dc559978e367b894e23a101d3937c5ade6fe36c96629cfddbc21b668b690827ec27d5\ + 9d6e", +}; + +/// ACVP-AES-XTS-2.0 tgId 13 tcId 640: AES-256, decrypt, tweakMode hex, 57 bytes (b = 9). +const V2_TG13_TC640: Vector = Vector { + source: "ACVP-AES-XTS-2.0 tgId 13 tcId 640", + key: "\ + f222058080b731845a6a64ceead954d05a85635ade124a235ab389f42daa124fc56edc769a372f57ef9f4ea2\ + 9273ed82310d96db7c0101cf999fb8b00f2123a9", + tweak: "f395c13b586f1939f93ce0ecc82d3b93", + sequence_number: None, + pt: "\ + c6d43c791a16be5294d948d5a5ec94ef81e69f75cbfa2ce03db3f47689d8b1a370f71bc63f072491f1d96323\ + d10d6da674d967a6f172b2ae99", + ct: "\ + 0cf742d85c85def160e05bdfe2e3c31263981651531f46074638fc782890374a7f30865586511b475eeafac3\ + 0848089618e140466ca3da934c", +}; + +/// ACVP-AES-XTS-2.0 tgId 13 tcId 649: AES-256, decrypt, tweakMode hex, 59 bytes (b = 11). +const V2_TG13_TC649: Vector = Vector { + source: "ACVP-AES-XTS-2.0 tgId 13 tcId 649", + key: "\ + 3a8c5ecf475e3dc20da414c965824312224d946aeee4ed9d9db450ba24747d44930b61cb9d2aa1676059a578\ + 2994a7d5415ca6b742aefa9b58fcf9e8c69d1cb2", + tweak: "d2f56bc08a8cf7f2858737313afd1bee", + sequence_number: None, + pt: "\ + b3d431bbcc8538abcd33ea5a7c5166b360f21beefc3f4800c25ca803a453f493ae941f279aad1033adf64893\ + 80eb31f7287e0e38d72e510006871a", + ct: "\ + 1c3e5d0c58856fc805d719e8804699969d175741269983f017ba510cf3a63f794225bec32b44ec999dcd51c6\ + 9e1256a909ec8f05175ed8db018850", +}; + +/// ACVP-AES-XTS-2.0 tgId 5 tcId 230: AES-256, encrypt, tweakMode hex, 77 bytes (b = 13). +const V2_TG5_TC230: Vector = Vector { + source: "ACVP-AES-XTS-2.0 tgId 5 tcId 230", + key: "\ + a0e54b4453a9c9d7740a8a88f4f72fb3a76f16d078197a1c69e5f69e68a710fb3555068bfe708ee35224f8cd\ + c5b238823a2b239e5cd6a0a6704ab4e18c1cfc6d", + tweak: "cc82acdf52a949538b9cc27c8e61a04a", + sequence_number: None, + pt: "\ + d7503a2c796adeca0e73a619c0ea661dc683ba6414e74c708280f6dd3a9c56f83db8b82cd0fe06f5903786a8\ + 4722276627ef7de3153a258f7c0b2a7f606e02941ced3ce7518d0d4466cf9f3a77", + ct: "\ + 31611d514838ab07ce6167149db16a0bca816ed32c55c5311f6d9a3b7913243b334e01d9ac661f48d0379f64\ + 1a0dcc2f8cb8c9442f2adfda7912cb4b5ba32563834821ad807a0bca4afc26e353", +}; + +/// ACVP-AES-XTS-2.0 tgId 15 tcId 717: AES-256, decrypt, tweakMode number, 78 bytes (b = 14). +const V2_TG15_TC717: Vector = Vector { + source: "ACVP-AES-XTS-2.0 tgId 15 tcId 717", + key: "\ + dc8b232a4635ce86276464428f2b0038bc149a74304ae557a3f63da68af81f37d57c1940be983288e3f6b482\ + a795aa04719b0a65484d0af6cbe2c279beb17ddb", + tweak: "65000000000000000000000000000000", + sequence_number: Some(101), + pt: "\ + f1dbec7f644d96647c88b946c4fa3ae44dbcb07c721783992239d316a5fbf12338d0b2f89baf3626a9c4425a\ + 3a03aacfb1e1c81c80f232aa8976fbbf4d9c41520e2441b2f32f57da1549ae46713f", + ct: "\ + e70bd73a2f71d4c67ae2c23b40b139656ffb5807d40643adb749b1925fac6ba531f533e0fb1affc9a2de6b8c\ + fbc1407d7422252956aed11aecd3552f3b76a5e56ebdfc802ead889525afb6a52030", +}; + +/// ACVP-AES-XTS-2.0 tgId 13 tcId 641: AES-256, decrypt, tweakMode hex, 84 bytes (b = 4). +const V2_TG13_TC641: Vector = Vector { + source: "ACVP-AES-XTS-2.0 tgId 13 tcId 641", + key: "\ + 34dc22fc6047a40f4ac0e6efe354128997a28b3b5c0ef60d1cc34c63003f97c1a176a8fd6be17e7801e44ba8\ + 68c6e7b4d09cba9730d928dcd98edddebfa6f495", + tweak: "ecc6873db15aaa23686c9c7bff6f38b1", + sequence_number: None, + pt: "\ + 0d93588848314be196d4a7394e7299cee4419b799b9b583c19824321fbb4072cb491362fd6c2f6690b741dba\ + d20966058133b0ac8e2eb815322ecf88994e62df4112cfccd861c1a945ea313e498bfa7293a32fcf", + ct: "\ + 684fb6ca08e2265239bc1584ebd09cfaa20b0af4d500105741b1e09233b8341669377904c189c0da91909741\ + 31698eb9211196f3bd5dcde1537754c8bdb8e2d1fe46ee798abd0c38ffc852a2e264ce957a9d4a16", +}; + +/// ACVP-AES-XTS-2.0 tgId 13 tcId 644: AES-256, decrypt, tweakMode hex, 86 bytes (b = 6). +const V2_TG13_TC644: Vector = Vector { + source: "ACVP-AES-XTS-2.0 tgId 13 tcId 644", + key: "\ + ec6cbedc8a6a66d571d880d5aa99d8052b933193e8d65b8c5888556856ced10f9ab2d48a796204780da64583\ + e5f5c27db783383615d43bc0f7383f8ee3737bb7", + tweak: "4779bd6f28599c39274f2c6964063988", + sequence_number: None, + pt: "\ + fde1ef403f19c49f43760d342435f6ff3534c87b7c1d8b940b253fe7b6d3008ccc3da904f72f3d35cfcd149a\ + e052781d213c0e196e7081f805b36495d10ff4976b2fc4c3e4294d84c95f16ad692ff3dc1f27077c852d", + ct: "\ + 5b65ca6c16908863c94767239652c4971738dcd2852d74651eea1b01c5cdc075c9dcd5a98cd9b69455bd648a\ + 395aab1239045ca4e94593310f5746cc25dd202dd2a17d4265fd9c73dcc517195f84bc65b740dee6fb92", +}; + +/// ACVP-AES-XTS-2.0 tgId 15 tcId 712: AES-256, decrypt, tweakMode number, 92 bytes (b = 12). +const V2_TG15_TC712: Vector = Vector { + source: "ACVP-AES-XTS-2.0 tgId 15 tcId 712", + key: "\ + 93fe122fd121d1450133086e9bb229381f572f6055127af61efa212973edf3f6b96ece04bd6b0df9a0bb25f6\ + 9dad503d323ad83a0118826103cf9ade1b720127", + tweak: "2a000000000000000000000000000000", + sequence_number: Some(42), + pt: "\ + 1292b98c98225013261708d38b99df9bece6132393a522216235061d2fc95b9cdc331a66f5b681e53bb634a2\ + a9c44379e7d4658a90ea9c267b92fca5f52b6506c9db44827de72cb5764eada1a1f79d8a83da435a52766e88\ + b22a22da", + ct: "\ + 2aa51cebef5c72f7923178d8737dc5b9d93c9c74141d9cd55abe612f629f2b199399746366297aceaeed589e\ + eedc2064fffd7d468c94c19e0983156a2a20e4ead066b494e2c5b656832808d6bba5596f298b504689fb8048\ + 2e56281d", +}; + +/// ACVP-AES-XTS-2.0 tgId 7 tcId 305: AES-256, encrypt, tweakMode number, 94 bytes (b = 14). +const V2_TG7_TC305: Vector = Vector { + source: "ACVP-AES-XTS-2.0 tgId 7 tcId 305", + key: "\ + 51c5973bdea6ffe02ab15c3d6b07ce940f8337d9f3662fefed7f07b283b7d8de95c52fb67847180624bed57d\ + dec5b9f5d7e2c2c84c5b24807c0f82f6ac239fff", + tweak: "36000000000000000000000000000000", + sequence_number: Some(54), + pt: "\ + 2e3b0325fda676d24b833518e7acfe7076b4d522b7071a98ea2c5def19648a59d6bc29dd352faaad0579d066\ + f30facd9fe9c5a367c75bc58193855a7537c4b1cea28279486fd0cd1eb5298736033d13fd3b06b65807482fe\ + 50afdb420195", + ct: "\ + 01331145cb441fb40ef1d6d5669ff934e5427645704a1d5a20947c2de257b9c2e0064902e5912f15aa0b2b1a\ + e973a337be3b765d253c0ffc47169d37fb143812f1ae419ff4eb010e6d05f184041430439022be3c7a5e8234\ + 47adf700fec0", +}; + +/// ACVP-AES-XTS-2.0 tgId 13 tcId 646: AES-256, decrypt, tweakMode hex, 308 bytes (b = 4). +const V2_TG13_TC646: Vector = Vector { + source: "ACVP-AES-XTS-2.0 tgId 13 tcId 646", + key: "\ + 6737c853f8522ef9313f5917151392568f1c63917c6e655baf09694ea6906ce89e2042d9f165e3d274a50ff5\ + 37a0f63710bf3052fdab8caa10bab9dc25a29f41", + tweak: "6fe228a190dbf0edcec119a0e5140c6c", + sequence_number: None, + pt: "\ + 69befc6730eb06f8078b01d610187e4e14bb1be0c9344a43dd1521240c8cd5d8da51cca4a870aac8661a590f\ + b917d66bc8cbe8a17a057939a3a8ac4f2858923be2f58214373654848812fb95dbc783483e48ccb2d6c25019\ + 37c7ef9b400da671aaac08f7e03b4bc323f34c1a1151c92d424bf0fa3abad868525454358303e3be4e53554b\ + d1edc2449eab840b1ed40dffe0d18e76daca0f45b598a7f29a9c450f4bfb97f4cbdd68cd92497bf15615f145\ + 08b14d0cb9c2c1d778e8292af6e77d0074d291c24665b6cb56dd5af714543f83d7800249c9a096fb540cd296\ + bf8613de6c00e85b28cb0e8302612a7fbadc28e2d88f485f2578aa687db095523e1c960d7d4b30c0070cac7c\ + 7427c2318c14c7a9aa92158ca68047f0f9b844043f9bd5173691f9e0b3b8260bd8164656a3d64ca3833c34c1", + ct: "\ + 3590b70b4aa216c06e603d0918751568e58ff145d1a278562c8d7b08265233b1af286b4d09dbc6010502f476\ + 02b9388cc2df2e59544e69a1ddc0e711a41bc363d63fc25102d84814e845943a445617149f2023e9b50af071\ + 796e2551efae47993d38cc19cdd7ace5c9e46344c0e2100212d7c0ecb4009ca3589028afbd11f84b8a541d54\ + 5829eb5f0cd7ea52ad4802a11de263e8fad2ed5b8d2442b837b9bcb336118dc2842ee576c0bbbea25b29c79b\ + 495f687ac52f5c1817a2823d9fab1acb79467b75e44b01865d291857eb05fd0f62e264518436fab286720d85\ + b442a0d812aaa758382a7eadb1edb1c0e1e38a2427378040842d75219fb4a062f8b2730ee9f93b762a2446e2\ + 22e87ff957996626d4063728508ad24e20d17d7f0da19630e60959470a5f2b5f5fd0ca567b95f21c33ad038f", +}; diff --git a/crypto/aes/tests/xts_tests.rs b/crypto/aes/tests/xts_tests.rs new file mode 100644 index 000000000..20a9f5eef --- /dev/null +++ b/crypto/aes/tests/xts_tests.rs @@ -0,0 +1,481 @@ +//! XTS-AES through its public API: known answers at the data-unit lengths that matter -- one +//! block, the ciphertext-stealing edges, a sector and the 2^20-block maximum -- from OpenSSL, an +//! independent implementation; every block of a data unit against a reference written here from +//! the definition, which pins the roles of the two key halves, the byte order of the tweak and +//! the multiplication by α; round trips at every length from one block to eight and a half; and +//! the key constructor's refusals. +//! +//! The published vectors are in `xts_acvp_tests.rs` and `xts_wycheproof.rs`. The compile-time +//! bounds on the data-unit length are doctests on `bouncycastle_cipher::modes::XTSKey`. + +use bouncycastle_aes::hazmat::{AES128Internal, AES256Internal}; +use bouncycastle_aes::{XTS_AES_128, XTS_AES_256}; +use bouncycastle_cipher::modes::{ + XTS_MAX_DATA_UNIT_LEN, XTS_MIN_DATA_UNIT_LEN, XTS_TWEAK_LEN, XTSKey, +}; +use bouncycastle_core::errors::{KeyMaterialError, SymmetricCipherError}; +use bouncycastle_core::hazmat::{BlockPermutation, KeyExpansion}; +use bouncycastle_core::key_material::{KeyMaterial, KeyMaterialTrait, KeyType}; +use bouncycastle_core::security_strength::SecurityStrength; +use bouncycastle_core::symmetric_key::FromKeyMaterial; +use bouncycastle_core_test_framework::from_key_material::TestFrameworkFromKeyMaterial; +use bouncycastle_hex as hex; + +/// The tweak of the known answers below. +const TWEAK: [u8; 16] = [ + 0xf0, 0xe1, 0xd2, 0xc3, 0xb4, 0xa5, 0x96, 0x87, 0x78, 0x69, 0x5a, 0x4b, 0x3c, 0x2d, 0x1e, 0x0f, +]; + +/// `Key_1 | Key_2` of the known answers: 0x01, 0x02, .., so the halves differ. +fn key_bytes() -> [u8; KEY_LEN] { + core::array::from_fn(|i| i as u8 + 1) +} + +/// The plaintext of the known answers: byte k of a data unit is k mod 251. +fn pattern(len: usize) -> Vec { + (0..len).map(|k| (k % 251) as u8).collect() +} + +fn material(bytes: &[u8]) -> KeyMaterial { + KeyMaterial::::from_bytes_as_type(bytes, KeyType::SymmetricCipherKey).unwrap() +} + +fn xts_key(bytes: &[u8; KEY_LEN]) -> XTSKey +where + XTSKey: FromKeyMaterial, +{ + XTSKey::::from_key_material(&material(bytes)).expect("a valid XTS key") +} + +// ---- known answers from OpenSSL ---------------------------------------------------------------- + +/// The first n bytes of `pattern` under `key_bytes()` and `TWEAK` encrypt to `ct`, and back. +fn kat(ct: &str) +where + P: BlockPermutation<16>, + XTSKey: FromKeyMaterial, +{ + let key = xts_key::(&key_bytes()); + let pt: [u8; N] = pattern(N).try_into().unwrap(); + let ct: [u8; N] = hex::decode(ct).unwrap().try_into().expect("an N-byte ciphertext"); + + let mut data_unit = pt; + assert_eq!(key.encrypt_inplace(&TWEAK, &mut data_unit), N); + assert_eq!(data_unit, ct, "{N}-byte data unit: encryption"); + let mut data_unit = ct; + assert_eq!(key.decrypt_inplace(&TWEAK, &mut data_unit), N); + assert_eq!(data_unit, pt, "{N}-byte data unit: decryption"); +} + +/// The lengths of the tables below: one block, one block and one byte, one byte short of two, +/// two, two and a byte, six and a quarter, one byte short of eight, and a 512-byte sector. +macro_rules! kats { + ($perm:ty, $key_len:literal, $table:expr) => { + for &(n, ct) in $table { + match n { + 16 => kat::<$perm, $key_len, 16>(ct), + 17 => kat::<$perm, $key_len, 17>(ct), + 31 => kat::<$perm, $key_len, 31>(ct), + 32 => kat::<$perm, $key_len, 32>(ct), + 33 => kat::<$perm, $key_len, 33>(ct), + 100 => kat::<$perm, $key_len, 100>(ct), + 127 => kat::<$perm, $key_len, 127>(ct), + 512 => kat::<$perm, $key_len, 512>(ct), + other => panic!("no arm for a {other}-byte known answer"), + } + } + }; +} + +#[test] +fn xts_aes_128_matches_openssl() { + kats!(AES128Internal, 32, KATS_128); +} + +#[test] +fn xts_aes_256_matches_openssl() { + kats!(AES256Internal, 64, KATS_256); +} + +/// A long known answer: a 16-byte fold of the ciphertext (`fold[k % 16] ^= ct[k]` over every +/// byte, so any wrong block shows), its first block and its last 32 bytes. +struct LongKat { + fold: &'static str, + first: &'static str, + last: &'static str, +} + +/// The longest data units against OpenSSL: the mask chain runs to α^(2^20 - 1), and one byte +/// short of the limit a ciphertext block is stolen at the far end. +fn long_kat(expected: &LongKat) +where + P: BlockPermutation<16>, + XTSKey: FromKeyMaterial, +{ + let key = xts_key::(&key_bytes()); + let pt = pattern(N); + let mut buf = pt.clone(); + let data_unit: &mut [u8; N] = buf.as_mut_slice().try_into().unwrap(); + + assert_eq!(key.encrypt_inplace(&TWEAK, data_unit), N); + let mut fold = [0u8; 16]; + for (k, byte) in data_unit.iter().enumerate() { + fold[k % 16] ^= byte; + } + assert_eq!(hex::encode(fold), expected.fold, "{N} bytes: the fold of the ciphertext"); + assert_eq!(hex::encode(&data_unit[..16]), expected.first, "{N} bytes: the first block"); + assert_eq!(hex::encode(&data_unit[N - 32..]), expected.last, "{N} bytes: the last 32 bytes"); + + assert_eq!(key.decrypt_inplace(&TWEAK, data_unit), N); + assert!(*data_unit == *pt, "{N} bytes: decryption restores the plaintext"); +} + +/// 2^20 blocks under XTS-AES-128, and one byte less under XTS-AES-256: each key size, and each +/// end of a maximal data unit, once. (About seven seconds each in a debug build.) +#[test] +fn the_longest_data_units_match_openssl() { + long_kat::(&LONG_128_MAX); + long_kat::(&LONG_256_MAX_MINUS_1); +} + +// ---- the definition, block by block ------------------------------------------------------------ + +/// `T ⊗ α` written independently of the implementation: the block as a 128-bit little-endian +/// integer, shifted left one bit, with x^128 reduced to x^7 + x^2 + x + 1 (0x87). +fn times_alpha(t: [u8; 16]) -> [u8; 16] { + let x = u128::from_le_bytes(t); + let reduction = if x >> 127 == 1 { 0x87 } else { 0 }; + ((x << 1) ^ reduction).to_le_bytes() +} + +/// Every block of an aligned data unit is `C_j = E_K1(P_j ^ T_j) ^ T_j` with +/// `T_j = E_K2(i) ⊗ α^j`, computed here through the raw permutation from the halves of the key: +/// the first half encrypts the data, the second the tweak, and the tweak goes in as given. +fn follows_the_definition() +where + P: KeyExpansion + BlockPermutation<16>, + XTSKey: FromKeyMaterial, +{ + let key_bytes = key_bytes::(); + let key1 = P::new(&material::(&key_bytes[..HALF])).unwrap(); + let key2 = P::new(&material::(&key_bytes[HALF..])).unwrap(); + + let pt: [u8; 512] = pattern(512).try_into().unwrap(); + let mut expected = pt; + let mut t = TWEAK; + key2.encrypt_block(&mut t); + for block in expected.as_chunks_mut::<16>().0 { + for (b, m) in block.iter_mut().zip(&t) { + *b ^= m; + } + key1.encrypt_block(block); + for (b, m) in block.iter_mut().zip(&t) { + *b ^= m; + } + t = times_alpha(t); + } + + let key = xts_key::(&key_bytes); + let mut data_unit = pt; + key.encrypt_inplace(&TWEAK, &mut data_unit); + assert_eq!(data_unit, expected); +} + +#[test] +fn every_block_follows_the_definition() { + follows_the_definition::(); + follows_the_definition::(); +} + +#[test] +fn the_reference_multiplication_reduces() { + // x^127 * x = x^128 = x^7 + x^2 + x + 1, and the low bits shift up without a reduction. + let mut top = [0u8; 16]; + top[15] = 0x80; + let mut reduced = [0u8; 16]; + reduced[0] = 0x87; + assert_eq!(times_alpha(top), reduced); + let mut one = [0u8; 16]; + one[0] = 0x01; + let mut two = [0u8; 16]; + two[0] = 0x02; + assert_eq!(times_alpha(one), two); +} + +// ---- round trips and tweaks -------------------------------------------------------------------- + +fn round_trip() { + let pt: [u8; N] = pattern(N).try_into().unwrap(); + let k128 = xts_key::(&key_bytes()); + let k256 = xts_key::(&key_bytes()); + + let mut a = pt; + assert_eq!(k128.encrypt_inplace(&TWEAK, &mut a), N); + assert_ne!(a, pt, "{N} bytes: XTS-AES-128 changed nothing"); + assert_eq!(k128.decrypt_inplace(&TWEAK, &mut a), N); + assert_eq!(a, pt, "{N} bytes: XTS-AES-128 round trip"); + + let mut b = pt; + k256.encrypt_inplace(&TWEAK, &mut b); + assert_ne!(b, pt, "{N} bytes: XTS-AES-256 changed nothing"); + k256.decrypt_inplace(&TWEAK, &mut b); + assert_eq!(b, pt, "{N} bytes: XTS-AES-256 round trip"); +} + +macro_rules! round_trips { + ($($n:literal),* $(,)?) => { + $(round_trip::<$n>();)* + }; +} + +/// Every length from one block to one byte short of nine: every tail length, and every way the +/// blocks before it divide into fours, twos and ones, in both directions. +#[test] +fn round_trips_at_every_length_up_to_nine_blocks() { + round_trips!( + 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, + 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, + 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, + 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, 96, 97, 98, 99, 100, 101, 102, 103, 104, 105, + 106, 107, 108, 109, 110, 111, 112, 113, 114, 115, 116, 117, 118, 119, 120, 121, 122, 123, + 124, 125, 126, 127, 128, 129, 130, 131, 132, 133, 134, 135, 136, 137, 138, 139, 140, 141, + 142, 143, + ); +} + +/// A tweak that differs in any one bit, the first or the last, gives a ciphertext that differs in +/// every block, including the stolen one. +fn every_tweak_bit_matters() { + let key = xts_key::(&key_bytes()); + let pt: [u8; N] = pattern(N).try_into().unwrap(); + let mut base = pt; + key.encrypt_inplace(&TWEAK, &mut base); + for bit in [0, 127] { + let mut tweak = TWEAK; + tweak[bit / 8] ^= 1 << (bit % 8); + let mut other = pt; + key.encrypt_inplace(&tweak, &mut other); + for (j, (a, b)) in base.chunks(16).zip(other.chunks(16)).enumerate() { + assert_ne!(a, b, "{N} bytes, tweak bit {bit}: block {j} did not change"); + } + // And it does not decrypt under the original tweak. + key.decrypt_inplace(&TWEAK, &mut other); + assert_ne!(other, pt); + } +} + +#[test] +fn every_tweak_bit_matters_to_every_block() { + every_tweak_bit_matters::<16>(); + every_tweak_bit_matters::<17>(); + every_tweak_bit_matters::<47>(); + every_tweak_bit_matters::<512>(); +} + +/// Consecutive sequence numbers, `n.to_le_bytes()`, are distinct tweaks: equal sectors under +/// them encrypt differently, and each decrypts only under its own. +#[test] +fn consecutive_sequence_numbers_encrypt_equal_sectors_differently() { + let key = xts_key::(&key_bytes()); + let sector = [0x11u8; 512]; + let mut s0 = sector; + let mut s1 = sector; + key.encrypt_inplace(&0u128.to_le_bytes(), &mut s0); + key.encrypt_inplace(&1u128.to_le_bytes(), &mut s1); + assert_ne!(s0, s1); + key.decrypt_inplace(&1u128.to_le_bytes(), &mut s1); + assert_eq!(s1, sector); +} + +/// Equal plaintext blocks at different positions in one data unit encrypt differently: each +/// position has its own mask. +#[test] +fn equal_blocks_encrypt_differently_at_every_position() { + let key = xts_key::(&key_bytes()); + let mut data_unit = [0u8; 512]; + key.encrypt_inplace(&TWEAK, &mut data_unit); + let (blocks, _) = data_unit.as_chunks::<16>(); + for i in 0..blocks.len() { + for j in i + 1..blocks.len() { + assert_ne!(blocks[i], blocks[j], "blocks {i} and {j}"); + } + } +} + +// ---- the key ----------------------------------------------------------------------------------- + +/// The construction suite -- key type, strength and `generate` -- at both key sizes. Each half +/// carries the key's strength, capped at its own length, so XTS-AES-128 takes a key of 128 bits +/// and up and XTS-AES-256 only one of 256: a 192-bit key, whose halves alone would have been +/// credited 256 bits each, is refused. +#[test] +fn the_keys_enforce_the_material_policy() { + let framework = TestFrameworkFromKeyMaterial::new(); + framework.test::<32, XTS_AES_128<512>>("XTS_AES_128", SecurityStrength::_128bit); + framework.test::<64, XTS_AES_256<512>>("XTS_AES_256", SecurityStrength::_256bit); +} + +// The refusals of the 32-byte key -- equal halves, a zero half, a short key -- are tested over +// the toy permutation in `crypto/cipher/tests/modes/xts_tests.rs`, since that path is generic. +// The 64-byte key is a second impl, which only a permutation with a 32-byte key reaches. + +fn refusal_256(key: &KeyMaterial<64>) -> KeyMaterialError { + match XTS_AES_256::<16>::from_key_material(key) { + Err(SymmetricCipherError::KeyMaterialError(e)) => e, + Err(e) => panic!("refused, but not as a KeyMaterialError: {e:?}"), + Ok(_) => panic!("accepted"), + } +} + +/// FIPS 140-3 IG C.I: Key_1 = Key_2 is refused; halves that differ in their last byte are not. +#[test] +fn xts_aes_256_refuses_equal_halves() { + let mut bytes: [u8; 64] = core::array::from_fn(|i| (i % 32) as u8 + 0x40); + assert!(matches!(refusal_256(&material(&bytes)), KeyMaterialError::GenericError(_))); + bytes[63] ^= 0x01; + XTS_AES_256::<16>::from_key_material(&material(&bytes)).expect("halves that differ"); +} + +/// A half that is all zeros is refused, as an all-zero AES key is; so is an all-zero key. +#[test] +fn xts_aes_256_refuses_zero_halves() { + let mut low_zero = key_bytes::<64>(); + low_zero[..32].fill(0); + let mut high_zero = key_bytes::<64>(); + high_zero[32..].fill(0); + for bytes in [low_zero, high_zero, [0u8; 64]] { + assert!(matches!(refusal_256(&material(&bytes)), KeyMaterialError::InvalidKeyType(_))); + } +} + +/// A `KeyMaterial<64>` holding fewer than 64 bytes is refused rather than split short. +#[test] +fn xts_aes_256_refuses_a_short_key() { + for len in [32, 63] { + let short = material::<64>(&key_bytes::<64>()[..len]); + assert_eq!(short.key_len(), len); + assert_eq!(refusal_256(&short), KeyMaterialError::InvalidLength); + } +} + +/// Swapping the halves gives another key: the order of `Key_1 | Key_2` matters. +#[test] +fn swapping_the_halves_changes_the_ciphertext() { + let bytes = key_bytes::<32>(); + let mut swapped = [0u8; 32]; + swapped[..16].copy_from_slice(&bytes[16..]); + swapped[16..].copy_from_slice(&bytes[..16]); + let mut a = [0u8; 32]; + let mut b = [0u8; 32]; + xts_key::(&bytes).encrypt_inplace(&TWEAK, &mut a); + xts_key::(&swapped).encrypt_inplace(&TWEAK, &mut b); + assert_ne!(a, b); +} + +#[test] +fn sizes() { + assert_eq!(XTS_TWEAK_LEN, 16); + assert_eq!(XTS_MIN_DATA_UNIT_LEN, 16); + assert_eq!(XTS_MAX_DATA_UNIT_LEN, 1 << 24); + // A key is its two schedules, whatever its data-unit length. + assert_eq!(size_of::>(), 2 * size_of::()); + assert_eq!(size_of::>(), 352); + assert_eq!(size_of::>(), 2 * size_of::()); + assert_eq!(size_of::>(), 480); +} + +// ---- the known answers ------------------------------------------------------------------------- + +/// XTS-AES-128 under `key_bytes()` and `TWEAK`: the ciphertext of the first n bytes of the +/// plaintext pattern, from OpenSSL 3.5.0. +const KATS_128: &[(usize, &str)] = &[ + (16, "b9606f8b4bcb9a6990a511c8e0b07aa6"), + (17, "600a1d04fddaccc03a7eb3687c450a2bb9"), + (31, "8abf6bf2f845d0e8d197131cfe1a842fb9606f8b4bcb9a6990a511c8e0b07a"), + (32, "b9606f8b4bcb9a6990a511c8e0b07aa651198810b01418fe0f857794c51ea98b"), + (33, "b9606f8b4bcb9a6990a511c8e0b07aa60b714d7e049f4e0b43da3efbda03aa4751"), + ( + 100, + "\ + b9606f8b4bcb9a6990a511c8e0b07aa651198810b01418fe0f857794c51ea98bc7e6973e0d79338c49e251f1\ + 0d070cceabc1a661121126f5eec5383cdea365a3146e37b0240045b381065b471f9fdcab78418073ac951418\ + a9dc9566a7993aafb7612495", + ), + ( + 127, + "\ + b9606f8b4bcb9a6990a511c8e0b07aa651198810b01418fe0f857794c51ea98bc7e6973e0d79338c49e251f1\ + 0d070cceabc1a661121126f5eec5383cdea365a3146e37b0240045b381065b471f9fdcabb761249542b8a235\ + 2ed012acd8eea817edf246aa1eb3e666684e309ddf13d983ef5a745062853be226bd41f9405f5a", + ), + ( + 512, + "\ + b9606f8b4bcb9a6990a511c8e0b07aa651198810b01418fe0f857794c51ea98bc7e6973e0d79338c49e251f1\ + 0d070cceabc1a661121126f5eec5383cdea365a3146e37b0240045b381065b471f9fdcabb761249542b8a235\ + 2ed012acd8eea817ef5a745062853be226bd41f9405f5a4c7a10be827fbf65207ac6c2ec18f0a7e802e8b89a\ + 6fdf1f2abcd8ba286a1d2a4682d1dc7a0a9883a5826b27e25e9434403d23eb94772498382c12ad7ec2af78ac\ + 0b28f092ec6a006311876eaa9ccbb3c15546163aba18b425f7a69f327c2207f31f1d6fe8aa7e7af6a0d72904\ + db44f0a930079b3009b562a10d84b6b66bfbfc0858c55f3de1d03ca687977654f59d52761e8b0d05f241d465\ + c4a05d31de4267786f1e652b9076c855e24a0aebac08ae210d3fdc3d8d3665f7956bddd09492ba00e82cd3ca\ + f5afd5c3dc4301fbcc7c41beaee8c15c0a001bd4d91471debdba432edb58aa65b76c22151837166fa4026f96\ + edef9cb64e9bacd8fc50ac0bbf2e21de677e97e194550e82a94eb40b52079cc7a61eb62f41560ab5c10c3c8c\ + 91bf50fc873dfced13548ef97cb7a0fb67d1cc676deb9d95c597c70cf31aa75305a19d0a5bb6bb5b1fbfe96d\ + 1ff8fc1009fd005aa37700c7d392e116454ff9a63054e24ffe637ca825d002dcd6f8791ae09d1b1ff47d6467\ + 859b134958f1504d4f19524687d16d4fe39d8f3c3c812695dcfbd91e", + ), +]; + +/// XTS-AES-256 under `key_bytes()` and `TWEAK`: the ciphertext of the first n bytes of the +/// plaintext pattern, from OpenSSL 3.5.0. +const KATS_256: &[(usize, &str)] = &[ + (16, "965c8f85ac79930ac1e8b46eb069dbe9"), + (17, "511ccdf0179233d1b03cd6e456946fb396"), + (31, "21ddbfd72ea45ba2b73f3bdce151f185965c8f85ac79930ac1e8b46eb069db"), + (32, "965c8f85ac79930ac1e8b46eb069dbe922edacc9dbfef62297d5914211e9ca91"), + (33, "965c8f85ac79930ac1e8b46eb069dbe976c2f1565310895c5157328752138c0722"), + ( + 100, + "\ + 965c8f85ac79930ac1e8b46eb069dbe922edacc9dbfef62297d5914211e9ca91b9457eb11290a93c9b93e731\ + 3b216008b5e4d99c52fe03c212f33964308ab8479fa6780a252c63c8b743c43d84a7539de8b3c26a9eaea33e\ + fea73210036bda48b466bdb7", + ), + ( + 127, + "\ + 965c8f85ac79930ac1e8b46eb069dbe922edacc9dbfef62297d5914211e9ca91b9457eb11290a93c9b93e731\ + 3b216008b5e4d99c52fe03c212f33964308ab8479fa6780a252c63c8b743c43d84a7539db466bdb79fd42757\ + f87fd0ed84ace41de0516f856e20c23269c7080dcb0d753834a93c3047f0edf9667a3673f42262", + ), + ( + 512, + "\ + 965c8f85ac79930ac1e8b46eb069dbe922edacc9dbfef62297d5914211e9ca91b9457eb11290a93c9b93e731\ + 3b216008b5e4d99c52fe03c212f33964308ab8479fa6780a252c63c8b743c43d84a7539db466bdb79fd42757\ + f87fd0ed84ace41d34a93c3047f0edf9667a3673f42262a4710cf8198821cff11d82c0388b9c5103cbf0a19f\ + 9b5167dfde5f96d12dcd967fdcb8ab03ea121c2c38a73c7c3d76f528642729af955c56166e9ee33d258a389c\ + 580d9b30945123718fdeef00abca17a80f102b67edce7221c154c4856ae81b0c477e8123e039b078bd0609a2\ + 68be561fce28d44cf9b6603a8db1fd70e2c46bf9d055f82a3518a41d647ee247594018b8760751baa729648e\ + f327f2150d4aa3b2443de64e56005e08244206ad9d3b5e55b3e53f41923227759dc6dad27fe2fce5733b37f1\ + bac14a1984b7019e479c4f1886892ba062ce295e95c27694884b9943506a804c03e5cf020f168335b3b1f6af\ + 2617de1dfb9debee13ef413c6c4fefcb718e4216201a923d8d7315a832797b226f79caec0a0df5e186ba800d\ + 41ccefb8cbde407967a29c2f9ccccb2642243fee94b96b739ea11df9cf3c7dc10396ca0f270671f0d7312c50\ + 06c52647b4cbddec2f00cea49f46978aab29e23285fb3d7c74e78589476552c44395b19739f900e161102f0e\ + 9dbdcdd4821d60f2b3ea839cff6330cee358a6b8e3d8376df070295e", + ), +]; + +/// XTS-AES-128, 2^24 bytes, from OpenSSL 3.5.0. +const LONG_128_MAX: LongKat = LongKat { + fold: "f74540d435c8ba594a381d4687ffd9fb", + first: "b9606f8b4bcb9a6990a511c8e0b07aa6", + last: "64ccf3f477de47b98f4ad98fa299e0ac57ec5f4034d784657408ed62efb09ba5", +}; + +/// XTS-AES-256, 2^24 - 1 bytes, from OpenSSL 3.5.0. +const LONG_256_MAX_MINUS_1: LongKat = LongKat { + fold: "d0f491c9ba261270a3b6e04b1fb47c6d", + first: "965c8f85ac79930ac1e8b46eb069dbe9", + last: "374c504dc69fa3f993be5c65153ac1e0a2b0dd68843f9d8bef7a4e52bfb4272c", +}; diff --git a/crypto/aes/tests/xts_wycheproof.rs b/crypto/aes/tests/xts_wycheproof.rs new file mode 100644 index 000000000..a147b3584 --- /dev/null +++ b/crypto/aes/tests/xts_wycheproof.rs @@ -0,0 +1,121 @@ +//! Project Wycheproof's `aes_xts_test.json` through `XTS_AES_128` and `XTS_AES_256`. Requires the +//! Wycheproof repository at `../wycheproof`; absent, the test warns and passes. +//! +//! Every case is a valid encryption of a pseudorandom message of 16 to 136 bytes, which between +//! them cover each ciphertext-stealing tail length; each is checked in both directions. The file +//! gives the tweak as an `iv` of 1 to 16 bytes, which is the leading bytes of the 128-bit tweak +//! with the rest zero: the data unit's sequence number in little-endian, at the width written. +//! OpenSSL reproduces every case in the file under that reading. The 384-bit-key groups are XTS +//! over AES-192, which neither IEEE 1619 nor SP 800-38E defines; they are counted and skipped. + +use bouncycastle_aes::hazmat::{AES128Internal, AES256Internal}; +use bouncycastle_cipher::modes::XTSKey; +use bouncycastle_core::hazmat::BlockPermutation; +use bouncycastle_core::key_material::{KeyMaterial, KeyType}; +use bouncycastle_core::symmetric_key::FromKeyMaterial; +use bouncycastle_core_test_framework::test_data_loaders::{Value, hex_field, wycheproof_json}; + +/// Checks one case through `XTSKey` under its `KEY_LEN`-byte key, in both directions. +fn check(case: &Value, tc_id: u64) +where + P: BlockPermutation<16>, + XTSKey: FromKeyMaterial, +{ + let material = KeyMaterial::::from_bytes_as_type( + &hex_field(case, "key", tc_id), + KeyType::SymmetricCipherKey, + ) + .unwrap(); + let key = XTSKey::::from_key_material(&material) + .unwrap_or_else(|e| panic!("tcId {tc_id}: the key is refused: {e:?}")); + + let iv = hex_field(case, "iv", tc_id); + let mut tweak = [0u8; 16]; + tweak[..iv.len()].copy_from_slice(&iv); + + let msg: [u8; N] = hex_field(case, "msg", tc_id).try_into().unwrap(); + let ct: [u8; N] = hex_field(case, "ct", tc_id).try_into().unwrap(); + + let mut data_unit = msg; + key.encrypt_inplace(&tweak, &mut data_unit); + assert_eq!(data_unit, ct, "tcId {tc_id}: encryption"); + key.decrypt_inplace(&tweak, &mut data_unit); + assert_eq!(data_unit, msg, "tcId {tc_id}: decryption"); +} + +fn check_128(case: &Value, tc_id: u64) { + check::(case, tc_id); +} + +fn check_256(case: &Value, tc_id: u64) { + check::(case, tc_id); +} + +/// Calls `$check::` for the message length `$len`. The data-unit length is a const parameter +/// of the key type, so every length in the file needs an arm; a new one fails loudly. +macro_rules! dispatch { + ($len:expr, $check:ident, $case:expr, $tc_id:expr) => { + match $len { + 16 => $check::<16>($case, $tc_id), + 17 => $check::<17>($case, $tc_id), + 18 => $check::<18>($case, $tc_id), + 19 => $check::<19>($case, $tc_id), + 20 => $check::<20>($case, $tc_id), + 21 => $check::<21>($case, $tc_id), + 22 => $check::<22>($case, $tc_id), + 23 => $check::<23>($case, $tc_id), + 24 => $check::<24>($case, $tc_id), + 25 => $check::<25>($case, $tc_id), + 26 => $check::<26>($case, $tc_id), + 27 => $check::<27>($case, $tc_id), + 28 => $check::<28>($case, $tc_id), + 29 => $check::<29>($case, $tc_id), + 30 => $check::<30>($case, $tc_id), + 31 => $check::<31>($case, $tc_id), + 32 => $check::<32>($case, $tc_id), + 33 => $check::<33>($case, $tc_id), + 48 => $check::<48>($case, $tc_id), + 51 => $check::<51>($case, $tc_id), + 64 => $check::<64>($case, $tc_id), + 68 => $check::<68>($case, $tc_id), + 96 => $check::<96>($case, $tc_id), + 102 => $check::<102>($case, $tc_id), + 128 => $check::<128>($case, $tc_id), + 136 => $check::<136>($case, $tc_id), + other => panic!("tcId {}: no arm for a {other}-byte message; add one", $tc_id), + } + }; +} + +#[test] +fn wycheproof_aes_xts() { + let Some(file) = wycheproof_json("aes_xts_test.json") else { + return; + }; + let (mut ran_128, mut ran_256, mut skipped_192) = (0usize, 0usize, 0usize); + for group in file["testGroups"].as_array().expect("testGroups") { + let key_size = group["keySize"].as_u64().expect("keySize"); + for case in group["tests"].as_array().expect("tests") { + let tc_id = case["tcId"].as_u64().expect("tcId"); + assert_eq!(case["result"], "valid", "tcId {tc_id}: only valid cases are expected"); + let len = hex_field(case, "msg", tc_id).len(); + match key_size { + 256 => { + dispatch!(len, check_128, case, tc_id); + ran_128 += 1; + } + 512 => { + dispatch!(len, check_256, case, tc_id); + ran_256 += 1; + } + 384 => skipped_192 += 1, + other => panic!("tcId {tc_id}: unexpected keySize {other}"), + } + } + } + println!( + "Wycheproof AES-XTS: {ran_128} XTS-AES-128 and {ran_256} XTS-AES-256 cases, \ + {skipped_192} AES-192 cases skipped" + ); + assert!(ran_128 > 0 && ran_256 > 0, "expected cases at both key sizes to run"); +} diff --git a/crypto/cipher/Cargo.toml b/crypto/cipher/Cargo.toml index 40568cb29..1cb2104ea 100644 --- a/crypto/cipher/Cargo.toml +++ b/crypto/cipher/Cargo.toml @@ -73,3 +73,7 @@ path = "tests/modes/kw_tests.rs" [[test]] name = "symmetric_cipher_api_tests" path = "tests/modes/symmetric_cipher_api_tests.rs" + +[[test]] +name = "xts_tests" +path = "tests/modes/xts_tests.rs" diff --git a/crypto/cipher/src/modes/mod.rs b/crypto/cipher/src/modes/mod.rs index f5005c831..ad7da818b 100644 --- a/crypto/cipher/src/modes/mod.rs +++ b/crypto/cipher/src/modes/mod.rs @@ -22,8 +22,9 @@ //! | GMAC | [`gmac`] | SP 800-38D Sec 5.2 | A MAC, not a cipher: GCM with no plaintext, so the tag is bound to a 96-bit nonce | //! | KW | [`kw`] | SP 800-38F Sec 6.2 | Key Wrap (RFC 3394). **Authenticated**, deterministic, no IV; whole 8-byte semiblocks only | //! | KWP | [`kwp`] | SP 800-38F Sec 6.3 | Key Wrap with Padding (RFC 5649). As KW, for data of any length | +//! | XTS | [`xts`] | SP 800-38E (IEEE Std 1619-2007) | XEX with ciphertext stealing, for storage: one data unit at a time under a tweak, no expansion | //! -//! They divide three ways, plus the key-wrap pair. +//! They divide three ways, plus the key-wrap pair and XTS. //! //! **ECB and CBC are block ciphers** ([`BlockCipherEncryptor`] / [`BlockCipherDecryptor`]): whole //! blocks in, whole blocks out, and arbitrary-length data needs the padding layer. @@ -45,6 +46,10 @@ //! general data as well, but they are deterministic, so for data that may repeat an AEAD is the //! better fit (see the [`kw`] security notes). //! +//! **XTS is a storage mode** ([`XTSKey`]): it encrypts one fixed-length data unit, such as a disk +//! sector, in place under a tweak naming its position, and its ciphertext is no longer than the +//! plaintext. It is unauthenticated and has no streaming API; see the [`xts`] security notes. +//! //! CBC, CFB, CFB8 and CTR all generate their own init data, or take the caller's through the key's //! `_nonce` forms: an IV for the first three, a nonce for CTR, which is shorter than a block //! because the rest of the counter block is the counter. ECB has @@ -179,6 +184,7 @@ pub mod hazmat; mod iv; pub mod kw; pub mod kwp; +pub mod xts; pub use cbc::{CBC, Cbc}; pub use ccm::{ @@ -192,6 +198,7 @@ pub use gcm::{GCM, GCM_NONCE_LEN, Gcm, GcmKeyState}; pub use gmac::{GMAC, Gmac}; pub use kw::{KW, KW_BLOCK_LEN, Kw, SEMIBLOCK_LEN}; pub use kwp::{KWP, Kwp}; +pub use xts::{XTS_MAX_DATA_UNIT_LEN, XTS_MIN_DATA_UNIT_LEN, XTS_TWEAK_LEN, XTSKey}; /// Selects the whole-block form of a mode that also has a padded form: `CBC` is a key /// for the block-aligned [`Cbc`] itself, on the block key path, where `CBC` is one for diff --git a/crypto/cipher/src/modes/possible_enhancements.md b/crypto/cipher/src/modes/possible_enhancements.md index 521e0bbd7..ac3805491 100644 --- a/crypto/cipher/src/modes/possible_enhancements.md +++ b/crypto/cipher/src/modes/possible_enhancements.md @@ -5,7 +5,6 @@ Possible additional modes or features to be added to this crate: a bit string whose length need not be a multiple of 8, which this crate has no type for. * **OFB**, the one remaining mode of SP 800-38A. It is a keystream mode and, like CFB, CFB8 and CTR, would implement [`StreamCipherEncryptor`] / [`StreamCipherDecryptor`]. -* **AES-XTS**: https://csrc.nist.gov/pubs/sp/800/38/e/final used primarily in full-disk-encryption systems. * **GCM with a nonce other than 96 bits** (SP 800-38D Algorithm 4 step 2's `len(IV) != 96` branch, which derives `J0` by GHASHing the IV). Sec 5.2.1.1 recommends restricting support to 96 bits, and [`Gcm`] does. diff --git a/crypto/cipher/src/modes/xts.rs b/crypto/cipher/src/modes/xts.rs new file mode 100644 index 000000000..f69631e66 --- /dev/null +++ b/crypto/cipher/src/modes/xts.rs @@ -0,0 +1,514 @@ +//! XTS, the XEX-based tweaked-codebook mode with ciphertext stealing, as IEEE Std 1619-2007 +//! specifies it for AES and NIST SP 800-38E approves it, over any 128-bit block permutation. +//! +//! XTS encrypts one *data unit* -- a disk sector, say -- under a key and a 128-bit *tweak* that +//! names the data unit's position, and the ciphertext is exactly as long as the plaintext: there +//! is no IV, no nonce, no padding and no tag. A data unit is at least one block, 16 bytes, and at +//! most 2^20 blocks, 16 MiB, the limit SP 800-38E Sec 4 adds to IEEE 1619: "The length of the data +//! unit for any instance of an implementation of XTS-AES shall not exceed 2^20 AES blocks". A data +//! unit that is not a whole number of blocks is encrypted with ciphertext stealing, so its +//! ciphertext is as long as it is. +//! +//! The key is [`XTSKey`], built with `from_key_material` from the XTS key `Key = Key_1 | Key_2`: +//! two keys for the permutation, `Key_1` encrypting the data and `Key_2` the tweak, so 32 bytes +//! over a permutation with a 16-byte key and 64 over one with a 32-byte key. The data-unit length +//! is the key type's `DATA_UNIT_LEN`, because SP 800-38E Sec 4 defines an instance of XTS-AES by +//! "a secret key" and "a single, fixed length for the data units that the key protects"; a length +//! outside the range is a compile error. The ready-made `XTS_AES_128` / `XTS_AES_256` aliases are +//! in `bouncycastle-aes`. IEEE 1619 specifies XTS for AES only, and AES is the only cipher +//! SP 800-38E approves it for. +//! +//! # The tweak +//! +//! The tweak is the 128-bit value `i` that the mode encrypts under `Key_2`, taken as given. For +//! storage it is the data unit's sequence number as a 128-bit little-endian integer, +//! `u128::to_le_bytes(n)`, the encoding of NIST's ACVP sequence-number vectors (sequence number +//! 255 is the tweak `FF 00 .. 00`). +//! +//! # Usage Examples +//! +//! Over `ToyBlockCipher` (see the [module docs](super) for why); `bouncycastle-aes`'s aliases +//! carry examples over AES with published vectors: +//! +//! ``` +//! # mod toy { include!("../../tests/common/toy_block_cipher.rs"); } +//! # use toy::ToyBlockCipher; +//! use bouncycastle_cipher::modes::XTSKey; +//! use bouncycastle_core::key_material::{KeyMaterial, KeyType}; +//! use bouncycastle_core::symmetric_key::FromKeyMaterial; +//! +//! // Key = Key_1 | Key_2: 32 bytes over a permutation with a 16-byte key, the two halves distinct. +//! let key_bytes: [u8; 32] = core::array::from_fn(|i| i as u8 + 1); +//! let material = KeyMaterial::<32>::from_bytes_as_type(&key_bytes, KeyType::SymmetricCipherKey) +//! .expect("a 32-byte symmetric cipher key"); +//! +//! // 512-byte data units: the length is part of the key's type. +//! let key = XTSKey::::from_key_material(&material).expect("an XTS key"); +//! +//! let mut sector = [0x5Au8; 512]; +//! let tweak = 7u128.to_le_bytes(); // the data unit's sequence number +//! assert_eq!(key.encrypt_inplace(&tweak, &mut sector), 512); +//! assert_ne!(sector, [0x5Au8; 512]); +//! assert_eq!(key.decrypt_inplace(&tweak, &mut sector), 512); +//! assert_eq!(sector, [0x5Au8; 512]); +//! ``` +//! +//! # 🚨 Security Considerations 🚨 +//! +//! ## XTS provides confidentiality only +//! +//! SP 800-38E: "The mode does not provide authentication of the data or its source." A changed +//! ciphertext block decrypts to an unpredictable plaintext block rather than to an error, and an +//! older ciphertext of a data unit decrypts to the older plaintext. Each 16-byte block is +//! encrypted on its own under its position's mask, so someone who sees two versions of a data +//! unit learns which of its blocks changed, and the same plaintext under the same key and tweak +//! always gives the same ciphertext. Where any of that matters, authenticate the data, or use an +//! AEAD, which a format that can store a nonce and a tag should. +//! +//! ## XTS is for storage +//! +//! SP 800-38E Sec 3: "The XTS-AES mode was not designed for other purposes, such as the +//! encryption of data in transit", and FIPS 140-3 IG C.I: "AES-XTS is only approved for storage +//! purposes." +//! +//! ## One tweak per data unit +//! +//! The tweak is what makes the encryption of each data unit differ. Two data units encrypted +//! under one key and one tweak are encrypted under the same masks, so a block that is equal in +//! both, at the same offset, has an equal ciphertext in both. Give every data unit under a key its +//! own tweak, its sequence number. +//! +//! ## `Key_1` and `Key_2` must be independent +//! +//! FIPS 140-3 IG C.I requires `Key_1` and `Key_2` to be "generated and/or established +//! independently", and a module to "check explicitly that Key_1 ≠ Key_2": with equal halves, XTS +//! falls to a chosen-ciphertext attack. The key's constructor refuses equal halves, and one of +//! all zeros, but it cannot check independence. Draw the whole key from an RNG, with +//! `FromKeyMaterial::generate`, rather than deriving one half from the other. +//! +//! ## One data-unit length per key +//! +//! An instance of XTS-AES has "a single, fixed length for the data units that the key protects" +//! (SP 800-38E Sec 4), which a key type, with its `DATA_UNIT_LEN`, keeps to. Constructing a +//! second key type of another length from the same material steps outside it. + +use crate::{Decrypting, Encrypting}; +use bouncycastle_core::errors::{KeyMaterialError, SymmetricCipherError}; +use bouncycastle_core::hazmat::{BlockPermutation, KeyExpansion}; +use bouncycastle_core::key_material::{KeyMaterial, KeyMaterialTrait, KeyType}; +use bouncycastle_core::security_strength::SecurityStrength; +use bouncycastle_core::symmetric_key::FromKeyMaterial; +use bouncycastle_utils::ct::ct_eq_bytes; +use bouncycastle_utils::min; +use bouncycastle_utils::secret::Secret; + +/// The block length XTS is defined on: 128 bits, the width of the field GF(2^128) in which the +/// tweak's mask is multiplied by α from one block to the next. +const BLOCK_LEN: usize = 16; + +/// A 128-bit block. +type Block = [u8; BLOCK_LEN]; + +/// The length of the tweak, in bytes: the 128-bit tweak value `i`. +pub const XTS_TWEAK_LEN: usize = 16; + +/// The shortest data unit, in bytes: one block. +pub const XTS_MIN_DATA_UNIT_LEN: usize = BLOCK_LEN; + +/// The longest data unit, in bytes: 2^20 blocks, 16 MiB (SP 800-38E Sec 4). +pub const XTS_MAX_DATA_UNIT_LEN: usize = (1 << 20) * BLOCK_LEN; + +/// An XTS key over the permutation `P`, for data units of exactly `DATA_UNIT_LEN` bytes: +/// `Key_1` and `Key_2`, each expanded once, when the key is made. +/// +/// Built with [`FromKeyMaterial`] from `Key = Key_1 | Key_2`, which is 32 bytes over a permutation +/// with a 16-byte key and 64 over one with a 32-byte key, tagged [`KeyType::SymmetricCipherKey`]. +/// It encrypts and decrypts one data unit at a time, in place, under the data unit's tweak; see +/// the [module docs](self) for the tweak, and for the security considerations. +/// +/// The only state is the two expanded keys, which the permutation holds so that they are +/// zeroized on drop; the key has no `Debug` and no way to read the material back. +/// +/// # Construction +/// +/// `from_key_material` refuses the key, as a [`SymmetricCipherError::KeyMaterialError`], with: +/// * [`KeyMaterialError::InvalidKeyType`] if it is not tagged [`KeyType::SymmetricCipherKey`], +/// or if either half is all zeros, which the permutation refuses as it does an all-zero key; +/// * [`KeyMaterialError::InvalidLength`] if it holds fewer bytes than the full key length; +/// * [`KeyMaterialError::GenericError`] if `Key_1` and `Key_2` are equal (FIPS 140-3 IG C.I); +/// * [`KeyMaterialError::SecurityStrength`] if it is tagged below the permutation's strength. +/// Each half carries the key's strength, capped at what the half's length can carry. +/// +/// # The data-unit length is checked at compile time +/// +/// A `DATA_UNIT_LEN` below [`XTS_MIN_DATA_UNIT_LEN`], an empty data unit included, or above +/// [`XTS_MAX_DATA_UNIT_LEN`] does not build. The check runs where the key type is used, so +/// `cargo build` and `cargo test` report it, and `cargo check` does not: +/// +/// ```compile_fail +/// # mod toy { include!("../../tests/common/toy_block_cipher.rs"); } +/// # use toy::ToyBlockCipher; +/// # use bouncycastle_cipher::modes::{XTS_MAX_DATA_UNIT_LEN, XTSKey}; +/// # use bouncycastle_core::key_material::{KeyMaterial, KeyType}; +/// # use bouncycastle_core::symmetric_key::FromKeyMaterial; +/// # let bytes: [u8; 32] = core::array::from_fn(|i| i as u8 + 1); +/// # let km = KeyMaterial::<32>::from_bytes_as_type(&bytes, KeyType::SymmetricCipherKey) +/// # .expect("a 32-byte key"); +/// // Shorter than one block. +/// let key = XTSKey::::from_key_material(&km); +/// ``` +/// +/// ```compile_fail +/// # mod toy { include!("../../tests/common/toy_block_cipher.rs"); } +/// # use toy::ToyBlockCipher; +/// # use bouncycastle_cipher::modes::{XTS_MAX_DATA_UNIT_LEN, XTSKey}; +/// # use bouncycastle_core::key_material::{KeyMaterial, KeyType}; +/// # use bouncycastle_core::symmetric_key::FromKeyMaterial; +/// # let bytes: [u8; 32] = core::array::from_fn(|i| i as u8 + 1); +/// # let km = KeyMaterial::<32>::from_bytes_as_type(&bytes, KeyType::SymmetricCipherKey) +/// # .expect("a 32-byte key"); +/// // Longer than 2^20 blocks. +/// let key = XTSKey::::from_key_material(&km); +/// ``` +/// +/// The two bounds themselves build: +/// +/// ``` +/// # mod toy { include!("../../tests/common/toy_block_cipher.rs"); } +/// # use toy::ToyBlockCipher; +/// # use bouncycastle_cipher::modes::{XTS_MAX_DATA_UNIT_LEN, XTSKey}; +/// # use bouncycastle_core::key_material::{KeyMaterial, KeyType}; +/// # use bouncycastle_core::symmetric_key::FromKeyMaterial; +/// # let bytes: [u8; 32] = core::array::from_fn(|i| i as u8 + 1); +/// # let km = KeyMaterial::<32>::from_bytes_as_type(&bytes, KeyType::SymmetricCipherKey) +/// # .expect("a 32-byte key"); +/// let shortest = XTSKey::::from_key_material(&km); +/// let longest = XTSKey::::from_key_material(&km); +/// # assert!(shortest.is_ok() && longest.is_ok()); +/// ``` +pub struct XTSKey { + /// `Key_1`, which encrypts the data. + key1: P, + /// `Key_2`, which encrypts the tweak. + key2: P, +} + +impl XTSKey { + /// The bounds on the data-unit length, a compile-time error where the key type is used: + /// evaluated when a constructor or a method is monomorphised, so that the private functions + /// below are never handed a data unit outside them. + const DATA_UNIT_LEN_CHECK: () = assert!( + DATA_UNIT_LEN >= XTS_MIN_DATA_UNIT_LEN && DATA_UNIT_LEN <= XTS_MAX_DATA_UNIT_LEN, + "an XTS data unit is from one block to 2^20 blocks (SP 800-38E Sec 4)" + ); +} + +impl, const DATA_UNIT_LEN: usize> XTSKey { + /// Encrypts one data unit in place under its tweak, and returns the number of bytes written, + /// which is always `DATA_UNIT_LEN`: the ciphertext is as long as the plaintext. + pub fn encrypt_inplace( + &self, + tweak: &[u8; XTS_TWEAK_LEN], + data_unit: &mut [u8; DATA_UNIT_LEN], + ) -> usize { + const { Self::DATA_UNIT_LEN_CHECK }; + encrypt(&self.key1, &self.key2, tweak, data_unit); + DATA_UNIT_LEN + } + + /// Decrypts one data unit in place under the tweak it was encrypted under, and returns the + /// number of bytes written, which is always `DATA_UNIT_LEN`. There is nothing to verify: any + /// data unit decrypts, a modified one to unpredictable plaintext. + pub fn decrypt_inplace( + &self, + tweak: &[u8; XTS_TWEAK_LEN], + data_unit: &mut [u8; DATA_UNIT_LEN], + ) -> usize { + const { Self::DATA_UNIT_LEN_CHECK }; + decrypt(&self.key1, &self.key2, tweak, data_unit); + DATA_UNIT_LEN + } +} + +// One impl per key length, because the XTS key's length, twice the permutation's, cannot be +// written as an expression over the permutation's on stable Rust. + +impl FromKeyMaterial<32> for XTSKey +where + P: KeyExpansion<16> + BlockPermutation, +{ + const KEY_TYPE: KeyType = KeyType::SymmetricCipherKey; + + /// Splits the 32-byte `Key_1 | Key_2` into two 16-byte keys and expands each; see + /// [`XTSKey`] for when it refuses. + fn from_key_material(key: &KeyMaterial<32>) -> Result { + const { Self::DATA_UNIT_LEN_CHECK }; + let (key1, key2) = expand_halves::(key)?; + Ok(Self { key1, key2 }) + } +} + +impl FromKeyMaterial<64> for XTSKey +where + P: KeyExpansion<32> + BlockPermutation, +{ + const KEY_TYPE: KeyType = KeyType::SymmetricCipherKey; + + /// Splits the 64-byte `Key_1 | Key_2` into two 32-byte keys and expands each; see + /// [`XTSKey`] for when it refuses. + fn from_key_material(key: &KeyMaterial<64>) -> Result { + const { Self::DATA_UNIT_LEN_CHECK }; + let (key1, key2) = expand_halves::(key)?; + Ok(Self { key1, key2 }) + } +} + +/// Parses `key` as `Key_1 | Key_2` and expands each half for `P`, after the checks that belong to +/// the XTS key as a whole: its type, its length, and `Key_1 != Key_2`. The permutation then checks +/// each half as it would any key of its own. +fn expand_halves( + key: &KeyMaterial, +) -> Result<(P, P), SymmetricCipherError> +where + P: KeyExpansion, +{ + const { assert!(FULL == 2 * HALF, "an XTS key is two keys for the permutation") }; + + // The halves are retagged for the permutation below, so the XTS key's own type is checked + // here; otherwise a MAC key, say, would pass as a cipher key. + if key.key_type() != KeyType::SymmetricCipherKey { + return Err(KeyMaterialError::InvalidKeyType( + "XTS requires a key of type KeyType::SymmetricCipherKey.", + ) + .into()); + } + // A `KeyMaterial` can hold fewer than FULL bytes. Splitting a short key would hand the + // permutation a short second half, or none; refuse it rather than take the buffer's zeros. + if key.key_len() != FULL { + return Err(KeyMaterialError::InvalidLength.into()); + } + + // FIPS 140-3 IG C.I: "Key is then parsed as the concatenation of two AES keys, denoted by + // Key_1 and Key_2". + let (key1, key2) = key.ref_to_bytes().split_at(HALF); + + // FIPS 140-3 IG C.I: "The module shall check explicitly that Key_1 ≠ Key_2, regardless of how + // Key_1 and Key_2 are obtained." In constant time; only the outcome, a refusal, is public. + if ct_eq_bytes(key1, key2) { + return Err(KeyMaterialError::GenericError( + "XTS requires Key_1 != Key_2 (FIPS 140-3 IG C.I).", + ) + .into()); + } + + let strength = key.security_strength(); + Ok((P::new(&half(key1, strength)?)?, P::new(&half(key2, strength)?)?)) +} + +/// One half of the XTS key as a key for the permutation: `bytes` tagged +/// [`KeyType::SymmetricCipherKey`], at the XTS key's `strength` capped at what `HALF` bytes carry. +/// +/// `from_bytes_as_type` credits a key with its full length, which for an XTS key tagged below +/// that would raise its strength in the halves; lowering it again needs no hazardous-operations +/// window. An all-zero half comes back [`KeyType::Zeroized`], at no strength, for the permutation +/// to refuse. +fn half( + bytes: &[u8], + strength: SecurityStrength, +) -> Result, SymmetricCipherError> { + let mut half = KeyMaterial::::from_bytes_as_type(bytes, KeyType::SymmetricCipherKey)?; + let capped = *min(&strength, &half.security_strength()); + half.set_security_strength(capped)?; + Ok(half) +} + +// The algorithm. IEEE 1619-2007 itself was not to hand when this was written; the conventions +// below -- the order of the key halves, the byte order of the multiplication by α, and the order +// of the two blocks that ciphertext stealing produces -- are those of NIST's ACVP reference +// implementation of XTS-AES, and the NIST ACVP and Wycheproof vectors in `bouncycastle-aes` pin +// every one of them. The procedure names are SP 800-38E's: XTS-AES-blockEnc and -blockDec on one +// block, XTS-AES-Enc and -Dec on a data unit. The step numbers in the comments are the ones that +// reference implementation gives the steps of XTS-AES-blockEnc and -blockDec. + +/// Step 3 of XTS-AES-blockEnc and XTS-AES-blockDec, the only step in which the two directions +/// differ: the forward cipher under `Key_1` when encrypting, the inverse when decrypting. The +/// mask, and its XOR on either side of the cipher, are the same in both. +trait CipherStep

{ + fn one(key1: &P, block: &mut Block); + fn two(key1: &P, blocks: &mut [Block; 2]); + fn four(key1: &P, blocks: &mut [Block; 4]); +} + +impl> CipherStep

for Encrypting { + fn one(key1: &P, block: &mut Block) { + key1.encrypt_block(block); + } + + fn two(key1: &P, blocks: &mut [Block; 2]) { + key1.encrypt_2blocks(blocks); + } + + fn four(key1: &P, blocks: &mut [Block; 4]) { + key1.encrypt_4blocks(blocks); + } +} + +impl> CipherStep

for Decrypting { + fn one(key1: &P, block: &mut Block) { + key1.decrypt_block(block); + } + + fn two(key1: &P, blocks: &mut [Block; 2]) { + key1.decrypt_2blocks(blocks); + } + + fn four(key1: &P, blocks: &mut [Block; 4]) { + key1.decrypt_4blocks(blocks); + } +} + +/// `T ⊗ α`: multiplication by the primitive element α = x of GF(2^128), modulo +/// x^128 + x^7 + x^2 + x + 1, with the block read as a little-endian polynomial -- byte 0 holds +/// the coefficients of x^0..x^7 (bit k of the byte for x^k), byte 15 those of x^120..x^127. +/// +/// That is a one-bit shift towards the top across the bytes, from byte 0 up; when the bit +/// shifted out of byte 15, the coefficient of x^127, is set, x^128 reduces to x^7 + x^2 + x + 1 +/// and 0x87 is XORed into byte 0. The reduction is selected with a mask rather than a branch, +/// since `T` is secret (it is the tweak encrypted under `Key_2`), as CMAC's doubling does. +fn mul_alpha(t: &mut Block) { + // The carry out of x^127, read before byte 15 is overwritten. + let carry = t[BLOCK_LEN - 1] >> 7; + // From the top byte down, so that byte k - 1 still holds its old value when byte k takes its + // top bit. The two operands of `|` have no bit in common, so `|` and `^` agree here. + for k in (1..BLOCK_LEN).rev() { + t[k] = (t[k] << 1) | (t[k - 1] >> 7); + } + t[0] = (t[0] << 1) ^ (0x87 & 0u8.wrapping_sub(carry)); +} + +/// `block ^= mask`. +fn xor_into(block: &mut Block, mask: &Block) { + for (b, m) in block.iter_mut().zip(mask) { + *b ^= m; + } +} + +/// XTS-AES-blockEnc (`D = Encrypting`) or -blockDec (`D = Decrypting`) of one block in place, +/// under the mask `t`, which is `T = AES-enc(Key_2, i) ⊗ α^j` for the block's index `j` (step +/// 1): step 2 XORs `T` in, step 3 runs the cipher under `Key_1`, step 4 XORs `T` in again. +fn xex>(key1: &P, t: &Block, block: &mut Block) { + xor_into(block, t); // step 2: PP = P ^ T (CC = C ^ T) + D::one(key1, block); // step 3: CC = AES-enc(Key_1, PP) (PP = AES-dec(Key_1, CC)) + xor_into(block, t); // step 4: C = CC ^ T (P = PP ^ T) +} + +/// [`xex`] on each of `blocks` in turn, with consecutive indices: the first under the mask in `t` +/// and each later one under the mask before it times α. Returns with `t` holding the mask for the +/// index after the last block. +/// +/// Given its mask, each block is independent of the others, so they go through the permutation +/// four at a time, then two, then one; the masks are the same sequence whatever the grouping. +fn xex_blocks>(key1: &P, t: &mut Block, blocks: &mut [Block]) { + // The masks of the blocks in flight. Declared once, before the loops, so that they are + // zeroized once, after them. + let mut masks: Secret<[Block; 4]> = Secret::new(); + + let (fours, rest) = blocks.as_chunks_mut::<4>(); + for four in fours { + for (block, mask) in four.iter_mut().zip(masks.iter_mut()) { + *mask = *t; + xor_into(block, mask); + mul_alpha(t); + } + D::four(key1, four); + for (block, mask) in four.iter_mut().zip(masks.iter()) { + xor_into(block, mask); + } + } + + // At most three blocks are left: a pair and a single, or one of them, or none. + let (twos, ones) = rest.as_chunks_mut::<2>(); + for two in twos { + for (block, mask) in two.iter_mut().zip(masks.iter_mut()) { + *mask = *t; + xor_into(block, mask); + mul_alpha(t); + } + D::two(key1, two); + for (block, mask) in two.iter_mut().zip(masks.iter()) { + xor_into(block, mask); + } + } + for one in ones { + xex::(key1, t, one); + mul_alpha(t); + } +} + +/// The mask of block 0 of a data unit under the tweak `i`: `T = AES-enc(Key_2, i) ⊗ α^0`, the +/// tweak encrypted under `Key_2` in both directions. +fn first_mask>(key2: &P, i: &Block) -> Secret { + let mut t: Secret = Secret::new(); + *t = *i; + key2.encrypt_block(&mut t); + t +} + +/// XTS-AES-Enc of the data unit `data`, in place, under the tweak `i`. `data` is from +/// [`XTS_MIN_DATA_UNIT_LEN`] to [`XTS_MAX_DATA_UNIT_LEN`] bytes long, which the callers check at +/// compile time. +fn encrypt>(key1: &P, key2: &P, i: &Block, data: &mut [u8]) { + let mut t = first_mask(key2, i); + + // `blocks` are P_0 .. P_{m-1}, the whole blocks, and `tail` is P_m, the b < 16 bytes after + // them, which is empty when the data unit is a whole number of blocks. + let (blocks, tail) = data.as_chunks_mut::(); + + // C_q = XTS-AES-blockEnc(P_q, i, q) for every whole block. Without a partial block that is + // the whole data unit; with one, the last of them is the CC that ciphertext stealing takes + // apart. + xex_blocks::(key1, &mut t, blocks); + + // Ciphertext stealing, SP 800-38E Sec 5: "Cm is the truncation of a block that is derived + // from Pm-1, and Cm-1 is derived from Pm, concatenated with the discarded bits from the + // truncation." The last whole block holds CC, P_{m-1} encrypted under index m - 1. Swapping + // its first b bytes with the tail leaves C_m = CC[..b] in the tail, in its place after C_{m-1}, + // and PP = P_m || CC[b..] in the block, which is then encrypted under index m -- the mask now + // in `t` -- to C_{m-1}. Every index here depends on the length alone. + if !tail.is_empty() + && let Some(last) = blocks.last_mut() + { + last[..tail.len()].swap_with_slice(tail); + xex::(key1, &t, last); + } +} + +/// XTS-AES-Dec of the data unit `data`, in place, under the tweak `i`. The length is as for +/// [`encrypt`]. +fn decrypt>(key1: &P, key2: &P, i: &Block, data: &mut [u8]) { + let mut t = first_mask(key2, i); + let (blocks, tail) = data.as_chunks_mut::(); + + // With a partial block, ciphertext stealing undoes the encryption's last two block + // operations, which used indices m - 1 and m, in the reverse order: C_{m-1} first, under m. + if !tail.is_empty() + && let Some((last, head)) = blocks.split_last_mut() + { + // P_q = XTS-AES-blockDec(C_q, i, q) for q < m - 1, leaving the mask of m - 1 in `t`. + xex_blocks::(key1, &mut t, head); + + // PP = XTS-AES-blockDec(C_{m-1}, i, m) = P_m || CC[b..], under the mask after `t`'s. + let mut t_m: Secret = Secret::new(); + *t_m = *t; + mul_alpha(&mut t_m); + xex::(key1, &t_m, last); + + // Swapping the first b bytes back puts P_m in the tail and CC = C_m || CC[b..] in the + // block, and P_{m-1} = XTS-AES-blockDec(CC, i, m - 1). + last[..tail.len()].swap_with_slice(tail); + xex::(key1, &t, last); + } else { + // P_q = XTS-AES-blockDec(C_q, i, q) for every block. + xex_blocks::(key1, &mut t, blocks); + } +} diff --git a/crypto/cipher/tests/modes/xts_tests.rs b/crypto/cipher/tests/modes/xts_tests.rs new file mode 100644 index 000000000..1f921dad2 --- /dev/null +++ b/crypto/cipher/tests/modes/xts_tests.rs @@ -0,0 +1,228 @@ +//! Structural tests for XTS, driven by a toy permutation: the key constructor's refusals, +//! ciphertext stealing as SP 800-38E Sec 5 describes it, which ciphertext blocks a change to each +//! plaintext block reaches, and that the pair and four-block paths are really taken. The known +//! answers -- NIST ACVP, Wycheproof and OpenSSL -- and the 64-byte key are in the `aes` crate, +//! `crypto/aes/tests/xts_*.rs`. + +mod common; + +use bouncycastle_cipher::modes::XTSKey; +use bouncycastle_core::errors::{KeyMaterialError, SymmetricCipherError}; +use bouncycastle_core::key_material::{KeyMaterial, KeyMaterialTrait, KeyType}; +use bouncycastle_core::security_strength::SecurityStrength; +use bouncycastle_core::symmetric_key::FromKeyMaterial; +use bouncycastle_core_test_framework::from_key_material::TestFrameworkFromKeyMaterial; +use common::{SwappedFourToy, SwappedPairToy, Toy}; + +const TWEAK: [u8; 16] = [ + 0x00, 0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77, 0x88, 0x99, 0xaa, 0xbb, 0xcc, 0xdd, 0xee, 0xff, +]; + +/// `Key_1 | Key_2` for the toy, with distinct halves. +fn key_bytes() -> [u8; 32] { + core::array::from_fn(|i| (i as u8).wrapping_mul(7).wrapping_add(3)) +} + +fn material(bytes: &[u8]) -> KeyMaterial<32> { + KeyMaterial::<32>::from_bytes_as_type(bytes, KeyType::SymmetricCipherKey).unwrap() +} + +fn toy_xts() -> XTSKey +where + XTSKey: FromKeyMaterial<32>, +{ + XTSKey::::from_key_material(&material(&key_bytes())).expect("a valid XTS key") +} + +fn pattern() -> [u8; N] { + core::array::from_fn(|k| (k as u8).wrapping_mul(13).wrapping_add(5)) +} + +fn encrypt(pt: &[u8; N]) -> [u8; N] { + let mut data_unit = *pt; + toy_xts::().encrypt_inplace(&TWEAK, &mut data_unit); + data_unit +} + +// ---- the key ----------------------------------------------------------------------------------- + +/// The construction suite: key type, strength and `generate`. +#[test] +fn the_key_enforces_the_material_policy() { + TestFrameworkFromKeyMaterial::new() + .test::<32, XTSKey>("XTS over the toy", SecurityStrength::_128bit); +} + +fn refusal(key: &KeyMaterial<32>) -> KeyMaterialError { + match XTSKey::::from_key_material(key) { + Err(SymmetricCipherError::KeyMaterialError(e)) => e, + Err(e) => panic!("refused, but not as a KeyMaterialError: {e:?}"), + Ok(_) => panic!("accepted"), + } +} + +/// FIPS 140-3 IG C.I: Key_1 = Key_2 is refused. Halves that differ only in their last byte, or +/// only in their first, are not. +#[test] +fn equal_halves_are_refused() { + let half: [u8; 16] = core::array::from_fn(|i| i as u8 + 0x40); + let mut bytes = [0u8; 32]; + bytes[..16].copy_from_slice(&half); + bytes[16..].copy_from_slice(&half); + assert!(matches!(refusal(&material(&bytes)), KeyMaterialError::GenericError(_))); + + for differing in [16, 31] { + let mut close = bytes; + close[differing] ^= 0x01; + XTSKey::::from_key_material(&material(&close)) + .expect("halves that differ in one byte are accepted"); + } +} + +/// A half of all zeros is refused, as the permutation refuses an all-zero key; so is a key of +/// all zeros, which `KeyMaterial` tags as zeroized. +#[test] +fn zero_halves_are_refused() { + let mut low_zero = key_bytes(); + low_zero[..16].fill(0); + let mut high_zero = key_bytes(); + high_zero[16..].fill(0); + for bytes in [low_zero, high_zero, [0u8; 32]] { + assert!(matches!(refusal(&material(&bytes)), KeyMaterialError::InvalidKeyType(_))); + } +} + +/// A `KeyMaterial<32>` holding fewer than 32 bytes is refused rather than split short. +#[test] +fn a_short_key_is_refused() { + for len in [1, 16, 31] { + let short = material(&key_bytes()[..len]); + assert_eq!(short.key_len(), len); + assert_eq!(refusal(&short), KeyMaterialError::InvalidLength); + } +} + +// ---- ciphertext stealing ----------------------------------------------------------------------- + +/// Ciphertext stealing for a data unit of `LEN` = 16m + b bytes, against the encryption of whole +/// blocks. `ALIGNED` is 16m, and `NEXT` 16(m + 1). SP 800-38E Sec 5: "Cm is the truncation of a +/// block that is derived from Pm-1, and Cm-1 is derived from Pm, concatenated with the discarded +/// bits from the truncation." +fn stealing() { + assert!(ALIGNED.is_multiple_of(16) && ALIGNED < LEN && LEN < NEXT && NEXT == ALIGNED + 16); + let b = LEN - ALIGNED; + let last = ALIGNED - 16; // where block m - 1 starts + + let pt: [u8; LEN] = pattern(); + let ct = encrypt(&pt); + + // The whole blocks P_0 .. P_{m-1}, encrypted on their own: CC, the encryption of P_{m-1} under + // index m - 1, is the last of them. + let aligned = encrypt::(pt[..ALIGNED].try_into().unwrap()); + let cc = &aligned[last..]; + + // Nothing before C_{m-1} is touched. + assert_eq!(ct[..last], aligned[..last], "{LEN} bytes: the leading blocks"); + // C_m is CC truncated to b bytes, and is the tail of the ciphertext. + assert_eq!(ct[ALIGNED..], cc[..b], "{LEN} bytes: C_m"); + // C_{m-1} is P_m || CC[b..] encrypted under index m: block m of a data unit one block longer. + let mut q: [u8; NEXT] = [0; NEXT]; + q[..ALIGNED].copy_from_slice(&pt[..ALIGNED]); + q[ALIGNED..ALIGNED + b].copy_from_slice(&pt[ALIGNED..]); + q[ALIGNED + b..].copy_from_slice(&cc[b..]); + assert_eq!(ct[last..ALIGNED], encrypt(&q)[ALIGNED..], "{LEN} bytes: C_m-1"); + + // And decryption undoes it. + let mut back = ct; + toy_xts::().decrypt_inplace(&TWEAK, &mut back); + assert_eq!(back, pt, "{LEN} bytes: decryption"); +} + +#[test] +fn ciphertext_stealing_is_as_sp_800_38e_describes_it() { + stealing::<16, 17, 32>(); // m = 1, b = 1 + stealing::<16, 31, 32>(); // m = 1, b = 15 + stealing::<32, 39, 48>(); // m = 2, b = 7 + stealing::<80, 83, 96>(); // m = 5, b = 3: the four path, then one block, before stealing + stealing::<128, 137, 144>(); // m = 8, b = 9 +} + +// ---- which blocks a change reaches ------------------------------------------------------------- + +/// The ciphertext blocks (16-byte chunks, the last one short) that differ between `a` and `b`. +fn changed_blocks(a: &[u8; N], b: &[u8; N]) -> Vec { + a.chunks(16) + .zip(b.chunks(16)) + .enumerate() + .filter(|(_, (x, y))| x != y) + .map(|(j, _)| j) + .collect() +} + +/// Each block is encrypted on its own under its position's mask, so a change to plaintext block +/// j reaches ciphertext block j only. With a partial block, P_{m-1} reaches both stolen blocks and +/// P_m only C_{m-1}. +#[test] +fn a_change_reaches_only_its_own_blocks() { + let pt: [u8; 64] = pattern(); + let ct = encrypt(&pt); + for j in 0..4 { + let mut changed = pt; + changed[16 * j..16 * (j + 1)].iter_mut().for_each(|b| *b = !*b); + assert_eq!(changed_blocks(&ct, &encrypt(&changed)), [j], "aligned, block {j}"); + } + + // m = 2, b = 8: P_0, P_1 = P_{m-1}, and the tail P_2 = P_m. + let pt: [u8; 40] = pattern(); + let ct = encrypt(&pt); + for (range, reached) in [(0..16, &[0][..]), (16..32, &[1, 2][..]), (32..40, &[1][..])] { + let mut changed = pt; + changed[range.clone()].iter_mut().for_each(|b| *b = !*b); + assert_eq!(changed_blocks(&ct, &encrypt(&changed)), reached, "stealing, bytes {range:?}"); + } +} + +// ---- the batched paths ------------------------------------------------------------------------- + +/// The pair path must be taken. [`SwappedPairToy`] returns its two pair results in the wrong +/// order and is otherwise [`Toy`], so a data unit of two whole blocks comes out differently over +/// it in either direction, while a single block, which takes the one-block path, does not. +#[test] +fn the_pair_path_is_really_used() { + let pt = [0x3Cu8; 32]; + let ct = encrypt(&pt); + let mut swapped = pt; + toy_xts::().encrypt_inplace(&TWEAK, &mut swapped); + assert_ne!(swapped, ct, "two blocks must go through encrypt_2blocks"); + let mut back = ct; + toy_xts::().decrypt_inplace(&TWEAK, &mut back); + assert_ne!(back, pt, "two blocks must go through decrypt_2blocks"); + + let one = [0x3Cu8; 16]; + let mut swapped = one; + toy_xts::().encrypt_inplace(&TWEAK, &mut swapped); + assert_eq!(swapped, encrypt(&one), "one block must not pair"); +} + +/// The four-block path must be taken, for whole fours only. [`SwappedFourToy`] rotates its four +/// results and is otherwise [`Toy`], so four blocks come out differently over it in either +/// direction, while three, a pair and one, do not. +#[test] +fn the_four_block_path_is_really_used() { + let pt = [0xC3u8; 64]; + let ct = encrypt(&pt); + let mut swapped = pt; + toy_xts::().encrypt_inplace(&TWEAK, &mut swapped); + assert_ne!(swapped, ct, "four blocks must go through encrypt_4blocks"); + let mut back = ct; + toy_xts::().decrypt_inplace(&TWEAK, &mut back); + assert_ne!(back, pt, "four blocks must go through decrypt_4blocks"); + + let three = [0xC3u8; 48]; + let mut swapped = three; + toy_xts::().encrypt_inplace(&TWEAK, &mut swapped); + assert_eq!(swapped, encrypt(&three), "three blocks must not batch in four"); + let mut back = swapped; + toy_xts::().decrypt_inplace(&TWEAK, &mut back); + assert_eq!(back, three); +} From f53d7d5d49a9d807d680c68a8603f7e7afdcc72f Mon Sep 17 00:00:00 2001 From: officialfrancismendoza Date: Wed, 11 Nov 2026 10:56:11 +0700 Subject: [PATCH 02/10] Corrected step citations, key scope, data per key, attributions, and compile-time length error message citation (#184) --- cli/src/xts_cmd.rs | 7 +- crypto/aes/src/xts.rs | 6 +- crypto/aes/tests/xts_tests.rs | 16 +-- crypto/aes/tests/xts_wycheproof.rs | 7 +- crypto/cipher/src/modes/xts.rs | 168 +++++++++++++------------ crypto/cipher/tests/modes/xts_tests.rs | 8 +- 6 files changed, 113 insertions(+), 99 deletions(-) diff --git a/cli/src/xts_cmd.rs b/cli/src/xts_cmd.rs index 9a49fd386..df62fd2a2 100644 --- a/cli/src/xts_cmd.rs +++ b/cli/src/xts_cmd.rs @@ -6,10 +6,9 @@ //! them: an XTS key protects data units of one fixed length (NIST SP 800-38E Sec 4), and the //! library fixes that length in the key's type, so the command offers the usual sector sizes and //! instantiates a key type for the one chosen. The first data unit is processed under `--tweak` and -//! each later one under the tweak before it plus one, as a 128-bit little-endian integer -- the -//! consecutive sequence numbers of consecutive sectors, as NIST's ACVP tests number the data units -//! of a longer payload. Nothing is prepended or appended: the output is exactly as long as the -//! input. +//! each later one under the tweak before it plus one, read as a 128-bit little-endian integer: the +//! numbering and the encoding of IEEE 1619-2007 Sec 5.1. Nothing is prepended or appended: the +//! output is exactly as long as the input. //! //! # Warning //! diff --git a/crypto/aes/src/xts.rs b/crypto/aes/src/xts.rs index 6505134bb..fdfae09da 100644 --- a/crypto/aes/src/xts.rs +++ b/crypto/aes/src/xts.rs @@ -13,8 +13,8 @@ use bouncycastle_cipher::modes::XTSKey; /// storage. The key is built once with [`FromKeyMaterial`] and encrypts and decrypts one data /// unit at a time, in place: [`encrypt_inplace`](XTSKey::encrypt_inplace) and /// [`decrypt_inplace`](XTSKey::decrypt_inplace). A data unit is from 16 bytes to 2^20 blocks, -/// and a length outside that range does not compile. SP 800-38E approves XTS with these two key -/// sizes only, so there is no XTS-AES-192. +/// and a length outside that range does not compile. IEEE 1619-2007 Sec 6 defines XTS-AES-128 +/// and XTS-AES-256 only, so there is no XTS-AES-192. /// /// # Usage Examples /// @@ -39,7 +39,7 @@ use bouncycastle_cipher::modes::XTSKey; /// 0xea, 0xfd, 0xbd, 0x33, 0x05, 0x11, 0xba, 0xa1, 0xc9, 0x12, 0xea, 0x24, 0xb7, 0xb1, /// 0x30, 0x35, 0x07, 0xab, 0x3a, 0xab, 0xe6, 0x62, 0x1c, /// ]; -/// // The tweak is the sequence number as a 128-bit little-endian integer. +/// // The tweak value, here the sequence number, in little-endian bytes (IEEE 1619-2007 Sec 5.1). /// let tweak = 202u128.to_le_bytes(); /// /// let mut data_unit = plaintext; diff --git a/crypto/aes/tests/xts_tests.rs b/crypto/aes/tests/xts_tests.rs index 20a9f5eef..e2f371221 100644 --- a/crypto/aes/tests/xts_tests.rs +++ b/crypto/aes/tests/xts_tests.rs @@ -1,9 +1,9 @@ //! XTS-AES through its public API: known answers at the data-unit lengths that matter -- one //! block, the ciphertext-stealing edges, a sector and the 2^20-block maximum -- from OpenSSL, an //! independent implementation; every block of a data unit against a reference written here from -//! the definition, which pins the roles of the two key halves, the byte order of the tweak and -//! the multiplication by α; round trips at every length from one block to eight and a half; and -//! the key constructor's refusals. +//! the definition (IEEE 1619-2007 Sec 5.2 and 5.3), which pins the roles of the two key halves, +//! the byte order of the tweak and the multiplication by α; round trips at every length from one +//! block to eight and a half; and the key constructor's refusals. //! //! The published vectors are in `xts_acvp_tests.rs` and `xts_wycheproof.rs`. The compile-time //! bounds on the data-unit length are doctests on `bouncycastle_cipher::modes::XTSKey`. @@ -140,8 +140,9 @@ fn the_longest_data_units_match_openssl() { // ---- the definition, block by block ------------------------------------------------------------ -/// `T ⊗ α` written independently of the implementation: the block as a 128-bit little-endian -/// integer, shifted left one bit, with x^128 reduced to x^7 + x^2 + x + 1 (0x87). +/// `T ⊗ α` (IEEE 1619-2007 Sec 5.2) written independently of the implementation: the block as a +/// 128-bit little-endian integer, shifted left one bit, with x^128 reduced to x^7 + x^2 + x + 1 +/// (0x87). fn times_alpha(t: [u8; 16]) -> [u8; 16] { let x = u128::from_le_bytes(t); let reduction = if x >> 127 == 1 { 0x87 } else { 0 }; @@ -149,8 +150,9 @@ fn times_alpha(t: [u8; 16]) -> [u8; 16] { } /// Every block of an aligned data unit is `C_j = E_K1(P_j ^ T_j) ^ T_j` with -/// `T_j = E_K2(i) ⊗ α^j`, computed here through the raw permutation from the halves of the key: -/// the first half encrypts the data, the second the tweak, and the tweak goes in as given. +/// `T_j = E_K2(i) ⊗ α^j` (IEEE 1619-2007 Sec 5.3.1), computed here through the raw permutation +/// from the halves of the key: the first half encrypts the data, the second the tweak, and the +/// tweak goes in as given. fn follows_the_definition() where P: KeyExpansion + BlockPermutation<16>, diff --git a/crypto/aes/tests/xts_wycheproof.rs b/crypto/aes/tests/xts_wycheproof.rs index a147b3584..fad4110aa 100644 --- a/crypto/aes/tests/xts_wycheproof.rs +++ b/crypto/aes/tests/xts_wycheproof.rs @@ -4,9 +4,10 @@ //! Every case is a valid encryption of a pseudorandom message of 16 to 136 bytes, which between //! them cover each ciphertext-stealing tail length; each is checked in both directions. The file //! gives the tweak as an `iv` of 1 to 16 bytes, which is the leading bytes of the 128-bit tweak -//! with the rest zero: the data unit's sequence number in little-endian, at the width written. -//! OpenSSL reproduces every case in the file under that reading. The 384-bit-key groups are XTS -//! over AES-192, which neither IEEE 1619 nor SP 800-38E defines; they are counted and skipped. +//! with the rest zero: the tweak value's little-endian encoding (IEEE 1619-2007 Sec 5.1) at the +//! width written, as the standard's Annex C pads a 64-bit sector number. OpenSSL reproduces every +//! case in the file under that reading. The 384-bit-key groups are XTS over AES-192, which +//! neither IEEE 1619 nor SP 800-38E defines; they are counted and skipped. use bouncycastle_aes::hazmat::{AES128Internal, AES256Internal}; use bouncycastle_cipher::modes::XTSKey; diff --git a/crypto/cipher/src/modes/xts.rs b/crypto/cipher/src/modes/xts.rs index f69631e66..09219cf01 100644 --- a/crypto/cipher/src/modes/xts.rs +++ b/crypto/cipher/src/modes/xts.rs @@ -1,29 +1,34 @@ -//! XTS, the XEX-based tweaked-codebook mode with ciphertext stealing, as IEEE Std 1619-2007 -//! specifies it for AES and NIST SP 800-38E approves it, over any 128-bit block permutation. +//! XTS, the "XEX Tweakable Block Cipher with Ciphertext Stealing" (SP 800-38E Sec 3), as IEEE Std +//! 1619-2007 Sec 5 specifies it for AES and NIST SP 800-38E approves it, over any 128-bit block +//! permutation. //! //! XTS encrypts one *data unit* -- a disk sector, say -- under a key and a 128-bit *tweak* that //! names the data unit's position, and the ciphertext is exactly as long as the plaintext: there -//! is no IV, no nonce, no padding and no tag. A data unit is at least one block, 16 bytes, and at -//! most 2^20 blocks, 16 MiB, the limit SP 800-38E Sec 4 adds to IEEE 1619: "The length of the data -//! unit for any instance of an implementation of XTS-AES shall not exceed 2^20 AES blocks". A data -//! unit that is not a whole number of blocks is encrypted with ciphertext stealing, so its -//! ciphertext is as long as it is. +//! is no IV, no nonce, no padding and no tag. A data unit is at least one block, 16 bytes +//! (IEEE 1619-2007 Sec 5.1), and at most 2^20 blocks, 16 MiB, a limit that Sec 5.1 recommends and +//! SP 800-38E Sec 4 requires: "The length of the data unit for any instance of an implementation +//! of XTS-AES shall not exceed 2^20 AES blocks". A data unit that is not a whole number of blocks +//! is encrypted with ciphertext stealing, so its ciphertext is as long as it is. IEEE 1619 +//! measures a data unit in bits; this implementation takes whole bytes, a restriction that +//! SP 800-38E Sec 4 allows an implementation to make. //! -//! The key is [`XTSKey`], built with `from_key_material` from the XTS key `Key = Key_1 | Key_2`: -//! two keys for the permutation, `Key_1` encrypting the data and `Key_2` the tweak, so 32 bytes -//! over a permutation with a 16-byte key and 64 over one with a 32-byte key. The data-unit length -//! is the key type's `DATA_UNIT_LEN`, because SP 800-38E Sec 4 defines an instance of XTS-AES by -//! "a secret key" and "a single, fixed length for the data units that the key protects"; a length -//! outside the range is a compile error. The ready-made `XTS_AES_128` / `XTS_AES_256` aliases are -//! in `bouncycastle-aes`. IEEE 1619 specifies XTS for AES only, and AES is the only cipher -//! SP 800-38E approves it for. +//! The key is [`XTSKey`], built with `from_key_material` from the XTS key `Key = Key_1 | Key_2` +//! (IEEE 1619-2007 Sec 5.3.1): two keys for the permutation, `Key_1` encrypting the data and +//! `Key_2` the tweak, so 32 bytes over a permutation with a 16-byte key and 64 over one with a +//! 32-byte key, the 256- and 512-bit keys of XTS-AES-128 and XTS-AES-256 (Sec 6). The data-unit +//! length is the key type's `DATA_UNIT_LEN`, because SP 800-38E Sec 4 defines an instance of +//! XTS-AES by "a secret key" and "a single, fixed length for the data units that the key +//! protects"; a length outside the range is a compile error. The ready-made `XTS_AES_128` / +//! `XTS_AES_256` aliases are in `bouncycastle-aes`. IEEE 1619 specifies XTS for AES only, and AES +//! is the only cipher SP 800-38E approves it for. //! //! # The tweak //! -//! The tweak is the 128-bit value `i` that the mode encrypts under `Key_2`, taken as given. For -//! storage it is the data unit's sequence number as a 128-bit little-endian integer, -//! `u128::to_le_bytes(n)`, the encoding of NIST's ACVP sequence-number vectors (sequence number -//! 255 is the tweak `FF 00 .. 00`). +//! The tweak value `i` is the data unit's position, a non-negative integer; the data units under +//! a key take consecutive values from any first one, typically the logical block address of the +//! first sector (IEEE 1619-2007 Sec 5.1, Sec 6). The methods take `i` as the 16 bytes that are +//! encrypted under `Key_2`, which Sec 5.1 makes its little-endian encoding: `i.to_le_bytes()` for +//! a `u128` `i`, so sector 255's tweak is `FF 00 .. 00`. //! //! # Usage Examples //! @@ -57,13 +62,14 @@ //! //! ## XTS provides confidentiality only //! -//! SP 800-38E: "The mode does not provide authentication of the data or its source." A changed -//! ciphertext block decrypts to an unpredictable plaintext block rather than to an error, and an -//! older ciphertext of a data unit decrypts to the older plaintext. Each 16-byte block is +//! SP 800-38E's abstract: "The mode does not provide authentication of the data or its source." A +//! changed ciphertext block decrypts to an unpredictable plaintext block rather than to an error, +//! and an older ciphertext of a data unit decrypts to the older plaintext. Each 16-byte block is //! encrypted on its own under its position's mask, so someone who sees two versions of a data //! unit learns which of its blocks changed, and the same plaintext under the same key and tweak -//! always gives the same ciphertext. Where any of that matters, authenticate the data, or use an -//! AEAD, which a format that can store a nonce and a tag should. +//! always gives the same ciphertext; IEEE 1619-2007 Annex D.2 and D.3 discuss these limits. Where +//! any of that matters, authenticate the data, or use an AEAD, which a format that can store a +//! nonce and a tag should. //! //! ## XTS is for storage //! @@ -71,12 +77,23 @@ //! encryption of data in transit", and FIPS 140-3 IG C.I: "AES-XTS is only approved for storage //! purposes." //! -//! ## One tweak per data unit +//! ## One key scope per key //! -//! The tweak is what makes the encryption of each data unit differ. Two data units encrypted -//! under one key and one tweak are encrypted under the same masks, so a block that is equal in -//! both, at the same offset, has an equal ciphertext in both. Give every data unit under a key its -//! own tweak, its sequence number. +//! IEEE 1619-2007 Sec 6 allows a key only one *key scope*: a run of data units of one length +//! under consecutive tweak values, so every data unit under the key has its own tweak. Two data +//! units encrypted under one key and one tweak are encrypted under the same masks, so a block that +//! is equal in both, at the same offset, has an equal ciphertext in both, and a ciphertext block +//! of one can be pasted into the other. A key type keeps to one length, its `DATA_UNIT_LEN`; a +//! second key type of another length made from the same material, or a second disk under the +//! same key, steps outside the key scope. +//! +//! ## A bounded amount of data per key +//! +//! The proof that IEEE 1619-2007 Annex D.4.3 (informative) cites gives a strong guarantee while a +//! key encrypts not much more than a terabyte, 2^36 blocks, and a weakening one beyond it; Annex +//! D.6 warns that a few hundred terabytes under one key make attacks possible. The bound comes +//! from the 128-bit block, so a longer key does not raise it. Nothing here counts the blocks a key +//! has encrypted. //! //! ## `Key_1` and `Key_2` must be independent //! @@ -85,12 +102,6 @@ //! falls to a chosen-ciphertext attack. The key's constructor refuses equal halves, and one of //! all zeros, but it cannot check independence. Draw the whole key from an RNG, with //! `FromKeyMaterial::generate`, rather than deriving one half from the other. -//! -//! ## One data-unit length per key -//! -//! An instance of XTS-AES has "a single, fixed length for the data units that the key protects" -//! (SP 800-38E Sec 4), which a key type, with its `DATA_UNIT_LEN`, keeps to. Constructing a -//! second key type of another length from the same material steps outside it. use crate::{Decrypting, Encrypting}; use bouncycastle_core::errors::{KeyMaterialError, SymmetricCipherError}; @@ -112,7 +123,7 @@ type Block = [u8; BLOCK_LEN]; /// The length of the tweak, in bytes: the 128-bit tweak value `i`. pub const XTS_TWEAK_LEN: usize = 16; -/// The shortest data unit, in bytes: one block. +/// The shortest data unit, in bytes: one block, 128 bits (IEEE 1619-2007 Sec 5.1). pub const XTS_MIN_DATA_UNIT_LEN: usize = BLOCK_LEN; /// The longest data unit, in bytes: 2^20 blocks, 16 MiB (SP 800-38E Sec 4). @@ -199,7 +210,7 @@ impl XTSKey { /// below are never handed a data unit outside them. const DATA_UNIT_LEN_CHECK: () = assert!( DATA_UNIT_LEN >= XTS_MIN_DATA_UNIT_LEN && DATA_UNIT_LEN <= XTS_MAX_DATA_UNIT_LEN, - "an XTS data unit is from one block to 2^20 blocks (SP 800-38E Sec 4)" + "an XTS data unit is 1 to 2^20 blocks (IEEE 1619-2007 Sec 5.1, SP 800-38E Sec 4)" ); } @@ -288,8 +299,7 @@ where return Err(KeyMaterialError::InvalidLength.into()); } - // FIPS 140-3 IG C.I: "Key is then parsed as the concatenation of two AES keys, denoted by - // Key_1 and Key_2". + // Key = Key_1 | Key_2, two halves of equal size (IEEE 1619-2007 Sec 5.3.1). let (key1, key2) = key.ref_to_bytes().split_at(HALF); // FIPS 140-3 IG C.I: "The module shall check explicitly that Key_1 ≠ Key_2, regardless of how @@ -322,13 +332,13 @@ fn half( Ok(half) } -// The algorithm. IEEE 1619-2007 itself was not to hand when this was written; the conventions -// below -- the order of the key halves, the byte order of the multiplication by α, and the order -// of the two blocks that ciphertext stealing produces -- are those of NIST's ACVP reference -// implementation of XTS-AES, and the NIST ACVP and Wycheproof vectors in `bouncycastle-aes` pin -// every one of them. The procedure names are SP 800-38E's: XTS-AES-blockEnc and -blockDec on one -// block, XTS-AES-Enc and -Dec on a data unit. The step numbers in the comments are the ones that -// reference implementation gives the steps of XTS-AES-blockEnc and -blockDec. +// The algorithm is IEEE 1619-2007 Sec 5, and the comments use its procedure names and step +// numbers: XTS-AES-blockEnc (Sec 5.3.1) and -blockDec (Sec 5.4.1) on one block, XTS-AES-Enc +// (Sec 5.3.2) and -Dec (Sec 5.4.2) on a data unit, and the multiplication by α (Sec 5.2). Sec +// 5.4.2 letters the sub-steps of its steps 3 and 4 continuously, b) to h), and the comments keep +// those letters. The NIST ACVP and Wycheproof vectors in `bouncycastle-aes` pin the conventions +// that interoperability rests on: the order of the key halves, the byte order of the tweak and of +// the multiplication by α, and the order of the two blocks that ciphertext stealing produces. /// Step 3 of XTS-AES-blockEnc and XTS-AES-blockDec, the only step in which the two directions /// differ: the forward cipher under `Key_1` when encrypting, the inverse when decrypting. The @@ -367,19 +377,22 @@ impl> CipherStep

for Decrypting { } } -/// `T ⊗ α`: multiplication by the primitive element α = x of GF(2^128), modulo -/// x^128 + x^7 + x^2 + x + 1, with the block read as a little-endian polynomial -- byte 0 holds -/// the coefficients of x^0..x^7 (bit k of the byte for x^k), byte 15 those of x^120..x^127. +/// `T ⊗ α` (IEEE 1619-2007 Sec 5.2): multiplication by the primitive element α = x of GF(2^128), +/// modulo x^128 + x^7 + x^2 + x + 1 (Sec 4.2). Byte 0 is the first byte of the AES block, and +/// bit k of byte j is the coefficient of x^(8j + k). /// -/// That is a one-bit shift towards the top across the bytes, from byte 0 up; when the bit -/// shifted out of byte 15, the coefficient of x^127, is set, x^128 reduces to x^7 + x^2 + x + 1 -/// and 0x87 is XORed into byte 0. The reduction is selected with a mask rather than a branch, -/// since `T` is secret (it is the tweak encrypted under `Key_2`), as CMAC's doubling does. +/// Sec 5.2's recurrence is a one-bit shift towards the top across the bytes, from byte 0 up: +/// byte k, for k from 1 to 15, becomes 2 (t[k] mod 128) ^ floor(t[k - 1] / 128), and byte 0 +/// becomes 2 (t[0] mod 128) ^ 135 floor(t[15] / 128). When the bit shifted out of byte 15, the +/// coefficient of x^127, is set, x^128 reduces to x^7 + x^2 + x + 1, and 135 = 0x87 is XORed into +/// byte 0. The reduction is selected with a mask rather than a branch, since `T` is secret (it is +/// the tweak encrypted under `Key_2`), as CMAC's doubling does. fn mul_alpha(t: &mut Block) { - // The carry out of x^127, read before byte 15 is overwritten. + // The carry out of x^127, floor(t[15] / 128), read before byte 15 is overwritten. let carry = t[BLOCK_LEN - 1] >> 7; // From the top byte down, so that byte k - 1 still holds its old value when byte k takes its - // top bit. The two operands of `|` have no bit in common, so `|` and `^` agree here. + // top bit. On a byte, 2 (t[k] mod 128) is `t[k] << 1`, and floor(t[k - 1] / 128) is + // `t[k - 1] >> 7`. The two operands of `|` have no bit in common, so `|` and `^` agree here. for k in (1..BLOCK_LEN).rev() { t[k] = (t[k] << 1) | (t[k - 1] >> 7); } @@ -393,9 +406,10 @@ fn xor_into(block: &mut Block, mask: &Block) { } } -/// XTS-AES-blockEnc (`D = Encrypting`) or -blockDec (`D = Decrypting`) of one block in place, -/// under the mask `t`, which is `T = AES-enc(Key_2, i) ⊗ α^j` for the block's index `j` (step -/// 1): step 2 XORs `T` in, step 3 runs the cipher under `Key_1`, step 4 XORs `T` in again. +/// XTS-AES-blockEnc (`D = Encrypting`, IEEE 1619-2007 Sec 5.3.1) or -blockDec (`D = Decrypting`, +/// Sec 5.4.1) of one block in place, under the mask `t`, which is `T = AES-enc(Key_2, i) ⊗ α^j` +/// for the block's index `j` (step 1): step 2 XORs `T` in, step 3 runs the cipher under `Key_1`, +/// step 4 XORs `T` in again. fn xex>(key1: &P, t: &Block, block: &mut Block) { xor_into(block, t); // step 2: PP = P ^ T (CC = C ^ T) D::one(key1, block); // step 3: CC = AES-enc(Key_1, PP) (PP = AES-dec(Key_1, CC)) @@ -446,7 +460,7 @@ fn xex_blocks>(key1: &P, t: &mut Block, blocks: &mut [Block] } /// The mask of block 0 of a data unit under the tweak `i`: `T = AES-enc(Key_2, i) ⊗ α^0`, the -/// tweak encrypted under `Key_2` in both directions. +/// tweak encrypted under `Key_2` in both directions (step 1 of Sec 5.3.1 and of Sec 5.4.1). fn first_mask>(key2: &P, i: &Block) -> Secret { let mut t: Secret = Secret::new(); *t = *i; @@ -454,9 +468,9 @@ fn first_mask>(key2: &P, i: &Block) -> Secret>(key1: &P, key2: &P, i: &Block, data: &mut [u8]) { let mut t = first_mask(key2, i); @@ -464,17 +478,15 @@ fn encrypt>(key1: &P, key2: &P, i: &Block, data: // them, which is empty when the data unit is a whole number of blocks. let (blocks, tail) = data.as_chunks_mut::(); - // C_q = XTS-AES-blockEnc(P_q, i, q) for every whole block. Without a partial block that is - // the whole data unit; with one, the last of them is the CC that ciphertext stealing takes - // apart. + // Step 1, and step 3a or 4a for the last whole block: XTS-AES-blockEnc(P_q, i, q) for every + // whole block. Without a partial block that is the whole data unit; with one, the last result + // is step 4a's CC, which ciphertext stealing takes apart. xex_blocks::(key1, &mut t, blocks); - // Ciphertext stealing, SP 800-38E Sec 5: "Cm is the truncation of a block that is derived - // from Pm-1, and Cm-1 is derived from Pm, concatenated with the discarded bits from the - // truncation." The last whole block holds CC, P_{m-1} encrypted under index m - 1. Swapping - // its first b bytes with the tail leaves C_m = CC[..b] in the tail, in its place after C_{m-1}, - // and PP = P_m || CC[b..] in the block, which is then encrypted under index m -- the mask now - // in `t` -- to C_{m-1}. Every index here depends on the length alone. + // Ciphertext stealing, steps 4b to 4e. Swapping CC's first b bytes with the tail puts them, + // C_m, in the tail (4b), after C_{m-1} as step 5 orders them, and leaves PP = P_m | CP in the + // block, CP being the rest of CC (4c, 4d); PP is then encrypted under index m -- the mask now + // in `t` -- to C_{m-1} (4e). Every index here depends on the length alone. if !tail.is_empty() && let Some(last) = blocks.last_mut() { @@ -483,8 +495,8 @@ fn encrypt>(key1: &P, key2: &P, i: &Block, data: } } -/// XTS-AES-Dec of the data unit `data`, in place, under the tweak `i`. The length is as for -/// [`encrypt`]. +/// XTS-AES-Dec (IEEE 1619-2007 Sec 5.4.2) of the data unit `data`, in place, under the tweak +/// `i`. The length is as for [`encrypt`]. fn decrypt>(key1: &P, key2: &P, i: &Block, data: &mut [u8]) { let mut t = first_mask(key2, i); let (blocks, tail) = data.as_chunks_mut::(); @@ -494,21 +506,21 @@ fn decrypt>(key1: &P, key2: &P, i: &Block, data: if !tail.is_empty() && let Some((last, head)) = blocks.split_last_mut() { - // P_q = XTS-AES-blockDec(C_q, i, q) for q < m - 1, leaving the mask of m - 1 in `t`. + // Step 1, P_q = XTS-AES-blockDec(C_q, i, q) for q < m - 1, leaves the mask of m - 1 in `t`. xex_blocks::(key1, &mut t, head); - // PP = XTS-AES-blockDec(C_{m-1}, i, m) = P_m || CC[b..], under the mask after `t`'s. + // Step 4d: PP = XTS-AES-blockDec(C_{m-1}, i, m) = P_m | CP, under the mask after `t`'s. let mut t_m: Secret = Secret::new(); *t_m = *t; mul_alpha(&mut t_m); xex::(key1, &t_m, last); - // Swapping the first b bytes back puts P_m in the tail and CC = C_m || CC[b..] in the - // block, and P_{m-1} = XTS-AES-blockDec(CC, i, m - 1). + // Swapping the first b bytes back puts P_m in the tail (4e) and CC = C_m | CP in the + // block (4f, 4g), and P_{m-1} = XTS-AES-blockDec(CC, i, m - 1) (4h). last[..tail.len()].swap_with_slice(tail); xex::(key1, &t, last); } else { - // P_q = XTS-AES-blockDec(C_q, i, q) for every block. + // Steps 1 and 3b: P_q = XTS-AES-blockDec(C_q, i, q) for every block. xex_blocks::(key1, &mut t, blocks); } } diff --git a/crypto/cipher/tests/modes/xts_tests.rs b/crypto/cipher/tests/modes/xts_tests.rs index 1f921dad2..08f4e62ad 100644 --- a/crypto/cipher/tests/modes/xts_tests.rs +++ b/crypto/cipher/tests/modes/xts_tests.rs @@ -104,10 +104,10 @@ fn a_short_key_is_refused() { // ---- ciphertext stealing ----------------------------------------------------------------------- -/// Ciphertext stealing for a data unit of `LEN` = 16m + b bytes, against the encryption of whole -/// blocks. `ALIGNED` is 16m, and `NEXT` 16(m + 1). SP 800-38E Sec 5: "Cm is the truncation of a -/// block that is derived from Pm-1, and Cm-1 is derived from Pm, concatenated with the discarded -/// bits from the truncation." +/// Ciphertext stealing (IEEE 1619-2007 Sec 5.3.2 step 4) for a data unit of `LEN` = 16m + b +/// bytes, against the encryption of whole blocks. `ALIGNED` is 16m, and `NEXT` 16(m + 1). +/// SP 800-38E Sec 5: "Cm is the truncation of a block that is derived from Pm-1, and Cm-1 is +/// derived from Pm, concatenated with the discarded bits from the truncation." fn stealing() { assert!(ALIGNED.is_multiple_of(16) && ALIGNED < LEN && LEN < NEXT && NEXT == ALIGNED + 16); let b = LEN - ALIGNED; From d82639e78f6e863352e51af314dd8a5d22a901ea Mon Sep 17 00:00:00 2001 From: officialfrancismendoza Date: Thu, 19 Nov 2026 11:18:02 -0800 Subject: [PATCH 03/10] Fix rustfmt issues (#184) --- cli/src/main.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/cli/src/main.rs b/cli/src/main.rs index 2dd06d912..fb858ce06 100644 --- a/cli/src/main.rs +++ b/cli/src/main.rs @@ -45,8 +45,8 @@ mod tdes_ctr_cmd; mod tdes_ecb_cmd; mod tdes_ofb_cmd; mod tdes_tkw_cmd; -mod xts_cmd; mod x25519_cmd; +mod xts_cmd; use crate::blake2_cmd::BLAKE2Variant; use crate::eccdh_cmd::ECCDHAction; From a6b9115b374fb08069092dba60a39a31e3953873 Mon Sep 17 00:00:00 2001 From: David Hook Date: Sun, 22 Nov 2026 22:08:15 +1100 Subject: [PATCH 04/10] ci: the no-std step tests digest's unit tests and scrypt's caller-memory tests only Since the digest crate took in the vector suites, the step ran tests that need bc-test-data, which the Build job does not check out, and the concatenation KDF's ACVP suite failed on the missing data. Assisted-by: Claude:claude-opus-5-5 (cherry picked from commit 98f284a0a5e86c43db8aebb4c0e7c40b7ed8018c) --- .gitea/workflows/rust-build.yml | 3 ++- .github/workflows/rust-build.yml | 3 ++- CLAUDE.md | 5 +++-- 3 files changed, 7 insertions(+), 4 deletions(-) diff --git a/.gitea/workflows/rust-build.yml b/.gitea/workflows/rust-build.yml index 4addfa7df..ace9c890b 100644 --- a/.gitea/workflows/rust-build.yml +++ b/.gitea/workflows/rust-build.yml @@ -35,4 +35,5 @@ jobs: # --all-features above never builds a crate with a default feature off. scrypt without # `std` is its caller-supplied-memory configuration, and it once did not compile. - name: Test bouncycastle-digest without std - run: cargo test -p bouncycastle-digest --no-default-features + # The vector suites need bc-test-data, which this job does not check out. + run: cargo test -p bouncycastle-digest --no-default-features --lib --test scrypt_scrypt_caller_memory_tests diff --git a/.github/workflows/rust-build.yml b/.github/workflows/rust-build.yml index 4d2d0c247..b74cb0f98 100644 --- a/.github/workflows/rust-build.yml +++ b/.github/workflows/rust-build.yml @@ -28,4 +28,5 @@ jobs: # --all-features above never builds a crate with a default feature off. scrypt without # `std` is its caller-supplied-memory configuration, and it once did not compile. - name: Test bouncycastle-digest without std - run: cargo test -p bouncycastle-digest --no-default-features + # The vector suites need bc-test-data, which this job does not check out. + run: cargo test -p bouncycastle-digest --no-default-features --lib --test scrypt_scrypt_caller_memory_tests diff --git a/CLAUDE.md b/CLAUDE.md index d4138454a..d5290f97a 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -471,8 +471,9 @@ external vector suites — is specified in QUALITY_AND_STYLE.md and CONTRIBUTING Six workflows under `.github/workflows/`, all triggered by pull requests: - `rust-build.yml`: `cargo build --workspace --all-targets --all-features` on stable, then - `cargo test -p bouncycastle-digest --no-default-features`, since `--all-features` never - builds a crate with a default feature off. + `cargo test -p bouncycastle-digest --no-default-features` on the crate's unit tests and scrypt's + caller-memory tests (the vector suites need bc-test-data, which that job does not check out), + since `--all-features` never builds a crate with a default feature off. - `rust-test.yml`: `cargo test --all` on stable, with `bcgit/bc-test-data` and `C2SP/wycheproof` checked out beside the repository. Wycheproof is pinned to a commit (`ref:` in the workflow), so that a change upstream does not fail an unrelated PR: a vector suite that is strict about the From d6be3ef80e00d97a34fc0d4d8310f174d0000ef9 Mon Sep 17 00:00:00 2001 From: David Hook Date: Mon, 23 Nov 2026 06:15:03 +1100 Subject: [PATCH 05/10] aes: the XTS tests use bouncycastle_core::hex hex moved into core on release. Assisted-by: Claude:claude-opus-5-5 --- crypto/aes/tests/xts_acvp_tests.rs | 2 +- crypto/aes/tests/xts_tests.rs | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/crypto/aes/tests/xts_acvp_tests.rs b/crypto/aes/tests/xts_acvp_tests.rs index 2e06f38d2..03163d591 100644 --- a/crypto/aes/tests/xts_acvp_tests.rs +++ b/crypto/aes/tests/xts_acvp_tests.rs @@ -16,9 +16,9 @@ use bouncycastle_aes::hazmat::{AES128Internal, AES256Internal}; use bouncycastle_cipher::modes::XTSKey; use bouncycastle_core::hazmat::BlockPermutation; +use bouncycastle_core::hex; use bouncycastle_core::key_material::{KeyMaterial, KeyType}; use bouncycastle_core::symmetric_key::FromKeyMaterial; -use bouncycastle_hex as hex; /// One ACVP test case, as hex. struct Vector { diff --git a/crypto/aes/tests/xts_tests.rs b/crypto/aes/tests/xts_tests.rs index e2f371221..834074a82 100644 --- a/crypto/aes/tests/xts_tests.rs +++ b/crypto/aes/tests/xts_tests.rs @@ -15,11 +15,11 @@ use bouncycastle_cipher::modes::{ }; use bouncycastle_core::errors::{KeyMaterialError, SymmetricCipherError}; use bouncycastle_core::hazmat::{BlockPermutation, KeyExpansion}; +use bouncycastle_core::hex; use bouncycastle_core::key_material::{KeyMaterial, KeyMaterialTrait, KeyType}; use bouncycastle_core::security_strength::SecurityStrength; use bouncycastle_core::symmetric_key::FromKeyMaterial; use bouncycastle_core_test_framework::from_key_material::TestFrameworkFromKeyMaterial; -use bouncycastle_hex as hex; /// The tweak of the known answers below. const TWEAK: [u8; 16] = [ From 6b2fc089fca39a89091b6e5f050b5596fb2bfe19 Mon Sep 17 00:00:00 2001 From: David Hook Date: Mon, 23 Nov 2026 08:15:08 +1100 Subject: [PATCH 06/10] aes: the XTS ACVP suite reads NIST's vector sets from bc-test-data The 41 vectors embedded in the test file are replaced by the ACVP-AES-XTS-1.0 and -2.0 sample sets in bc-test-data/crypto/acvp (ACVP-Server commit 975de31e). Every single-data-unit case of whole bytes runs, in both directions: 260 from 1.0 and 72 from 2.0. The bit-length and multiple-data-unit cases are counted and skipped, and the counts are asserted. Assisted-by: Claude:claude-fable-5-2 --- crypto/aes/tests/xts_acvp_tests.rs | 859 +++++------------------------ 1 file changed, 140 insertions(+), 719 deletions(-) diff --git a/crypto/aes/tests/xts_acvp_tests.rs b/crypto/aes/tests/xts_acvp_tests.rs index 03163d591..a4ed710ce 100644 --- a/crypto/aes/tests/xts_acvp_tests.rs +++ b/crypto/aes/tests/xts_acvp_tests.rs @@ -1,747 +1,168 @@ -//! XTS-AES-128 and XTS-AES-256 against NIST's ACVP sample vectors. +//! XTS-AES-128 and XTS-AES-256 against NIST's ACVP sample vector sets `ACVP-AES-XTS-1.0` and +//! `ACVP-AES-XTS-2.0`: `prompt.json` and `expectedResults.json` in +//! `bc-test-data/crypto/acvp/ACVP-AES-XTS-{1.0,2.0}/`, as published in NIST's ACVP-Server +//! repository (`gen-val/json-files`, commit `975de31e`). Requires bc-test-data at +//! `../bc-test-data`; absent, the tests warn and pass. //! -//! The vectors are copied from the `internalProjection.json` of `ACVP-AES-XTS-1.0` and -//! `ACVP-AES-XTS-2.0` in NIST's ACVP-Server repository (`gen-val/json-files`, commit `975de31e`), -//! whose expected values come from NIST's reference implementation; each was also reproduced with -//! OpenSSL when it was copied. bc-test-data has no AES-XTS set, so a subset is embedded here: -//! every whole-byte `ACVP-AES-XTS-2.0` vector of at most 128 bytes -- ciphertext stealing with -//! tails of most lengths, both directions and both tweak modes -- and the shortest of 129 to 700 -//! bytes for each key size, direction and tweak mode that has one. (An ACVP data unit can be any -//! number of bits; this API takes whole bytes.) +//! Every case that is one data unit of a whole number of bytes is run, in both directions +//! whichever one it was generated for. The rest are counted and skipped: an ACVP data unit can be +//! any number of bits, where this API takes whole bytes, and the 2.0 set's cases whose +//! `dataUnitLen` differs from their `payloadLen` are not a data unit of the key's one length. The +//! counts are asserted, so a case cannot drop out of the run unnoticed. //! -//! Each vector is checked in both directions, whichever one it was generated for. A vector of -//! tweak mode "number" gives the data unit's sequence number as well as the tweak, and the check -//! confirms that the tweak is the number's 128-bit little-endian encoding before using it. +//! A case of tweak mode "number" gives the data unit's sequence number, and the tweak is its +//! 128-bit little-endian encoding (IEEE 1619-2007 Sec 5.1); one of mode "hex" gives the tweak. use bouncycastle_aes::hazmat::{AES128Internal, AES256Internal}; use bouncycastle_cipher::modes::XTSKey; use bouncycastle_core::hazmat::BlockPermutation; -use bouncycastle_core::hex; use bouncycastle_core::key_material::{KeyMaterial, KeyType}; use bouncycastle_core::symmetric_key::FromKeyMaterial; +use bouncycastle_core_test_framework::test_data_loaders::{Value, bc_test_data_json, hex_field}; +use std::collections::HashMap; -/// One ACVP test case, as hex. -struct Vector { - /// The revision, `tgId` and `tcId` it was copied from. - source: &'static str, - key: &'static str, - /// The 128-bit tweak value, `tweakValue`. - tweak: &'static str, - /// `sequenceNumber`, for tweak mode "number". - sequence_number: Option, - pt: &'static str, - ct: &'static str, +/// A number, which the files give as a number or as a string. +fn number(v: &Value) -> u64 { + v.as_u64().unwrap_or_else(|| v.as_str().expect("a number").parse().expect("a number")) } -/// Checks `v` through `XTSKey` under its `KEY_LEN`-byte key, in both directions. -fn check(v: &Vector) -where +/// Checks one case through `XTSKey` under its `KEY_LEN`-byte key, in both directions. +fn check( + key: &[u8], + tweak: &[u8; 16], + pt: &[u8], + ct: &[u8], + tc_id: u64, +) where P: BlockPermutation<16>, XTSKey: FromKeyMaterial, { - let material = KeyMaterial::::from_bytes_as_type( - &hex::decode(v.key).unwrap(), - KeyType::SymmetricCipherKey, - ) - .unwrap(); + let material = + KeyMaterial::::from_bytes_as_type(key, KeyType::SymmetricCipherKey).unwrap(); let key = XTSKey::::from_key_material(&material) - .unwrap_or_else(|e| panic!("{}: the key is refused: {e:?}", v.source)); - - let tweak: [u8; 16] = hex::decode(v.tweak).unwrap().try_into().unwrap(); - if let Some(n) = v.sequence_number { - assert_eq!(n.to_le_bytes(), tweak, "{}: the tweak is the sequence number, LE", v.source); - } - let pt: [u8; N] = hex::decode(v.pt).unwrap().try_into().expect("an N-byte plaintext"); - let ct: [u8; N] = hex::decode(v.ct).unwrap().try_into().expect("an N-byte ciphertext"); + .unwrap_or_else(|e| panic!("tcId {tc_id}: the key is refused: {e:?}")); + let pt: [u8; N] = pt.try_into().expect("an N-byte plaintext"); + let ct: [u8; N] = ct.try_into().expect("an N-byte ciphertext"); let mut data_unit = pt; - assert_eq!(key.encrypt_inplace(&tweak, &mut data_unit), N, "{}", v.source); - assert_eq!(data_unit, ct, "{}: encryption", v.source); + assert_eq!(key.encrypt_inplace(tweak, &mut data_unit), N, "tcId {tc_id}"); + assert_eq!(data_unit, ct, "tcId {tc_id}: encryption"); let mut data_unit = ct; - assert_eq!(key.decrypt_inplace(&tweak, &mut data_unit), N, "{}", v.source); - assert_eq!(data_unit, pt, "{}: decryption", v.source); + assert_eq!(key.decrypt_inplace(tweak, &mut data_unit), N, "tcId {tc_id}"); + assert_eq!(data_unit, pt, "tcId {tc_id}: decryption"); } -#[test] -fn acvp_xts_aes_128() { - check::(&V2_TG1_TC4); - check::(&V2_TG3_TC131); - check::(&V2_TG9_TC444); - check::(&V2_TG11_TC535); - check::(&V2_TG3_TC125); - check::(&V2_TG11_TC503); - check::(&V2_TG11_TC516); - check::(&V2_TG3_TC139); - check::(&V2_TG3_TC101); - check::(&V2_TG1_TC13); - check::(&V2_TG1_TC38); - check::(&V2_TG11_TC525); - check::(&V2_TG1_TC36); - check::(&V2_TG11_TC502); - check::(&V2_TG11_TC548); - check::(&V2_TG3_TC144); - check::(&V2_TG9_TC412); - check::(&V2_TG9_TC433); - check::(&V2_TG11_TC508); - check::(&V2_TG9_TC441); - check::(&V2_TG3_TC127); - check::(&V2_TG1_TC18); +fn check_128(key: &[u8], tweak: &[u8; 16], pt: &[u8], ct: &[u8], tc_id: u64) { + check::(key, tweak, pt, ct, tc_id); } -#[test] -fn acvp_xts_aes_256() { - check::(&V1_TG11_TC101); - check::(&V1_TG18_TC171); - check::(&V2_TG5_TC233); - check::(&V2_TG7_TC319); - check::(&V2_TG13_TC642); - check::(&V2_TG15_TC719); - check::(&V2_TG15_TC702); - check::(&V2_TG5_TC237); - check::(&V2_TG15_TC737); - check::(&V2_TG13_TC603); - check::(&V2_TG13_TC640); - check::(&V2_TG13_TC649); - check::(&V2_TG5_TC230); - check::(&V2_TG15_TC717); - check::(&V2_TG13_TC641); - check::(&V2_TG13_TC644); - check::(&V2_TG15_TC712); - check::(&V2_TG7_TC305); - check::(&V2_TG13_TC646); +fn check_256(key: &[u8], tweak: &[u8; 16], pt: &[u8], ct: &[u8], tc_id: u64) { + check::(key, tweak, pt, ct, tc_id); } -// ---- the vectors ---- - -/// ACVP-AES-XTS-2.0 tgId 1 tcId 4: AES-128, encrypt, tweakMode hex, 16 bytes. -const V2_TG1_TC4: Vector = Vector { - source: "ACVP-AES-XTS-2.0 tgId 1 tcId 4", - key: "8acb99d1d215612314d6b262147343f23f1b1e8f34f1dcbd6d57200fae54e8c4", - tweak: "bf0d3404d7bce2b4132d02e90a256ebf", - sequence_number: None, - pt: "ea29098cb827a1de9d69f5b47a500c34", - ct: "7a4cc60de7997471aab765348f08d935", -}; - -/// ACVP-AES-XTS-2.0 tgId 3 tcId 131: AES-128, encrypt, tweakMode number, 16 bytes. -const V2_TG3_TC131: Vector = Vector { - source: "ACVP-AES-XTS-2.0 tgId 3 tcId 131", - key: "852d1f431ecedb3434b856b664b97a319fb70ae546b0a8b359edcc7b00fa0b45", - tweak: "4d000000000000000000000000000000", - sequence_number: Some(77), - pt: "0625bd766ef28555c68ac0a200347f55", - ct: "3ae27f24b6c9ebf7b13d9709c18d1769", -}; - -/// ACVP-AES-XTS-2.0 tgId 9 tcId 444: AES-128, decrypt, tweakMode hex, 16 bytes. -const V2_TG9_TC444: Vector = Vector { - source: "ACVP-AES-XTS-2.0 tgId 9 tcId 444", - key: "ad17809726942ffde1060dd99de05415906c3ea6647ae52d8dbea10238341580", - tweak: "7daa90322aa35fd658cd72f818159f2b", - sequence_number: None, - pt: "a5fdabb4e63926bf33bebfc73e01c05b", - ct: "dc6929d5f7a1c1bb50f5ad10d0ed94fa", -}; - -/// ACVP-AES-XTS-2.0 tgId 11 tcId 535: AES-128, decrypt, tweakMode number, 16 bytes. -const V2_TG11_TC535: Vector = Vector { - source: "ACVP-AES-XTS-2.0 tgId 11 tcId 535", - key: "6aa59d12e31dc3850e22d0ea0641f47478779bd5b8f0dc4b0a0e49e05e7ac055", - tweak: "a9000000000000000000000000000000", - sequence_number: Some(169), - pt: "8732826aad287e864070694a0af4255a", - ct: "1242abfca4a5041936ea5a55c810c7e2", -}; - -/// ACVP-AES-XTS-2.0 tgId 3 tcId 125: AES-128, encrypt, tweakMode number, 23 bytes (b = 7). -const V2_TG3_TC125: Vector = Vector { - source: "ACVP-AES-XTS-2.0 tgId 3 tcId 125", - key: "c3d3dc0b7a345ccfe48b232075e47299ebf11e5c40e1bfe42acf96e1840b7353", - tweak: "ca000000000000000000000000000000", - sequence_number: Some(202), - pt: "eafdbd330511baa1c912ea24b7b1303507ab3aabe6621c", - ct: "b0c68b8a8c230a35676338546d361e15178b8cc3426e31", -}; - -/// ACVP-AES-XTS-2.0 tgId 11 tcId 503: AES-128, decrypt, tweakMode number, 29 bytes (b = 13). -const V2_TG11_TC503: Vector = Vector { - source: "ACVP-AES-XTS-2.0 tgId 11 tcId 503", - key: "0e00f2017e1fba4bd287e57b95d197e57bd0e7253be250b31380426cdd19dde5", - tweak: "d0000000000000000000000000000000", - sequence_number: Some(208), - pt: "0df94f3f3eb892dbfad8fa149d5e275af6e81e0f9578861668354385a6", - ct: "7b3af90fb25385a545804d183a624931d1b02aeb5654f2070fa55503c5", -}; - -/// ACVP-AES-XTS-2.0 tgId 11 tcId 516: AES-128, decrypt, tweakMode number, 46 bytes (b = 14). -const V2_TG11_TC516: Vector = Vector { - source: "ACVP-AES-XTS-2.0 tgId 11 tcId 516", - key: "8e52f6fd062d7c3dca35e3959e0b1d397af6ceedcc8a833c807a6da14c108e8f", - tweak: "5c000000000000000000000000000000", - sequence_number: Some(92), - pt: "\ - 72bbecdcac5b9913780ac9d439bbdbc46367f61cb3d6f0b0dcb100a2e33a4189ff812cccb7af572d0b183752\ - 9f79", - ct: "\ - 18aea17a4d782407848151529c59fa54a35a413fa9b9352fcd43752a3400bf1c8780ee9860c094bc3577a702\ - ba50", -}; - -/// ACVP-AES-XTS-2.0 tgId 3 tcId 139: AES-128, encrypt, tweakMode number, 48 bytes. -const V2_TG3_TC139: Vector = Vector { - source: "ACVP-AES-XTS-2.0 tgId 3 tcId 139", - key: "b45cf630863a2e65ca84e55e4cdd7d14c3ca25f86a4aed34fd35cee38c859aeb", - tweak: "5f000000000000000000000000000000", - sequence_number: Some(95), - pt: "\ - b6c799f91fc6c3b84092b1993f28f5ca743f7577b69a464d5516f74af26ef87b1e258641a8f2533941dc93b0\ - 97424bf4", - ct: "\ - d892c20885d33a10ad528b4a6022ce5d60b7ce3e77a99bd21bd267d7a6da43123e4ea8f10ebed953c4c735dd\ - 5b1ee7b7", -}; - -/// ACVP-AES-XTS-2.0 tgId 3 tcId 101: AES-128, encrypt, tweakMode number, 56 bytes (b = 8). -const V2_TG3_TC101: Vector = Vector { - source: "ACVP-AES-XTS-2.0 tgId 3 tcId 101", - key: "4d283fa6573813ebbb3e2ecc03013416972c53c40249fbb4fc582e0005fe58bb", - tweak: "f5000000000000000000000000000000", - sequence_number: Some(245), - pt: "\ - 2dc07c5d016cdfaf10dd3698a0583d659e897452b3e314c985401336e824c9f2d6ce254066d2a00b7f06a716\ - 1280f50f8f1725cef02e8a52", - ct: "\ - b80a9187ab9638477dfb6a4c4a759b361cb2b496e9ea882d684cf9d231e43d37e91f5fba1798f84b45ba9c85\ - 61e71be17cbe3465b72ec3b7", -}; - -/// ACVP-AES-XTS-2.0 tgId 1 tcId 13: AES-128, encrypt, tweakMode hex, 62 bytes (b = 14). -const V2_TG1_TC13: Vector = Vector { - source: "ACVP-AES-XTS-2.0 tgId 1 tcId 13", - key: "6fa0ae27860cb658b40a3d95666954442e418ee3e4565657dd08edc69e20e5d2", - tweak: "c7c71ac8a3f858145b9ba0e658491af7", - sequence_number: None, - pt: "\ - 316f416dd8828155aafe1efa50361d48613e073e1b4b66b00d86a908626157d3058dcb83b1b6833580aa2f4a\ - 0663de87115027f5f4eb60fcf2f2235bb801", - ct: "\ - 74fccb3c6fa20bae9d1fba9525519a5aebb0bd4f2803a40c4ec0d80fbe3d5ecf53ea3d8c7456d23b4fd7772c\ - 4bc44b06c0c7a533e53747a4cb94927d4572", -}; - -/// ACVP-AES-XTS-2.0 tgId 1 tcId 38: AES-128, encrypt, tweakMode hex, 64 bytes. -const V2_TG1_TC38: Vector = Vector { - source: "ACVP-AES-XTS-2.0 tgId 1 tcId 38", - key: "4e202f28cdc52b4652cb8a58aa7333ce3a64d343098f278d7e88125b58605d7e", - tweak: "530d55c0b4d4a7c7041a5cc2af8ceae9", - sequence_number: None, - pt: "\ - d01a71806151bb27515e4fdc62264f1675b5220c0bbb03bfa1917989ed7ca5a2a8ec7ffa8aa8835c71deff0c\ - 4ec81ef812ffd8fe02056b5014fb29e5ae2d0650", - ct: "\ - dd50d20ed7b5d4a9083d0b8410aa8392f627a41a765c7436bf3cce3feede6a4e0c2ea4053701f532d43ac7e6\ - 04703f13d7cc2b9258eb1db12ab6e29ba5cd7fd8", -}; - -/// ACVP-AES-XTS-2.0 tgId 11 tcId 525: AES-128, decrypt, tweakMode number, 75 bytes (b = 11). -const V2_TG11_TC525: Vector = Vector { - source: "ACVP-AES-XTS-2.0 tgId 11 tcId 525", - key: "88cfdd08e11ea2981cd342080a7770300effbd1e0b2738562f060bffacbd9af7", - tweak: "d8000000000000000000000000000000", - sequence_number: Some(216), - pt: "\ - 42e0b4f015fdb8e0c9f1339a5ec6c940cb3e4f84088e2d05e966d457e3eb7bd96dce0ff96b4c0e9aeb3cbf00\ - 35c0c66b3b2ba29d0a7ba98c8ef9cdadbc04f558368d2bfed49fc7af696b8b", - ct: "\ - 103672952d6947df8aee1cf3779a536ce5620efe4f9e01fa650b7129fd2c8638c7b9a25de456921dfe0cbc0c\ - 219d61a12f092b33f661b0b29357ebc08645eb46fb3e91d83b827611950460", -}; - -/// ACVP-AES-XTS-2.0 tgId 1 tcId 36: AES-128, encrypt, tweakMode hex, 86 bytes (b = 6). -const V2_TG1_TC36: Vector = Vector { - source: "ACVP-AES-XTS-2.0 tgId 1 tcId 36", - key: "a1e04e9180658a01af0882bf5319a88a097e43aa00c9140abbebade5fe63eea8", - tweak: "4fdb844b178e00df69c41096b076b231", - sequence_number: None, - pt: "\ - 90b44113367f8b928685152b98bccb17a90efa9f1e42e5e3f385100cf71087c4331a7b1f305299031e61ede6\ - ad088fcbf7a4f5852722c30cd37265cf82aaf4736cc2332888c3bb9f9321c2e14eb856595592b6eb83f3", - ct: "\ - 1561acd6c5f0052a9241049416bebf907971c31c6724b2891495b03d93f308a4e37406db648469eff0bd1a4b\ - f0b6ea66781e5b513e942b7d259742c0692b21feb025affeb65230fdaca4f3ad4bba7ef53ff198adfe5b", -}; - -/// ACVP-AES-XTS-2.0 tgId 11 tcId 502: AES-128, decrypt, tweakMode number, 92 bytes (b = 12). -const V2_TG11_TC502: Vector = Vector { - source: "ACVP-AES-XTS-2.0 tgId 11 tcId 502", - key: "0692f81900c50b2171aa24a718b8cc0e29d723c7e9d0b0c7ca490b0abba4eaa7", - tweak: "cc000000000000000000000000000000", - sequence_number: Some(204), - pt: "\ - 7d4230b7fae49be48c71a98bbb2224b44650d0492739a200f0dd1ad71f18636c5cbcf35075f5d16f61a39e69\ - 2e5eaf82cfce4b62245b2289112947380bc64e3c687901dabb2a99973bbdef14549b31f9c43b5d13f03dfc0a\ - fc17c675", - ct: "\ - 8c010cb5f0f4dec68df4b6bffe9d5dbb08fca75bd7fe411248e80dde8c9816286922457674d50bd032fbc52b\ - e2f9b0d72897a2d2cd54c9d177808afbc411c1532099b8ae758653abce74afa1d0b993d3e4d1f04deb37c221\ - d1bafcc7", -}; - -/// ACVP-AES-XTS-2.0 tgId 11 tcId 548: AES-128, decrypt, tweakMode number, 93 bytes (b = 13). -const V2_TG11_TC548: Vector = Vector { - source: "ACVP-AES-XTS-2.0 tgId 11 tcId 548", - key: "d169f425fb98179f9b6a0c72ee490c36f9ba04a5cc59fc71f292e2ebeea3e60d", - tweak: "f5000000000000000000000000000000", - sequence_number: Some(245), - pt: "\ - 32c873f28118bd7141869f15dd1632cb2b9916e508230dd8ede7928b78aaa92d4c7a49492f8d442f881d6b5c\ - b8b439157a1481ca12b14e1732ee1f7b4ae94a599c7662d5b1093aa53a9b0a1185164ff87ed47f2cd35c710a\ - 45e7948af6", - ct: "\ - 2c6926de92a4c7e0b6d91ac808618808c2b0f6133da310f74886c9c378cd79b63215d47751cee7f0ce4149dc\ - 5044f8bc555ab8675a182300e077ad79949621ffb66b0c011ede637b18512c60a4f06ef5005e599acd2f213f\ - 16f255b549", -}; - -/// ACVP-AES-XTS-2.0 tgId 3 tcId 144: AES-128, encrypt, tweakMode number, 94 bytes (b = 14). -const V2_TG3_TC144: Vector = Vector { - source: "ACVP-AES-XTS-2.0 tgId 3 tcId 144", - key: "02f67f1a707e9ccb6208263996a6a3f2ede1d9357cb1d71fe1e9a0930a7838dc", - tweak: "0a000000000000000000000000000000", - sequence_number: Some(10), - pt: "\ - 54bdbf9e132107e5cab8e3cff0f327fa64f235f9bbdb41c194933b7863668446d8172dbea007e422da9410bd\ - 726cb21d6104f98ebe11f3817b5fa6f844e279db76563ca21188fe5d80f30aaf5cbc203a8c805add42fb9c14\ - ba3e469e6565", - ct: "\ - 37ca552b306aa35d80756b6ab82e5cd3fb72df960e939629eaf6c3465515a1093d6c387b7e3b7aaf37554bff\ - c2aceac8b56d58f302e304e2d0db471733cdbb25911b8f405f50bb114dc29da2638b52ab51d45f013298901f\ - 3cf2a3b580f4", -}; - -/// ACVP-AES-XTS-2.0 tgId 9 tcId 412: AES-128, decrypt, tweakMode hex, 94 bytes (b = 14). -const V2_TG9_TC412: Vector = Vector { - source: "ACVP-AES-XTS-2.0 tgId 9 tcId 412", - key: "274976d0a13779af9de7d91b0c3b56b15be1d2b9771a75850eaa595b732c4e97", - tweak: "f2fc1bf4ee74720ecab2a2e114a777ff", - sequence_number: None, - pt: "\ - 55a9ab8095e2025e007c5229ab6c3c6ac2a4a87558a82e54531f383a67260dac51d5a4d1a0165ea9a9325fb5\ - 98415e3ac9bb86e1cf030439de3342dd211311390ee92f482ba03b64610d5d69fbd173356db3b01a6a16d7f6\ - 0f0ccd6b2151", - ct: "\ - 562c4483eaf6a0c4b6920f63fa80b8240d160d623ecd2b6bcd61c642fb3042ac4ad39bc55f63c768441187a3\ - 8642e6d5ec558bb6d8996bf1f1a3e7b15ee4d63d3595a6e155a57998cce6fbaabe1d0eb4132527d26d7842f1\ - b4f06bd9fc93", -}; - -/// ACVP-AES-XTS-2.0 tgId 9 tcId 433: AES-128, decrypt, tweakMode hex, 100 bytes (b = 4). -const V2_TG9_TC433: Vector = Vector { - source: "ACVP-AES-XTS-2.0 tgId 9 tcId 433", - key: "38a415450a8a52b171ac7a571eb9f8abd96ef5d3f59558c296817d018349fea5", - tweak: "6cc3a5fc6c25df36fc5adb6bc4714b2a", - sequence_number: None, - pt: "\ - c96a17bd3e6c0fc9443c9c3e3ddae29b32ca140236e34b1b544c593fa1c82d4d44f644a639a8a9d4a2f0ffcd\ - 338ca2257cadd6415133e491ba116bf7e3d2fc662e3c3cebc7aa8a2722d16cec871af01c3fbe37420438cafd\ - 607a66b5581065819949fc74", - ct: "\ - 31a976845781c861969b91c5e776b7795c5eb4c2177cd3af296cc6d2ece94d037261cdd533540a8d310c4fc9\ - 45812e5d5469ebd04c7006fe7fa9d9610ff96de665d64716d30ce3472f01331d7b525902cdd6cc5acfb2d9b9\ - 77a1e2169c398f642acb1c9e", -}; - -/// ACVP-AES-XTS-2.0 tgId 11 tcId 508: AES-128, decrypt, tweakMode number, 100 bytes (b = 4). -const V2_TG11_TC508: Vector = Vector { - source: "ACVP-AES-XTS-2.0 tgId 11 tcId 508", - key: "c0c85a32988822fd2f146178cf21c0b417c198f35e621835085e182b0fe9a7c8", - tweak: "49000000000000000000000000000000", - sequence_number: Some(73), - pt: "\ - 01c97075dbca87fdd44086eea98060f526fe7962895cf954e33307fb7813b704dedd05bccb2b98449d52557c\ - 0d709fdcbbdbce58d313c9c1fe3263a05118cb5a4c9956023e05e26055f37d90c3a54e59a8d1a47488134b2b\ - 1e97012ce8cadc0d3a0ae2a9", - ct: "\ - b59cf115c0f380ca04a27d29a58157095721a40fbd5f74b1dd1b251952269fac3e07fa272b17d5bcd05653d2\ - 14f6502e776b52ae95e5cfb0c31c2c96af512057749120f5b0cf75a9d03af58c0f38ce0ab1d56a737e133e5e\ - fcaaf6a0c1a5f7c6e3630be3", -}; - -/// ACVP-AES-XTS-2.0 tgId 9 tcId 441: AES-128, decrypt, tweakMode hex, 119 bytes (b = 7). -const V2_TG9_TC441: Vector = Vector { - source: "ACVP-AES-XTS-2.0 tgId 9 tcId 441", - key: "05b104202f78cb71331bfccefb9bce77977f6bfce3d01e4e167f001fe2c82250", - tweak: "eddca8e9cae2487d4fcc200e6491a790", - sequence_number: None, - pt: "\ - cb872fb2d7596de44cb51bd3d6269d58772c09bd3ce0d294d344f39e9353da555f8d8e4433226c12650a231e\ - d7bfe482ee8c1c3a38ab6394541234edd27e54aab13156d5bee738d2c7cd1c2b362040fe2a94e5912459ec4b\ - 33bc40d320e6a002f0ce816dd1d0cf8281b4c2b102b54e53e3dc11c6b9f384", - ct: "\ - 0cee96da18921858d88cbae9315efd4feb02d687e1b37e9c8c1cb248d1a3fded042d2df8ebb97a6d074caf62\ - 6caa6bc8c7d1c2dfb5277e39e6829492ff1fa588ee27949d27c520ade18caf5fec641e21afb267772cec1598\ - ca54bd0c675cf9b6ac9cc78bcc1a7a2f48efcbcbc0498ea48efceef9d55125", -}; - -/// ACVP-AES-XTS-2.0 tgId 3 tcId 127: AES-128, encrypt, tweakMode number, 126 bytes (b = 14). -const V2_TG3_TC127: Vector = Vector { - source: "ACVP-AES-XTS-2.0 tgId 3 tcId 127", - key: "4c819dce0edea0af7ca2cadc18a6d1213d4d7120ffd01e84114fd2d438678cd9", - tweak: "9a000000000000000000000000000000", - sequence_number: Some(154), - pt: "\ - 94bc929bca0e94c32e603538e39d37aa91d00007cc09dfde1d67dca2a2cf0fb1daae7a4f5162f13e553e2ade\ - af3beceef275a3481967870e0be3febc4ce902583ee474d08b291f3418196e5418eac21b24288ca4284e964f\ - 7e067870960a58c39342c9715711177e19cb97afb60615845495c7a4ad959b0755cbe1a3a739", - ct: "\ - 6456c9ebb196d4bb0a5a1e65c2c9cba208a726ac47365bac7a1fc0bd37d93b667b401ae6abc40b7a6d91be06\ - bf60ba51abb2f398ea93f19e60eec3456b74ee996ded4162525aa14a7962e482eaf80edbe75d2d7b1297be9e\ - 83845d288c6c549675c73bb2f9e1a2b54bdedae3297680189d339926e99884f7b653e72482cb", -}; - -/// ACVP-AES-XTS-2.0 tgId 1 tcId 18: AES-128, encrypt, tweakMode hex, 262 bytes (b = 6). -const V2_TG1_TC18: Vector = Vector { - source: "ACVP-AES-XTS-2.0 tgId 1 tcId 18", - key: "a961fa246936e474bd453ad6d21affa859dae7322bcad53030e82d5506610f54", - tweak: "e2bcc8951a6d4ba8001676fd052998da", - sequence_number: None, - pt: "\ - 1910d9ac563533caeef460ef9d7b902d6b7d5f157eb2eb820d50599d01d3681e34d85263486b25b8ef66e416\ - 4de3808a852e286f7f442d6b7321177ced2330d30aaed21e05165c94ecde5aab1e5ea425cc47c031a773cc07\ - f65779a400129649110374f2084cd1465fcfe24c4c23c3edc6188e846d41d77fa0db6ad75cbc64cf2aa6cee2\ - 4b6a3d5bcc2e737ef26ce3612fd66065e2c1f0e0e5c05c46a79e74d34dd4b82f84f3c3277d71465e22bc3ffd\ - 211275d08fb2a4e3d653d50f91bacc128c953a326a0473a5a6f01786a4c734bbd0ee0174b0006888062334f8\ - 996a1794f8ea25567710ec228626d1f83aab060b4c6e79a94fc4fdb1ecb2425627facc78e85232abd280", - ct: "\ - 52c66c83c4701ac5209861cfb07a978115fafbfc66da33b683fd4560d952dac3dd566efae5d8573b5692820d\ - e4999a0210f9ba4efc843d9cd8f91da5ced139e3d6b83fc4656ab80242926cfca430210139b3872e47a00529\ - cf5801f9258f4eec7dc786d816df6f935216678b00af9d775a15a8d0c198366406bc19a3414426457a8b7c3a\ - 77cf5db5f4ccb412524832056dda2e2a17b7da298763752c1765397779e94e306399b6af55ef90ea61f94a02\ - b8f226a57ed869722a24a37625de01ee9c20de72adee49520bb443537c392a8d75d5a5a63477b4fc25376d8c\ - aaffea407af287ff0affb1f63bb569bcbb312ba2e1b7aed532f81e0fd045a4b0849dae7c0266bf91416d", -}; - -/// ACVP-AES-XTS-1.0 tgId 11 tcId 101: AES-256, encrypt, tweakMode hex, 320 bytes. -const V1_TG11_TC101: Vector = Vector { - source: "ACVP-AES-XTS-1.0 tgId 11 tcId 101", - key: "\ - 2ba2f3f25c0819edb749996effc95a8cd5c4c70b353f1bcad9903dea946b8720650863b3fba7eeda72e09ba4\ - 8b1ef7beba8c8464187b408e56ee9a4be38bce52", - tweak: "1366aa5b88c0456680cff819ddf81537", - sequence_number: None, - pt: "\ - ee258cf68714185a28df8675cd71b973db207662be7545f1ffebc8140217baf85669164591d2df30ee43da5e\ - 6c3f7a1e039c629d8424bb046a1ec86644079d033ef3b54890bc103dbefa867979b00fc7520c1b9f1af8eb0b\ - b1a602a20f9d2b75bc540e7c07cc2b1e3c7c96702f6caa6cc0d8046f7d5a574d70bc14bbdb4dba546bb5e624\ - 1cd0a0567c99fa72455cc7c561ddefcaf2962ba3782b4da722a7b737eedcccf7320b4ab0a2f706a8fdd078bd\ - 6337629384a93137ad18306780424d8341f842be192bfcc471747323ced8bca892ceea702af92f319ae6222f\ - d0bb24161ad580ba790b8b4da88d8db3dacb1dd0480022a5586858c2b2bbc9a579a452fe274defeca804a9b5\ - 7343d983bbe1ed638b9cd422b94c640ac129be22c0ff9181104895c72fa96c1c22dcf1bc721aec71de89a40a\ - 266347bd151e951520cb9165", - ct: "\ - 5181e91d815a44163a8ca2f12dd6a5b51a82eeed30c9665d5d8cc7e3e3359e2534461f5b9bee4a9836647dae\ - 81bac117e8c8aebe0a31864e3b9df05f34de5bac15aeb162d8cb77eb2d893de06edfd064e258d36e113226bb\ - 01c26ce532ef82bb2f0506b7797aa5a4b1ccbd0713964ce74868728cc42da69b74914ecd4775e01dad6d5d66\ - cde80f91db57894cc280be52ffe79725afdc7fcd5a4c26fc22bfa2c7bd5f367389e31285dd3137e94885e714\ - f988bef70ec4cf2022c2320fe9e527cbbb8abc0612e1c8fda67d6f208449a23ee2860f31fd7b6f36521537e0\ - f08dddb766314d400d616ea2f6721a70201cf5a85b7a3b69c462057398cebdcce5e7308fb322d2c4ae9bf966\ - 2941f53d787c6e093106cad99554773f9db9a7ce3e6a15eccc1667fa64425357c6fd5b72d086dca76722c312\ - cdc823d08f653a0d1a7a5427", -}; - -/// ACVP-AES-XTS-1.0 tgId 18 tcId 171: AES-256, encrypt, tweakMode number, 559 bytes (b = 15). -const V1_TG18_TC171: Vector = Vector { - source: "ACVP-AES-XTS-1.0 tgId 18 tcId 171", - key: "\ - 4553964ee112435943a1dfddb0db6dfedfbcaae3765036dd86ffb11969d501df2381b7ab692e365fc2e609a8\ - b6556189e592f9443a9114fcffff7d1771063f4c", - tweak: "46000000000000000000000000000000", - sequence_number: Some(70), - pt: "\ - 4a953211645291d801e4758b4d35dc0317231fa9224b7555921bfefa063843377156de935878ac053c1b90af\ - e7a718fdf98350b43db0a328288a891057cdf391945c326533d68667d75d59c6749ee01c2c56c7facad794a3\ - bc1169dfdf836295e2054dc8c34553c17d1a8cd254603a926a6894ba63d596e124f6ab86980481642fae27ae\ - 304a84c1102ad061b9b899689801e361e8924409b37e13480764ec4d7b468aeec9d2944eca7d4da7df4a6037\ - 3eb3ea8452fdaaba9cf081c5994f3f5dd2afab19f0d81b8286365f934de1f93543ac9746c2befc27607bc6e5\ - 551a8429109a88d87fa3e4d6faad424e250a3663d5d6df1d784ff85b872bbdd4ae1630c885849d8344ce0b23\ - ca1096ba1984531d5075fb85e309adae1ecda78bc6aee690675bd3782886d8d05bc32726fd17282eb7848395\ - a7972458fdc60a1c9f67e6f13794d241b20aa2d30aa21d0862ab7429e946f2ad9f1e25399d8583ca5ae37378\ - cb89d172401175a93122b3ccd1c2de809065ff12e0b17b0906125327b4d3f6be6eeeca402b058ee959d25e1a\ - 272b4cf0ad379e50a1e16795c9fd77cefbce7c903ddbf71eb38bb82eb5a1f4474744067de14ff63063339a66\ - 0d7dcbe433438b4d1aa65f2ea82d40a36801843b48741395e1aa12871c97369d0aa04bf32f21303add3dbc5b\ - d9e828f4d612c79ad1a4075870fb05647e688ad7013916d12216b6309c55df50cd8490e70e90efa76e38d620\ - 726d09e552cc8fbd8d8adf6acf3785c5b936d2a7c579c67ae057300d251861", - ct: "\ - 795d9ef272b0b923cdfca4fbc4457ec624875688a120b498ad62b1a337354895165b910ad5f2e119e601acde\ - bc9984b8f7cc0f1e7590144b64a3dd48e7d154df06355905e6ce778dd946c6e4e428c846870b8dfc5bda1f13\ - 675cd69568a81003e7b3802f6b1b447dfc81a24b5bb42a7ab695052e8992695d3da3125412ea58ae90cb4b01\ - 6d2646017dbefaa96f1c45e9fd63958387e0a56f47a86fdd2bdcbf59e3aaf35633186aa99273234a78a80821\ - 4f471eab9012b48c034694ce4d8f00743e7bea666fc7e0c86c29dc888083d1bd9dcdc4dcdb457d032a894460\ - 2e62b50e8f696a329537ed113cdbbcb4c298f31a1a0df8f4d84aca643fb7ba98f430bf226e7587d69e0e8522\ - fc3da498d0eb382aca86741861654954178b20469230d1ea63a9434a4688c36fb83c63833431be2847ddfeec\ - 0b907fb4d4bfe640d5d5e0457a2f3e701cd79b2e6081520fbdbf44c91a57a5179801861550e6a4f90d01b5a6\ - 6b05c73d3af0f990124525f59d6742c54d27841ee0fcf2ff3d57825d4c32ec52cf909c36ab26f60b79650eeb\ - b75b3bcc4f5e55bad56b117224daaf2e2184183016eff3a4e311f90e1b4ba68cde1a3d7ed702c55d38ae5a7b\ - 6f4b5b80b19ed457ec64967d277ebc927404ceb03b909c9fc3a4d2f6d5ea2c13492fb64cbac155923b4f7bd6\ - 6c8774e08cbd23777c48a5bb457b01ddf194feda4e2ca5d1e34ae7d48b94184e42e6028368064e8e0f20fd34\ - 980b5b06748ae66dd9d4634c5174c07deef68b7aa08e22f7fe090f48b05d7d", -}; - -/// ACVP-AES-XTS-2.0 tgId 5 tcId 233: AES-256, encrypt, tweakMode hex, 16 bytes. -const V2_TG5_TC233: Vector = Vector { - source: "ACVP-AES-XTS-2.0 tgId 5 tcId 233", - key: "\ - 9d9674635844373fbac65ea8fefccf4bedb7b1845c89dc1b28b343fdcd5df7af1c0a96edeead069c6666b741\ - 153fa3f367ad7538f9615c348462115fe09da571", - tweak: "eae1092e65f917efaf69e01740494551", - sequence_number: None, - pt: "0873e8a1ef36f962efaae5b9bd617d39", - ct: "6ea0f22583c4c6397adcaf702a08c27d", -}; - -/// ACVP-AES-XTS-2.0 tgId 7 tcId 319: AES-256, encrypt, tweakMode number, 16 bytes. -const V2_TG7_TC319: Vector = Vector { - source: "ACVP-AES-XTS-2.0 tgId 7 tcId 319", - key: "\ - 95f8cac93590607136175e70d8fa55465a1edaa5e128c31f17821fb29cdd5d218d8e637502eec9e88acb1b28\ - 8727561ce79b01bf11efbef86dccb7fe78ea3c52", - tweak: "f9000000000000000000000000000000", - sequence_number: Some(249), - pt: "40e5982e173de25bdeec94a02130ebcf", - ct: "4b9c0a90753d611c4df75991c4d4abc8", -}; - -/// ACVP-AES-XTS-2.0 tgId 13 tcId 642: AES-256, decrypt, tweakMode hex, 16 bytes. -const V2_TG13_TC642: Vector = Vector { - source: "ACVP-AES-XTS-2.0 tgId 13 tcId 642", - key: "\ - 074beb63ea25525f509e04562158a49f1c5de35dd0b32528de9673f9d8b2c1e799c852ee2ce4a5487e49822f\ - e803860ed6eb5cc61ddc965a3a18478f6ed1a8d2", - tweak: "642178ce09bf25ef9bdc12a9043643cd", - sequence_number: None, - pt: "bc564ad27849d52c0fe571248907f6d8", - ct: "ceec59a7677a8a78230139670e604025", -}; - -/// ACVP-AES-XTS-2.0 tgId 15 tcId 719: AES-256, decrypt, tweakMode number, 16 bytes. -const V2_TG15_TC719: Vector = Vector { - source: "ACVP-AES-XTS-2.0 tgId 15 tcId 719", - key: "\ - 530d1742668119cf2be522a070fca1262dc0a85543440998fa1abe81d5f16f522cc220cd9e7cffba88ebb933\ - 2aa42e9a8a6d8a2af9639a73dab5bf663ca1bae5", - tweak: "b7000000000000000000000000000000", - sequence_number: Some(183), - pt: "39a576b8e051682d9bb974522bc8173f", - ct: "184c449f962b94b8eba1b8ddb7e44db9", -}; - -/// ACVP-AES-XTS-2.0 tgId 15 tcId 702: AES-256, decrypt, tweakMode number, 21 bytes (b = 5). -const V2_TG15_TC702: Vector = Vector { - source: "ACVP-AES-XTS-2.0 tgId 15 tcId 702", - key: "\ - 6838b46d0a41d3468520baef2f28dacd770a7f2e2a53328345bcd010d40799bb1e2ed2e127c0cb999f4d4946\ - d1026fa90b9344d11d59223b1adc2dd6db7394ce", - tweak: "2f000000000000000000000000000000", - sequence_number: Some(47), - pt: "dd3870cb70e39e96f1b70404030dabfe2d1a54cc89", - ct: "678cf29fd1e660bcdc9d874c8e4c5f7292ab8368d5", -}; - -/// ACVP-AES-XTS-2.0 tgId 5 tcId 237: AES-256, encrypt, tweakMode hex, 27 bytes (b = 11). -const V2_TG5_TC237: Vector = Vector { - source: "ACVP-AES-XTS-2.0 tgId 5 tcId 237", - key: "\ - dcf8c5f5ac2ff90719df2dcbbee159c53c44e80bcfa95c718c659c4e8f6fc0a4c85a9e3c16527e66bdd924c1\ - 3ec8314987f0f3e89089007b34dc472b95b7e03e", - tweak: "7eb2097b64cc3bccad39608427ecc1a5", - sequence_number: None, - pt: "a06b93f02ae1b52f2d7995d024914dd490320670ad610f5b4bc91e", - ct: "87e96fcd94d73ba5e2cfe45a96be469c2a13ce2f621cd76fc1c875", -}; - -/// ACVP-AES-XTS-2.0 tgId 15 tcId 737: AES-256, decrypt, tweakMode number, 31 bytes (b = 15). -const V2_TG15_TC737: Vector = Vector { - source: "ACVP-AES-XTS-2.0 tgId 15 tcId 737", - key: "\ - a373bfc7b1697d90e3338fa4eda3a6b47333e128afd5ab041deec226c678a02a1595a2c29ffcc534dea529d5\ - e0fc611c77825ae6127a9146365fc3779d5b350c", - tweak: "f6000000000000000000000000000000", - sequence_number: Some(246), - pt: "a6f75098bd821c44d18a6e5870a7133b15800c27d6d2c7450309e80d07d586", - ct: "0870a04fbf1d37cd1af4a2411be163e1655f82fc85a99ab6e462e0d6c9df28", -}; - -/// ACVP-AES-XTS-2.0 tgId 13 tcId 603: AES-256, decrypt, tweakMode hex, 46 bytes (b = 14). -const V2_TG13_TC603: Vector = Vector { - source: "ACVP-AES-XTS-2.0 tgId 13 tcId 603", - key: "\ - fe08576b2820261bb57ee5164416885f9b154ba446ec82e129345825e30721c87a13ac02fde62cd5d7a34433\ - e5eb021be485ea54422113aa0b545154f5fdbef9", - tweak: "89325d57b103c2cdc2bfa2e3327aa6ff", - sequence_number: None, - pt: "\ - c1355ee7100214f1bf77a1d8d1b0c2229ec647806e7d8004cca909350315a03d7d62b84dba97cda22359554b\ - 744b", - ct: "\ - b2ca0147326de586698dc559978e367b894e23a101d3937c5ade6fe36c96629cfddbc21b668b690827ec27d5\ - 9d6e", -}; - -/// ACVP-AES-XTS-2.0 tgId 13 tcId 640: AES-256, decrypt, tweakMode hex, 57 bytes (b = 9). -const V2_TG13_TC640: Vector = Vector { - source: "ACVP-AES-XTS-2.0 tgId 13 tcId 640", - key: "\ - f222058080b731845a6a64ceead954d05a85635ade124a235ab389f42daa124fc56edc769a372f57ef9f4ea2\ - 9273ed82310d96db7c0101cf999fb8b00f2123a9", - tweak: "f395c13b586f1939f93ce0ecc82d3b93", - sequence_number: None, - pt: "\ - c6d43c791a16be5294d948d5a5ec94ef81e69f75cbfa2ce03db3f47689d8b1a370f71bc63f072491f1d96323\ - d10d6da674d967a6f172b2ae99", - ct: "\ - 0cf742d85c85def160e05bdfe2e3c31263981651531f46074638fc782890374a7f30865586511b475eeafac3\ - 0848089618e140466ca3da934c", -}; - -/// ACVP-AES-XTS-2.0 tgId 13 tcId 649: AES-256, decrypt, tweakMode hex, 59 bytes (b = 11). -const V2_TG13_TC649: Vector = Vector { - source: "ACVP-AES-XTS-2.0 tgId 13 tcId 649", - key: "\ - 3a8c5ecf475e3dc20da414c965824312224d946aeee4ed9d9db450ba24747d44930b61cb9d2aa1676059a578\ - 2994a7d5415ca6b742aefa9b58fcf9e8c69d1cb2", - tweak: "d2f56bc08a8cf7f2858737313afd1bee", - sequence_number: None, - pt: "\ - b3d431bbcc8538abcd33ea5a7c5166b360f21beefc3f4800c25ca803a453f493ae941f279aad1033adf64893\ - 80eb31f7287e0e38d72e510006871a", - ct: "\ - 1c3e5d0c58856fc805d719e8804699969d175741269983f017ba510cf3a63f794225bec32b44ec999dcd51c6\ - 9e1256a909ec8f05175ed8db018850", -}; - -/// ACVP-AES-XTS-2.0 tgId 5 tcId 230: AES-256, encrypt, tweakMode hex, 77 bytes (b = 13). -const V2_TG5_TC230: Vector = Vector { - source: "ACVP-AES-XTS-2.0 tgId 5 tcId 230", - key: "\ - a0e54b4453a9c9d7740a8a88f4f72fb3a76f16d078197a1c69e5f69e68a710fb3555068bfe708ee35224f8cd\ - c5b238823a2b239e5cd6a0a6704ab4e18c1cfc6d", - tweak: "cc82acdf52a949538b9cc27c8e61a04a", - sequence_number: None, - pt: "\ - d7503a2c796adeca0e73a619c0ea661dc683ba6414e74c708280f6dd3a9c56f83db8b82cd0fe06f5903786a8\ - 4722276627ef7de3153a258f7c0b2a7f606e02941ced3ce7518d0d4466cf9f3a77", - ct: "\ - 31611d514838ab07ce6167149db16a0bca816ed32c55c5311f6d9a3b7913243b334e01d9ac661f48d0379f64\ - 1a0dcc2f8cb8c9442f2adfda7912cb4b5ba32563834821ad807a0bca4afc26e353", -}; - -/// ACVP-AES-XTS-2.0 tgId 15 tcId 717: AES-256, decrypt, tweakMode number, 78 bytes (b = 14). -const V2_TG15_TC717: Vector = Vector { - source: "ACVP-AES-XTS-2.0 tgId 15 tcId 717", - key: "\ - dc8b232a4635ce86276464428f2b0038bc149a74304ae557a3f63da68af81f37d57c1940be983288e3f6b482\ - a795aa04719b0a65484d0af6cbe2c279beb17ddb", - tweak: "65000000000000000000000000000000", - sequence_number: Some(101), - pt: "\ - f1dbec7f644d96647c88b946c4fa3ae44dbcb07c721783992239d316a5fbf12338d0b2f89baf3626a9c4425a\ - 3a03aacfb1e1c81c80f232aa8976fbbf4d9c41520e2441b2f32f57da1549ae46713f", - ct: "\ - e70bd73a2f71d4c67ae2c23b40b139656ffb5807d40643adb749b1925fac6ba531f533e0fb1affc9a2de6b8c\ - fbc1407d7422252956aed11aecd3552f3b76a5e56ebdfc802ead889525afb6a52030", -}; - -/// ACVP-AES-XTS-2.0 tgId 13 tcId 641: AES-256, decrypt, tweakMode hex, 84 bytes (b = 4). -const V2_TG13_TC641: Vector = Vector { - source: "ACVP-AES-XTS-2.0 tgId 13 tcId 641", - key: "\ - 34dc22fc6047a40f4ac0e6efe354128997a28b3b5c0ef60d1cc34c63003f97c1a176a8fd6be17e7801e44ba8\ - 68c6e7b4d09cba9730d928dcd98edddebfa6f495", - tweak: "ecc6873db15aaa23686c9c7bff6f38b1", - sequence_number: None, - pt: "\ - 0d93588848314be196d4a7394e7299cee4419b799b9b583c19824321fbb4072cb491362fd6c2f6690b741dba\ - d20966058133b0ac8e2eb815322ecf88994e62df4112cfccd861c1a945ea313e498bfa7293a32fcf", - ct: "\ - 684fb6ca08e2265239bc1584ebd09cfaa20b0af4d500105741b1e09233b8341669377904c189c0da91909741\ - 31698eb9211196f3bd5dcde1537754c8bdb8e2d1fe46ee798abd0c38ffc852a2e264ce957a9d4a16", -}; - -/// ACVP-AES-XTS-2.0 tgId 13 tcId 644: AES-256, decrypt, tweakMode hex, 86 bytes (b = 6). -const V2_TG13_TC644: Vector = Vector { - source: "ACVP-AES-XTS-2.0 tgId 13 tcId 644", - key: "\ - ec6cbedc8a6a66d571d880d5aa99d8052b933193e8d65b8c5888556856ced10f9ab2d48a796204780da64583\ - e5f5c27db783383615d43bc0f7383f8ee3737bb7", - tweak: "4779bd6f28599c39274f2c6964063988", - sequence_number: None, - pt: "\ - fde1ef403f19c49f43760d342435f6ff3534c87b7c1d8b940b253fe7b6d3008ccc3da904f72f3d35cfcd149a\ - e052781d213c0e196e7081f805b36495d10ff4976b2fc4c3e4294d84c95f16ad692ff3dc1f27077c852d", - ct: "\ - 5b65ca6c16908863c94767239652c4971738dcd2852d74651eea1b01c5cdc075c9dcd5a98cd9b69455bd648a\ - 395aab1239045ca4e94593310f5746cc25dd202dd2a17d4265fd9c73dcc517195f84bc65b740dee6fb92", -}; +/// Calls `$check::` for the data-unit length `$len`. The length is a const parameter of the +/// key type, so every whole-byte length in the two files has an arm. +macro_rules! dispatch { + ($len:expr, $check:ident, $args:tt, $tc_id:expr, [$($n:literal)*]) => { + match $len { + $($n => $check::<$n> $args,)* + other => panic!("tcId {}: no arm for a {other}-byte data unit; add one", $tc_id), + } + }; +} -/// ACVP-AES-XTS-2.0 tgId 15 tcId 712: AES-256, decrypt, tweakMode number, 92 bytes (b = 12). -const V2_TG15_TC712: Vector = Vector { - source: "ACVP-AES-XTS-2.0 tgId 15 tcId 712", - key: "\ - 93fe122fd121d1450133086e9bb229381f572f6055127af61efa212973edf3f6b96ece04bd6b0df9a0bb25f6\ - 9dad503d323ad83a0118826103cf9ade1b720127", - tweak: "2a000000000000000000000000000000", - sequence_number: Some(42), - pt: "\ - 1292b98c98225013261708d38b99df9bece6132393a522216235061d2fc95b9cdc331a66f5b681e53bb634a2\ - a9c44379e7d4658a90ea9c267b92fca5f52b6506c9db44827de72cb5764eada1a1f79d8a83da435a52766e88\ - b22a22da", - ct: "\ - 2aa51cebef5c72f7923178d8737dc5b9d93c9c74141d9cd55abe612f629f2b199399746366297aceaeed589e\ - eedc2064fffd7d468c94c19e0983156a2a20e4ead066b494e2c5b656832808d6bba5596f298b504689fb8048\ - 2e56281d", -}; +/// Runs every whole-byte, single-data-unit case of one revision's vector set, and returns how +/// many ran under each key size and how many were skipped. +fn run(revision: &str) -> Option<(usize, usize, usize)> { + let dir = format!("crypto/acvp/ACVP-AES-XTS-{revision}"); + let prompt = bc_test_data_json(&dir, "prompt.json")?; + let expected = bc_test_data_json(&dir, "expectedResults.json")?; + let results: HashMap = expected["testGroups"] + .as_array() + .expect("testGroups") + .iter() + .flat_map(|g| g["tests"].as_array().expect("tests")) + .map(|t| (number(&t["tcId"]), t)) + .collect(); + + let (mut ran_128, mut ran_256, mut skipped) = (0usize, 0usize, 0usize); + for group in prompt["testGroups"].as_array().expect("testGroups") { + let key_len = number(&group["keyLen"]); + let encrypt = match group["direction"].as_str().expect("direction") { + "encrypt" => true, + "decrypt" => false, + other => panic!("unexpected direction {other}"), + }; + for case in group["tests"].as_array().expect("tests") { + let tc_id = number(&case["tcId"]); + // Revision 1.0 gives the length once per group, 2.0 per case and beside the + // data-unit length. + let payload_bits = number(case.get("payloadLen").unwrap_or(&group["payloadLen"])); + let data_unit_bits = case.get("dataUnitLen").map_or(payload_bits, number); + if !payload_bits.is_multiple_of(8) || data_unit_bits != payload_bits { + skipped += 1; + continue; + } + let len = (payload_bits / 8) as usize; + + let tweak: [u8; 16] = match group["tweakMode"].as_str().expect("tweakMode") { + "hex" => hex_field(case, "tweakValue", tc_id).try_into().expect("a 16-byte tweak"), + "number" => u128::from(number(&case["sequenceNumber"])).to_le_bytes(), + other => panic!("tcId {tc_id}: unexpected tweakMode {other}"), + }; + let key = hex_field(case, "key", tc_id); + let result = results[&tc_id]; + let (pt, ct) = if encrypt { + (hex_field(case, "pt", tc_id), hex_field(result, "ct", tc_id)) + } else { + (hex_field(result, "pt", tc_id), hex_field(case, "ct", tc_id)) + }; + assert_eq!(pt.len(), len, "tcId {tc_id}: the plaintext is payloadLen bits"); + + #[rustfmt::skip] + macro_rules! by_len { + ($check:ident) => { + dispatch!(len, $check, (&key, &tweak, &pt, &ct, tc_id), tc_id, [ + 16 21 23 27 29 31 46 48 56 57 59 62 64 75 77 78 84 86 92 93 94 100 119 126 + 262 308 320 559 669 912 919 1184 1447 1451 1568 1616 1950 2051 2528 2538 + 2669 2792 3001 3152 3216 3536 3632 3744 3788 4000 4151 4539 4610 5166 5344 + 5375 5909 6317 6321 6494 6528 6672 6732 6780 7089 7312 7856 7968 8024 8192 + ]) + }; + } + match key_len { + 128 => { + by_len!(check_128); + ran_128 += 1; + } + 256 => { + by_len!(check_256); + ran_256 += 1; + } + other => panic!("tcId {tc_id}: unexpected keyLen {other}"), + } + } + } + println!( + "ACVP-AES-XTS-{revision}: {ran_128} XTS-AES-128 and {ran_256} XTS-AES-256 cases, \ + {skipped} skipped (not whole bytes, or not one data unit)" + ); + Some((ran_128, ran_256, skipped)) +} -/// ACVP-AES-XTS-2.0 tgId 7 tcId 305: AES-256, encrypt, tweakMode number, 94 bytes (b = 14). -const V2_TG7_TC305: Vector = Vector { - source: "ACVP-AES-XTS-2.0 tgId 7 tcId 305", - key: "\ - 51c5973bdea6ffe02ab15c3d6b07ce940f8337d9f3662fefed7f07b283b7d8de95c52fb67847180624bed57d\ - dec5b9f5d7e2c2c84c5b24807c0f82f6ac239fff", - tweak: "36000000000000000000000000000000", - sequence_number: Some(54), - pt: "\ - 2e3b0325fda676d24b833518e7acfe7076b4d522b7071a98ea2c5def19648a59d6bc29dd352faaad0579d066\ - f30facd9fe9c5a367c75bc58193855a7537c4b1cea28279486fd0cd1eb5298736033d13fd3b06b65807482fe\ - 50afdb420195", - ct: "\ - 01331145cb441fb40ef1d6d5669ff934e5427645704a1d5a20947c2de257b9c2e0064902e5912f15aa0b2b1a\ - e973a337be3b765d253c0ffc47169d37fb143812f1ae419ff4eb010e6d05f184041430439022be3c7a5e8234\ - 47adf700fec0", -}; +#[test] +fn acvp_aes_xts_1_0() { + let Some(counts) = run("1.0") else { + return; + }; + assert_eq!(counts, (130, 130, 140)); +} -/// ACVP-AES-XTS-2.0 tgId 13 tcId 646: AES-256, decrypt, tweakMode hex, 308 bytes (b = 4). -const V2_TG13_TC646: Vector = Vector { - source: "ACVP-AES-XTS-2.0 tgId 13 tcId 646", - key: "\ - 6737c853f8522ef9313f5917151392568f1c63917c6e655baf09694ea6906ce89e2042d9f165e3d274a50ff5\ - 37a0f63710bf3052fdab8caa10bab9dc25a29f41", - tweak: "6fe228a190dbf0edcec119a0e5140c6c", - sequence_number: None, - pt: "\ - 69befc6730eb06f8078b01d610187e4e14bb1be0c9344a43dd1521240c8cd5d8da51cca4a870aac8661a590f\ - b917d66bc8cbe8a17a057939a3a8ac4f2858923be2f58214373654848812fb95dbc783483e48ccb2d6c25019\ - 37c7ef9b400da671aaac08f7e03b4bc323f34c1a1151c92d424bf0fa3abad868525454358303e3be4e53554b\ - d1edc2449eab840b1ed40dffe0d18e76daca0f45b598a7f29a9c450f4bfb97f4cbdd68cd92497bf15615f145\ - 08b14d0cb9c2c1d778e8292af6e77d0074d291c24665b6cb56dd5af714543f83d7800249c9a096fb540cd296\ - bf8613de6c00e85b28cb0e8302612a7fbadc28e2d88f485f2578aa687db095523e1c960d7d4b30c0070cac7c\ - 7427c2318c14c7a9aa92158ca68047f0f9b844043f9bd5173691f9e0b3b8260bd8164656a3d64ca3833c34c1", - ct: "\ - 3590b70b4aa216c06e603d0918751568e58ff145d1a278562c8d7b08265233b1af286b4d09dbc6010502f476\ - 02b9388cc2df2e59544e69a1ddc0e711a41bc363d63fc25102d84814e845943a445617149f2023e9b50af071\ - 796e2551efae47993d38cc19cdd7ace5c9e46344c0e2100212d7c0ecb4009ca3589028afbd11f84b8a541d54\ - 5829eb5f0cd7ea52ad4802a11de263e8fad2ed5b8d2442b837b9bcb336118dc2842ee576c0bbbea25b29c79b\ - 495f687ac52f5c1817a2823d9fab1acb79467b75e44b01865d291857eb05fd0f62e264518436fab286720d85\ - b442a0d812aaa758382a7eadb1edb1c0e1e38a2427378040842d75219fb4a062f8b2730ee9f93b762a2446e2\ - 22e87ff957996626d4063728508ad24e20d17d7f0da19630e60959470a5f2b5f5fd0ca567b95f21c33ad038f", -}; +#[test] +fn acvp_aes_xts_2_0() { + let Some(counts) = run("2.0") else { + return; + }; + assert_eq!(counts, (42, 30, 728)); +} From 5504aab3ebcc67a73e5618c06487bcb6f6f00683 Mon Sep 17 00:00:00 2001 From: officialfrancismendoza Date: Sun, 22 Nov 2026 17:04:20 -0800 Subject: [PATCH 07/10] Made fixes to XTS-AES for data-unit length (#184) --- alpha_0.1.4_release_notes.md | 4 +- cli/src/main.rs | 20 +- cli/src/xts_cmd.rs | 111 ++++---- cli/tests/aes_xts_cli_tests.rs | 101 ++++---- crypto/aes/benches/aes_xts_benches.rs | 48 ++-- crypto/aes/src/xts.rs | 47 ++-- crypto/aes/tests/xts_acvp_tests.rs | 64 +---- crypto/aes/tests/xts_tests.rs | 258 ++++++++++--------- crypto/aes/tests/xts_wycheproof.rs | 67 +---- crypto/cipher/src/modes/mod.rs | 6 +- crypto/cipher/src/modes/xts.rs | 165 +++++------- crypto/cipher/tests/modes/xts_tests.rs | 175 ++++++++----- mem_usage_benches/src/bench_aes_mem_usage.rs | 111 ++++++++ 13 files changed, 623 insertions(+), 554 deletions(-) diff --git a/alpha_0.1.4_release_notes.md b/alpha_0.1.4_release_notes.md index fed41c3cf..5e8d94a77 100644 --- a/alpha_0.1.4_release_notes.md +++ b/alpha_0.1.4_release_notes.md @@ -28,8 +28,8 @@ bytes for TKW). * AES Key Wrap -- AES_KW and AES_KWP (NIST SP 800-38F; RFC 3394 / RFC 5649) over any 128-bit block permutation, with the `KeyWrapper` / `KeyUnwrapper` core traits and the `aes*-kw` / `aes*-kwp` CLI commands. -* AES-XTS -- XTS-AES-128 and XTS-AES-256 (NIST SP 800-38E; IEEE Std 1619-2007) for storage, as `XTS_AES_128` / - `XTS_AES_256` over `bouncycastle_cipher::modes::XTSKey`, with the data-unit length `N` checked at compile time; +* AES-XTS -- XTS-AES-128 and XTS-AES-256 (NIST SP 800-38E; IEEE Std 1619-2007) for storage, as `XTS_AES_128` / + `XTS_AES_256` over `bouncycastle_cipher::modes::XTSKey`, taking one data unit of 16 bytes to 2^20 blocks per call; the `aes128-xts` / `aes256-xts` CLI commands. * ECDSA -- FIPS 186-5 signatures over P-256, P-384, P-521, secp256k1, brainpoolP256r1, brainpoolP384r1 and brainpoolP512r1, with the RFC 6979 deterministic variant, through the `SigningKey` / `DeterministicSigningKey` / diff --git a/cli/src/main.rs b/cli/src/main.rs index 6d1b8dcc7..b65d83da9 100644 --- a/cli/src/main.rs +++ b/cli/src/main.rs @@ -3789,12 +3789,13 @@ enum Subcommands { /// XTS-AES-128 (NIST SP 800-38E; IEEE Std 1619-2007), for storage: streams stdin to stdout one /// data unit at a time. /// - /// The input is a sequence of data units of `--data-unit-len` bytes -- 512, 1024, 2048 or 4096, - /// the usual sector sizes -- and must be a whole number of them; the output is exactly as long - /// as the input, with nothing prepended. The first data unit is processed under `--tweak` and - /// each one after it under the tweak before it plus one, read as a 128-bit little-endian - /// integer. For sectors numbered from n, `--tweak` is n in 16 little-endian bytes: sector 1 is - /// 01000000000000000000000000000000. `decrypt` needs the same `--tweak` and `--data-unit-len`. + /// The input is a sequence of data units of `--data-unit-len` bytes -- any length from 16 (one + /// block) to 16777216 (2^20 blocks), such as a 512- or 4096-byte sector -- and must be a whole + /// number of them; the output is exactly as long as the input, with nothing prepended. The + /// first data unit is processed under `--tweak` and each one after it under the tweak before + /// it plus one, read as a 128-bit little-endian integer. For sectors numbered from n, `--tweak` + /// is n in 16 little-endian bytes: sector 1 is 01000000000000000000000000000000. `decrypt` + /// needs the same `--tweak` and `--data-unit-len`. /// /// The key is 32 bytes, Key_1 | Key_2: two AES-128 keys, the first for the data and the second /// for the tweak, which must differ (FIPS 140-3 IG C.I) and should be generated independently. @@ -3802,7 +3803,8 @@ enum Subcommands { /// WARNING: XTS provides confidentiality only, and is for data at rest, not in transit. Nothing /// detects a modified ciphertext, which decrypts to unpredictable data rather than to an error, /// or an old one, which decrypts to the old data, and the same data under the same key and - /// tweak always encrypts the same way. Give every data unit under a key its own tweak. + /// tweak always encrypts the same way. Give every data unit under a key its own tweak, and the + /// same length. /// /// Note: in production uses, secrets should not be passed on the command-line because they get /// logged in shell history. Use the file-based input instead. @@ -3824,7 +3826,7 @@ enum Subcommands { #[arg(long)] tweak: String, - /// The length of a data unit in bytes: 512, 1024, 2048 or 4096. + /// The length of a data unit in bytes, from 16 to 16777216 (2^20 blocks). #[arg(long)] data_unit_len: usize, @@ -3856,7 +3858,7 @@ enum Subcommands { #[arg(long)] tweak: String, - /// The length of a data unit in bytes: 512, 1024, 2048 or 4096. + /// The length of a data unit in bytes, from 16 to 16777216 (2^20 blocks). #[arg(long)] data_unit_len: usize, diff --git a/cli/src/xts_cmd.rs b/cli/src/xts_cmd.rs index df62fd2a2..505ec39c7 100644 --- a/cli/src/xts_cmd.rs +++ b/cli/src/xts_cmd.rs @@ -3,12 +3,11 @@ //! length. //! //! The input is a sequence of data units of `--data-unit-len` bytes, and must be a whole number of -//! them: an XTS key protects data units of one fixed length (NIST SP 800-38E Sec 4), and the -//! library fixes that length in the key's type, so the command offers the usual sector sizes and -//! instantiates a key type for the one chosen. The first data unit is processed under `--tweak` and -//! each later one under the tweak before it plus one, read as a 128-bit little-endian integer: the -//! numbering and the encoding of IEEE 1619-2007 Sec 5.1. Nothing is prepended or appended: the -//! output is exactly as long as the input. +//! them: an XTS key protects data units of one fixed length (NIST SP 800-38E Sec 4), so one length +//! serves the whole input. The first data unit is processed under `--tweak` and each later one +//! under the tweak before it plus one, read as a 128-bit little-endian integer: the numbering and +//! the encoding of IEEE 1619-2007 Sec 5.1. Nothing is prepended or appended: the output is exactly +//! as long as the input. //! //! # Warning //! @@ -18,13 +17,15 @@ use crate::helpers::block_mode_helpers::{CipherDirection, load_key_object}; use crate::helpers::{ decode_hex_arg, flush_stdout, read_stdin_chunk, write_bytes_or_hex, write_stdout, }; -use bouncycastle::cipher::modes::{XTS_TWEAK_LEN, XTSKey}; +use bouncycastle::cipher::modes::{ + XTS_MAX_DATA_UNIT_LEN, XTS_MIN_DATA_UNIT_LEN, XTS_TWEAK_LEN, XTSKey, +}; use bouncycastle::core::hazmat::BlockPermutation; use bouncycastle::core::symmetric_key::FromKeyMaterial; use std::process::exit; -/// XTS over the permutation `P` with a `KEY_LEN`-byte key, `Key_1 | Key_2`; `alg` names the -/// algorithm in messages. Exits with an error for a `data_unit_len` it does not offer. +/// XTS over the permutation `P` with a `KEY_LEN`-byte key, `Key_1 | Key_2`, on `data_unit_len`-byte +/// data units; `alg` names the algorithm in messages. pub(crate) fn xts_cmd( action: &CipherDirection, key: &Option, @@ -35,79 +36,56 @@ pub(crate) fn xts_cmd( alg: &str, ) where P: BlockPermutation<16>, - XTSKey: FromKeyMaterial, - XTSKey: FromKeyMaterial, - XTSKey: FromKeyMaterial, - XTSKey: FromKeyMaterial, + XTSKey

: FromKeyMaterial, { - let tweak = load_tweak(tweak); - match data_unit_len { - 512 => run::(action, key, key_file, &tweak, output_hex, alg), - 1024 => run::(action, key, key_file, &tweak, output_hex, alg), - 2048 => run::(action, key, key_file, &tweak, output_hex, alg), - 4096 => run::(action, key, key_file, &tweak, output_hex, alg), - other => { - eprintln!("Error: --data-unit-len must be 512, 1024, 2048 or 4096 bytes, not {other}."); - exit(-1); - } + let first_tweak = load_tweak(tweak); + // The library refuses a data unit outside these bounds at each call; checking the length here + // as well refuses it before the buffer of that length is allocated or any input is read. + if !(XTS_MIN_DATA_UNIT_LEN..=XTS_MAX_DATA_UNIT_LEN).contains(&data_unit_len) { + eprintln!( + "Error: --data-unit-len must be from {XTS_MIN_DATA_UNIT_LEN} to \ + {XTS_MAX_DATA_UNIT_LEN} bytes (one block to 2^20 blocks), not {data_unit_len}." + ); + exit(-1); } -} - -/// `--tweak`: exactly 16 bytes of hex, the 128-bit tweak of the first data unit. -fn load_tweak(tweak: &str) -> [u8; XTS_TWEAK_LEN] { - let bytes = decode_hex_arg(tweak, "tweak"); - bytes.as_slice().try_into().unwrap_or_else(|_| { - eprintln!("Error: the tweak is {} bytes; XTS takes exactly {XTS_TWEAK_LEN}.", bytes.len()); - exit(-1) - }) -} + let key = load_key_object::, KEY_LEN>(key, key_file, alg); -/// Processes stdin a data unit at a time under consecutive tweaks from `first_tweak`. -fn run( - action: &CipherDirection, - key: &Option, - key_file: &Option, - first_tweak: &[u8; XTS_TWEAK_LEN], - output_hex: bool, - alg: &str, -) where - P: BlockPermutation<16>, - XTSKey: FromKeyMaterial, -{ - let key = load_key_object::, KEY_LEN>(key, key_file, alg); - let mut sequence_number = u128::from_le_bytes(*first_tweak); - let mut data_unit = [0u8; N]; - let mut units = 0u64; + // `None` once a data unit has taken the tweak 2^128 - 1: there is no next one, and wrapping + // round to 0 could repeat a tweak an earlier data unit used. + let mut next_tweak = Some(u128::from_le_bytes(first_tweak)); + let mut data_unit = vec![0u8; data_unit_len]; loop { let filled = fill(&mut data_unit); if filled == 0 { break; } - if filled < N { + if filled < data_unit_len { // The whole data units before it are already written; flush them so that the error // follows the output rather than landing inside it. flush_stdout(); eprintln!( - "\nError: input to {alg} must be a whole number of {N}-byte data units \ - (data contained {filled} trailing byte(s))." + "\nError: input to {alg} must be a whole number of {data_unit_len}-byte data \ + units (data contained {filled} trailing byte(s))." ); exit(-1); } - if units > 0 { - // Fail rather than wrap round to a tweak an earlier data unit may have used. - sequence_number = sequence_number.checked_add(1).unwrap_or_else(|| { - flush_stdout(); - eprintln!("\nError: the tweak cannot go past 2^128 - 1."); - exit(-1) - }); - } + let Some(sequence_number) = next_tweak else { + flush_stdout(); + eprintln!("\nError: the tweak cannot go past 2^128 - 1."); + exit(-1) + }; let tweak = sequence_number.to_le_bytes(); - match action { + let processed = match action { CipherDirection::Encrypt => key.encrypt_inplace(&tweak, &mut data_unit), CipherDirection::Decrypt => key.decrypt_inplace(&tweak, &mut data_unit), }; + if let Err(e) = processed { + flush_stdout(); + eprintln!("\nError: {alg} refused the data unit: {e:?}"); + exit(-1); + } write_bytes_or_hex(&data_unit, output_hex); - units += 1; + next_tweak = sequence_number.checked_add(1); } if output_hex { write_stdout(b"\n"); @@ -115,6 +93,15 @@ fn run( flush_stdout(); } +/// `--tweak`: exactly 16 bytes of hex, the 128-bit tweak of the first data unit. +fn load_tweak(tweak: &str) -> [u8; XTS_TWEAK_LEN] { + let bytes = decode_hex_arg(tweak, "tweak"); + bytes.as_slice().try_into().unwrap_or_else(|_| { + eprintln!("Error: the tweak is {} bytes; XTS takes exactly {XTS_TWEAK_LEN}.", bytes.len()); + exit(-1) + }) +} + /// Reads stdin into `buf` until it is full or the input ends, and returns how much was read. fn fill(buf: &mut [u8]) -> usize { let mut filled = 0; diff --git a/cli/tests/aes_xts_cli_tests.rs b/cli/tests/aes_xts_cli_tests.rs index d9b7d783e..b07b66e1c 100644 --- a/cli/tests/aes_xts_cli_tests.rs +++ b/cli/tests/aes_xts_cli_tests.rs @@ -1,10 +1,13 @@ -//! Tests for the `aes128-xts` and `aes256-xts` subcommands: the library's answer at every offered -//! data-unit length, and an OpenSSL known answer, through the command; consecutive tweaks across -//! data units, including a carry; the refusals of partial data units, a wrapping tweak and bad -//! arguments; and the help listing. +//! Tests for the `aes128-xts` and `aes256-xts` subcommands: the library's answer at data-unit +//! lengths from one block to a 4 KiB sector, and an OpenSSL known answer, through the command; +//! consecutive tweaks across data units, including a carry; the refusals of partial data units, a +//! wrapping tweak and bad arguments, a data-unit length outside the bounds among them; and the +//! help listing. mod common; use bouncycastle::aes::{XTS_AES_128, XTS_AES_256}; +use bouncycastle::cipher::modes::{XTS_MAX_DATA_UNIT_LEN, XTS_MIN_DATA_UNIT_LEN, XTSKey}; +use bouncycastle::core::hazmat::BlockPermutation; use common::{ KEY32, key_object, listed_in_help, pseudo_random, run, run_err_silent, run_ok, unhex, }; @@ -16,34 +19,35 @@ const KEY64: &str = "000102030405060708090a0b0c0d0e0f101112131415161718191a1b1c1 const TWEAK: &str = "f0e1d2c3b4a5968778695a4b3c2d1e0f"; -/// The library's answer for `data` as consecutive `N`-byte data units from the tweak `first`. -fn library_128(key: &str, first: &str, data: &[u8], encrypt: bool) -> Vec { - let key: XTS_AES_128 = key_object::<32, _>(key); +/// The library's answer for `data` as consecutive `len`-byte data units from the tweak `first`. +fn library>( + key: &XTSKey

, + first: &str, + len: usize, + data: &[u8], + encrypt: bool, +) -> Vec { let first = u128::from_le_bytes(unhex(first).try_into().unwrap()); let mut out = data.to_vec(); - for (n, unit) in (first..).zip(out.as_chunks_mut::().0) { - if encrypt { - key.encrypt_inplace(&n.to_le_bytes(), unit); + for (n, unit) in (first..).zip(out.chunks_exact_mut(len)) { + let processed = if encrypt { + key.encrypt_inplace(&n.to_le_bytes(), unit) } else { - key.decrypt_inplace(&n.to_le_bytes(), unit); - } + key.decrypt_inplace(&n.to_le_bytes(), unit) + }; + assert_eq!(processed, Ok(len)); } out } -/// As [`library_128`], for XTS-AES-256. -fn library_256(key: &str, first: &str, data: &[u8], encrypt: bool) -> Vec { - let key: XTS_AES_256 = key_object::<64, _>(key); - let first = u128::from_le_bytes(unhex(first).try_into().unwrap()); - let mut out = data.to_vec(); - for (n, unit) in (first..).zip(out.as_chunks_mut::().0) { - if encrypt { - key.encrypt_inplace(&n.to_le_bytes(), unit); - } else { - key.decrypt_inplace(&n.to_le_bytes(), unit); - } - } - out +/// [`library`] under the XTS-AES-128 key `key`. +fn library_128(key: &str, first: &str, len: usize, data: &[u8], encrypt: bool) -> Vec { + library(&key_object::<32, XTS_AES_128>(key), first, len, data, encrypt) +} + +/// [`library`] under the XTS-AES-256 key `key`. +fn library_256(key: &str, first: &str, len: usize, data: &[u8], encrypt: bool) -> Vec { + library(&key_object::<64, XTS_AES_256>(key), first, len, data, encrypt) } /// The arguments of `cmd` in `direction` under `key`, from `tweak`, in `len`-byte data units. @@ -71,32 +75,20 @@ fn agrees(cmd: &str, key: &str, len: usize, data: &[u8], expected: &[u8]) { assert_eq!(pt, data, "{cmd} at {len}: decrypt"); } +/// One block, one block and a byte, the usual sector sizes, and lengths between them that leave +/// a partial block. #[test] -fn the_commands_agree_with_the_library_at_every_data_unit_length() { - for len in [512, 1024, 2048, 4096] { +fn the_commands_agree_with_the_library_at_any_data_unit_length() { + for len in [16, 17, 512, 1000, 1024, 2048, 4096] { let data = pseudo_random(3 * len, len as u32); - let expected = match len { - 512 => library_128::<512>(KEY32, TWEAK, &data, true), - 1024 => library_128::<1024>(KEY32, TWEAK, &data, true), - 2048 => library_128::<2048>(KEY32, TWEAK, &data, true), - _ => library_128::<4096>(KEY32, TWEAK, &data, true), - }; + let expected = library_128(KEY32, TWEAK, len, &data, true); agrees("aes128-xts", KEY32, len, &data, &expected); } - for len in [512, 4096] { + for len in [16, 512, 4095, 4096] { let data = pseudo_random(3 * len, len as u32 + 1); - let expected = match len { - 512 => library_256::<512>(KEY64, TWEAK, &data, true), - _ => library_256::<4096>(KEY64, TWEAK, &data, true), - }; + let expected = library_256(KEY64, TWEAK, len, &data, true); agrees("aes256-xts", KEY64, len, &data, &expected); - assert_eq!( - match len { - 512 => library_256::<512>(KEY64, TWEAK, &expected, false), - _ => library_256::<4096>(KEY64, TWEAK, &expected, false), - }, - data - ); + assert_eq!(library_256(KEY64, TWEAK, len, &expected, false), data); } } @@ -140,7 +132,7 @@ fn consecutive_data_units_take_consecutive_tweaks() { &data[512..], ); assert_eq!(both[512..], second[..]); - assert_eq!(both, library_128::<512>(KEY32, "ff000000000000000000000000000000", &data, true)); + assert_eq!(both, library_128(KEY32, "ff000000000000000000000000000000", 512, &data, true)); } /// Input that is not a whole number of data units is refused; the whole ones before the @@ -173,22 +165,29 @@ fn the_tweak_does_not_wrap() { assert!(String::from_utf8_lossy(&out.stderr).contains("cannot go past 2^128 - 1")); } -/// A wrong key length, equal key halves, a malformed tweak and an unsupported data-unit length -/// are all refused before anything is written. +/// A wrong key length, equal key halves, a malformed tweak and a data-unit length outside the +/// bounds, at either end, are all refused before anything is written. #[test] fn bad_arguments_are_refused() { let short_key = &KEY32[..62]; let equal_halves = "00112233445566778899aabbccddeeff00112233445566778899aabbccddeeff"; - let cases: [(&str, &str, &str, usize, &str); 6] = [ + let bounds = "--data-unit-len must be from 16 to 16777216 bytes"; + let cases: [(&str, &str, &str, usize, &str); 9] = [ ("aes128-xts", short_key, TWEAK, 512, "needs a 32-byte key"), ("aes256-xts", KEY32, TWEAK, 512, "needs a 64-byte key"), ("aes128-xts", equal_halves, TWEAK, 512, "Key_1 != Key_2"), ("aes128-xts", KEY32, &TWEAK[..30], 512, "the tweak is 15 bytes"), ("aes128-xts", KEY32, "not hex", 512, "`--tweak` must be hex"), - ("aes256-xts", KEY64, TWEAK, 1000, "--data-unit-len must be 512, 1024, 2048 or 4096"), + ("aes128-xts", KEY32, TWEAK, 0, bounds), + ("aes128-xts", KEY32, TWEAK, XTS_MIN_DATA_UNIT_LEN - 1, bounds), + ("aes256-xts", KEY64, TWEAK, XTS_MAX_DATA_UNIT_LEN + 1, bounds), + ("aes256-xts", KEY64, TWEAK, usize::MAX, bounds), ]; for (cmd, key, tweak, len, msg) in cases { - let err = run_err_silent(&args(&xts(cmd, "encrypt", key, tweak, len)), &[0x42; 512]); + let out = run(&args(&xts(cmd, "encrypt", key, tweak, len)), &[0x42; 512]); + assert!(!out.status.success(), "{cmd} {key} {tweak} {len}: accepted"); + assert!(out.stdout.is_empty(), "{cmd} {key} {tweak} {len}: wrote output"); + let err = String::from_utf8_lossy(&out.stderr); assert!(err.contains(msg), "{cmd} {key} {tweak} {len}: stderr was: {err}"); } } diff --git a/crypto/aes/benches/aes_xts_benches.rs b/crypto/aes/benches/aes_xts_benches.rs index 3cb2f0df9..163941184 100644 --- a/crypto/aes/benches/aes_xts_benches.rs +++ b/crypto/aes/benches/aes_xts_benches.rs @@ -31,30 +31,26 @@ fn key() -> KeyMaterial { KeyMaterial::::from_bytes_as_type(&bytes, KeyType::SymmetricCipherKey).unwrap() } -/// Encryption and decryption of one `N`-byte data unit, reported as `label`. -fn data_unit( +/// Encryption and decryption of one `len`-byte data unit, reported as `label`. +fn data_unit( group: &mut BenchmarkGroup<'_, WallTime>, + len: usize, label: &str, ) where P: BlockPermutation<16>, - XTSKey: FromKeyMaterial, + XTSKey

: FromKeyMaterial, { - let key = XTSKey::::from_key_material(&key::()).unwrap(); - let plaintext: Box<[u8; N]> = (0..N) - .map(|i| (i as u8).wrapping_mul(31)) - .collect::>() - .into_boxed_slice() - .try_into() - .unwrap(); + let key = XTSKey::

::from_key_material(&key::()).unwrap(); + let plaintext: Vec = (0..len).map(|i| (i as u8).wrapping_mul(31)).collect(); let mut ciphertext = plaintext.clone(); - key.encrypt_inplace(&TWEAK, &mut ciphertext); + key.encrypt_inplace(&TWEAK, &mut ciphertext).unwrap(); - group.throughput(Throughput::Bytes(N as u64)); + group.throughput(Throughput::Bytes(len as u64)); group.bench_function(format!("encrypt {label}"), |b| { b.iter_batched( || plaintext.clone(), |mut unit| { - key.encrypt_inplace(black_box(&TWEAK), &mut unit); + key.encrypt_inplace(black_box(&TWEAK), &mut unit).unwrap(); black_box(&unit); }, BatchSize::SmallInput, @@ -64,7 +60,7 @@ fn data_unit( b.iter_batched( || ciphertext.clone(), |mut unit| { - key.decrypt_inplace(black_box(&TWEAK), &mut unit); + key.decrypt_inplace(black_box(&TWEAK), &mut unit).unwrap(); black_box(&unit); }, BatchSize::SmallInput, @@ -74,21 +70,21 @@ fn data_unit( fn bench_xts_aes_128(c: &mut Criterion) { let mut group = c.benchmark_group("modes::xts::XTS_AES_128"); - data_unit::(&mut group, "16B (one block)"); - data_unit::(&mut group, "512B sector"); - data_unit::(&mut group, "4KiB sector"); - data_unit::(&mut group, "4095B (ciphertext stealing)"); - data_unit::(&mut group, "64KiB"); + data_unit::(&mut group, 16, "16B (one block)"); + data_unit::(&mut group, 512, "512B sector"); + data_unit::(&mut group, 4096, "4KiB sector"); + data_unit::(&mut group, 4095, "4095B (ciphertext stealing)"); + data_unit::(&mut group, 65536, "64KiB"); group.finish(); } fn bench_xts_aes_256(c: &mut Criterion) { let mut group = c.benchmark_group("modes::xts::XTS_AES_256"); - data_unit::(&mut group, "16B (one block)"); - data_unit::(&mut group, "512B sector"); - data_unit::(&mut group, "4KiB sector"); - data_unit::(&mut group, "4095B (ciphertext stealing)"); - data_unit::(&mut group, "64KiB"); + data_unit::(&mut group, 16, "16B (one block)"); + data_unit::(&mut group, 512, "512B sector"); + data_unit::(&mut group, 4096, "4KiB sector"); + data_unit::(&mut group, 4095, "4095B (ciphertext stealing)"); + data_unit::(&mut group, 65536, "64KiB"); group.finish(); } @@ -98,10 +94,10 @@ fn bench_xts_init(c: &mut Criterion) { let material_128 = key::<32>(); let material_256 = key::<64>(); group.bench_function("XTS_AES_128 from_key_material (two key schedules)", |b| { - b.iter(|| black_box(XTS_AES_128::<4096>::from_key_material(black_box(&material_128)))) + b.iter(|| black_box(XTS_AES_128::from_key_material(black_box(&material_128)))) }); group.bench_function("XTS_AES_256 from_key_material (two key schedules)", |b| { - b.iter(|| black_box(XTS_AES_256::<4096>::from_key_material(black_box(&material_256)))) + b.iter(|| black_box(XTS_AES_256::from_key_material(black_box(&material_256)))) }); group.finish(); } diff --git a/crypto/aes/src/xts.rs b/crypto/aes/src/xts.rs index fdfae09da..f08906128 100644 --- a/crypto/aes/src/xts.rs +++ b/crypto/aes/src/xts.rs @@ -4,17 +4,16 @@ use crate::hazmat::{AES128Internal, AES256Internal}; use bouncycastle_cipher::modes::XTSKey; -/// XTS-AES-128 (NIST SP 800-38E; IEEE Std 1619-2007) for data units of exactly `DATA_UNIT_LEN` -/// bytes: a 256-bit key `Key_1 | Key_2`, each half an AES-128 key, `Key_1` for the data and -/// `Key_2` for the tweak. +/// XTS-AES-128 (NIST SP 800-38E; IEEE Std 1619-2007): a 256-bit key `Key_1 | Key_2`, each half +/// an AES-128 key, `Key_1` for the data and `Key_2` for the tweak. /// /// It is the key object of [`bouncycastle_cipher::modes::xts`], which describes the tweak and the /// security considerations; read those before using XTS, which is unauthenticated and meant for /// storage. The key is built once with [`FromKeyMaterial`] and encrypts and decrypts one data /// unit at a time, in place: [`encrypt_inplace`](XTSKey::encrypt_inplace) and /// [`decrypt_inplace`](XTSKey::decrypt_inplace). A data unit is from 16 bytes to 2^20 blocks, -/// and a length outside that range does not compile. IEEE 1619-2007 Sec 6 defines XTS-AES-128 -/// and XTS-AES-256 only, so there is no XTS-AES-192. +/// and one outside that range is refused. IEEE 1619-2007 Sec 6 defines XTS-AES-128 and +/// XTS-AES-256 only, so there is no XTS-AES-192. /// /// # Usage Examples /// @@ -33,7 +32,7 @@ use bouncycastle_cipher::modes::XTSKey; /// ]; /// let material = KeyMaterial::<32>::from_bytes_as_type(&key_bytes, KeyType::SymmetricCipherKey) /// .expect("a 32-byte symmetric cipher key"); -/// let key = XTS_AES_128::<23>::from_key_material(&material).expect("a valid XTS-AES-128 key"); +/// let key = XTS_AES_128::from_key_material(&material).expect("a valid XTS-AES-128 key"); /// /// let plaintext = [ /// 0xea, 0xfd, 0xbd, 0x33, 0x05, 0x11, 0xba, 0xa1, 0xc9, 0x12, 0xea, 0x24, 0xb7, 0xb1, @@ -43,7 +42,7 @@ use bouncycastle_cipher::modes::XTSKey; /// let tweak = 202u128.to_le_bytes(); /// /// let mut data_unit = plaintext; -/// assert_eq!(key.encrypt_inplace(&tweak, &mut data_unit), 23); +/// assert_eq!(key.encrypt_inplace(&tweak, &mut data_unit), Ok(23)); /// assert_eq!( /// data_unit, /// [ @@ -51,7 +50,7 @@ use bouncycastle_cipher::modes::XTSKey; /// 0x1e, 0x15, 0x17, 0x8b, 0x8c, 0xc3, 0x42, 0x6e, 0x31, /// ] /// ); -/// key.decrypt_inplace(&tweak, &mut data_unit); +/// key.decrypt_inplace(&tweak, &mut data_unit).expect("a 23-byte data unit"); /// assert_eq!(data_unit, plaintext); /// ``` /// @@ -63,29 +62,37 @@ use bouncycastle_cipher::modes::XTSKey; /// use bouncycastle_rng::HashDRBG_SHA512; /// /// let mut rng = HashDRBG_SHA512::new_from_os(); -/// let key = XTS_AES_256::<4096>::generate(&mut rng).expect("a 256-bit RNG"); +/// let key = XTS_AES_256::generate(&mut rng).expect("a 256-bit RNG"); /// /// let mut disk = vec![0u8; 8 * 4096]; -/// let (sectors, rest) = disk.as_chunks_mut::<4096>(); -/// assert!(rest.is_empty()); -/// for (n, sector) in (100u128..).zip(sectors.iter_mut()) { -/// key.encrypt_inplace(&n.to_le_bytes(), sector); +/// for (n, sector) in (100u128..).zip(disk.chunks_exact_mut(4096)) { +/// key.encrypt_inplace(&n.to_le_bytes(), sector).expect("a 4096-byte sector"); /// } /// // Equal plaintext sectors, under different sequence numbers, encrypt differently. -/// assert_ne!(sectors[0], sectors[1]); +/// assert_ne!(disk[..4096], disk[4096..2 * 4096]); /// ``` /// /// # Memory Usage /// /// A key is two AES schedules: 352 bytes for XTS-AES-128 and 480 for XTS-AES-256. A call works in -/// the caller's buffer; beside the permutation's own frame it keeps the tweak's mask and the -/// masks of the four blocks in flight on the stack. +/// the caller's buffer, so its stack does not grow with the data unit. Measured as the deepest +/// frame chain below each call in the release build on x86-64 (return addresses included, the +/// caller's buffer not), over `mem_usage_benches/src/bench_aes_mem_usage.rs`: +/// +/// | Call | XTS-AES-128 | XTS-AES-256 | +/// |---|---|---| +/// | `from_key_material` | 1 568 B | 2 112 B | +/// | `encrypt_inplace` | 368 B | 368 B | +/// | `decrypt_inplace` | 472 B | 472 B | +/// +/// The peak of a call is on its four-block path: the masks of the four blocks in flight, and the +/// permutation's four-block frame below them. /// /// [`FromKeyMaterial`]: bouncycastle_core::symmetric_key::FromKeyMaterial #[allow(non_camel_case_types)] -pub type XTS_AES_128 = XTSKey; +pub type XTS_AES_128 = XTSKey; -/// XTS-AES-256 (NIST SP 800-38E; IEEE Std 1619-2007) for data units of exactly `DATA_UNIT_LEN` -/// bytes: a 512-bit key `Key_1 | Key_2`, each half an AES-256 key. See [`XTS_AES_128`]. +/// XTS-AES-256 (NIST SP 800-38E; IEEE Std 1619-2007): a 512-bit key `Key_1 | Key_2`, each half +/// an AES-256 key. See [`XTS_AES_128`]. #[allow(non_camel_case_types)] -pub type XTS_AES_256 = XTSKey; +pub type XTS_AES_256 = XTSKey; diff --git a/crypto/aes/tests/xts_acvp_tests.rs b/crypto/aes/tests/xts_acvp_tests.rs index a4ed710ce..a90097adc 100644 --- a/crypto/aes/tests/xts_acvp_tests.rs +++ b/crypto/aes/tests/xts_acvp_tests.rs @@ -6,8 +6,8 @@ //! //! Every case that is one data unit of a whole number of bytes is run, in both directions //! whichever one it was generated for. The rest are counted and skipped: an ACVP data unit can be -//! any number of bits, where this API takes whole bytes, and the 2.0 set's cases whose -//! `dataUnitLen` differs from their `payloadLen` are not a data unit of the key's one length. The +//! any number of bits, where this API takes whole bytes, and the payload of a 2.0 case whose +//! `dataUnitLen` differs from its `payloadLen` is not one data unit of the stated length. The //! counts are asserted, so a case cannot drop out of the run unnoticed. //! //! A case of tweak mode "number" gives the data unit's sequence number, and the tweak is its @@ -26,52 +26,27 @@ fn number(v: &Value) -> u64 { v.as_u64().unwrap_or_else(|| v.as_str().expect("a number").parse().expect("a number")) } -/// Checks one case through `XTSKey` under its `KEY_LEN`-byte key, in both directions. -fn check( - key: &[u8], - tweak: &[u8; 16], - pt: &[u8], - ct: &[u8], - tc_id: u64, -) where +/// Checks one case through `XTSKey

` under its `KEY_LEN`-byte key, in both directions. +fn check(key: &[u8], tweak: &[u8; 16], pt: &[u8], ct: &[u8], tc_id: u64) +where P: BlockPermutation<16>, - XTSKey: FromKeyMaterial, + XTSKey

: FromKeyMaterial, { let material = KeyMaterial::::from_bytes_as_type(key, KeyType::SymmetricCipherKey).unwrap(); - let key = XTSKey::::from_key_material(&material) + let key = XTSKey::

::from_key_material(&material) .unwrap_or_else(|e| panic!("tcId {tc_id}: the key is refused: {e:?}")); - let pt: [u8; N] = pt.try_into().expect("an N-byte plaintext"); - let ct: [u8; N] = ct.try_into().expect("an N-byte ciphertext"); + assert_eq!(ct.len(), pt.len(), "tcId {tc_id}: the ciphertext is as long as the plaintext"); - let mut data_unit = pt; - assert_eq!(key.encrypt_inplace(tweak, &mut data_unit), N, "tcId {tc_id}"); + let mut data_unit = pt.to_vec(); + assert_eq!(key.encrypt_inplace(tweak, &mut data_unit), Ok(pt.len()), "tcId {tc_id}"); assert_eq!(data_unit, ct, "tcId {tc_id}: encryption"); - let mut data_unit = ct; - assert_eq!(key.decrypt_inplace(tweak, &mut data_unit), N, "tcId {tc_id}"); + let mut data_unit = ct.to_vec(); + assert_eq!(key.decrypt_inplace(tweak, &mut data_unit), Ok(ct.len()), "tcId {tc_id}"); assert_eq!(data_unit, pt, "tcId {tc_id}: decryption"); } -fn check_128(key: &[u8], tweak: &[u8; 16], pt: &[u8], ct: &[u8], tc_id: u64) { - check::(key, tweak, pt, ct, tc_id); -} - -fn check_256(key: &[u8], tweak: &[u8; 16], pt: &[u8], ct: &[u8], tc_id: u64) { - check::(key, tweak, pt, ct, tc_id); -} - -/// Calls `$check::` for the data-unit length `$len`. The length is a const parameter of the -/// key type, so every whole-byte length in the two files has an arm. -macro_rules! dispatch { - ($len:expr, $check:ident, $args:tt, $tc_id:expr, [$($n:literal)*]) => { - match $len { - $($n => $check::<$n> $args,)* - other => panic!("tcId {}: no arm for a {other}-byte data unit; add one", $tc_id), - } - }; -} - /// Runs every whole-byte, single-data-unit case of one revision's vector set, and returns how /// many ran under each key size and how many were skipped. fn run(revision: &str) -> Option<(usize, usize, usize)> { @@ -120,24 +95,13 @@ fn run(revision: &str) -> Option<(usize, usize, usize)> { }; assert_eq!(pt.len(), len, "tcId {tc_id}: the plaintext is payloadLen bits"); - #[rustfmt::skip] - macro_rules! by_len { - ($check:ident) => { - dispatch!(len, $check, (&key, &tweak, &pt, &ct, tc_id), tc_id, [ - 16 21 23 27 29 31 46 48 56 57 59 62 64 75 77 78 84 86 92 93 94 100 119 126 - 262 308 320 559 669 912 919 1184 1447 1451 1568 1616 1950 2051 2528 2538 - 2669 2792 3001 3152 3216 3536 3632 3744 3788 4000 4151 4539 4610 5166 5344 - 5375 5909 6317 6321 6494 6528 6672 6732 6780 7089 7312 7856 7968 8024 8192 - ]) - }; - } match key_len { 128 => { - by_len!(check_128); + check::(&key, &tweak, &pt, &ct, tc_id); ran_128 += 1; } 256 => { - by_len!(check_256); + check::(&key, &tweak, &pt, &ct, tc_id); ran_256 += 1; } other => panic!("tcId {tc_id}: unexpected keyLen {other}"), diff --git a/crypto/aes/tests/xts_tests.rs b/crypto/aes/tests/xts_tests.rs index 834074a82..58a3fe2c5 100644 --- a/crypto/aes/tests/xts_tests.rs +++ b/crypto/aes/tests/xts_tests.rs @@ -3,10 +3,12 @@ //! independent implementation; every block of a data unit against a reference written here from //! the definition (IEEE 1619-2007 Sec 5.2 and 5.3), which pins the roles of the two key halves, //! the byte order of the tweak and the multiplication by α; round trips at every length from one -//! block to eight and a half; and the key constructor's refusals. +//! block to eight and a half; the refusal of a data unit outside the bounds at both key sizes; +//! and the key constructor's refusals. //! -//! The published vectors are in `xts_acvp_tests.rs` and `xts_wycheproof.rs`. The compile-time -//! bounds on the data-unit length are doctests on `bouncycastle_cipher::modes::XTSKey`. +//! The published vectors are in `xts_acvp_tests.rs` and `xts_wycheproof.rs`. The bounds on the +//! data-unit length are tested at both ends over a toy permutation in +//! `crypto/cipher/tests/modes/xts_tests.rs`. use bouncycastle_aes::hazmat::{AES128Internal, AES256Internal}; use bouncycastle_aes::{XTS_AES_128, XTS_AES_256}; @@ -40,61 +42,48 @@ fn material(bytes: &[u8]) -> KeyMaterial { KeyMaterial::::from_bytes_as_type(bytes, KeyType::SymmetricCipherKey).unwrap() } -fn xts_key(bytes: &[u8; KEY_LEN]) -> XTSKey +fn xts_key(bytes: &[u8; KEY_LEN]) -> XTSKey

where - XTSKey: FromKeyMaterial, + XTSKey

: FromKeyMaterial, { - XTSKey::::from_key_material(&material(bytes)).expect("a valid XTS key") + XTSKey::

::from_key_material(&material(bytes)).expect("a valid XTS key") } // ---- known answers from OpenSSL ---------------------------------------------------------------- /// The first n bytes of `pattern` under `key_bytes()` and `TWEAK` encrypt to `ct`, and back. -fn kat(ct: &str) +fn kat(n: usize, ct: &str) where P: BlockPermutation<16>, - XTSKey: FromKeyMaterial, + XTSKey

: FromKeyMaterial, { - let key = xts_key::(&key_bytes()); - let pt: [u8; N] = pattern(N).try_into().unwrap(); - let ct: [u8; N] = hex::decode(ct).unwrap().try_into().expect("an N-byte ciphertext"); - - let mut data_unit = pt; - assert_eq!(key.encrypt_inplace(&TWEAK, &mut data_unit), N); - assert_eq!(data_unit, ct, "{N}-byte data unit: encryption"); + let key = xts_key::(&key_bytes()); + let pt = pattern(n); + let ct = hex::decode(ct).unwrap(); + assert_eq!(ct.len(), n, "the table's {n}-byte ciphertext"); + + let mut data_unit = pt.clone(); + assert_eq!(key.encrypt_inplace(&TWEAK, &mut data_unit), Ok(n)); + assert_eq!(data_unit, ct, "{n}-byte data unit: encryption"); let mut data_unit = ct; - assert_eq!(key.decrypt_inplace(&TWEAK, &mut data_unit), N); - assert_eq!(data_unit, pt, "{N}-byte data unit: decryption"); + assert_eq!(key.decrypt_inplace(&TWEAK, &mut data_unit), Ok(n)); + assert_eq!(data_unit, pt, "{n}-byte data unit: decryption"); } /// The lengths of the tables below: one block, one block and one byte, one byte short of two, /// two, two and a byte, six and a quarter, one byte short of eight, and a 512-byte sector. -macro_rules! kats { - ($perm:ty, $key_len:literal, $table:expr) => { - for &(n, ct) in $table { - match n { - 16 => kat::<$perm, $key_len, 16>(ct), - 17 => kat::<$perm, $key_len, 17>(ct), - 31 => kat::<$perm, $key_len, 31>(ct), - 32 => kat::<$perm, $key_len, 32>(ct), - 33 => kat::<$perm, $key_len, 33>(ct), - 100 => kat::<$perm, $key_len, 100>(ct), - 127 => kat::<$perm, $key_len, 127>(ct), - 512 => kat::<$perm, $key_len, 512>(ct), - other => panic!("no arm for a {other}-byte known answer"), - } - } - }; -} - #[test] fn xts_aes_128_matches_openssl() { - kats!(AES128Internal, 32, KATS_128); + for &(n, ct) in KATS_128 { + kat::(n, ct); + } } #[test] fn xts_aes_256_matches_openssl() { - kats!(AES256Internal, 64, KATS_256); + for &(n, ct) in KATS_256 { + kat::(n, ct); + } } /// A long known answer: a 16-byte fold of the ciphertext (`fold[k % 16] ^= ct[k]` over every @@ -107,35 +96,42 @@ struct LongKat { /// The longest data units against OpenSSL: the mask chain runs to α^(2^20 - 1), and one byte /// short of the limit a ciphertext block is stolen at the far end. -fn long_kat(expected: &LongKat) +fn long_kat(n: usize, expected: &LongKat) where P: BlockPermutation<16>, - XTSKey: FromKeyMaterial, + XTSKey

: FromKeyMaterial, { - let key = xts_key::(&key_bytes()); - let pt = pattern(N); - let mut buf = pt.clone(); - let data_unit: &mut [u8; N] = buf.as_mut_slice().try_into().unwrap(); + let key = xts_key::(&key_bytes()); + let pt = pattern(n); + let mut data_unit = pt.clone(); - assert_eq!(key.encrypt_inplace(&TWEAK, data_unit), N); + assert_eq!(key.encrypt_inplace(&TWEAK, &mut data_unit), Ok(n)); let mut fold = [0u8; 16]; for (k, byte) in data_unit.iter().enumerate() { fold[k % 16] ^= byte; } - assert_eq!(hex::encode(fold), expected.fold, "{N} bytes: the fold of the ciphertext"); - assert_eq!(hex::encode(&data_unit[..16]), expected.first, "{N} bytes: the first block"); - assert_eq!(hex::encode(&data_unit[N - 32..]), expected.last, "{N} bytes: the last 32 bytes"); + assert_eq!(hex::encode(fold), expected.fold, "{n} bytes: the fold of the ciphertext"); + assert_eq!(hex::encode(&data_unit[..16]), expected.first, "{n} bytes: the first block"); + assert_eq!(hex::encode(&data_unit[n - 32..]), expected.last, "{n} bytes: the last 32 bytes"); - assert_eq!(key.decrypt_inplace(&TWEAK, data_unit), N); - assert!(*data_unit == *pt, "{N} bytes: decryption restores the plaintext"); + assert_eq!(key.decrypt_inplace(&TWEAK, &mut data_unit), Ok(n)); + assert!(data_unit == pt, "{n} bytes: decryption restores the plaintext"); } -/// 2^20 blocks under XTS-AES-128, and one byte less under XTS-AES-256: each key size, and each -/// end of a maximal data unit, once. (About seven seconds each in a debug build.) +// The two longest data units, each key size and each end of a maximal data unit once, are two +// tests so that the test harness runs them in parallel: each takes several seconds in a debug +// build. + +/// 2^20 blocks under XTS-AES-128: the longest data unit there is. #[test] -fn the_longest_data_units_match_openssl() { - long_kat::(&LONG_128_MAX); - long_kat::(&LONG_256_MAX_MINUS_1); +fn the_longest_data_unit_matches_openssl() { + long_kat::(XTS_MAX_DATA_UNIT_LEN, &LONG_128_MAX); +} + +/// One byte short of 2^20 blocks under XTS-AES-256: the last whole block is stolen from. +#[test] +fn one_byte_short_of_the_longest_data_unit_matches_openssl() { + long_kat::(XTS_MAX_DATA_UNIT_LEN - 1, &LONG_256_MAX_MINUS_1); } // ---- the definition, block by block ------------------------------------------------------------ @@ -156,7 +152,7 @@ fn times_alpha(t: [u8; 16]) -> [u8; 16] { fn follows_the_definition() where P: KeyExpansion + BlockPermutation<16>, - XTSKey: FromKeyMaterial, + XTSKey

: FromKeyMaterial, { let key_bytes = key_bytes::(); let key1 = P::new(&material::(&key_bytes[..HALF])).unwrap(); @@ -177,9 +173,9 @@ where t = times_alpha(t); } - let key = xts_key::(&key_bytes); + let key = xts_key::(&key_bytes); let mut data_unit = pt; - key.encrypt_inplace(&TWEAK, &mut data_unit); + assert_eq!(key.encrypt_inplace(&TWEAK, &mut data_unit), Ok(512)); assert_eq!(data_unit, expected); } @@ -206,86 +202,73 @@ fn the_reference_multiplication_reduces() { // ---- round trips and tweaks -------------------------------------------------------------------- -fn round_trip() { - let pt: [u8; N] = pattern(N).try_into().unwrap(); - let k128 = xts_key::(&key_bytes()); - let k256 = xts_key::(&key_bytes()); - - let mut a = pt; - assert_eq!(k128.encrypt_inplace(&TWEAK, &mut a), N); - assert_ne!(a, pt, "{N} bytes: XTS-AES-128 changed nothing"); - assert_eq!(k128.decrypt_inplace(&TWEAK, &mut a), N); - assert_eq!(a, pt, "{N} bytes: XTS-AES-128 round trip"); - - let mut b = pt; - k256.encrypt_inplace(&TWEAK, &mut b); - assert_ne!(b, pt, "{N} bytes: XTS-AES-256 changed nothing"); - k256.decrypt_inplace(&TWEAK, &mut b); - assert_eq!(b, pt, "{N} bytes: XTS-AES-256 round trip"); -} - -macro_rules! round_trips { - ($($n:literal),* $(,)?) => { - $(round_trip::<$n>();)* - }; +fn round_trip(n: usize) { + let pt = pattern(n); + let k128 = xts_key::(&key_bytes()); + let k256 = xts_key::(&key_bytes()); + + let mut a = pt.clone(); + assert_eq!(k128.encrypt_inplace(&TWEAK, &mut a), Ok(n)); + assert_ne!(a, pt, "{n} bytes: XTS-AES-128 changed nothing"); + assert_eq!(k128.decrypt_inplace(&TWEAK, &mut a), Ok(n)); + assert_eq!(a, pt, "{n} bytes: XTS-AES-128 round trip"); + + let mut b = pt.clone(); + assert_eq!(k256.encrypt_inplace(&TWEAK, &mut b), Ok(n)); + assert_ne!(b, pt, "{n} bytes: XTS-AES-256 changed nothing"); + assert_eq!(k256.decrypt_inplace(&TWEAK, &mut b), Ok(n)); + assert_eq!(b, pt, "{n} bytes: XTS-AES-256 round trip"); } /// Every length from one block to one byte short of nine: every tail length, and every way the /// blocks before it divide into fours, twos and ones, in both directions. #[test] fn round_trips_at_every_length_up_to_nine_blocks() { - round_trips!( - 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, - 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, - 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, - 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, 96, 97, 98, 99, 100, 101, 102, 103, 104, 105, - 106, 107, 108, 109, 110, 111, 112, 113, 114, 115, 116, 117, 118, 119, 120, 121, 122, 123, - 124, 125, 126, 127, 128, 129, 130, 131, 132, 133, 134, 135, 136, 137, 138, 139, 140, 141, - 142, 143, - ); + for n in 16..144 { + round_trip(n); + } } /// A tweak that differs in any one bit, the first or the last, gives a ciphertext that differs in /// every block, including the stolen one. -fn every_tweak_bit_matters() { - let key = xts_key::(&key_bytes()); - let pt: [u8; N] = pattern(N).try_into().unwrap(); - let mut base = pt; - key.encrypt_inplace(&TWEAK, &mut base); +fn every_tweak_bit_matters(n: usize) { + let key = xts_key::(&key_bytes()); + let pt = pattern(n); + let mut base = pt.clone(); + key.encrypt_inplace(&TWEAK, &mut base).unwrap(); for bit in [0, 127] { let mut tweak = TWEAK; tweak[bit / 8] ^= 1 << (bit % 8); - let mut other = pt; - key.encrypt_inplace(&tweak, &mut other); + let mut other = pt.clone(); + key.encrypt_inplace(&tweak, &mut other).unwrap(); for (j, (a, b)) in base.chunks(16).zip(other.chunks(16)).enumerate() { - assert_ne!(a, b, "{N} bytes, tweak bit {bit}: block {j} did not change"); + assert_ne!(a, b, "{n} bytes, tweak bit {bit}: block {j} did not change"); } // And it does not decrypt under the original tweak. - key.decrypt_inplace(&TWEAK, &mut other); + key.decrypt_inplace(&TWEAK, &mut other).unwrap(); assert_ne!(other, pt); } } #[test] fn every_tweak_bit_matters_to_every_block() { - every_tweak_bit_matters::<16>(); - every_tweak_bit_matters::<17>(); - every_tweak_bit_matters::<47>(); - every_tweak_bit_matters::<512>(); + for n in [16, 17, 47, 512] { + every_tweak_bit_matters(n); + } } /// Consecutive sequence numbers, `n.to_le_bytes()`, are distinct tweaks: equal sectors under /// them encrypt differently, and each decrypts only under its own. #[test] fn consecutive_sequence_numbers_encrypt_equal_sectors_differently() { - let key = xts_key::(&key_bytes()); + let key = xts_key::(&key_bytes()); let sector = [0x11u8; 512]; let mut s0 = sector; let mut s1 = sector; - key.encrypt_inplace(&0u128.to_le_bytes(), &mut s0); - key.encrypt_inplace(&1u128.to_le_bytes(), &mut s1); + key.encrypt_inplace(&0u128.to_le_bytes(), &mut s0).unwrap(); + key.encrypt_inplace(&1u128.to_le_bytes(), &mut s1).unwrap(); assert_ne!(s0, s1); - key.decrypt_inplace(&1u128.to_le_bytes(), &mut s1); + key.decrypt_inplace(&1u128.to_le_bytes(), &mut s1).unwrap(); assert_eq!(s1, sector); } @@ -293,9 +276,9 @@ fn consecutive_sequence_numbers_encrypt_equal_sectors_differently() { /// position has its own mask. #[test] fn equal_blocks_encrypt_differently_at_every_position() { - let key = xts_key::(&key_bytes()); + let key = xts_key::(&key_bytes()); let mut data_unit = [0u8; 512]; - key.encrypt_inplace(&TWEAK, &mut data_unit); + key.encrypt_inplace(&TWEAK, &mut data_unit).unwrap(); let (blocks, _) = data_unit.as_chunks::<16>(); for i in 0..blocks.len() { for j in i + 1..blocks.len() { @@ -313,8 +296,8 @@ fn equal_blocks_encrypt_differently_at_every_position() { #[test] fn the_keys_enforce_the_material_policy() { let framework = TestFrameworkFromKeyMaterial::new(); - framework.test::<32, XTS_AES_128<512>>("XTS_AES_128", SecurityStrength::_128bit); - framework.test::<64, XTS_AES_256<512>>("XTS_AES_256", SecurityStrength::_256bit); + framework.test::<32, XTS_AES_128>("XTS_AES_128", SecurityStrength::_128bit); + framework.test::<64, XTS_AES_256>("XTS_AES_256", SecurityStrength::_256bit); } // The refusals of the 32-byte key -- equal halves, a zero half, a short key -- are tested over @@ -322,7 +305,7 @@ fn the_keys_enforce_the_material_policy() { // The 64-byte key is a second impl, which only a permutation with a 32-byte key reaches. fn refusal_256(key: &KeyMaterial<64>) -> KeyMaterialError { - match XTS_AES_256::<16>::from_key_material(key) { + match XTS_AES_256::from_key_material(key) { Err(SymmetricCipherError::KeyMaterialError(e)) => e, Err(e) => panic!("refused, but not as a KeyMaterialError: {e:?}"), Ok(_) => panic!("accepted"), @@ -335,7 +318,7 @@ fn xts_aes_256_refuses_equal_halves() { let mut bytes: [u8; 64] = core::array::from_fn(|i| (i % 32) as u8 + 0x40); assert!(matches!(refusal_256(&material(&bytes)), KeyMaterialError::GenericError(_))); bytes[63] ^= 0x01; - XTS_AES_256::<16>::from_key_material(&material(&bytes)).expect("halves that differ"); + XTS_AES_256::from_key_material(&material(&bytes)).expect("halves that differ"); } /// A half that is all zeros is refused, as an all-zero AES key is; so is an all-zero key. @@ -369,21 +352,60 @@ fn swapping_the_halves_changes_the_ciphertext() { swapped[16..].copy_from_slice(&bytes[..16]); let mut a = [0u8; 32]; let mut b = [0u8; 32]; - xts_key::(&bytes).encrypt_inplace(&TWEAK, &mut a); - xts_key::(&swapped).encrypt_inplace(&TWEAK, &mut b); + xts_key::(&bytes).encrypt_inplace(&TWEAK, &mut a).unwrap(); + xts_key::(&swapped).encrypt_inplace(&TWEAK, &mut b).unwrap(); assert_ne!(a, b); } +// ---- the length of a data unit ----------------------------------------------------------------- + +/// Under either key, a data unit shorter than one block or longer than 2^20 blocks is refused in +/// both directions and left as it was. (That the bounds themselves are accepted is in the known +/// answers: 16 bytes in the tables, 2^20 blocks in the longest.) +fn refuses_out_of_bounds() +where + P: BlockPermutation<16>, + XTSKey

: FromKeyMaterial, +{ + let key = xts_key::(&key_bytes()); + for len in [0, XTS_MIN_DATA_UNIT_LEN - 1, XTS_MAX_DATA_UNIT_LEN + 1] { + let original = pattern(len); + let mut data_unit = original.clone(); + let refusals = [ + key.encrypt_inplace(&TWEAK, &mut data_unit), + key.decrypt_inplace(&TWEAK, &mut data_unit), + ]; + for refusal in refusals { + match refusal { + Err(SymmetricCipherError::InvalidInputLength(_)) => { + assert!(len < XTS_MIN_DATA_UNIT_LEN) + } + Err(SymmetricCipherError::DataLimitExceeded) => { + assert!(len > XTS_MAX_DATA_UNIT_LEN) + } + other => panic!("{len} bytes: {other:?}"), + } + } + assert!(data_unit == original, "{len} bytes: the refused data unit was changed"); + } +} + +#[test] +fn data_units_outside_the_bounds_are_refused() { + refuses_out_of_bounds::(); + refuses_out_of_bounds::(); +} + #[test] fn sizes() { assert_eq!(XTS_TWEAK_LEN, 16); assert_eq!(XTS_MIN_DATA_UNIT_LEN, 16); assert_eq!(XTS_MAX_DATA_UNIT_LEN, 1 << 24); - // A key is its two schedules, whatever its data-unit length. - assert_eq!(size_of::>(), 2 * size_of::()); - assert_eq!(size_of::>(), 352); - assert_eq!(size_of::>(), 2 * size_of::()); - assert_eq!(size_of::>(), 480); + // A key is its two schedules. + assert_eq!(size_of::(), 2 * size_of::()); + assert_eq!(size_of::(), 352); + assert_eq!(size_of::(), 2 * size_of::()); + assert_eq!(size_of::(), 480); } // ---- the known answers ------------------------------------------------------------------------- diff --git a/crypto/aes/tests/xts_wycheproof.rs b/crypto/aes/tests/xts_wycheproof.rs index fad4110aa..a9798695b 100644 --- a/crypto/aes/tests/xts_wycheproof.rs +++ b/crypto/aes/tests/xts_wycheproof.rs @@ -16,78 +16,34 @@ use bouncycastle_core::key_material::{KeyMaterial, KeyType}; use bouncycastle_core::symmetric_key::FromKeyMaterial; use bouncycastle_core_test_framework::test_data_loaders::{Value, hex_field, wycheproof_json}; -/// Checks one case through `XTSKey` under its `KEY_LEN`-byte key, in both directions. -fn check(case: &Value, tc_id: u64) +/// Checks one case through `XTSKey

` under its `KEY_LEN`-byte key, in both directions. +fn check(case: &Value, tc_id: u64) where P: BlockPermutation<16>, - XTSKey: FromKeyMaterial, + XTSKey

: FromKeyMaterial, { let material = KeyMaterial::::from_bytes_as_type( &hex_field(case, "key", tc_id), KeyType::SymmetricCipherKey, ) .unwrap(); - let key = XTSKey::::from_key_material(&material) + let key = XTSKey::

::from_key_material(&material) .unwrap_or_else(|e| panic!("tcId {tc_id}: the key is refused: {e:?}")); let iv = hex_field(case, "iv", tc_id); let mut tweak = [0u8; 16]; tweak[..iv.len()].copy_from_slice(&iv); - let msg: [u8; N] = hex_field(case, "msg", tc_id).try_into().unwrap(); - let ct: [u8; N] = hex_field(case, "ct", tc_id).try_into().unwrap(); + let msg = hex_field(case, "msg", tc_id); + let ct = hex_field(case, "ct", tc_id); - let mut data_unit = msg; - key.encrypt_inplace(&tweak, &mut data_unit); + let mut data_unit = msg.clone(); + assert_eq!(key.encrypt_inplace(&tweak, &mut data_unit), Ok(msg.len()), "tcId {tc_id}"); assert_eq!(data_unit, ct, "tcId {tc_id}: encryption"); - key.decrypt_inplace(&tweak, &mut data_unit); + assert_eq!(key.decrypt_inplace(&tweak, &mut data_unit), Ok(msg.len()), "tcId {tc_id}"); assert_eq!(data_unit, msg, "tcId {tc_id}: decryption"); } -fn check_128(case: &Value, tc_id: u64) { - check::(case, tc_id); -} - -fn check_256(case: &Value, tc_id: u64) { - check::(case, tc_id); -} - -/// Calls `$check::` for the message length `$len`. The data-unit length is a const parameter -/// of the key type, so every length in the file needs an arm; a new one fails loudly. -macro_rules! dispatch { - ($len:expr, $check:ident, $case:expr, $tc_id:expr) => { - match $len { - 16 => $check::<16>($case, $tc_id), - 17 => $check::<17>($case, $tc_id), - 18 => $check::<18>($case, $tc_id), - 19 => $check::<19>($case, $tc_id), - 20 => $check::<20>($case, $tc_id), - 21 => $check::<21>($case, $tc_id), - 22 => $check::<22>($case, $tc_id), - 23 => $check::<23>($case, $tc_id), - 24 => $check::<24>($case, $tc_id), - 25 => $check::<25>($case, $tc_id), - 26 => $check::<26>($case, $tc_id), - 27 => $check::<27>($case, $tc_id), - 28 => $check::<28>($case, $tc_id), - 29 => $check::<29>($case, $tc_id), - 30 => $check::<30>($case, $tc_id), - 31 => $check::<31>($case, $tc_id), - 32 => $check::<32>($case, $tc_id), - 33 => $check::<33>($case, $tc_id), - 48 => $check::<48>($case, $tc_id), - 51 => $check::<51>($case, $tc_id), - 64 => $check::<64>($case, $tc_id), - 68 => $check::<68>($case, $tc_id), - 96 => $check::<96>($case, $tc_id), - 102 => $check::<102>($case, $tc_id), - 128 => $check::<128>($case, $tc_id), - 136 => $check::<136>($case, $tc_id), - other => panic!("tcId {}: no arm for a {other}-byte message; add one", $tc_id), - } - }; -} - #[test] fn wycheproof_aes_xts() { let Some(file) = wycheproof_json("aes_xts_test.json") else { @@ -99,14 +55,13 @@ fn wycheproof_aes_xts() { for case in group["tests"].as_array().expect("tests") { let tc_id = case["tcId"].as_u64().expect("tcId"); assert_eq!(case["result"], "valid", "tcId {tc_id}: only valid cases are expected"); - let len = hex_field(case, "msg", tc_id).len(); match key_size { 256 => { - dispatch!(len, check_128, case, tc_id); + check::(case, tc_id); ran_128 += 1; } 512 => { - dispatch!(len, check_256, case, tc_id); + check::(case, tc_id); ran_256 += 1; } 384 => skipped_192 += 1, diff --git a/crypto/cipher/src/modes/mod.rs b/crypto/cipher/src/modes/mod.rs index 549036e0d..24f9a1ceb 100644 --- a/crypto/cipher/src/modes/mod.rs +++ b/crypto/cipher/src/modes/mod.rs @@ -49,9 +49,9 @@ //! general data as well, but they are deterministic, so for data that may repeat an AEAD is the //! better fit (see the [`kw`] security notes). //! -//! **XTS is a storage mode** ([`XTSKey`]): it encrypts one fixed-length data unit, such as a disk -//! sector, in place under a tweak naming its position, and its ciphertext is no longer than the -//! plaintext. It is unauthenticated and has no streaming API; see the [`xts`] security notes. +//! **XTS is a storage mode** ([`XTSKey`]): it encrypts one data unit, such as a disk sector, in +//! place under a tweak naming its position, and its ciphertext is no longer than the plaintext. +//! It is unauthenticated and has no streaming API; see the [`xts`] security notes. //! //! CBC, CFB, CFB8, OFB and CTR all generate their own init data, or take the caller's through the //! key's `_nonce` forms: an IV for the first four, a nonce for CTR, which is shorter than a block diff --git a/crypto/cipher/src/modes/xts.rs b/crypto/cipher/src/modes/xts.rs index 00f5e9d55..c3097adfb 100644 --- a/crypto/cipher/src/modes/xts.rs +++ b/crypto/cipher/src/modes/xts.rs @@ -15,12 +15,11 @@ //! The key is [`XTSKey`], built with `from_key_material` from the XTS key `Key = Key_1 | Key_2` //! (IEEE 1619-2007 Sec 5.3.1): two keys for the permutation, `Key_1` encrypting the data and //! `Key_2` the tweak, so 32 bytes over a permutation with a 16-byte key and 64 over one with a -//! 32-byte key, the 256- and 512-bit keys of XTS-AES-128 and XTS-AES-256 (Sec 6). The data-unit -//! length is the key type's `DATA_UNIT_LEN`, because SP 800-38E Sec 4 defines an instance of -//! XTS-AES by "a secret key" and "a single, fixed length for the data units that the key -//! protects"; a length outside the range is a compile error. The ready-made `XTS_AES_128` / -//! `XTS_AES_256` aliases are in `bouncycastle-aes`. IEEE 1619 specifies XTS for AES only, and AES -//! is the only cipher SP 800-38E approves it for. +//! 32-byte key, the 256- and 512-bit keys of XTS-AES-128 and XTS-AES-256 (Sec 6). Each call takes +//! one data unit of any length in that range and refuses one outside it; keeping every data unit +//! under a key to one length is the caller's to do (see the security considerations). The +//! ready-made `XTS_AES_128` / `XTS_AES_256` aliases are in `bouncycastle-aes`. IEEE 1619 specifies +//! XTS for AES only, and AES is the only cipher SP 800-38E approves it for. //! //! # The tweak //! @@ -47,14 +46,14 @@ //! let material = KeyMaterial::<32>::from_bytes_as_type(&key_bytes, KeyType::SymmetricCipherKey) //! .expect("a 32-byte symmetric cipher key"); //! -//! // 512-byte data units: the length is part of the key's type. -//! let key = XTSKey::::from_key_material(&material).expect("an XTS key"); +//! let key = XTSKey::::from_key_material(&material).expect("an XTS key"); //! +//! // A 512-byte sector, under its sequence number. //! let mut sector = [0x5Au8; 512]; -//! let tweak = 7u128.to_le_bytes(); // the data unit's sequence number -//! assert_eq!(key.encrypt_inplace(&tweak, &mut sector), 512); +//! let tweak = 7u128.to_le_bytes(); +//! assert_eq!(key.encrypt_inplace(&tweak, &mut sector), Ok(512)); //! assert_ne!(sector, [0x5Au8; 512]); -//! assert_eq!(key.decrypt_inplace(&tweak, &mut sector), 512); +//! assert_eq!(key.decrypt_inplace(&tweak, &mut sector), Ok(512)); //! assert_eq!(sector, [0x5Au8; 512]); //! ``` //! @@ -80,12 +79,14 @@ //! ## One key scope per key //! //! IEEE 1619-2007 Sec 6 allows a key only one *key scope*: a run of data units of one length -//! under consecutive tweak values, so every data unit under the key has its own tweak. Two data -//! units encrypted under one key and one tweak are encrypted under the same masks, so a block that -//! is equal in both, at the same offset, has an equal ciphertext in both, and a ciphertext block -//! of one can be pasted into the other. A key type keeps to one length, its `DATA_UNIT_LEN`; a -//! second key type of another length made from the same material, or a second disk under the -//! same key, steps outside the key scope. +//! under consecutive tweak values, so every data unit under the key has its own tweak. SP 800-38E +//! Sec 4 likewise defines an instance of XTS-AES by "a secret key" and "a single, fixed length for +//! the data units that the key protects". Two data units encrypted under one key and one tweak are +//! encrypted under the same masks, so a block that is equal in both, at the same offset, has an +//! equal ciphertext in both, and a ciphertext block of one can be pasted into the other. The key +//! takes a data unit of any valid length at every call, so keeping all of its data units to one +//! length, each under its own tweak, is the caller's obligation: a second length, or a second +//! disk, under the same key steps outside the key scope. //! //! ## A bounded amount of data per key //! @@ -129,17 +130,14 @@ pub const XTS_MIN_DATA_UNIT_LEN: usize = BLOCK_LEN; /// The longest data unit, in bytes: 2^20 blocks, 16 MiB (SP 800-38E Sec 4). pub const XTS_MAX_DATA_UNIT_LEN: usize = (1 << 20) * BLOCK_LEN; -/// An XTS key over the permutation `P`, for data units of exactly `DATA_UNIT_LEN` bytes: -/// `Key_1` and `Key_2`, each expanded once, when the key is made. +/// An XTS key over the permutation `P`: `Key_1` and `Key_2`, each expanded once, when the key is +/// made. /// /// Built with [`FromKeyMaterial`] from `Key = Key_1 | Key_2`, which is 32 bytes over a permutation /// with a 16-byte key and 64 over one with a 32-byte key, tagged [`KeyType::SymmetricCipherKey`]. /// It encrypts and decrypts one data unit at a time, in place, under the data unit's tweak; see /// the [module docs](self) for the tweak, and for the security considerations. /// -/// The only state is the two expanded keys, which the permutation holds so that they are -/// zeroized on drop; the key has no `Debug` and no way to read the material back. -/// /// # Construction /// /// `from_key_material` refuses the key, as a [`SymmetricCipherError::KeyMaterialError`], with: @@ -149,109 +147,80 @@ pub const XTS_MAX_DATA_UNIT_LEN: usize = (1 << 20) * BLOCK_LEN; /// * [`KeyMaterialError::GenericError`] if `Key_1` and `Key_2` are equal (FIPS 140-3 IG C.I); /// * [`KeyMaterialError::SecurityStrength`] if it is tagged below the permutation's strength. /// Each half carries the key's strength, capped at what the half's length can carry. -/// -/// # The data-unit length is checked at compile time -/// -/// A `DATA_UNIT_LEN` below [`XTS_MIN_DATA_UNIT_LEN`], an empty data unit included, or above -/// [`XTS_MAX_DATA_UNIT_LEN`] does not build. The check runs where the key type is used, so -/// `cargo build` and `cargo test` report it, and `cargo check` does not: -/// -/// ```compile_fail -/// # mod toy { include!("../../tests/common/toy_block_cipher.rs"); } -/// # use toy::ToyBlockCipher; -/// # use bouncycastle_cipher::modes::{XTS_MAX_DATA_UNIT_LEN, XTSKey}; -/// # use bouncycastle_core::key_material::{KeyMaterial, KeyType}; -/// # use bouncycastle_core::symmetric_key::FromKeyMaterial; -/// # let bytes: [u8; 32] = core::array::from_fn(|i| i as u8 + 1); -/// # let km = KeyMaterial::<32>::from_bytes_as_type(&bytes, KeyType::SymmetricCipherKey) -/// # .expect("a 32-byte key"); -/// // Shorter than one block. -/// let key = XTSKey::::from_key_material(&km); -/// ``` -/// -/// ```compile_fail -/// # mod toy { include!("../../tests/common/toy_block_cipher.rs"); } -/// # use toy::ToyBlockCipher; -/// # use bouncycastle_cipher::modes::{XTS_MAX_DATA_UNIT_LEN, XTSKey}; -/// # use bouncycastle_core::key_material::{KeyMaterial, KeyType}; -/// # use bouncycastle_core::symmetric_key::FromKeyMaterial; -/// # let bytes: [u8; 32] = core::array::from_fn(|i| i as u8 + 1); -/// # let km = KeyMaterial::<32>::from_bytes_as_type(&bytes, KeyType::SymmetricCipherKey) -/// # .expect("a 32-byte key"); -/// // Longer than 2^20 blocks. -/// let key = XTSKey::::from_key_material(&km); -/// ``` -/// -/// The two bounds themselves build: -/// -/// ``` -/// # mod toy { include!("../../tests/common/toy_block_cipher.rs"); } -/// # use toy::ToyBlockCipher; -/// # use bouncycastle_cipher::modes::{XTS_MAX_DATA_UNIT_LEN, XTSKey}; -/// # use bouncycastle_core::key_material::{KeyMaterial, KeyType}; -/// # use bouncycastle_core::symmetric_key::FromKeyMaterial; -/// # let bytes: [u8; 32] = core::array::from_fn(|i| i as u8 + 1); -/// # let km = KeyMaterial::<32>::from_bytes_as_type(&bytes, KeyType::SymmetricCipherKey) -/// # .expect("a 32-byte key"); -/// let shortest = XTSKey::::from_key_material(&km); -/// let longest = XTSKey::::from_key_material(&km); -/// # assert!(shortest.is_ok() && longest.is_ok()); -/// ``` -pub struct XTSKey { +pub struct XTSKey

{ + // Nothing but the two expanded keys, which the permutation holds and wipes on drop (AES keeps + // its schedule in a `Secret`). /// `Key_1`, which encrypts the data. key1: P, /// `Key_2`, which encrypts the tweak. key2: P, } -impl XTSKey { - /// The bounds on the data-unit length, a compile-time error where the key type is used: - /// evaluated when a constructor or a method is monomorphised, so that the private functions - /// below are never handed a data unit outside them. - const DATA_UNIT_LEN_CHECK: () = assert!( - DATA_UNIT_LEN >= XTS_MIN_DATA_UNIT_LEN && DATA_UNIT_LEN <= XTS_MAX_DATA_UNIT_LEN, - "an XTS data unit is 1 to 2^20 blocks (IEEE 1619-2007 Sec 5.1, SP 800-38E Sec 4)" - ); -} - -impl, const DATA_UNIT_LEN: usize> XTSKey { +impl> XTSKey

{ /// Encrypts one data unit in place under its tweak, and returns the number of bytes written, - /// which is always `DATA_UNIT_LEN`: the ciphertext is as long as the plaintext. Over a - /// permutation that decrypts only ([`BlockPermutation::DECRYPT_ONLY`]) it does not compile. + /// `data_unit.len()`: the ciphertext is as long as the plaintext. Over a permutation that + /// decrypts only ([`BlockPermutation::DECRYPT_ONLY`]) it does not compile. + /// + /// # Errors + /// + /// A data unit shorter than [`XTS_MIN_DATA_UNIT_LEN`] is refused with + /// [`SymmetricCipherError::InvalidInputLength`], and one longer than + /// [`XTS_MAX_DATA_UNIT_LEN`] with [`SymmetricCipherError::DataLimitExceeded`]; a refused data + /// unit is left as it was. pub fn encrypt_inplace( &self, tweak: &[u8; XTS_TWEAK_LEN], - data_unit: &mut [u8; DATA_UNIT_LEN], - ) -> usize { - const { Self::DATA_UNIT_LEN_CHECK }; + data_unit: &mut [u8], + ) -> Result { const { assert!( !P::DECRYPT_ONLY, "this permutation decrypts only (BlockPermutation::DECRYPT_ONLY): no data unit may be encrypted over it" ) }; + check_data_unit_len(data_unit.len())?; encrypt(&self.key1, &self.key2, tweak, data_unit); - DATA_UNIT_LEN + Ok(data_unit.len()) } /// Decrypts one data unit in place under the tweak it was encrypted under, and returns the - /// number of bytes written, which is always `DATA_UNIT_LEN`. There is nothing to verify: any - /// data unit decrypts, a modified one to unpredictable plaintext. + /// number of bytes written, `data_unit.len()`. There is nothing to verify: any data unit of a + /// valid length decrypts, a modified one to unpredictable plaintext. + /// + /// # Errors + /// + /// As for [`encrypt_inplace`](Self::encrypt_inplace): a data unit shorter than + /// [`XTS_MIN_DATA_UNIT_LEN`] or longer than [`XTS_MAX_DATA_UNIT_LEN`] is refused, and left as + /// it was. pub fn decrypt_inplace( &self, tweak: &[u8; XTS_TWEAK_LEN], - data_unit: &mut [u8; DATA_UNIT_LEN], - ) -> usize { - const { Self::DATA_UNIT_LEN_CHECK }; + data_unit: &mut [u8], + ) -> Result { + check_data_unit_len(data_unit.len())?; decrypt(&self.key1, &self.key2, tweak, data_unit); - DATA_UNIT_LEN + Ok(data_unit.len()) + } +} + +/// The bounds on a data unit's length, checked before the data unit is touched, so that the +/// private functions below are never handed one outside them. +fn check_data_unit_len(len: usize) -> Result<(), SymmetricCipherError> { + if len < XTS_MIN_DATA_UNIT_LEN { + return Err(SymmetricCipherError::InvalidInputLength( + "an XTS data unit is at least one block, 16 bytes (IEEE 1619-2007 Sec 5.1)", + )); + } + if len > XTS_MAX_DATA_UNIT_LEN { + return Err(SymmetricCipherError::DataLimitExceeded); } + Ok(()) } // One impl per key length, because the XTS key's length, twice the permutation's, cannot be // written as an expression over the permutation's on stable Rust. -impl FromKeyMaterial<32> for XTSKey +impl

FromKeyMaterial<32> for XTSKey

where P: KeyExpansion<16> + BlockPermutation, { @@ -260,13 +229,12 @@ where /// Splits the 32-byte `Key_1 | Key_2` into two 16-byte keys and expands each; see /// [`XTSKey`] for when it refuses. fn from_key_material(key: &KeyMaterial<32>) -> Result { - const { Self::DATA_UNIT_LEN_CHECK }; let (key1, key2) = expand_halves::(key)?; Ok(Self { key1, key2 }) } } -impl FromKeyMaterial<64> for XTSKey +impl

FromKeyMaterial<64> for XTSKey

where P: KeyExpansion<32> + BlockPermutation, { @@ -275,7 +243,6 @@ where /// Splits the 64-byte `Key_1 | Key_2` into two 32-byte keys and expands each; see /// [`XTSKey`] for when it refuses. fn from_key_material(key: &KeyMaterial<64>) -> Result { - const { Self::DATA_UNIT_LEN_CHECK }; let (key1, key2) = expand_halves::(key)?; Ok(Self { key1, key2 }) } @@ -477,7 +444,7 @@ fn first_mask>(key2: &P, i: &Block) -> Secret>(key1: &P, key2: &P, i: &Block, data: &mut [u8]) { let mut t = first_mask(key2, i); diff --git a/crypto/cipher/tests/modes/xts_tests.rs b/crypto/cipher/tests/modes/xts_tests.rs index 08f4e62ad..606b70c4c 100644 --- a/crypto/cipher/tests/modes/xts_tests.rs +++ b/crypto/cipher/tests/modes/xts_tests.rs @@ -1,12 +1,12 @@ -//! Structural tests for XTS, driven by a toy permutation: the key constructor's refusals, -//! ciphertext stealing as SP 800-38E Sec 5 describes it, which ciphertext blocks a change to each -//! plaintext block reaches, and that the pair and four-block paths are really taken. The known -//! answers -- NIST ACVP, Wycheproof and OpenSSL -- and the 64-byte key are in the `aes` crate, -//! `crypto/aes/tests/xts_*.rs`. +//! Structural tests for XTS, driven by a toy permutation: the key constructor's refusals, the +//! bounds on a data unit's length, ciphertext stealing as SP 800-38E Sec 5 describes it, which +//! ciphertext blocks a change to each plaintext block reaches, and that the pair and four-block +//! paths are really taken. The known answers -- NIST ACVP, Wycheproof and OpenSSL -- and the +//! 64-byte key are in the `aes` crate, `crypto/aes/tests/xts_*.rs`. mod common; -use bouncycastle_cipher::modes::XTSKey; +use bouncycastle_cipher::modes::{XTS_MAX_DATA_UNIT_LEN, XTS_MIN_DATA_UNIT_LEN, XTSKey}; use bouncycastle_core::errors::{KeyMaterialError, SymmetricCipherError}; use bouncycastle_core::key_material::{KeyMaterial, KeyMaterialTrait, KeyType}; use bouncycastle_core::security_strength::SecurityStrength; @@ -27,20 +27,20 @@ fn material(bytes: &[u8]) -> KeyMaterial<32> { KeyMaterial::<32>::from_bytes_as_type(bytes, KeyType::SymmetricCipherKey).unwrap() } -fn toy_xts() -> XTSKey +fn toy_xts

() -> XTSKey

where - XTSKey: FromKeyMaterial<32>, + XTSKey

: FromKeyMaterial<32>, { - XTSKey::::from_key_material(&material(&key_bytes())).expect("a valid XTS key") + XTSKey::

::from_key_material(&material(&key_bytes())).expect("a valid XTS key") } -fn pattern() -> [u8; N] { - core::array::from_fn(|k| (k as u8).wrapping_mul(13).wrapping_add(5)) +fn pattern(len: usize) -> Vec { + (0..len).map(|k| (k as u8).wrapping_mul(13).wrapping_add(5)).collect() } -fn encrypt(pt: &[u8; N]) -> [u8; N] { - let mut data_unit = *pt; - toy_xts::().encrypt_inplace(&TWEAK, &mut data_unit); +fn encrypt(pt: &[u8]) -> Vec { + let mut data_unit = pt.to_vec(); + assert_eq!(toy_xts::().encrypt_inplace(&TWEAK, &mut data_unit), Ok(pt.len())); data_unit } @@ -50,11 +50,11 @@ fn encrypt(pt: &[u8; N]) -> [u8; N] { #[test] fn the_key_enforces_the_material_policy() { TestFrameworkFromKeyMaterial::new() - .test::<32, XTSKey>("XTS over the toy", SecurityStrength::_128bit); + .test::<32, XTSKey>("XTS over the toy", SecurityStrength::_128bit); } fn refusal(key: &KeyMaterial<32>) -> KeyMaterialError { - match XTSKey::::from_key_material(key) { + match XTSKey::::from_key_material(key) { Err(SymmetricCipherError::KeyMaterialError(e)) => e, Err(e) => panic!("refused, but not as a KeyMaterialError: {e:?}"), Ok(_) => panic!("accepted"), @@ -74,7 +74,7 @@ fn equal_halves_are_refused() { for differing in [16, 31] { let mut close = bytes; close[differing] ^= 0x01; - XTSKey::::from_key_material(&material(&close)) + XTSKey::::from_key_material(&material(&close)) .expect("halves that differ in one byte are accepted"); } } @@ -102,55 +102,114 @@ fn a_short_key_is_refused() { } } +// ---- the length of a data unit ----------------------------------------------------------------- + +/// A data unit shorter than one block, an empty one included, is refused as an invalid length, +/// and one longer than 2^20 blocks as over the data limit, in both directions and before anything +/// is written: the buffer comes back as it went in. +#[test] +fn data_units_outside_the_bounds_are_refused_unchanged() { + let key = toy_xts::(); + for len in [0, 1, XTS_MIN_DATA_UNIT_LEN - 1, XTS_MAX_DATA_UNIT_LEN + 1] { + let original = pattern(len); + let mut data_unit = original.clone(); + let encrypted = key.encrypt_inplace(&TWEAK, &mut data_unit); + assert!(data_unit == original, "encrypt, {len} bytes: the refused data unit was changed"); + let decrypted = key.decrypt_inplace(&TWEAK, &mut data_unit); + assert!(data_unit == original, "decrypt, {len} bytes: the refused data unit was changed"); + + for (direction, result) in [("encrypt", encrypted), ("decrypt", decrypted)] { + if len < XTS_MIN_DATA_UNIT_LEN { + assert!( + matches!(result, Err(SymmetricCipherError::InvalidInputLength(_))), + "{direction}, {len} bytes: {result:?}" + ); + } else { + assert_eq!(result, Err(SymmetricCipherError::DataLimitExceeded), "{direction}"); + } + } + } +} + +/// The bounds themselves are data units: one block, and 2^20 blocks, each through a round trip +/// that reports the whole length in both directions. +#[test] +fn the_shortest_and_the_longest_data_units_are_accepted() { + let key = toy_xts::(); + for len in [XTS_MIN_DATA_UNIT_LEN, XTS_MAX_DATA_UNIT_LEN] { + let pt = pattern(len); + let mut data_unit = pt.clone(); + assert_eq!(key.encrypt_inplace(&TWEAK, &mut data_unit), Ok(len), "{len} bytes: encrypt"); + assert!(data_unit != pt, "{len} bytes: encryption changed nothing"); + assert_eq!(key.decrypt_inplace(&TWEAK, &mut data_unit), Ok(len), "{len} bytes: decrypt"); + assert!(data_unit == pt, "{len} bytes: the round trip"); + } +} + +/// One key takes data units of different lengths, each in its own call: the length is the +/// caller's to keep to. +#[test] +fn one_key_takes_any_valid_length() { + let key = toy_xts::(); + for len in [16, 17, 512, 4095] { + let pt = pattern(len); + let mut data_unit = pt.clone(); + assert_eq!(key.encrypt_inplace(&TWEAK, &mut data_unit), Ok(len)); + assert_eq!(key.decrypt_inplace(&TWEAK, &mut data_unit), Ok(len)); + assert_eq!(data_unit, pt); + } +} + // ---- ciphertext stealing ----------------------------------------------------------------------- -/// Ciphertext stealing (IEEE 1619-2007 Sec 5.3.2 step 4) for a data unit of `LEN` = 16m + b -/// bytes, against the encryption of whole blocks. `ALIGNED` is 16m, and `NEXT` 16(m + 1). -/// SP 800-38E Sec 5: "Cm is the truncation of a block that is derived from Pm-1, and Cm-1 is -/// derived from Pm, concatenated with the discarded bits from the truncation." -fn stealing() { - assert!(ALIGNED.is_multiple_of(16) && ALIGNED < LEN && LEN < NEXT && NEXT == ALIGNED + 16); - let b = LEN - ALIGNED; - let last = ALIGNED - 16; // where block m - 1 starts +/// Ciphertext stealing (IEEE 1619-2007 Sec 5.3.2 step 4) for a data unit of 16m + b bytes, against +/// the encryption of whole blocks. SP 800-38E Sec 5: "Cm is the truncation of a block that is +/// derived from Pm-1, and Cm-1 is derived from Pm, concatenated with the discarded bits from the +/// truncation." +fn stealing(m: usize, b: usize) { + assert!(m >= 1 && (1..16).contains(&b)); + let aligned = 16 * m; // where P_m starts + let len = aligned + b; + let last = aligned - 16; // where block m - 1 starts - let pt: [u8; LEN] = pattern(); + let pt = pattern(len); let ct = encrypt(&pt); // The whole blocks P_0 .. P_{m-1}, encrypted on their own: CC, the encryption of P_{m-1} under // index m - 1, is the last of them. - let aligned = encrypt::(pt[..ALIGNED].try_into().unwrap()); - let cc = &aligned[last..]; + let whole = encrypt(&pt[..aligned]); + let cc = &whole[last..]; // Nothing before C_{m-1} is touched. - assert_eq!(ct[..last], aligned[..last], "{LEN} bytes: the leading blocks"); + assert_eq!(ct[..last], whole[..last], "{len} bytes: the leading blocks"); // C_m is CC truncated to b bytes, and is the tail of the ciphertext. - assert_eq!(ct[ALIGNED..], cc[..b], "{LEN} bytes: C_m"); + assert_eq!(ct[aligned..], cc[..b], "{len} bytes: C_m"); // C_{m-1} is P_m || CC[b..] encrypted under index m: block m of a data unit one block longer. - let mut q: [u8; NEXT] = [0; NEXT]; - q[..ALIGNED].copy_from_slice(&pt[..ALIGNED]); - q[ALIGNED..ALIGNED + b].copy_from_slice(&pt[ALIGNED..]); - q[ALIGNED + b..].copy_from_slice(&cc[b..]); - assert_eq!(ct[last..ALIGNED], encrypt(&q)[ALIGNED..], "{LEN} bytes: C_m-1"); + let mut q = Vec::with_capacity(aligned + 16); + q.extend_from_slice(&pt[..aligned]); + q.extend_from_slice(&pt[aligned..]); + q.extend_from_slice(&cc[b..]); + assert_eq!(ct[last..aligned], encrypt(&q)[aligned..], "{len} bytes: C_m-1"); // And decryption undoes it. let mut back = ct; - toy_xts::().decrypt_inplace(&TWEAK, &mut back); - assert_eq!(back, pt, "{LEN} bytes: decryption"); + assert_eq!(toy_xts::().decrypt_inplace(&TWEAK, &mut back), Ok(len)); + assert_eq!(back, pt, "{len} bytes: decryption"); } #[test] fn ciphertext_stealing_is_as_sp_800_38e_describes_it() { - stealing::<16, 17, 32>(); // m = 1, b = 1 - stealing::<16, 31, 32>(); // m = 1, b = 15 - stealing::<32, 39, 48>(); // m = 2, b = 7 - stealing::<80, 83, 96>(); // m = 5, b = 3: the four path, then one block, before stealing - stealing::<128, 137, 144>(); // m = 8, b = 9 + stealing(1, 1); + stealing(1, 15); + stealing(2, 7); + stealing(5, 3); // the four path, then one block, before stealing + stealing(8, 9); } // ---- which blocks a change reaches ------------------------------------------------------------- /// The ciphertext blocks (16-byte chunks, the last one short) that differ between `a` and `b`. -fn changed_blocks(a: &[u8; N], b: &[u8; N]) -> Vec { +fn changed_blocks(a: &[u8], b: &[u8]) -> Vec { a.chunks(16) .zip(b.chunks(16)) .enumerate() @@ -164,19 +223,19 @@ fn changed_blocks(a: &[u8; N], b: &[u8; N]) -> Vec { /// P_m only C_{m-1}. #[test] fn a_change_reaches_only_its_own_blocks() { - let pt: [u8; 64] = pattern(); + let pt = pattern(64); let ct = encrypt(&pt); for j in 0..4 { - let mut changed = pt; + let mut changed = pt.clone(); changed[16 * j..16 * (j + 1)].iter_mut().for_each(|b| *b = !*b); assert_eq!(changed_blocks(&ct, &encrypt(&changed)), [j], "aligned, block {j}"); } // m = 2, b = 8: P_0, P_1 = P_{m-1}, and the tail P_2 = P_m. - let pt: [u8; 40] = pattern(); + let pt = pattern(40); let ct = encrypt(&pt); for (range, reached) in [(0..16, &[0][..]), (16..32, &[1, 2][..]), (32..40, &[1][..])] { - let mut changed = pt; + let mut changed = pt.clone(); changed[range.clone()].iter_mut().for_each(|b| *b = !*b); assert_eq!(changed_blocks(&ct, &encrypt(&changed)), reached, "stealing, bytes {range:?}"); } @@ -192,16 +251,16 @@ fn the_pair_path_is_really_used() { let pt = [0x3Cu8; 32]; let ct = encrypt(&pt); let mut swapped = pt; - toy_xts::().encrypt_inplace(&TWEAK, &mut swapped); - assert_ne!(swapped, ct, "two blocks must go through encrypt_2blocks"); + toy_xts::().encrypt_inplace(&TWEAK, &mut swapped).unwrap(); + assert_ne!(swapped[..], ct, "two blocks must go through encrypt_2blocks"); let mut back = ct; - toy_xts::().decrypt_inplace(&TWEAK, &mut back); + toy_xts::().decrypt_inplace(&TWEAK, &mut back).unwrap(); assert_ne!(back, pt, "two blocks must go through decrypt_2blocks"); let one = [0x3Cu8; 16]; let mut swapped = one; - toy_xts::().encrypt_inplace(&TWEAK, &mut swapped); - assert_eq!(swapped, encrypt(&one), "one block must not pair"); + toy_xts::().encrypt_inplace(&TWEAK, &mut swapped).unwrap(); + assert_eq!(swapped[..], encrypt(&one), "one block must not pair"); } /// The four-block path must be taken, for whole fours only. [`SwappedFourToy`] rotates its four @@ -212,17 +271,17 @@ fn the_four_block_path_is_really_used() { let pt = [0xC3u8; 64]; let ct = encrypt(&pt); let mut swapped = pt; - toy_xts::().encrypt_inplace(&TWEAK, &mut swapped); - assert_ne!(swapped, ct, "four blocks must go through encrypt_4blocks"); + toy_xts::().encrypt_inplace(&TWEAK, &mut swapped).unwrap(); + assert_ne!(swapped[..], ct, "four blocks must go through encrypt_4blocks"); let mut back = ct; - toy_xts::().decrypt_inplace(&TWEAK, &mut back); + toy_xts::().decrypt_inplace(&TWEAK, &mut back).unwrap(); assert_ne!(back, pt, "four blocks must go through decrypt_4blocks"); let three = [0xC3u8; 48]; let mut swapped = three; - toy_xts::().encrypt_inplace(&TWEAK, &mut swapped); - assert_eq!(swapped, encrypt(&three), "three blocks must not batch in four"); + toy_xts::().encrypt_inplace(&TWEAK, &mut swapped).unwrap(); + assert_eq!(swapped[..], encrypt(&three), "three blocks must not batch in four"); let mut back = swapped; - toy_xts::().decrypt_inplace(&TWEAK, &mut back); + toy_xts::().decrypt_inplace(&TWEAK, &mut back).unwrap(); assert_eq!(back, three); } diff --git a/mem_usage_benches/src/bench_aes_mem_usage.rs b/mem_usage_benches/src/bench_aes_mem_usage.rs index 14e02bbb7..61ed70f63 100644 --- a/mem_usage_benches/src/bench_aes_mem_usage.rs +++ b/mem_usage_benches/src/bench_aes_mem_usage.rs @@ -44,10 +44,31 @@ //! //! The point of comparison is that a table-driven AES adds 256 B (`AESLightEngine`) to 8 KiB //! (T-tables) of static data on top of these numbers; this implementation adds zero. +//! +//! # XTS +//! +//! The `xts_*` benches measure `XTS_AES_128` and `XTS_AES_256`, whose figures are in their docs. +//! Those are the deepest frame chain below each `measure` instance, counted as for +//! `bench_gcm_siv_mem_usage`: a return address per hop over the `bouncycastle_*` symbols, the +//! root's own not, and no leaf's red zone. They were read from the release build's assembly for +//! `x86_64-unknown-linux-gnu`, with `main` calling `xts_all` so that none is dead-stripped: +//! +//! ```text +//! RUSTFLAGS="-C symbol-mangling-version=v0" cargo rustc --release -p mem_usage_benches \ +//! --bin bench_aes_mem_usage --target x86_64-unknown-linux-gnu -- --emit asm +//! ``` +//! +//! A function's frame is its largest `.cfi_def_cfa_offset`, and the v0 names tell the generic +//! instances apart. Off Linux the link step fails for want of a Linux linker, after the `.s` files +//! are written to `target/x86_64-unknown-linux-gnu/release/deps/`. #![allow(dead_code)] use bouncycastle::aes::hazmat::{AES128Internal, AES192Internal, AES256Internal}; +use bouncycastle::aes::{XTS_AES_128, XTS_AES_256}; +use bouncycastle::cipher::modes::XTSKey; +use bouncycastle::core::hazmat::BlockPermutation; +use bouncycastle::core::symmetric_key::FromKeyMaterial; use mem_usage_benches::block_cipher_mem_usage as bench; @@ -63,10 +84,93 @@ const KEY_256: [u8; 32] = [ 0x1f, 0x35, 0x2c, 0x07, 0x3b, 0x61, 0x08, 0xd7, 0x2d, 0x98, 0x10, 0xa3, 0x09, 0x14, 0xdf, 0xf4, ]; +/// `Key_1 | Key_2` for XTS-AES-128: the key of NIST's ACVP-AES-XTS-2.0 tcId 125. +const XTS_KEY_128: [u8; 32] = [ + 0xc3, 0xd3, 0xdc, 0x0b, 0x7a, 0x34, 0x5c, 0xcf, 0xe4, 0x8b, 0x23, 0x20, 0x75, 0xe4, 0x72, 0x99, + 0xeb, 0xf1, 0x1e, 0x5c, 0x40, 0xe1, 0xbf, 0xe4, 0x2a, 0xcf, 0x96, 0xe1, 0x84, 0x0b, 0x73, 0x53, +]; +/// `Key_1 | Key_2` for XTS-AES-256: counting bytes, whose halves differ. +const XTS_KEY_256: [u8; 64] = [ + 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f, 0x10, + 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 0x18, 0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f, 0x20, + 0x21, 0x22, 0x23, 0x24, 0x25, 0x26, 0x27, 0x28, 0x29, 0x2a, 0x2b, 0x2c, 0x2d, 0x2e, 0x2f, 0x30, + 0x31, 0x32, 0x33, 0x34, 0x35, 0x36, 0x37, 0x38, 0x39, 0x3a, 0x3b, 0x3c, 0x3d, 0x3e, 0x3f, 0x40, +]; +const XTS_TWEAK: [u8; 16] = [0x5a; 16]; + +/// The data unit the XTS benches process: seven whole blocks and seven bytes. Encryption takes the +/// four-, two- and one-block paths and then steals; decryption takes the four- and two-block paths +/// and then undoes the stealing a block at a time. The data unit is the caller's buffer, so +/// beyond which of those paths run, the call's stack does not depend on its length. +const XTS_DATA_UNIT_LEN: usize = 119; + fn print_struct_sizes() { bench::print_struct_size::("AES128Internal"); bench::print_struct_size::("AES192Internal"); bench::print_struct_size::("AES256Internal"); + bench::print_struct_size::("XTS_AES_128"); + bench::print_struct_size::("XTS_AES_256"); +} + +/// The XTS key, built out of line so that its frame is a sibling of the operation's. +#[inline(never)] +fn xts_load, const N: usize>(bytes: &[u8; N]) -> K { + K::from_key_material(&bench::key(bytes)).unwrap() +} + +// The XTS benches keep their output out of `measure`: `black_box` holds the result inside, and the +// data unit, which is the caller's buffer, is printed after, so that the closure's frame is the +// call's and nothing else. Key construction keeps its `Result` whole, the one slot a caller of +// `from_key_material` needs, rather than unwrapping it into a second copy of the key. + +/// XTS key construction: the checks on `Key_1 | Key_2`, the split, and the two key expansions. +fn xts_key_construction, const N: usize>(name: &str, bytes: &[u8; N]) { + eprintln!("{name}::from_key_material"); + let material = bench::key(bytes); + bench::measure(|| { + let key = K::from_key_material(&material); + assert!(core::hint::black_box(&key).is_ok()); + }); + print!("{}", core::mem::size_of::()); +} + +/// XTS `encrypt_inplace` of one [`XTS_DATA_UNIT_LEN`]-byte data unit. +fn xts_encrypt, const N: usize>(name: &str, bytes: &[u8; N]) +where + XTSKey

: FromKeyMaterial, +{ + eprintln!("{name}::encrypt_inplace, {XTS_DATA_UNIT_LEN} B"); + let key: XTSKey

= xts_load(bytes); + let mut data_unit = [0x11u8; XTS_DATA_UNIT_LEN]; + bench::measure(|| { + core::hint::black_box(key.encrypt_inplace(&XTS_TWEAK, &mut data_unit).unwrap()); + }); + print!("{data_unit:x?}"); +} + +/// XTS `decrypt_inplace` of one [`XTS_DATA_UNIT_LEN`]-byte data unit. +fn xts_decrypt, const N: usize>(name: &str, bytes: &[u8; N]) +where + XTSKey

: FromKeyMaterial, +{ + eprintln!("{name}::decrypt_inplace, {XTS_DATA_UNIT_LEN} B"); + let key: XTSKey

= xts_load(bytes); + let mut data_unit = [0x11u8; XTS_DATA_UNIT_LEN]; + bench::measure(|| { + core::hint::black_box(key.decrypt_inplace(&XTS_TWEAK, &mut data_unit).unwrap()); + }); + print!("{data_unit:x?}"); +} + +/// Every XTS bench, so that a build with `main` calling this keeps all of them for the +/// frame-layout remarks. +fn xts_all() { + xts_key_construction::("XTS_AES_128", &XTS_KEY_128); + xts_encrypt::("XTS_AES_128", &XTS_KEY_128); + xts_decrypt::("XTS_AES_128", &XTS_KEY_128); + xts_key_construction::("XTS_AES_256", &XTS_KEY_256); + xts_encrypt::("XTS_AES_256", &XTS_KEY_256); + xts_decrypt::("XTS_AES_256", &XTS_KEY_256); } fn main() { @@ -96,4 +200,11 @@ fn main() { // bench::decrypt_2blocks::("AES256Internal", &KEY_256) // bench::encrypt_4blocks::("AES256Internal", &KEY_256) // bench::decrypt_4blocks::("AES256Internal", &KEY_256) + // xts_all() + // xts_key_construction::("XTS_AES_128", &XTS_KEY_128) + // xts_encrypt::("XTS_AES_128", &XTS_KEY_128) + // xts_decrypt::("XTS_AES_128", &XTS_KEY_128) + // xts_key_construction::("XTS_AES_256", &XTS_KEY_256) + // xts_encrypt::("XTS_AES_256", &XTS_KEY_256) + // xts_decrypt::("XTS_AES_256", &XTS_KEY_256) } From b6a38285483858d14d00d470167dd663b6d25030 Mon Sep 17 00:00:00 2001 From: David Hook Date: Mon, 23 Nov 2026 13:14:56 +1100 Subject: [PATCH 08/10] cipher: XTS's first mask is filled in the caller's Secret, and the decrypt-only guard has a doctest first_mask built T = E_Key2(i) in a local Secret and returned it by value, which moves the mask out of a copy nothing wipes when the function is not inlined. encrypt and decrypt now declare the Secret and first_mask fills it through &mut. The output is unchanged. XTSKey::encrypt_inplace's const assertion on BlockPermutation::DECRYPT_ONLY had no test. Its docs gain a compile_fail,E0080 doctest over a decrypt-only wrapper of the toy permutation, and beside it the same key decrypting, so that the failure is known to be the guard's. Assisted-by: Claude:claude-fable-5-2 --- crypto/cipher/src/modes/xts.rs | 108 ++++++++++++++++++++++++++++++--- 1 file changed, 99 insertions(+), 9 deletions(-) diff --git a/crypto/cipher/src/modes/xts.rs b/crypto/cipher/src/modes/xts.rs index c3097adfb..8569abdb2 100644 --- a/crypto/cipher/src/modes/xts.rs +++ b/crypto/cipher/src/modes/xts.rs @@ -159,7 +159,93 @@ pub struct XTSKey

{ impl> XTSKey

{ /// Encrypts one data unit in place under its tweak, and returns the number of bytes written, /// `data_unit.len()`: the ciphertext is as long as the plaintext. Over a permutation that - /// decrypts only ([`BlockPermutation::DECRYPT_ONLY`]) it does not compile. + /// decrypts only ([`BlockPermutation::DECRYPT_ONLY`]) it does not compile: + /// + /// ```compile_fail,E0080 + /// # mod toy { include!("../../tests/common/toy_block_cipher.rs"); } + /// # use toy::ToyBlockCipher; + /// use bouncycastle_cipher::modes::XTSKey; + /// use bouncycastle_core::hazmat::BlockPermutation; + /// # use bouncycastle_core::errors::SymmetricCipherError; + /// # use bouncycastle_core::hazmat::KeyExpansion; + /// use bouncycastle_core::key_material::{KeyMaterial, KeyType}; + /// # use bouncycastle_core::security_strength::SecurityStrength; + /// use bouncycastle_core::symmetric_key::FromKeyMaterial; + /// # use bouncycastle_core::traits::Algorithm; + /// + /// struct DecryptOnly(ToyBlockCipher); + /// + /// impl BlockPermutation<16> for DecryptOnly { + /// const DECRYPT_ONLY: bool = true; + /// # fn encrypt_block(&self, block: &mut [u8; 16]) { self.0.encrypt_block(block) } + /// # fn decrypt_block(&self, block: &mut [u8; 16]) { self.0.decrypt_block(block) } + /// # fn encrypt_2blocks(&self, blocks: &mut [[u8; 16]; 2]) { self.0.encrypt_2blocks(blocks) } + /// # fn decrypt_2blocks(&self, blocks: &mut [[u8; 16]; 2]) { self.0.decrypt_2blocks(blocks) } + /// # fn encrypt_4blocks(&self, blocks: &mut [[u8; 16]; 4]) { self.0.encrypt_4blocks(blocks) } + /// # fn decrypt_4blocks(&self, blocks: &mut [[u8; 16]; 4]) { self.0.decrypt_4blocks(blocks) } + /// } + /// # impl Algorithm for DecryptOnly { + /// # const ALG_NAME: &'static str = "DecryptOnly"; + /// # const MAX_SECURITY_STRENGTH: SecurityStrength = SecurityStrength::_128bit; + /// # } + /// # impl KeyExpansion<16> for DecryptOnly { + /// # fn new(key: &KeyMaterial<16>) -> Result { + /// # ToyBlockCipher::new(key).map(Self) + /// # } + /// # } + /// + /// let key_bytes: [u8; 32] = core::array::from_fn(|i| i as u8 + 1); + /// let material = KeyMaterial::<32>::from_bytes_as_type(&key_bytes, KeyType::SymmetricCipherKey) + /// .expect("a 32-byte symmetric cipher key"); + /// let key = XTSKey::::from_key_material(&material).expect("an XTS key"); + /// let mut sector = [0x5Au8; 512]; + /// // Refused when the program is built: the permutation decrypts only. + /// let _ = key.encrypt_inplace(&[0u8; 16], &mut sector); + /// ``` + /// + /// The same key does decrypt: + /// + /// ``` + /// # mod toy { include!("../../tests/common/toy_block_cipher.rs"); } + /// # use toy::ToyBlockCipher; + /// use bouncycastle_cipher::modes::XTSKey; + /// use bouncycastle_core::hazmat::BlockPermutation; + /// # use bouncycastle_core::errors::SymmetricCipherError; + /// # use bouncycastle_core::hazmat::KeyExpansion; + /// use bouncycastle_core::key_material::{KeyMaterial, KeyType}; + /// # use bouncycastle_core::security_strength::SecurityStrength; + /// use bouncycastle_core::symmetric_key::FromKeyMaterial; + /// # use bouncycastle_core::traits::Algorithm; + /// + /// struct DecryptOnly(ToyBlockCipher); + /// + /// impl BlockPermutation<16> for DecryptOnly { + /// const DECRYPT_ONLY: bool = true; + /// # fn encrypt_block(&self, block: &mut [u8; 16]) { self.0.encrypt_block(block) } + /// # fn decrypt_block(&self, block: &mut [u8; 16]) { self.0.decrypt_block(block) } + /// # fn encrypt_2blocks(&self, blocks: &mut [[u8; 16]; 2]) { self.0.encrypt_2blocks(blocks) } + /// # fn decrypt_2blocks(&self, blocks: &mut [[u8; 16]; 2]) { self.0.decrypt_2blocks(blocks) } + /// # fn encrypt_4blocks(&self, blocks: &mut [[u8; 16]; 4]) { self.0.encrypt_4blocks(blocks) } + /// # fn decrypt_4blocks(&self, blocks: &mut [[u8; 16]; 4]) { self.0.decrypt_4blocks(blocks) } + /// } + /// # impl Algorithm for DecryptOnly { + /// # const ALG_NAME: &'static str = "DecryptOnly"; + /// # const MAX_SECURITY_STRENGTH: SecurityStrength = SecurityStrength::_128bit; + /// # } + /// # impl KeyExpansion<16> for DecryptOnly { + /// # fn new(key: &KeyMaterial<16>) -> Result { + /// # ToyBlockCipher::new(key).map(Self) + /// # } + /// # } + /// + /// let key_bytes: [u8; 32] = core::array::from_fn(|i| i as u8 + 1); + /// let material = KeyMaterial::<32>::from_bytes_as_type(&key_bytes, KeyType::SymmetricCipherKey) + /// .expect("a 32-byte symmetric cipher key"); + /// let key = XTSKey::::from_key_material(&material).expect("an XTS key"); + /// let mut sector = [0x5Au8; 512]; + /// // Decryption is not gated. + /// assert_eq!(key.decrypt_inplace(&[0u8; 16], &mut sector), Ok(512)); + /// ``` /// /// # Errors /// @@ -433,20 +519,23 @@ fn xex_blocks>(key1: &P, t: &mut Block, blocks: &mut [Block] } } -/// The mask of block 0 of a data unit under the tweak `i`: `T = AES-enc(Key_2, i) ⊗ α^0`, the -/// tweak encrypted under `Key_2` in both directions (step 1 of Sec 5.3.1 and of Sec 5.4.1). -fn first_mask>(key2: &P, i: &Block) -> Secret { - let mut t: Secret = Secret::new(); +/// Sets `t` to the mask of block 0 of a data unit under the tweak `i`: `T = AES-enc(Key_2, i) ⊗ +/// α^0`, the tweak encrypted under `Key_2` in both directions (step 1 of Sec 5.3.1 and of Sec +/// 5.4.1). +/// +/// The mask is written into the caller's `Secret`, which wipes it on drop; returned by value, it +/// would be moved out of a local here that nothing wipes. +fn first_mask>(key2: &P, i: &Block, t: &mut Block) { *t = *i; - key2.encrypt_block(&mut t); - t + key2.encrypt_block(t); } /// XTS-AES-Enc (IEEE 1619-2007 Sec 5.3.2) of the data unit `data`, in place, under the tweak /// `i`. `data` is from [`XTS_MIN_DATA_UNIT_LEN`] to [`XTS_MAX_DATA_UNIT_LEN`] bytes long, which /// the callers check. fn encrypt>(key1: &P, key2: &P, i: &Block, data: &mut [u8]) { - let mut t = first_mask(key2, i); + let mut t: Secret = Secret::new(); + first_mask(key2, i, &mut t); // `blocks` are P_0 .. P_{m-1}, the whole blocks, and `tail` is P_m, the b < 16 bytes after // them, which is empty when the data unit is a whole number of blocks. @@ -472,7 +561,8 @@ fn encrypt>(key1: &P, key2: &P, i: &Block, data: /// XTS-AES-Dec (IEEE 1619-2007 Sec 5.4.2) of the data unit `data`, in place, under the tweak /// `i`. The length is as for [`encrypt`]. fn decrypt>(key1: &P, key2: &P, i: &Block, data: &mut [u8]) { - let mut t = first_mask(key2, i); + let mut t: Secret = Secret::new(); + first_mask(key2, i, &mut t); let (blocks, tail) = data.as_chunks_mut::(); // With a partial block, ciphertext stealing undoes the encryption's last two block From 23eb08e7f2540dc28c0dffed81ed9f09848005c7 Mon Sep 17 00:00:00 2001 From: David Hook Date: Mon, 23 Nov 2026 13:14:56 +1100 Subject: [PATCH 09/10] aes: the crate docs no longer say XTS is used through a mode-bound key XTS_AES_128 was listed among the modes that the following sentence says are used through a key such as AES256Key handing out encryptors and decryptors. XTS has its own key type and no workers; the sentence now says so. Assisted-by: Claude:claude-fable-5-2 --- crypto/aes/src/lib.rs | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/crypto/aes/src/lib.rs b/crypto/aes/src/lib.rs index ce9e7ff66..983550321 100644 --- a/crypto/aes/src/lib.rs +++ b/crypto/aes/src/lib.rs @@ -28,9 +28,10 @@ //! * [`AES_OFB_128`] //! * [`XTS_AES_128`], for storage: one data unit at a time, in place, under a tweak //! -//! Each mode is used through a mode-bound key object such as [`AES256Key`](AES256Key), -//! which validates and expands the material once and hands out the mode's encryptors and -//! decryptors; see [`AES128Key`]. +//! Each mode but XTS is used through a mode-bound key object such as +//! [`AES256Key`](AES256Key), which validates and expands the material once and hands out +//! the mode's encryptors and decryptors; see [`AES128Key`]. XTS has a key type of its own, +//! [`XTS_AES_128`], with no workers: the key encrypts and decrypts a data unit itself. //! //! AES in ECB mode, [`AES_ECB_128`](hazmat::AES_ECB_128) and friends, is under [`hazmat`] because //! it is a building block for other modes, not itself a confidentiality mode for data. From 40f212d58bbf4e78d1aba7c1affe49f7388e4cae Mon Sep 17 00:00:00 2001 From: David Hook Date: Mon, 23 Nov 2026 13:14:56 +1100 Subject: [PATCH 10/10] cli: the XTS commands name the keys XTS refuses, and the module header points at the help An all-zero --key drew the block cipher loader's warning that it was proceeding and then XTS's refusal of equal halves, and a key with one all-zero half was refused with AES's InvalidKeyType debug message. The commands now load their key themselves, once, and refuse equal halves and an all-zero half with a message that names the cause, before the key is built; the halves are compared in constant time. The shared loader is unchanged. The module header repeated the subcommand help on data units and the tweak; it now points there. Assisted-by: Claude:claude-fable-5-2 --- cli/src/xts_cmd.rs | 78 ++++++++++++++++++++++++++-------- cli/tests/aes_xts_cli_tests.rs | 28 ++++++++++++ 2 files changed, 89 insertions(+), 17 deletions(-) diff --git a/cli/src/xts_cmd.rs b/cli/src/xts_cmd.rs index 505ec39c7..aed542c1a 100644 --- a/cli/src/xts_cmd.rs +++ b/cli/src/xts_cmd.rs @@ -1,27 +1,19 @@ -//! XTS-AES encryption and decryption of stdin to stdout, one data unit at a time: the -//! `aes128-xts` and `aes256-xts` commands, one generic function that `main` instantiates per key -//! length. -//! -//! The input is a sequence of data units of `--data-unit-len` bytes, and must be a whole number of -//! them: an XTS key protects data units of one fixed length (NIST SP 800-38E Sec 4), so one length -//! serves the whole input. The first data unit is processed under `--tweak` and each later one -//! under the tweak before it plus one, read as a 128-bit little-endian integer: the numbering and -//! the encoding of IEEE 1619-2007 Sec 5.1. Nothing is prepended or appended: the output is exactly -//! as long as the input. -//! -//! # Warning -//! -//! XTS provides confidentiality only, and only for data at rest; see the subcommand help. +//! The `aes128-xts` and `aes256-xts` commands: one generic function that `main` instantiates per +//! key length. What the commands do with their input, the tweak and the key is in the subcommand +//! help in `main.rs`. -use crate::helpers::block_mode_helpers::{CipherDirection, load_key_object}; +use crate::helpers::block_mode_helpers::CipherDirection; use crate::helpers::{ - decode_hex_arg, flush_stdout, read_stdin_chunk, write_bytes_or_hex, write_stdout, + decode_hex_arg, flush_stdout, load_secret, read_stdin_chunk, strip_trailing_newline, + write_bytes_or_hex, write_stdout, }; use bouncycastle::cipher::modes::{ XTS_MAX_DATA_UNIT_LEN, XTS_MIN_DATA_UNIT_LEN, XTS_TWEAK_LEN, XTSKey, }; use bouncycastle::core::hazmat::BlockPermutation; +use bouncycastle::core::key_material::{KeyMaterial, KeyMaterialTrait, KeyType}; use bouncycastle::core::symmetric_key::FromKeyMaterial; +use bouncycastle_utils::ct::{ct_eq_bytes, ct_eq_zero_bytes}; use std::process::exit; /// XTS over the permutation `P` with a `KEY_LEN`-byte key, `Key_1 | Key_2`, on `data_unit_len`-byte @@ -48,7 +40,7 @@ pub(crate) fn xts_cmd( ); exit(-1); } - let key = load_key_object::, KEY_LEN>(key, key_file, alg); + let key = load_xts_key::(key, key_file, alg); // `None` once a data unit has taken the tweak 2^128 - 1: there is no next one, and wrapping // round to 0 could repeat a tweak an earlier data unit used. @@ -93,6 +85,58 @@ pub(crate) fn xts_cmd( flush_stdout(); } +/// The XTS key from `--key-file` or `--key`, exactly `KEY_LEN` bytes after one trailing newline +/// in a raw file is set aside, as the other cipher commands load theirs. +/// +/// The two keys XTS refuses are named here, before the key is built: the block cipher commands' +/// loader would accept an all-zero key with a warning that it is proceeding, which XTS does not, +/// and the library's refusal of an all-zero half does not say which key it is refusing or why. +fn load_xts_key( + key: &Option, + key_file: &Option, + alg: &str, +) -> XTSKey

+where + XTSKey

: FromKeyMaterial, +{ + let secret = load_secret(key, key_file, "key"); + let trimmed = strip_trailing_newline(secret.ref_to_bytes()); + let key_bytes = if trimmed.len() == KEY_LEN { trimmed } else { secret.ref_to_bytes() }; + if key_bytes.len() != KEY_LEN { + eprintln!("Error: {alg} needs a {KEY_LEN}-byte key, got {} bytes.", key_bytes.len()); + exit(-1); + } + + // Key = Key_1 | Key_2. Compared in constant time, as the library does: only the refusal is + // public. + let (key1, key2) = key_bytes.split_at(KEY_LEN / 2); + if ct_eq_bytes(key1, key2) { + eprintln!( + "Error: the two halves of the {alg} key, Key_1 and Key_2, are equal (an all-zero key \ + is the usual case). XTS requires Key_1 != Key_2 (FIPS 140-3 IG C.I)." + ); + exit(-1); + } + if ct_eq_zero_bytes(key1) | ct_eq_zero_bytes(key2) { + eprintln!( + "Error: one half of the {alg} key, Key_1 or Key_2, is all zeros. Each half is an AES \ + key, and an all-zero AES key is refused." + ); + exit(-1); + } + + let material = + KeyMaterial::::from_bytes_as_type(key_bytes, KeyType::SymmetricCipherKey) + .unwrap_or_else(|e| { + eprintln!("Error: couldn't load the key: {e:?}"); + exit(-1); + }); + XTSKey::

::from_key_material(&material).unwrap_or_else(|e| { + eprintln!("Error: couldn't load the key: {e:?}"); + exit(-1); + }) +} + /// `--tweak`: exactly 16 bytes of hex, the 128-bit tweak of the first data unit. fn load_tweak(tweak: &str) -> [u8; XTS_TWEAK_LEN] { let bytes = decode_hex_arg(tweak, "tweak"); diff --git a/cli/tests/aes_xts_cli_tests.rs b/cli/tests/aes_xts_cli_tests.rs index b07b66e1c..f9d927aca 100644 --- a/cli/tests/aes_xts_cli_tests.rs +++ b/cli/tests/aes_xts_cli_tests.rs @@ -192,6 +192,34 @@ fn bad_arguments_are_refused() { } } +/// The keys XTS refuses are refused by name, before anything is written: equal halves, of which +/// the all-zero key is one -- without the other commands' warning that an all-zero key is being +/// proceeded with -- and a half that is all zeros, whichever half it is. +#[test] +fn degenerate_keys_are_refused_by_name() { + let zero16 = "00".repeat(16); + let zero32 = "00".repeat(32); + let equal = "Key_1 and Key_2, are equal"; + let zero_half = "Key_1 or Key_2, is all zeros"; + let cases: [(&str, String, &str); 7] = [ + ("aes128-xts", "00".repeat(32), equal), + ("aes256-xts", "00".repeat(64), equal), + ("aes128-xts", "00112233445566778899aabbccddeeff".repeat(2), equal), + ("aes128-xts", format!("{zero16}{}", &KEY32[32..]), zero_half), + ("aes128-xts", format!("{}{zero16}", &KEY32[32..]), zero_half), + ("aes256-xts", format!("{zero32}{}", &KEY64[64..]), zero_half), + ("aes256-xts", format!("{}{zero32}", &KEY64[64..]), zero_half), + ]; + for (cmd, key, msg) in cases { + for direction in ["encrypt", "decrypt"] { + let err = run_err_silent(&args(&xts(cmd, direction, &key, TWEAK, 512)), &[0x42; 512]); + assert!(err.contains(msg), "{cmd} {direction} {key}: stderr was: {err}"); + assert!(!err.contains("Proceeding"), "{cmd} {direction} {key}: stderr was: {err}"); + assert!(!err.contains("InvalidKeyType"), "{cmd} {direction} {key}: stderr was: {err}"); + } + } +} + #[test] fn the_commands_are_listed_in_help() { listed_in_help(&["aes128-xts", "aes256-xts"]);