Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
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<N>` /
`XTS_AES_256<N>` over `bouncycastle_cipher::modes::XTSKey`, with the data-unit length `N` checked at compile time;
the `aes128-xts` / `aes256-xts` CLI commands.
* ECDSA -- FIPS 186-5 signatures over P-256, P-384, P-521, secp256k1, brainpoolP256r1, brainpoolP384r1 and
brainpoolP512r1, with the RFC 6979 deterministic variant, through the `SigningKey` / `DeterministicSigningKey` /
`VerifyingKey` core roles; the `ecdsa-*` CLI commands.
Expand Down
90 changes: 90 additions & 0 deletions cli/src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -46,6 +46,7 @@ mod tdes_ecb_cmd;
mod tdes_ofb_cmd;
mod tdes_tkw_cmd;
mod x25519_cmd;
mod xts_cmd;

use crate::blake2_cmd::BLAKE2Variant;
use crate::eccdh_cmd::ECCDHAction;
Expand Down Expand Up @@ -3670,6 +3671,85 @@ enum Subcommands {
x: bool,
},

/// XTS-AES-128 (NIST SP 800-38E; IEEE Std 1619-2007), for storage: streams stdin to stdout one
/// data unit at a time.
///
/// The input is a sequence of data units of `--data-unit-len` bytes -- 512, 1024, 2048 or 4096,
/// the usual sector sizes -- and must be a whole number of them; the output is exactly as long
/// as the input, with nothing prepended. The first data unit is processed under `--tweak` and
/// each one after it under the tweak before it plus one, read as a 128-bit little-endian
/// integer. For sectors numbered from n, `--tweak` is n in 16 little-endian bytes: sector 1 is
/// 01000000000000000000000000000000. `decrypt` needs the same `--tweak` and `--data-unit-len`.
///
/// The key is 32 bytes, Key_1 | Key_2: two AES-128 keys, the first for the data and the second
/// for the tweak, which must differ (FIPS 140-3 IG C.I) and should be generated independently.
///
/// WARNING: XTS provides confidentiality only, and is for data at rest, not in transit. Nothing
/// detects a modified ciphertext, which decrypts to unpredictable data rather than to an error,
/// or an old one, which decrypts to the old data, and the same data under the same key and
/// tweak always encrypts the same way. Give every data unit under a key its own tweak.
///
/// Note: in production uses, secrets should not be passed on the command-line because they get
/// logged in shell history. Use the file-based input instead.
AES128_XTS {
#[arg(short, long)]
direction: CipherDirection,

/// The 32-byte XTS key, Key_1 | Key_2, in hex.
/// The `key_file` option is preferred to avoid leaving key material in command history.
#[arg(long)]
key: Option<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: 512, 1024, 2048 or 4096.
#[arg(long)]
data_unit_len: usize,

#[arg(short)]
/// Output in hex format.
x: bool,
},

/// XTS-AES-256 (NIST SP 800-38E; IEEE Std 1619-2007), for storage: streams stdin to stdout one
/// data unit at a time.
///
/// See `aes128-xts` for the data units, the tweak and the warnings; only the key differs: 64
/// bytes, Key_1 | Key_2, two AES-256 keys.
AES256_XTS {
#[arg(short, long)]
direction: CipherDirection,

/// The 64-byte XTS key, Key_1 | Key_2, in hex.
/// The `key_file` option is preferred to avoid leaving key material in command history.
#[arg(long)]
key: Option<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: 512, 1024, 2048 or 4096.
#[arg(long)]
data_unit_len: usize,

#[arg(short)]
/// Output in hex format.
x: bool,
},

/// Camellia-128 Key Wrap (RFC 3657 `id-camellia128-wrap`; NIST SP 800-38F Sec 6.2 over the
/// Camellia permutation): `-d encrypt` wraps stdin to stdout, `-d decrypt` unwraps it.
///
Expand Down Expand Up @@ -7991,6 +8071,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
129 changes: 129 additions & 0 deletions cli/src/xts_cmd.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,129 @@
//! XTS-AES encryption and decryption of stdin to stdout, one data unit at a time: the
//! `aes128-xts` and `aes256-xts` commands, one generic function that `main` instantiates per key
//! length.
//!
//! The input is a sequence of data units of `--data-unit-len` bytes, and must be a whole number of
//! them: an XTS key protects data units of one fixed length (NIST SP 800-38E Sec 4), and the
//! library fixes that length in the key's type, so the command offers the usual sector sizes and
//! instantiates a key type for the one chosen. The first data unit is processed under `--tweak` and
//! each later one under the tweak before it plus one, read as a 128-bit little-endian integer: the
//! numbering and the encoding of IEEE 1619-2007 Sec 5.1. Nothing is prepended or appended: the
//! output is exactly as long as the input.
//!
//! # Warning
//!
//! XTS provides confidentiality only, and only for data at rest; see the subcommand help.

use crate::helpers::block_mode_helpers::{CipherDirection, load_key_object};
use crate::helpers::{
decode_hex_arg, flush_stdout, read_stdin_chunk, write_bytes_or_hex, write_stdout,
};
use bouncycastle::cipher::modes::{XTS_TWEAK_LEN, XTSKey};
use bouncycastle::core::hazmat::BlockPermutation;
use bouncycastle::core::symmetric_key::FromKeyMaterial;
use std::process::exit;

/// XTS over the permutation `P` with a `KEY_LEN`-byte key, `Key_1 | Key_2`; `alg` names the
/// algorithm in messages. Exits with an error for a `data_unit_len` it does not offer.
pub(crate) fn xts_cmd<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, 512>: FromKeyMaterial<KEY_LEN>,
XTSKey<P, 1024>: FromKeyMaterial<KEY_LEN>,
XTSKey<P, 2048>: FromKeyMaterial<KEY_LEN>,
XTSKey<P, 4096>: FromKeyMaterial<KEY_LEN>,
{
let tweak = load_tweak(tweak);
match data_unit_len {
512 => run::<P, KEY_LEN, 512>(action, key, key_file, &tweak, output_hex, alg),
1024 => run::<P, KEY_LEN, 1024>(action, key, key_file, &tweak, output_hex, alg),
2048 => run::<P, KEY_LEN, 2048>(action, key, key_file, &tweak, output_hex, alg),
4096 => run::<P, KEY_LEN, 4096>(action, key, key_file, &tweak, output_hex, alg),
other => {
eprintln!("Error: --data-unit-len must be 512, 1024, 2048 or 4096 bytes, not {other}.");
exit(-1);
}
}
}

/// `--tweak`: exactly 16 bytes of hex, the 128-bit tweak of the first data unit.
fn load_tweak(tweak: &str) -> [u8; XTS_TWEAK_LEN] {
let bytes = decode_hex_arg(tweak, "tweak");
bytes.as_slice().try_into().unwrap_or_else(|_| {
eprintln!("Error: the tweak is {} bytes; XTS takes exactly {XTS_TWEAK_LEN}.", bytes.len());
exit(-1)
})
}

/// Processes stdin a data unit at a time under consecutive tweaks from `first_tweak`.
fn run<P, const KEY_LEN: usize, const N: usize>(
action: &CipherDirection,
key: &Option<String>,
key_file: &Option<String>,
first_tweak: &[u8; XTS_TWEAK_LEN],
output_hex: bool,
alg: &str,
) where
P: BlockPermutation<16>,
XTSKey<P, N>: FromKeyMaterial<KEY_LEN>,
{
let key = load_key_object::<XTSKey<P, N>, KEY_LEN>(key, key_file, alg);
let mut sequence_number = u128::from_le_bytes(*first_tweak);
let mut data_unit = [0u8; N];
let mut units = 0u64;
loop {
let filled = fill(&mut data_unit);
if filled == 0 {
break;
}
if filled < N {
// The whole data units before it are already written; flush them so that the error
// follows the output rather than landing inside it.
flush_stdout();
eprintln!(
"\nError: input to {alg} must be a whole number of {N}-byte data units \
(data contained {filled} trailing byte(s))."
);
exit(-1);
}
if units > 0 {
// Fail rather than wrap round to a tweak an earlier data unit may have used.
sequence_number = sequence_number.checked_add(1).unwrap_or_else(|| {
flush_stdout();
eprintln!("\nError: the tweak cannot go past 2^128 - 1.");
exit(-1)
});
}
let tweak = sequence_number.to_le_bytes();
match action {
CipherDirection::Encrypt => key.encrypt_inplace(&tweak, &mut data_unit),
CipherDirection::Decrypt => key.decrypt_inplace(&tweak, &mut data_unit),
};
write_bytes_or_hex(&data_unit, output_hex);
units += 1;
}
if output_hex {
write_stdout(b"\n");
}
flush_stdout();
}

/// Reads stdin into `buf` until it is full or the input ends, and returns how much was read.
fn fill(buf: &mut [u8]) -> usize {
let mut filled = 0;
while filled < buf.len() {
let n = read_stdin_chunk(&mut buf[filled..]);
if n == 0 {
break;
}
filled += n;
}
filled
}
Loading
Loading