Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
18 commits
Select commit Hold shift + click to select a range
8a94ded
Initial add for AES-XTS (#184)
officialfrancismendoza Nov 11, 2026
f53d7d5
Corrected step citations, key scope, data per key, attributions, and …
officialfrancismendoza Nov 11, 2026
7949527
Fixed merge conflicts with updated release/0.1.4alpha (#184)
officialfrancismendoza Nov 19, 2026
b480bda
Merge branch 'release/0.1.4alpha' into feature/officialfrancismendoza…
officialfrancismendoza Nov 19, 2026
d82639e
Fix rustfmt issues (#184)
officialfrancismendoza Nov 19, 2026
5da1c29
Merge branch 'release/0.1.4alpha' into feature/officialfrancismendoza…
dghgit Nov 21, 2026
347fb2a
Merge branch 'release/0.1.4alpha' into feature/officialfrancismendoza…
dghgit Nov 22, 2026
a6b9115
ci: the no-std step tests digest's unit tests and scrypt's caller-mem…
dghgit Nov 22, 2026
34b3c69
Merge branch 'release/0.1.4alpha' into feature/officialfrancismendoza…
dghgit Nov 22, 2026
d6be3ef
aes: the XTS tests use bouncycastle_core::hex
dghgit Nov 22, 2026
6b2fc08
aes: the XTS ACVP suite reads NIST's vector sets from bc-test-data
dghgit Nov 22, 2026
5504aab
Made fixes to XTS-AES for data-unit length (#184)
officialfrancismendoza Nov 23, 2026
b6a3828
cipher: XTS's first mask is filled in the caller's Secret, and the de…
dghgit Nov 23, 2026
23eb08e
aes: the crate docs no longer say XTS is used through a mode-bound key
dghgit Nov 23, 2026
40f212d
cli: the XTS commands name the keys XTS refuses, and the module heade…
dghgit Nov 23, 2026
02a67f5
Merge remote-tracking branch 'origin/release/0.1.4alpha' into feature…
dghgit Nov 23, 2026
294027e
Merge remote-tracking branch 'origin/release/0.1.4alpha' into feature…
dghgit Nov 23, 2026
a86d4e8
Merge remote-tracking branch 'origin/release/0.1.4alpha' into feature…
dghgit Nov 23, 2026
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions alpha_0.1.4_release_notes.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down
92 changes: 92 additions & 0 deletions cli/src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down Expand Up @@ -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<String>,

/// 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<String>,

/// 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<String>,

/// 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<String>,

/// 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.
///
Expand Down Expand Up @@ -8690,6 +8772,16 @@ fn run() {
Some(Subcommands::AES256_KWP { direction, key, key_file, x }) => {
kw_cmd::kwp_cmd::<AES256Internal, 32>(direction, key, key_file, *x, "AES-256");
}
Some(Subcommands::AES128_XTS { direction, key, key_file, tweak, data_unit_len, x }) => {
xts_cmd::xts_cmd::<AES128Internal, 32>(
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::<AES256Internal, 64>(
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::<Camellia128Internal, 16>(direction, key, key_file, *x, "Camellia-128");
}
Expand Down
160 changes: 160 additions & 0 deletions cli/src/xts_cmd.rs
Original file line number Diff line number Diff line change
@@ -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<P, const KEY_LEN: usize>(
action: &CipherDirection,
key: &Option<String>,
key_file: &Option<String>,
tweak: &str,
data_unit_len: usize,
output_hex: bool,
alg: &str,
) where
P: BlockPermutation<16>,
XTSKey<P>: FromKeyMaterial<KEY_LEN>,
{
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::<P, KEY_LEN>(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<P, const KEY_LEN: usize>(
key: &Option<String>,
key_file: &Option<String>,
alg: &str,
) -> XTSKey<P>
where
XTSKey<P>: FromKeyMaterial<KEY_LEN>,
{
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::<KEY_LEN>::from_bytes_as_type(key_bytes, KeyType::SymmetricCipherKey)
.unwrap_or_else(|e| {
eprintln!("Error: couldn't load the key: {e:?}");
exit(-1);
});
XTSKey::<P>::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
}
Loading
Loading