diff --git a/alpha_0.1.4_release_notes.md b/alpha_0.1.4_release_notes.md index 4d5794633..038bf6d2c 100644 --- a/alpha_0.1.4_release_notes.md +++ b/alpha_0.1.4_release_notes.md @@ -28,6 +28,9 @@ 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`, 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` / `VerifyingKey` core roles; the `ecdsa-*` CLI commands. diff --git a/cli/src/main.rs b/cli/src/main.rs index af3445c2e..ec6799173 100644 --- a/cli/src/main.rs +++ b/cli/src/main.rs @@ -54,6 +54,7 @@ mod tdes_ofb_cmd; mod tdes_tkw_cmd; mod x25519_cmd; mod x448_cmd; +mod xts_cmd; use crate::blake2_cmd::BLAKE2Variant; use crate::eccdh_cmd::ECCDHAction; @@ -3792,6 +3793,87 @@ 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 -- 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. + /// + /// 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, 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. + 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, from 16 to 16777216 (2^20 blocks). + #[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, from 16 to 16777216 (2^20 blocks). + #[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. /// @@ -8690,6 +8772,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..aed542c1a --- /dev/null +++ b/cli/src/xts_cmd.rs @@ -0,0 +1,160 @@ +//! 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; +use crate::helpers::{ + 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 +/// data units; `alg` names the algorithm in messages. +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, +{ + 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); + } + 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. + 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 < 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 {data_unit_len}-byte data \ + units (data contained {filled} trailing byte(s))." + ); + 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(); + 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); + next_tweak = sequence_number.checked_add(1); + } + if output_hex { + write_stdout(b"\n"); + } + 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"); + 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; + 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..f9d927aca --- /dev/null +++ b/cli/tests/aes_xts_cli_tests.rs @@ -0,0 +1,226 @@ +//! 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, +}; + +/// `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 `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.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) + }; + assert_eq!(processed, Ok(len)); + } + 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. +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"); +} + +/// 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_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 = library_128(KEY32, TWEAK, len, &data, true); + agrees("aes128-xts", KEY32, len, &data, &expected); + } + for len in [16, 512, 4095, 4096] { + let data = pseudo_random(3 * len, len as u32 + 1); + let expected = library_256(KEY64, TWEAK, len, &data, true); + agrees("aes256-xts", KEY64, len, &data, &expected); + assert_eq!(library_256(KEY64, TWEAK, len, &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(KEY32, "ff000000000000000000000000000000", 512, &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 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 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"), + ("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 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}"); + } +} + +/// 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"]); +} diff --git a/crypto/aes/Cargo.toml b/crypto/aes/Cargo.toml index f79ee9628..fef3b4b42 100644 --- a/crypto/aes/Cargo.toml +++ b/crypto/aes/Cargo.toml @@ -25,3 +25,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..163941184 --- /dev/null +++ b/crypto/aes/benches/aes_xts_benches.rs @@ -0,0 +1,106 @@ +//! 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 `len`-byte data unit, reported as `label`. +fn data_unit( + group: &mut BenchmarkGroup<'_, WallTime>, + len: usize, + label: &str, +) where + P: BlockPermutation<16>, + XTSKey

: FromKeyMaterial, +{ + 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).unwrap(); + + 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).unwrap(); + 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).unwrap(); + 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, 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, 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(); +} + +/// 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::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::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 b6f9f4690..983550321 100644 --- a/crypto/aes/src/lib.rs +++ b/crypto/aes/src/lib.rs @@ -26,10 +26,12 @@ //! * [`AES_GMAC_128`], a nonce-based MAC rather than a cipher //! * [`AES_KW_128`] and [`AES_KWP_128`], key wraps rather than ciphers //! * [`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. @@ -74,10 +76,10 @@ //! 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*, and OFB in both directions, cannot, because each forward cipher -//! input depends on the previous output (SP 800-38A Sec 6.2, 6.3 and 6.4), so those 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*, and OFB in both directions, cannot, because each +//! forward cipher input depends on the previous output (SP 800-38A Sec 6.2, 6.3 and 6.4), so those +//! 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 @@ -203,6 +205,7 @@ mod ofb; mod round; mod sbox; mod schedule; +mod xts; use bouncycastle_utils::secret::{NoPadding, ZeroizablePrimitive}; @@ -292,3 +295,4 @@ 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 ofb::{AES_OFB_128, AES_OFB_192, AES_OFB_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..f08906128 --- /dev/null +++ b/crypto/aes/src/xts.rs @@ -0,0 +1,98 @@ +//! 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): 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 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 +/// +/// 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::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 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; +/// assert_eq!(key.encrypt_inplace(&tweak, &mut data_unit), Ok(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).expect("a 23-byte 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::generate(&mut rng).expect("a 256-bit RNG"); +/// +/// let mut disk = vec![0u8; 8 * 4096]; +/// 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!(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, 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; + +/// 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; diff --git a/crypto/aes/tests/xts_acvp_tests.rs b/crypto/aes/tests/xts_acvp_tests.rs new file mode 100644 index 000000000..a90097adc --- /dev/null +++ b/crypto/aes/tests/xts_acvp_tests.rs @@ -0,0 +1,132 @@ +//! 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. +//! +//! 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 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 +//! 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::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; + +/// 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 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(key, KeyType::SymmetricCipherKey).unwrap(); + let key = XTSKey::

::from_key_material(&material) + .unwrap_or_else(|e| panic!("tcId {tc_id}: the key is refused: {e:?}")); + assert_eq!(ct.len(), pt.len(), "tcId {tc_id}: the ciphertext is as long as the plaintext"); + + 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.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"); +} + +/// 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"); + + match key_len { + 128 => { + check::(&key, &tweak, &pt, &ct, tc_id); + ran_128 += 1; + } + 256 => { + check::(&key, &tweak, &pt, &ct, tc_id); + 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)) +} + +#[test] +fn acvp_aes_xts_1_0() { + let Some(counts) = run("1.0") else { + return; + }; + assert_eq!(counts, (130, 130, 140)); +} + +#[test] +fn acvp_aes_xts_2_0() { + let Some(counts) = run("2.0") else { + return; + }; + assert_eq!(counts, (42, 30, 728)); +} diff --git a/crypto/aes/tests/xts_tests.rs b/crypto/aes/tests/xts_tests.rs new file mode 100644 index 000000000..58a3fe2c5 --- /dev/null +++ b/crypto/aes/tests/xts_tests.rs @@ -0,0 +1,505 @@ +//! 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 (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; 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 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}; +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::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; + +/// 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(n: usize, ct: &str) +where + P: BlockPermutation<16>, + XTSKey

: FromKeyMaterial, +{ + 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), 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. +#[test] +fn xts_aes_128_matches_openssl() { + for &(n, ct) in KATS_128 { + kat::(n, ct); + } +} + +#[test] +fn xts_aes_256_matches_openssl() { + 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 +/// 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(n: usize, expected: &LongKat) +where + P: BlockPermutation<16>, + XTSKey

: FromKeyMaterial, +{ + let key = xts_key::(&key_bytes()); + let pt = pattern(n); + let mut data_unit = pt.clone(); + + 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!(key.decrypt_inplace(&TWEAK, &mut data_unit), Ok(n)); + assert!(data_unit == pt, "{n} bytes: decryption restores the plaintext"); +} + +// 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_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 ------------------------------------------------------------ + +/// `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 }; + ((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` (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>, + 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; + assert_eq!(key.encrypt_inplace(&TWEAK, &mut data_unit), Ok(512)); + 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(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() { + 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(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.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"); + } + // And it does not decrypt under the original tweak. + key.decrypt_inplace(&TWEAK, &mut other).unwrap(); + assert_ne!(other, pt); + } +} + +#[test] +fn every_tweak_bit_matters_to_every_block() { + 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 sector = [0x11u8; 512]; + let mut s0 = sector; + let mut s1 = sector; + 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).unwrap(); + 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).unwrap(); + 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>("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 +// 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::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::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).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. + 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..a9798695b --- /dev/null +++ b/crypto/aes/tests/xts_wycheproof.rs @@ -0,0 +1,77 @@ +//! 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 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; +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 = hex_field(case, "msg", tc_id); + let ct = hex_field(case, "ct", tc_id); + + 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"); + assert_eq!(key.decrypt_inplace(&tweak, &mut data_unit), Ok(msg.len()), "tcId {tc_id}"); + assert_eq!(data_unit, msg, "tcId {tc_id}: decryption"); +} + +#[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"); + match key_size { + 256 => { + check::(case, tc_id); + ran_128 += 1; + } + 512 => { + check::(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 b8a75925f..3a78645d5 100644 --- a/crypto/cipher/Cargo.toml +++ b/crypto/cipher/Cargo.toml @@ -85,3 +85,7 @@ path = "tests/modes/ofb_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 0605aad58..24f9a1ceb 100644 --- a/crypto/cipher/src/modes/mod.rs +++ b/crypto/cipher/src/modes/mod.rs @@ -25,8 +25,9 @@ //! | 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 | //! | TKW | [`tkw`] | SP 800-38F Sec 7 | TDEA Key Wrap: KW at 64-bit blocks and 32-bit semiblocks. **Legacy only** | +//! | 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 trio. +//! They divide three ways, plus the key-wrap trio and XTS. //! //! **ECB and CBC are block ciphers** ([`BlockCipherEncryptor`] / [`BlockCipherDecryptor`]): whole //! blocks in, whole blocks out, and arbitrary-length data needs the padding layer. @@ -48,6 +49,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 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 //! because the rest of the counter block is the counter. ECB has @@ -197,6 +202,7 @@ pub(crate) mod modes_common; pub mod ofb; mod polyval; pub mod tkw; +pub mod xts; pub use cbc::{CBC, Cbc}; pub use ccm::{ @@ -213,6 +219,7 @@ pub use kw::{KW, KW_BLOCK_LEN, Kw, SEMIBLOCK_LEN}; pub use kwp::{KWP, Kwp}; pub use ofb::{OFB, Ofb}; pub use tkw::{TKW, TKW_BLOCK_LEN, TKW_SEMIBLOCK_LEN, Tkw}; +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 a0bc557d8..b593eb40a 100644 --- a/crypto/cipher/src/modes/possible_enhancements.md +++ b/crypto/cipher/src/modes/possible_enhancements.md @@ -3,7 +3,6 @@ Possible additional modes or features to be added to this crate: * **CFB1**, the `s = 1` segment size (SP 800-38A Appendix F.3.1-F.3.6). Its segment is a single *bit*, so unlike [`Cfb`] and [`Cfb8`] it does not fit a byte-oriented API at all: a message is a bit string whose length need not be a multiple of 8, which this crate has no type for. -* **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..8569abdb2 --- /dev/null +++ b/crypto/cipher/src/modes/xts.rs @@ -0,0 +1,590 @@ +//! 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 +//! (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` +//! (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). 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 +//! +//! 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 +//! +//! 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"); +//! +//! 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(); +//! assert_eq!(key.encrypt_inplace(&tweak, &mut sector), Ok(512)); +//! assert_ne!(sector, [0x5Au8; 512]); +//! assert_eq!(key.decrypt_inplace(&tweak, &mut sector), Ok(512)); +//! assert_eq!(sector, [0x5Au8; 512]); +//! ``` +//! +//! # 🚨 Security Considerations 🚨 +//! +//! ## XTS provides confidentiality only +//! +//! 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; 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 +//! +//! 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 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. 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 +//! +//! 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 +//! +//! 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. + +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, 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). +pub const XTS_MAX_DATA_UNIT_LEN: usize = (1 << 20) * BLOCK_LEN; + +/// 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. +/// +/// # 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. +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

{ + /// 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: + /// + /// ```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 + /// + /// 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], + ) -> 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); + Ok(data_unit.len()) + } + + /// Decrypts one data unit in place under the tweak it was encrypted under, and returns the + /// 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], + ) -> Result { + check_data_unit_len(data_unit.len())?; + decrypt(&self.key1, &self.key2, tweak, data_unit); + 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

+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 { + 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 { + 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()); + } + + // 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 + // 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 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 +/// 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 ⊗ α` (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). +/// +/// 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, 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. 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); + } + 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`, 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)) + 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); + } +} + +/// 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(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: 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. + let (blocks, tail) = data.as_chunks_mut::(); + + // 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, 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() + { + last[..tail.len()].swap_with_slice(tail); + xex::(key1, &t, last); + } +} + +/// 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: 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 + // 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() + { + // 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); + + // 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 (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 { + // 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 new file mode 100644 index 000000000..606b70c4c --- /dev/null +++ b/crypto/cipher/tests/modes/xts_tests.rs @@ -0,0 +1,287 @@ +//! 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::{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; +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(len: usize) -> Vec { + (0..len).map(|k| (k as u8).wrapping_mul(13).wrapping_add(5)).collect() +} + +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 +} + +// ---- 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); + } +} + +// ---- 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 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 = 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 whole = encrypt(&pt[..aligned]); + let cc = &whole[last..]; + + // Nothing before C_{m-1} is touched. + 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"); + // C_{m-1} is P_m || CC[b..] encrypted under index m: block m of a data unit one block longer. + 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; + 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(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], b: &[u8]) -> 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 = pattern(64); + let ct = encrypt(&pt); + for j in 0..4 { + 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 = pattern(40); + let ct = encrypt(&pt); + for (range, reached) in [(0..16, &[0][..]), (16..32, &[1, 2][..]), (32..40, &[1][..])] { + 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:?}"); + } +} + +// ---- 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).unwrap(); + assert_ne!(swapped[..], ct, "two blocks must go through encrypt_2blocks"); + let mut back = ct; + 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).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 +/// 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).unwrap(); + assert_ne!(swapped[..], ct, "four blocks must go through encrypt_4blocks"); + let mut back = ct; + 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).unwrap(); + assert_eq!(swapped[..], encrypt(&three), "three blocks must not batch in four"); + let mut back = swapped; + 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) }