diff --git a/Cargo.toml b/Cargo.toml
index 38cd2227..b31813db 100644
--- a/Cargo.toml
+++ b/Cargo.toml
@@ -44,6 +44,7 @@ bouncycastle-sha2 = { path = "./crypto/sha2" }
bouncycastle-sha3 = { path = "./crypto/sha3" }
bouncycastle-sm2 = { path = "./crypto/sm2" }
bouncycastle-sm3 = { path = "./crypto/sm3" }
+bouncycastle-tdes = { path = "./crypto/tdes" }
bouncycastle-sm4 = { path = "./crypto/sm4" }
bouncycastle-utils = { path = "./crypto/utils" }
bouncycastle-x963kdf = { path = "./crypto/x963kdf" }
@@ -102,5 +103,6 @@ bouncycastle-sha2.workspace = true
bouncycastle-sha3.workspace = true
bouncycastle-sm2.workspace = true
bouncycastle-sm3.workspace = true
+bouncycastle-tdes.workspace = true
bouncycastle-sm4.workspace = true
bouncycastle-x963kdf.workspace = true
diff --git a/alpha_0.1.4_release_notes.md b/alpha_0.1.4_release_notes.md
index 8c8ade1c..4aeeac9a 100644
--- a/alpha_0.1.4_release_notes.md
+++ b/alpha_0.1.4_release_notes.md
@@ -15,6 +15,13 @@
CBC, CFB, CFB8, CTR, GCM and CCM (RFC 8998's AEAD_SM4_GCM and AEAD_SM4_CCM), KW and KWP; the
`sm4-{cbc,cfb,cfb8,ctr,gcm,ccm,kw,kwp}` CLI commands.
* CHACHA20 -- ChaCha20, Poly1305 and ChaCha20-Poly1305 (RFC 8439).
+* TDES -- three-key TDEA (NIST SP 800-67 Rev 2) as a constant-time, table-free bit-sliced engine under `hazmat`,
+ with ECB, CBC, CFB64, CFB8 and CTR (SP 800-38A Appendix E) and TDEA Key Wrap (SP 800-38F TKW) through the key
+ role traits; two-key TDEA decrypts, unwraps and verifies CMAC tags only, which `BlockPermutation::DECRYPT_ONLY`
+ makes a compile error for every encrypting, wrapping and tag-generating route (CMAC over TDEA is reached through
+ the generic `BlockCipherKey`, not `TDESKey`); the `tdes-*` and `tdes2-*` CLI commands, whose `encrypt` refuses input past
+ SP 800-67 Rev 2 Sec 3.4's 2^20 blocks counted as the blocks TDEA processes (8 MiB; 1 MiB for CFB8, 699,048
+ 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.
* ECDSA -- FIPS 186-5 signatures over P-256, P-384, P-521, secp256k1, brainpoolP256r1, brainpoolP384r1 and
@@ -27,6 +34,11 @@
## Minor features / bug fixes
+* The key-wrap workers `Kw`, `Kwp` and `Tkw` carry their direction in the type, as the cipher modes do:
+ `KeyWrapper` is implemented for the encrypting worker only, so an unwrapper has no wrapping method and a
+ permutation that decrypts only is refused a wrapper at compile time by every route. The `AES_KW_*`, `AES_KWP_*`,
+ `ARIA_KW_*`, `ARIA_KWP_*`, `Camellia_KW_*`, `SM4_KW`, `SM4_KWP` and `TDES_TKW` aliases gain the `Dir` parameter;
+ `TDES2_TKW` is the decrypting one.
* `bouncycastle_utils::bitslice` holds what the bit-sliced ciphers share: the `PlaneWord` trait, the byte-lane
transpose `ortho`, and the non-linear section of the Boyar-Peralta AES S-box circuit as `gf256_inverse_nonlinear`,
which the AES, ARIA, Camellia and SM4 S-boxes all call instead of carrying their own copies.
diff --git a/cli/src/cbc_cmd.rs b/cli/src/cbc_cmd.rs
index 616fa470..d6b72772 100644
--- a/cli/src/cbc_cmd.rs
+++ b/cli/src/cbc_cmd.rs
@@ -12,8 +12,7 @@
//! separately.
use crate::helpers::block_mode_helpers::{
- BLOCK_LEN, CipherDirection, decrypt_stream, encrypt_stream, load_iv, load_key_object,
- start_encryptor,
+ CipherDirection, decrypt_stream, encrypt_stream, load_iv, load_key_object, start_encryptor,
};
use bouncycastle::cipher::BlockCipherKey;
use bouncycastle::cipher::modes::CBC;
@@ -22,6 +21,9 @@ use bouncycastle::cipher::padding::PKCS7;
use bouncycastle::core::hazmat::ElectronicCodeBook;
use bouncycastle::core::symmetric_key::{SymmetricDecryptionKey, SymmetricEncryptionKey};
+/// The 128-bit block of the ciphers these commands serve; TDES has its own commands.
+const BLOCK_LEN: usize = 16;
+
/// CBC with PKCS7 padding under a `KEY_LEN`-byte key for the permutation `P`; `alg` names the
/// cipher and key length in messages, "AES-128" and the like.
pub(crate) fn cbc_cmd
(
@@ -60,10 +62,13 @@ fn run(
|rng| key.create_encryptor(rng),
|iv| key.create_encryptor_nonce(iv),
);
- encrypt_stream::<_, BLOCK_LEN>(enc, generated_iv.as_ref(), output_hex, None)
- }
- CipherDirection::Decrypt => {
- decrypt_stream::<_, BLOCK_LEN>(iv, |iv| key.create_decryptor(iv), output_hex, None)
+ encrypt_stream::<_, BLOCK_LEN, BLOCK_LEN>(enc, generated_iv.as_ref(), output_hex, None)
}
+ CipherDirection::Decrypt => decrypt_stream::<_, BLOCK_LEN, BLOCK_LEN>(
+ iv,
+ |iv| key.create_decryptor(iv),
+ output_hex,
+ None,
+ ),
}
}
diff --git a/cli/src/cfb8_cmd.rs b/cli/src/cfb8_cmd.rs
index 15397a17..11a55392 100644
--- a/cli/src/cfb8_cmd.rs
+++ b/cli/src/cfb8_cmd.rs
@@ -27,7 +27,7 @@
//! plaintext byte, corrupts the following 16 bytes, and then decryption resynchronises. Do not
//! decrypt data you have not authenticated separately.
-use crate::helpers::block_mode_helpers::{BLOCK_LEN, CipherDirection, load_iv, load_key_object};
+use crate::helpers::block_mode_helpers::{CipherDirection, load_iv, load_key_object};
use crate::helpers::stream_mode_helpers::run_stream_mode;
use bouncycastle::cipher::BlockCipherKey;
use bouncycastle::cipher::modes::CFB8;
@@ -36,6 +36,9 @@ use bouncycastle::core::hazmat::ElectronicCodeBook;
use bouncycastle::core::symmetric_key::{SymmetricDecryptionKey, SymmetricEncryptionKey};
use bouncycastle::core::traits::{StreamCipherDecryptor, StreamCipherEncryptor};
+/// The 128-bit block of the ciphers these commands serve; TDES has its own commands.
+const BLOCK_LEN: usize = 16;
+
/// CFB8 under a `KEY_LEN`-byte key for the permutation `P`; `alg` names the cipher and key
/// length in messages.
pub(crate) fn cfb8_cmd(
diff --git a/cli/src/cfb_cmd.rs b/cli/src/cfb_cmd.rs
index 2c559708..14223ad1 100644
--- a/cli/src/cfb_cmd.rs
+++ b/cli/src/cfb_cmd.rs
@@ -28,7 +28,7 @@
//! of the plaintext in the *same* block, so an attacker edits the block they aimed at, at the cost
//! of randomising the next one. Do not decrypt data you have not authenticated separately.
-use crate::helpers::block_mode_helpers::{BLOCK_LEN, CipherDirection, load_iv, load_key_object};
+use crate::helpers::block_mode_helpers::{CipherDirection, load_iv, load_key_object};
use crate::helpers::stream_mode_helpers::run_stream_mode;
use bouncycastle::cipher::BlockCipherKey;
use bouncycastle::cipher::modes::CFB;
@@ -37,6 +37,9 @@ use bouncycastle::core::hazmat::ElectronicCodeBook;
use bouncycastle::core::symmetric_key::{SymmetricDecryptionKey, SymmetricEncryptionKey};
use bouncycastle::core::traits::{StreamCipherDecryptor, StreamCipherEncryptor};
+/// The 128-bit block of the ciphers these commands serve; TDES has its own commands.
+const BLOCK_LEN: usize = 16;
+
/// CFB under a `KEY_LEN`-byte key for the permutation `P`; `alg` names the cipher and key
/// length in messages.
pub(crate) fn cfb_cmd
(
diff --git a/cli/src/ctr_cmd.rs b/cli/src/ctr_cmd.rs
index 24786c9f..af12dfe8 100644
--- a/cli/src/ctr_cmd.rs
+++ b/cli/src/ctr_cmd.rs
@@ -36,7 +36,7 @@
//! reproducing published vectors and for formats that carry the nonce themselves; with them, its
//! uniqueness under the key is the caller's to keep.
-use crate::helpers::block_mode_helpers::{BLOCK_LEN, CipherDirection, load_iv, load_key_object};
+use crate::helpers::block_mode_helpers::{CipherDirection, load_iv, load_key_object};
use crate::helpers::stream_mode_helpers::run_stream_mode;
use bouncycastle::aes::CTR_NONCE_LEN;
use bouncycastle::cipher::BlockCipherKey;
@@ -46,6 +46,9 @@ use bouncycastle::core::hazmat::ElectronicCodeBook;
use bouncycastle::core::symmetric_key::{SymmetricDecryptionKey, SymmetricEncryptionKey};
use bouncycastle::core::traits::{StreamCipherDecryptor, StreamCipherEncryptor};
+/// The 128-bit block of the ciphers these commands serve; TDES has its own commands.
+const BLOCK_LEN: usize = 16;
+
// Every block cipher crate fixes the same CTR nonce length, so one command serves them all.
const _: () = assert!(
CTR_NONCE_LEN == bouncycastle::aria::CTR_NONCE_LEN
diff --git a/cli/src/ecb_cmd.rs b/cli/src/ecb_cmd.rs
index b5334c59..8dc36263 100644
--- a/cli/src/ecb_cmd.rs
+++ b/cli/src/ecb_cmd.rs
@@ -17,7 +17,7 @@
//! `aes*-cbc` or `aes*-cfb` under separate authentication, or better an AEAD.
use crate::helpers::block_mode_helpers::{
- BLOCK_LEN, CipherDirection, decrypt_stream, encrypt_stream, load_key_object, start_encryptor,
+ CipherDirection, decrypt_stream, encrypt_stream, load_key_object, start_encryptor,
};
use bouncycastle::cipher::BlockCipherKey;
use bouncycastle::cipher::modes::ModeNames;
@@ -26,6 +26,9 @@ use bouncycastle::cipher::padding::NoPadding;
use bouncycastle::core::hazmat::ElectronicCodeBook;
use bouncycastle::core::symmetric_key::{SymmetricDecryptionKey, SymmetricEncryptionKey};
+/// The 128-bit block of the ciphers these commands serve; TDES has its own commands.
+const BLOCK_LEN: usize = 16;
+
const MODE: &str = "ECB";
/// ECB without padding under a `KEY_LEN`-byte key for the permutation `P`; `alg` names the
@@ -59,9 +62,9 @@ where
|rng| key.create_encryptor(rng),
|no_iv| key.create_encryptor_nonce(no_iv),
);
- encrypt_stream::<_, 0>(enc, None, output_hex, Some(MODE))
+ encrypt_stream::<_, 0, BLOCK_LEN>(enc, None, output_hex, Some(MODE))
}
- CipherDirection::Decrypt => decrypt_stream::<_, 0>(
+ CipherDirection::Decrypt => decrypt_stream::<_, 0, BLOCK_LEN>(
None,
|no_iv| key.create_decryptor(no_iv),
output_hex,
diff --git a/cli/src/helpers/block_mode_helpers.rs b/cli/src/helpers/block_mode_helpers.rs
index d3d795fd..daa74b9c 100644
--- a/cli/src/helpers/block_mode_helpers.rs
+++ b/cli/src/helpers/block_mode_helpers.rs
@@ -69,11 +69,8 @@ use std::io;
use std::io::{Read, Write};
use std::process::exit;
-/// The AES block length in bytes.
-pub(crate) const BLOCK_LEN: usize = 16;
-
/// Bytes read from stdin per call: 1 KiB = 64 blocks, shared with the stream-mode commands.
-pub(crate) const CHUNK_LEN: usize = 64 * BLOCK_LEN;
+pub(crate) const CHUNK_LEN: usize = 1024;
/// Which direction to run. Shared by cipher subcommands, -- see the specific subcommand's
/// own `--help` (`bc-rust aes128-ccm --help` and friends) for what `encrypt`/`decrypt` actually do
@@ -86,6 +83,13 @@ pub(crate) enum CipherDirection {
Decrypt,
}
+/// The one action a decryption-only command offers. A separate enum rather than a flag, so that
+/// `tdes2-* encrypt` is rejected by the parser with the list of valid values, not by the command.
+#[derive(ValueEnum, Clone, Debug)]
+pub(crate) enum DecryptOnlyAction {
+ Decrypt,
+}
+
/// Loads the key from `--key-file` (raw bytes; hex with `--hex-input`) or `--key` (hex), and
/// checks its length.
///
@@ -232,11 +236,70 @@ pub(crate) fn start_encryptor(
/// the ciphertext; see [`start_encryptor`]. `aligned_mode` names a mode whose input must be a
/// whole number of blocks, for the error that reports a partial one (ECB under `NoPadding`); it is
/// `None` for a padded mode, which takes any length.
-pub(crate) fn encrypt_stream(
+pub(crate) fn encrypt_stream(
+ enc: E,
+ generated_iv: Option<&[u8; INIT_DATA_LEN]>,
+ output_hex: bool,
+ aligned_mode: Option<&str>,
+) where
+ E: SymmetricCipherEncryptor,
+{
+ encrypt_stream_bounded::(
+ enc, generated_iv, output_hex, aligned_mode, None,
+ )
+}
+
+/// A bound on how much one invocation may encrypt under its key, for an algorithm whose
+/// standard limits the data a key may protect: the command refuses input past `max_bytes` with
+/// `message` on stderr and an error exit, before any byte past the bound is processed.
+pub(crate) struct InputLimit {
+ pub(crate) max_bytes: u64,
+ pub(crate) message: &'static str,
+}
+
+/// SP 800-67 Rev 2 Sec 3.4: "One key bundle shall not be used to apply cryptographic protection
+/// (e.g., encrypt) more than 2^20 64-bit data blocks", 8 MiB for a mode that passes each 8 bytes
+/// of input through TDEA once (ECB, CBC, CFB64, CTR). The bound counts blocks the cipher
+/// processes, so a mode that invokes TDEA more often per byte has a lower figure below. The
+/// command is the one place that sees a bundle's whole use within an invocation, so it holds the
+/// input to that; it cannot count across invocations.
+pub(crate) const TDEA_LIMIT: InputLimit = InputLimit {
+ max_bytes: 1 << 23,
+ message: "TDEA: one key bundle may protect at most 2^20 blocks (8 MiB; SP 800-67 Rev 2 Sec \
+ 3.4), and the input exceeds that",
+};
+
+/// The same bound for a padded mode, whose padding adds up to one block: one byte less, so the
+/// padded message still fits.
+pub(crate) const TDEA_LIMIT_PADDED: InputLimit =
+ InputLimit { max_bytes: (1 << 23) - 1, message: TDEA_LIMIT.message };
+
+/// The bound for CFB8, which enciphers one block per byte (SP 800-38A Sec 6.3, `s = 8`): 2^20
+/// blocks is 2^20 bytes, 1 MiB.
+pub(crate) const TDEA_LIMIT_CFB8: InputLimit = InputLimit {
+ max_bytes: 1 << 20,
+ message: "TDEA: one key bundle may protect at most 2^20 blocks (SP 800-67 Rev 2 Sec 3.4), and \
+ CFB8 enciphers one block per byte, so the input exceeds that at 1 MiB",
+};
+
+/// The bound for TKW, whose wrapping function makes six TDEA calls per 4-byte semiblock of
+/// plaintext (SP 800-38F Algorithm 7, `s = 6(n - 1)`): 2^20 blocks is `2^20 / 6` semiblocks,
+/// 699,048 bytes.
+pub(crate) const TDEA_LIMIT_TKW: InputLimit = InputLimit {
+ max_bytes: (1 << 20) / 6 * 4,
+ message: "TDEA: one key bundle may protect at most 2^20 blocks (SP 800-67 Rev 2 Sec 3.4), and \
+ TKW makes six TDEA calls per 4-byte block of input, so the input exceeds that at \
+ 699,048 bytes",
+};
+
+/// [`encrypt_stream`] under an [`InputLimit`]: the running input total is checked against the
+/// bound before each chunk is encrypted, so nothing past it is ever written.
+pub(crate) fn encrypt_stream_bounded(
mut enc: E,
generated_iv: Option<&[u8; INIT_DATA_LEN]>,
output_hex: bool,
aligned_mode: Option<&str>,
+ limit: Option<&InputLimit>,
) where
E: SymmetricCipherEncryptor,
{
@@ -246,8 +309,17 @@ pub(crate) fn encrypt_stream(
write_bytes_or_hex(iv, output_hex);
}
+ const { assert!(CHUNK_LEN.is_multiple_of(BLOCK_LEN), "the chunk must be whole blocks") };
let mut out = [0u8; CHUNK_LEN];
+ let mut seen: u64 = 0;
let total = stream_chunks(|data| {
+ seen += data.len() as u64;
+ if let Some(limit) = limit
+ && seen > limit.max_bytes
+ {
+ eprintln!("Error: {}", limit.message);
+ exit(-1);
+ }
// Cannot fail: `out` has room for every whole block of `data` plus the fewer than
// `BLOCK_LEN` bytes held over from the last call, and none of these modes has a per-IV
// data limit.
@@ -256,7 +328,7 @@ pub(crate) fn encrypt_stream(
});
if let Some(mode) = aligned_mode {
- check_aligned(mode, total);
+ check_aligned::(mode, total);
}
// The padded final block; under `NoPadding` an aligned message has none, and this reports 0.
let (last, last_len) = enc.do_encrypt_final().unwrap_or_else(|e| {
@@ -271,7 +343,7 @@ pub(crate) fn encrypt_stream(
/// Decrypts stdin to stdout through the worker `make_decryptor` gives for the init data (the IV):
/// `iv` if it was supplied, else the first `INIT_DATA_LEN` bytes of input -- one block for CBC,
/// nothing for ECB. `aligned_mode` is as for [`encrypt_stream`].
-pub(crate) fn decrypt_stream(
+pub(crate) fn decrypt_stream(
iv: Option<[u8; INIT_DATA_LEN]>,
make_decryptor: impl FnOnce(&[u8; INIT_DATA_LEN]) -> D,
output_hex: bool,
@@ -306,7 +378,7 @@ pub(crate) fn decrypt_stream(
});
if let Some(mode) = aligned_mode {
- check_aligned(mode, total);
+ check_aligned::(mode, total);
}
// Releases the block held back above, unpadded; under `NoPadding` all of it is data. A
// padded ciphertext that is unaligned or has malformed padding fails here.
@@ -343,7 +415,7 @@ fn stream_chunks(mut process: impl FnMut(&[u8])) -> usize {
/// Exits with an error if `total` is not a whole number of blocks, for a mode that is defined only
/// on whole blocks and pads nothing. `NoPadding` would also refuse it at `do_*_final`, but without
/// saying how many bytes were left over.
-fn check_aligned(mode: &str, total: usize) {
+fn check_aligned(mode: &str, total: usize) {
if !total.is_multiple_of(BLOCK_LEN) {
// Everything before the misaligned tail has already been written (bar the one block a
// decryptor holds back until `do_decrypt_final`), and in hex mode is
diff --git a/cli/src/helpers/stream_mode_helpers.rs b/cli/src/helpers/stream_mode_helpers.rs
index 884803d9..713af2c8 100644
--- a/cli/src/helpers/stream_mode_helpers.rs
+++ b/cli/src/helpers/stream_mode_helpers.rs
@@ -28,7 +28,7 @@
//! stdin is read as binary so the commands compose in a pipeline. `-x` renders the *output* as hex.
//! For hex input, pipe through `hex-decode` first.
-use crate::helpers::block_mode_helpers::{CHUNK_LEN, CipherDirection, start_encryptor};
+use crate::helpers::block_mode_helpers::{CHUNK_LEN, CipherDirection, InputLimit, start_encryptor};
use crate::helpers::{flush_stdout, write_bytes_or_hex, write_stdout};
use bouncycastle::core::symmetric_key::{SymmetricDecryptionKey, SymmetricEncryptionKey};
use bouncycastle::core::traits::{StreamCipherDecryptor, StreamCipherEncryptor};
@@ -37,13 +37,16 @@ use std::io::Read;
use std::process::exit;
/// Encrypts stdin to stdout under the key's stream mode. With no `iv`, the IV is generated and
-/// written first; with one, it is used and the output is ciphertext only.
+/// written first; with one, it is used and the output is ciphertext only. Under an
+/// [`InputLimit`], the running input total is checked against the bound before each chunk is
+/// encrypted, so nothing past it is ever written.
///
/// `INIT_DATA_LEN` is the mode's: one block for CFB and CFB8, 12 bytes for CTR.
pub(crate) fn encrypt_stream<'k, K, const KEY_LEN: usize, const INIT_DATA_LEN: usize>(
key: &'k K,
iv: Option<[u8; INIT_DATA_LEN]>,
output_hex: bool,
+ limit: Option<&InputLimit>,
) where
K: SymmetricEncryptionKey,
K::Encryptor<'k>: StreamCipherEncryptor,
@@ -58,7 +61,15 @@ pub(crate) fn encrypt_stream<'k, K, const KEY_LEN: usize, const INIT_DATA_LEN: u
}
// The cipher works in place: `data` holds plaintext on the way in and ciphertext on the way out.
+ let mut seen: u64 = 0;
stream(|data| {
+ seen += data.len() as u64;
+ if let Some(limit) = limit
+ && seen > limit.max_bytes
+ {
+ eprintln!("Error: {}", limit.message);
+ exit(-1);
+ }
// Cannot fail: neither CFB nor CFB8 has a per-IV data limit.
// CFB and CFB8 cannot fail here; CTR can, once its counter is exhausted, which is a real
// limit a long enough stream reaches rather than a bug.
@@ -152,10 +163,26 @@ pub(crate) fn run_stream_mode<'k, K, const KEY_LEN: usize, const INIT_DATA_LEN:
+ SymmetricDecryptionKey,
K::Encryptor<'k>: StreamCipherEncryptor,
K::Decryptor<'k>: StreamCipherDecryptor,
+{
+ run_stream_mode_bounded::(action, key, iv, output_hex, None)
+}
+
+/// [`run_stream_mode`] with an [`InputLimit`] on the encrypting direction.
+pub(crate) fn run_stream_mode_bounded<'k, K, const KEY_LEN: usize, const INIT_DATA_LEN: usize>(
+ action: &CipherDirection,
+ key: &'k K,
+ iv: Option<[u8; INIT_DATA_LEN]>,
+ output_hex: bool,
+ limit: Option<&InputLimit>,
+) where
+ K: SymmetricEncryptionKey
+ + SymmetricDecryptionKey,
+ K::Encryptor<'k>: StreamCipherEncryptor,
+ K::Decryptor<'k>: StreamCipherDecryptor,
{
match action {
CipherDirection::Encrypt => {
- encrypt_stream::(key, iv, output_hex)
+ encrypt_stream::(key, iv, output_hex, limit)
}
CipherDirection::Decrypt => {
decrypt_stream::(key, iv, output_hex)
diff --git a/cli/src/kw_cmd.rs b/cli/src/kw_cmd.rs
index 5715ccc9..b2371c13 100644
--- a/cli/src/kw_cmd.rs
+++ b/cli/src/kw_cmd.rs
@@ -46,7 +46,7 @@
//! | bc-rust aes128-kw -d encrypt --key 000102030405060708090a0b0c0d0e0f -x
//! ```
-use crate::helpers::block_mode_helpers::{CipherDirection, load_key_object};
+use crate::helpers::block_mode_helpers::{CipherDirection, InputLimit, load_key_object};
use crate::helpers::write_bytes_or_hex;
use bouncycastle::cipher::BlockCipherKey;
use bouncycastle::cipher::modes::ModeNames;
@@ -72,6 +72,7 @@ pub(crate) fn kw_cmd(
run::<_, KEY_LEN>(
direction,
&load_key_object::, KEY_LEN>(key, key_file, &alg),
+ None,
output_hex,
&alg,
);
@@ -91,29 +92,52 @@ pub(crate) fn kwp_cmd(
run::<_, KEY_LEN>(
direction,
&load_key_object::, KEY_LEN>(key, key_file, &alg),
+ None,
output_hex,
&alg,
);
}
/// Reads all of stdin, wraps or unwraps it under `kek`, and writes the result. `alg` names the
-/// algorithm in error messages.
-fn run(direction: &CipherDirection, kek: &K, output_hex: bool, alg: &str)
-where
+/// algorithm in error messages. Shared with the other block ciphers' key-wrap commands.
+pub(crate) fn run(
+ direction: &CipherDirection,
+ kek: &K,
+ limit: Option<&InputLimit>,
+ output_hex: bool,
+ alg: &str,
+) where
K: KeyWrappingKey + KeyUnwrappingKey,
{
+ match direction {
+ CipherDirection::Encrypt => run_with(|input| kek.wrap(input), limit, output_hex, alg),
+ CipherDirection::Decrypt => run_with(|input| kek.unwrap(input), None, output_hex, alg),
+ }
+}
+
+/// Reads all of stdin, applies `op` to it and writes the result; the unwrap-only commands pass
+/// their key's `unwrap` alone, so that no wrapper is ever instantiated for their key type.
+/// `limit`, for a wrapping command whose standard bounds what one key may protect, is checked
+/// against the whole input before `op` runs.
+pub(crate) fn run_with(
+ op: impl FnOnce(&[u8]) -> Result, SymmetricCipherError>,
+ limit: Option<&InputLimit>,
+ output_hex: bool,
+ alg: &str,
+) {
let mut input = Vec::new();
if let Err(e) = std::io::stdin().read_to_end(&mut input) {
eprintln!("Error: couldn't read stdin: {e}");
exit(-1);
}
+ if let Some(limit) = limit
+ && input.len() as u64 > limit.max_bytes
+ {
+ eprintln!("Error: {}", limit.message);
+ exit(-1);
+ }
- let result = match direction {
- CipherDirection::Encrypt => kek.wrap(&input),
- CipherDirection::Decrypt => kek.unwrap(&input),
- };
-
- match result {
+ match op(&input) {
Ok(output) => write_bytes_or_hex(&output, output_hex),
Err(SymmetricCipherError::DecryptionFailed) => {
eprintln!(
diff --git a/cli/src/main.rs b/cli/src/main.rs
index 01569006..c2eda64e 100644
--- a/cli/src/main.rs
+++ b/cli/src/main.rs
@@ -27,6 +27,17 @@ mod sha2_cmd;
mod sha3_cmd;
mod sm2_cmd;
mod sm3_cmd;
+mod tdes2_cbc_cmd;
+mod tdes2_cfb8_cmd;
+mod tdes2_cfb_cmd;
+mod tdes2_ctr_cmd;
+mod tdes2_ecb_cmd;
+mod tdes_cbc_cmd;
+mod tdes_cfb8_cmd;
+mod tdes_cfb_cmd;
+mod tdes_ctr_cmd;
+mod tdes_ecb_cmd;
+mod tdes_tkw_cmd;
use crate::blake2_cmd::BLAKE2Variant;
use crate::eccdh_cmd::ECCDHAction;
@@ -50,7 +61,7 @@ use bouncycastle::concatkdf::{
use bouncycastle::sm4::hazmat::SM4Internal;
use bouncycastle::x963kdf::{X963KDF_SHA256, X963KDF_SHA384, X963KDF_SHA512};
use clap::{Parser, Subcommand};
-use helpers::block_mode_helpers::CipherDirection;
+use helpers::block_mode_helpers::{CipherDirection, DecryptOnlyAction};
#[derive(Parser)]
#[command(version, about, long_about=None, arg_required_else_help=true)]
@@ -3390,6 +3401,64 @@ enum Subcommands {
x: bool,
},
+ /// Triple DES Key Wrap, TKW (NIST SP 800-38F Sec 7): `-d encrypt` wraps stdin to stdout,
+ /// `-d decrypt` unwraps it. LEGACY ONLY: SP 800-38F approves TKW to support legacy systems
+ /// and says it should not be used for new applications.
+ ///
+ /// The same command as `aes128-kw` over TDEA at half the width: input to `encrypt` is a whole
+ /// number of 4-byte blocks, at least 8 bytes, and the output is 4 bytes longer; input to
+ /// `decrypt` is a whole number of 4-byte blocks, at least 12 bytes. There is NO IV, and the
+ /// whole input is read before anything is written. See `aes128-kw` for the rest.
+ ///
+ /// `encrypt` refuses input past the SP 800-67 Rev 2 Sec 3.4 bound, counted as the blocks
+ /// TDEA processes: TKW makes six calls per 4-byte block of input, so at most 699,048 bytes.
+ ///
+ /// The key is 24 bytes, KEY1 || KEY2 || KEY3, with three distinct component keys none of which
+ /// is a weak DES key (SP 800-67 Rev 2 Sec 3.1 and 3.3.2). Two-key TDEA unwraps through
+ /// `tdes2-tkw`.
+ ///
+ /// 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.
+ TDES_TKW {
+ #[arg(short, long)]
+ direction: CipherDirection,
+
+ /// The 24-byte TDES key-encryption key bundle in hex.
+ /// The `key_file` option is preferred to avoid leaving key material in command history.
+ #[arg(long)]
+ key: Option,
+
+ /// A file containing the 24-byte TDES key-encryption key bundle (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,
+
+ #[arg(short)]
+ /// Output in hex format.
+ x: bool,
+ },
+
+ /// Two-key Triple DES Key Wrap (2TDEA TKW), UNWRAPPING ONLY. See `tdes2-cbc` for why there is
+ /// no `encrypt`, and `tdes-tkw` for the input rules.
+ TDES2_TKW {
+ #[arg(short = 'd', long = "direction")]
+ action: DecryptOnlyAction,
+
+ /// The 16-byte two-key TDES bundle in hex.
+ /// The `key_file` option is preferred to avoid leaving key material in command history.
+ #[arg(long)]
+ key: Option,
+
+ /// A file containing the 16-byte two-key TDES bundle (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,
+
+ #[arg(short)]
+ /// Output in hex format.
+ x: bool,
+ },
+
/// The ML-KEM-512 key encapsulation algorithm.
MLKEM512 {
action: mlkem_cmd::MLKEMAction,
@@ -5660,6 +5729,386 @@ enum Subcommands {
x: bool,
},
+ /// Triple DES (three-key TDEA, NIST SP 800-67 Rev 2) in CBC mode (SP 800-38A Sec 6.2) with
+ /// PKCS7 padding, streaming stdin to stdout. LEGACY: NIST disallows TDEA for encryption after
+ /// 2023 (SP 800-131A Rev 2); this exists for data and protocols that still depend on it.
+ ///
+ /// On `encrypt`, a fresh unpredictable IV is generated and written as the FIRST 8 BYTES of the
+ /// output; on `decrypt` it is read back from the first 8 bytes of the input, so the two compose
+ /// directly in a pipeline. With `--iv` (hex) or `--iv-file` (raw bytes; hex with --hex-input), the IV is supplied
+ /// instead: `encrypt` uses it and writes ONLY the ciphertext, and `decrypt` reads ONLY
+ /// ciphertext from stdin, as for `aes128-cbc`.
+ ///
+ /// Input may be any length: it is padded with PKCS7 to a whole number of 8-byte blocks, so the
+ /// ciphertext after the IV is 1 to 8 bytes longer than the plaintext, and `decrypt` rejects a
+ /// ciphertext whose padding is malformed.
+ ///
+ /// The key is 24 bytes, KEY1 || KEY2 || KEY3, with three distinct component keys none of which
+ /// is a weak DES key (SP 800-67 Rev 2 Sec 3.1 and 3.3.2). Two-key TDEA decrypts through the
+ /// `tdes2-*` commands.
+ ///
+ /// WARNING: CBC provides confidentiality only. It does not detect tampering, and neither the
+ /// ciphertext nor the IV is authenticated. Do not decrypt data you have not authenticated
+ /// separately. One key bundle must not encrypt more than 2^20 blocks (8 MiB) in total:
+ /// `encrypt` refuses longer input, and counting across invocations is the caller's.
+ ///
+ /// 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.
+ TDES_CBC {
+ #[arg(short, long)]
+ direction: CipherDirection,
+
+ /// The 24-byte TDES key bundle in hex.
+ /// The `key_file` option is preferred to avoid leaving key material in command history.
+ #[arg(long)]
+ key: Option,
+
+ /// A file containing the 24-byte TDES key bundle (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 8-byte IV in hex. Supplied instead of generated: `encrypt` then writes no IV and
+ /// `decrypt` reads none. See the IV paragraph above.
+ #[arg(long, visible_alias = "nonce")]
+ iv: Option,
+
+ /// A file containing the 8-byte IV, (raw bytes; hex with --hex-input).
+ /// If both iv and iv_file options are provided, the file will be used.
+ #[arg(long, visible_alias = "nonce-file")]
+ iv_file: Option,
+
+ #[arg(short)]
+ /// Output in hex format.
+ x: bool,
+ },
+
+ /// Triple DES (three-key TDEA) in CFB64 mode (SP 800-38A Sec 6.3, segment = block), streaming
+ /// stdin to stdout. LEGACY: see `tdes-cbc`.
+ ///
+ /// The segment size is the full 8-byte block, i.e. CFB64. SP 800-38A's 8-bit CFB is a
+ /// different, non-interoperable mode; use `tdes-cfb8` for that.
+ ///
+ /// On `encrypt`, a fresh unpredictable IV is generated and written as the FIRST 8 BYTES of the
+ /// output; on `decrypt` it is read back from the first 8 bytes of the input. With `--iv` (hex)
+ /// or `--iv-file` (raw bytes; hex with --hex-input), the IV is supplied instead and only ciphertext is written or
+ /// read.
+ ///
+ /// Input may be ANY length: CFB is a stream cipher, so nothing is padded and the ciphertext is
+ /// exactly as long as the plaintext.
+ ///
+ /// See `tdes-cbc` for the key format and the warnings, which apply unchanged.
+ TDES_CFB {
+ #[arg(short, long)]
+ direction: CipherDirection,
+
+ /// The 24-byte TDES key bundle in hex.
+ /// The `key_file` option is preferred to avoid leaving key material in command history.
+ #[arg(long)]
+ key: Option,
+
+ /// A file containing the 24-byte TDES key bundle (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 8-byte IV in hex. Supplied instead of generated: `encrypt` then writes no IV and
+ /// `decrypt` reads none. See the IV paragraph above.
+ #[arg(long, visible_alias = "nonce")]
+ iv: Option,
+
+ /// A file containing the 8-byte IV, (raw bytes; hex with --hex-input).
+ /// If both iv and iv_file options are provided, the file will be used.
+ #[arg(long, visible_alias = "nonce-file")]
+ iv_file: Option,
+
+ #[arg(short)]
+ /// Output in hex format.
+ x: bool,
+ },
+
+ /// Triple DES (three-key TDEA) in CFB8 mode (SP 800-38A Sec 6.3, s = 8), streaming stdin to
+ /// stdout. LEGACY: see `tdes-cbc`.
+ ///
+ /// CFB8 is a DIFFERENT mode from `tdes-cfb`, not a variant: the two ciphertexts agree only on
+ /// their first byte. It also costs one TDES call per byte, eight times the work of `tdes-cfb`,
+ /// so prefer that unless a byte-granular mode is specifically required. That is also why
+ /// `encrypt` here refuses input past 2^20 bytes (1 MiB): the SP 800-67 Rev 2 Sec 3.4 bound
+ /// counts the blocks TDEA processes, one per byte in this mode.
+ ///
+ /// See `tdes-cfb` for the IV convention and input-length rule, and `tdes-cbc` for the key
+ /// format and the warnings, which apply unchanged.
+ TDES_CFB8 {
+ #[arg(short, long)]
+ direction: CipherDirection,
+
+ /// The 24-byte TDES key bundle in hex.
+ /// The `key_file` option is preferred to avoid leaving key material in command history.
+ #[arg(long)]
+ key: Option,
+
+ /// A file containing the 24-byte TDES key bundle (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 8-byte IV in hex. Supplied instead of generated: `encrypt` then writes no IV and
+ /// `decrypt` reads none. See the IV paragraph above.
+ #[arg(long, visible_alias = "nonce")]
+ iv: Option,
+
+ /// A file containing the 8-byte IV, (raw bytes; hex with --hex-input).
+ /// If both iv and iv_file options are provided, the file will be used.
+ #[arg(long, visible_alias = "nonce-file")]
+ iv_file: Option,
+
+ #[arg(short)]
+ /// Output in hex format.
+ x: bool,
+ },
+
+ /// Triple DES (three-key TDEA) in CTR mode (SP 800-38A Sec 6.5, TDEA per its Appendix E),
+ /// streaming stdin to stdout. LEGACY: see `tdes-cbc`.
+ /// On `encrypt`, a fresh 6-BYTE NONCE is generated and written as the first 6 bytes of the
+ /// output; on `decrypt` it is read back from the first 6 bytes of the input. With `--iv` (hex)
+ /// or `--iv-file` (raw bytes; hex with --hex-input), the nonce is supplied instead and only
+ /// ciphertext is written or read; it MUST then be unique per message under one key bundle. The
+ /// remaining 2 bytes of the 8-byte counter block are the counter, so a single message is
+ /// limited to 65 536 blocks (512 KiB); longer input fails rather than repeating a counter
+ /// block.
+ ///
+ /// Input may be any length up to that limit: CTR is a stream cipher, so nothing is padded and
+ /// the ciphertext is exactly as long as the plaintext.
+ ///
+ /// WARNING: CTR provides confidentiality only, and is the most malleable of the modes here: a
+ /// flipped ciphertext bit flips exactly the corresponding plaintext bit. A repeated nonce under
+ /// one key is fatal, and the nonce is only 48 bits, so the number of messages under one key
+ /// bundle must stay small. See `tdes-cbc` for the key format and the other warnings.
+ TDES_CTR {
+ #[arg(short, long)]
+ direction: CipherDirection,
+
+ /// The 24-byte TDES key bundle in hex.
+ /// The `key_file` option is preferred to avoid leaving key material in command history.
+ #[arg(long)]
+ key: Option,
+
+ /// A file containing the 24-byte TDES key bundle (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 6-byte nonce in hex. Supplied instead of generated: `encrypt` then writes none
+ /// and `decrypt` reads none. See the nonce paragraph above.
+ #[arg(long, visible_alias = "nonce")]
+ iv: Option,
+
+ /// A file containing the 6-byte nonce (raw bytes; hex with --hex-input). If both iv and
+ /// iv_file options are provided, the file will be used.
+ #[arg(long, visible_alias = "nonce-file")]
+ iv_file: Option,
+
+ #[arg(short)]
+ /// Output in hex format.
+ x: bool,
+ },
+
+ /// Triple DES (three-key TDEA) in ECB mode (SP 800-38A Sec 6.1), streaming stdin to stdout.
+ /// LEGACY: see `tdes-cbc`.
+ ///
+ /// WARNING: ECB is NOT a confidentiality mode for data. Under a given key every plaintext
+ /// block maps to the same ciphertext block, so equal blocks stay visibly equal, the same input
+ /// always gives the same output, and blocks can be reordered, repeated or removed undetectably.
+ /// This command exists for interoperability with systems that require ECB and for test
+ /// vectors.
+ ///
+ /// There is NO IV: nothing is prepended on `encrypt` and nothing is consumed on `decrypt`, so
+ /// the output is exactly as long as the input.
+ ///
+ /// Input must be a whole number of 8-byte blocks: this command is block-aligned and applies no
+ /// padding, so unaligned input is rejected rather than padded.
+ ///
+ /// See `tdes-cbc` for the key format.
+ TDES_ECB {
+ #[arg(short, long)]
+ direction: CipherDirection,
+
+ /// The 24-byte TDES key bundle in hex.
+ /// The `key_file` option is preferred to avoid leaving key material in command history.
+ #[arg(long)]
+ key: Option,
+
+ /// A file containing the 24-byte TDES key bundle (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,
+
+ #[arg(short)]
+ /// Output in hex format.
+ x: bool,
+ },
+
+ /// Two-key Triple DES (2TDEA, Key3 = Key1) in CBC mode, DECRYPTION ONLY, streaming stdin to
+ /// stdout. NIST SP 800-131A Rev 2 Table 1 disallows two-key TDEA for encryption and allows
+ /// decryption for legacy use, so `encrypt` does not exist for this command. That is a guard
+ /// against accidental encryption: `tdes2-cfb` and `tdes2-ctr` decryption are the forward
+ /// cipher, which a determined caller can turn into encryption, so a deployment that must rule
+ /// that out should expose only `tdes2-cbc` and `tdes2-ecb`.
+ ///
+ /// The first 8 bytes of input are the IV, as the `tdes-cbc decrypt` convention, unless `--iv`
+ /// or `--iv-file` supplies it; the rest is PKCS7-padded ciphertext, as `tdes-cbc` writes it.
+ ///
+ /// The key is 16 bytes, KEY1 || KEY2, with two distinct component keys neither of which is a
+ /// weak DES key (SP 800-67 Rev 2 Sec 3.1 and 3.3.2).
+ ///
+ /// 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.
+ TDES2_CBC {
+ #[arg(short = 'd', long = "direction")]
+ action: DecryptOnlyAction,
+
+ /// The 16-byte two-key TDES bundle in hex.
+ /// The `key_file` option is preferred to avoid leaving key material in command history.
+ #[arg(long)]
+ key: Option,
+
+ /// A file containing the 16-byte two-key TDES bundle (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 8-byte IV in hex. Supplied instead of read from the input, which is then
+ /// ciphertext only.
+ #[arg(long, visible_alias = "nonce")]
+ iv: Option,
+
+ /// A file containing the 8-byte IV, (raw bytes; hex with --hex-input).
+ /// If both iv and iv_file options are provided, the file will be used.
+ #[arg(long, visible_alias = "nonce-file")]
+ iv_file: Option,
+
+ #[arg(short)]
+ /// Output in hex format.
+ x: bool,
+ },
+
+ /// Two-key Triple DES (2TDEA) in CFB64 mode, DECRYPTION ONLY. See `tdes2-cbc` for why there is
+ /// no `encrypt`, and `tdes-cfb` for the IV convention (first 8 bytes of input, or `--iv`) and
+ /// the any-length input rule.
+ TDES2_CFB {
+ #[arg(short = 'd', long = "direction")]
+ action: DecryptOnlyAction,
+
+ /// The 16-byte two-key TDES bundle in hex.
+ /// The `key_file` option is preferred to avoid leaving key material in command history.
+ #[arg(long)]
+ key: Option,
+
+ /// A file containing the 16-byte two-key TDES bundle (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 8-byte IV in hex. Supplied instead of read from the input, which is then
+ /// ciphertext only.
+ #[arg(long, visible_alias = "nonce")]
+ iv: Option,
+
+ /// A file containing the 8-byte IV, (raw bytes; hex with --hex-input).
+ /// If both iv and iv_file options are provided, the file will be used.
+ #[arg(long, visible_alias = "nonce-file")]
+ iv_file: Option,
+
+ #[arg(short)]
+ /// Output in hex format.
+ x: bool,
+ },
+
+ /// Two-key Triple DES (2TDEA) in CFB8 mode, DECRYPTION ONLY. See `tdes2-cbc` for why there is
+ /// no `encrypt`, and `tdes-cfb8` for the IV convention and the difference from CFB64.
+ TDES2_CFB8 {
+ #[arg(short = 'd', long = "direction")]
+ action: DecryptOnlyAction,
+
+ /// The 16-byte two-key TDES bundle in hex.
+ /// The `key_file` option is preferred to avoid leaving key material in command history.
+ #[arg(long)]
+ key: Option,
+
+ /// A file containing the 16-byte two-key TDES bundle (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 8-byte IV in hex. Supplied instead of read from the input, which is then
+ /// ciphertext only.
+ #[arg(long, visible_alias = "nonce")]
+ iv: Option,
+
+ /// A file containing the 8-byte IV, (raw bytes; hex with --hex-input).
+ /// If both iv and iv_file options are provided, the file will be used.
+ #[arg(long, visible_alias = "nonce-file")]
+ iv_file: Option,
+
+ #[arg(short)]
+ /// Output in hex format.
+ x: bool,
+ },
+
+ /// Two-key Triple DES (2TDEA) in CTR mode, DECRYPTION ONLY. See `tdes2-cbc` for why there is
+ /// no `encrypt`, and `tdes-ctr` for the nonce convention (first 6 bytes of input, or `--iv`)
+ /// and the 512 KiB per-message limit.
+ TDES2_CTR {
+ #[arg(short = 'd', long = "direction")]
+ action: DecryptOnlyAction,
+
+ /// The 16-byte two-key TDES bundle in hex.
+ /// The `key_file` option is preferred to avoid leaving key material in command history.
+ #[arg(long)]
+ key: Option,
+
+ /// A file containing the 16-byte two-key TDES bundle (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 6-byte nonce in hex. Supplied instead of read from the input, which is then
+ /// ciphertext only.
+ #[arg(long, visible_alias = "nonce")]
+ iv: Option,
+
+ /// A file containing the 6-byte nonce (raw bytes; hex with --hex-input). If both iv and
+ /// iv_file options are provided, the file will be used.
+ #[arg(long, visible_alias = "nonce-file")]
+ iv_file: Option,
+
+ #[arg(short)]
+ /// Output in hex format.
+ x: bool,
+ },
+
+ /// Two-key Triple DES (2TDEA) in ECB mode, DECRYPTION ONLY. See `tdes2-cbc` for why there is
+ /// no `encrypt`, and `tdes-ecb` for the ECB warning: no IV, input a whole number of 8-byte
+ /// blocks, no unpadding.
+ TDES2_ECB {
+ #[arg(short = 'd', long = "direction")]
+ action: DecryptOnlyAction,
+
+ /// The 16-byte two-key TDES bundle in hex.
+ /// The `key_file` option is preferred to avoid leaving key material in command history.
+ #[arg(long)]
+ key: Option,
+
+ /// A file containing the 16-byte two-key TDES bundle (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,
+
+ #[arg(short)]
+ /// Output in hex format.
+ x: bool,
+ },
+
/// Perform TupleHash128 (NIST SP 800-185 Sec 5) over a tuple of strings. The tuple is given
/// by repeated --element flags, each in hex; with none, stdin is hashed as a single element.
/// The boundaries between elements are part of the hash.
@@ -5756,7 +6205,7 @@ enum Subcommands {
fn main() {
std::thread::Builder::new()
.name("bc-rust-main".to_string())
- .stack_size(8 * 1024 * 1024)
+ .stack_size(32 * 1024 * 1024)
.spawn(run)
.expect("failed to start CLI thread")
.join()
@@ -6492,6 +6941,12 @@ fn run() {
Some(Subcommands::SM4_KWP { direction, key, key_file, x }) => {
kw_cmd::kwp_cmd::(direction, key, key_file, *x, "SM4");
}
+ Some(Subcommands::TDES_TKW { direction, key, key_file, x }) => {
+ tdes_tkw_cmd::tdes_tkw_cmd(direction, key, key_file, *x);
+ }
+ Some(Subcommands::TDES2_TKW { action, key, key_file, x }) => {
+ tdes_tkw_cmd::tdes2_tkw_cmd(action, key, key_file, *x);
+ }
Some(Subcommands::MLKEM512 { action, skfile, pkfile, ctfile, x }) => {
mlkem_cmd::mlkem_cmd(&mlkem_cmd::MLKEM512_SET, action, skfile, pkfile, ctfile, *x);
}
@@ -6991,6 +7446,36 @@ fn run() {
direction, key, key_file, iv, iv_file, aad, aad_file, *x, "SM4",
);
}
+ Some(Subcommands::TDES_CBC { direction, key, key_file, iv, iv_file, x }) => {
+ tdes_cbc_cmd::tdes_cbc_cmd(direction, key, key_file, iv, iv_file, *x);
+ }
+ Some(Subcommands::TDES_CFB { direction, key, key_file, iv, iv_file, x }) => {
+ tdes_cfb_cmd::tdes_cfb_cmd(direction, key, key_file, iv, iv_file, *x);
+ }
+ Some(Subcommands::TDES_CFB8 { direction, key, key_file, iv, iv_file, x }) => {
+ tdes_cfb8_cmd::tdes_cfb8_cmd(direction, key, key_file, iv, iv_file, *x);
+ }
+ Some(Subcommands::TDES_CTR { direction, key, key_file, iv, iv_file, x }) => {
+ tdes_ctr_cmd::tdes_ctr_cmd(direction, key, key_file, iv, iv_file, *x);
+ }
+ Some(Subcommands::TDES_ECB { direction, key, key_file, x }) => {
+ tdes_ecb_cmd::tdes_ecb_cmd(direction, key, key_file, *x);
+ }
+ Some(Subcommands::TDES2_CBC { action, key, key_file, iv, iv_file, x }) => {
+ tdes2_cbc_cmd::tdes2_cbc_cmd(action, key, key_file, iv, iv_file, *x);
+ }
+ Some(Subcommands::TDES2_CFB { action, key, key_file, iv, iv_file, x }) => {
+ tdes2_cfb_cmd::tdes2_cfb_cmd(action, key, key_file, iv, iv_file, *x);
+ }
+ Some(Subcommands::TDES2_CFB8 { action, key, key_file, iv, iv_file, x }) => {
+ tdes2_cfb8_cmd::tdes2_cfb8_cmd(action, key, key_file, iv, iv_file, *x);
+ }
+ Some(Subcommands::TDES2_CTR { action, key, key_file, iv, iv_file, x }) => {
+ tdes2_ctr_cmd::tdes2_ctr_cmd(action, key, key_file, iv, iv_file, *x);
+ }
+ Some(Subcommands::TDES2_ECB { action, key, key_file, x }) => {
+ tdes2_ecb_cmd::tdes2_ecb_cmd(action, key, key_file, *x);
+ }
Some(Subcommands::TUPLEHASH128 {
length,
elements,
diff --git a/cli/src/tdes2_cbc_cmd.rs b/cli/src/tdes2_cbc_cmd.rs
new file mode 100644
index 00000000..6f9b0329
--- /dev/null
+++ b/cli/src/tdes2_cbc_cmd.rs
@@ -0,0 +1,34 @@
+//! Two-key TDES-CBC decryption, streaming stdin to stdout.
+//!
+//! Decryption only: NIST SP 800-131A Rev 2 Table 1 disallows two-key TDEA for encryption,
+//! `TDES2Key::create_encryptor` does not compile, and
+//! [`DecryptOnlyAction`] has no `encrypt`. Everything else is `tdes-cbc decrypt` -- the first 8
+//! bytes of input are the IV unless `--iv` supplies it, the rest PKCS7-padded ciphertext -- see
+//! [`crate::tdes_cbc_cmd`] and [`crate::helpers::block_mode_helpers`]. The key is the 16-byte
+//! `KEY1 || KEY2`.
+
+use crate::helpers::block_mode_helpers::{
+ DecryptOnlyAction, decrypt_stream, load_iv, load_key_object,
+};
+use bouncycastle::cipher::modes::CBC;
+use bouncycastle::cipher::padding::PKCS7;
+use bouncycastle::core::symmetric_key::SymmetricDecryptionKey;
+use bouncycastle::tdes::{BLOCK_LEN, KEY_LEN_2KEY, TDES2Key};
+
+pub(crate) fn tdes2_cbc_cmd(
+ action: &DecryptOnlyAction,
+ key: &Option,
+ key_file: &Option,
+ iv: &Option,
+ iv_file: &Option,
+ output_hex: bool,
+) {
+ let DecryptOnlyAction::Decrypt = action;
+ let key = load_key_object::>, KEY_LEN_2KEY>(key, key_file, "two-key TDES");
+ decrypt_stream::<_, BLOCK_LEN, BLOCK_LEN>(
+ load_iv::(iv, iv_file),
+ |iv| key.create_decryptor(iv),
+ output_hex,
+ None,
+ )
+}
diff --git a/cli/src/tdes2_cfb8_cmd.rs b/cli/src/tdes2_cfb8_cmd.rs
new file mode 100644
index 00000000..ba3828a9
--- /dev/null
+++ b/cli/src/tdes2_cfb8_cmd.rs
@@ -0,0 +1,26 @@
+//! Two-key TDES-CFB8 decryption, streaming stdin to stdout.
+//!
+//! Decryption only: NIST SP 800-131A Rev 2 Table 1 disallows two-key TDEA for encryption,
+//! `TDES2Key::create_encryptor` does not compile, and
+//! [`DecryptOnlyAction`] has no `encrypt`. Everything else is `tdes-cfb8 decrypt` -- the first 8
+//! bytes of input are the IV unless `--iv` supplies it, the rest any length -- see
+//! [`crate::tdes_cfb8_cmd`] for how CFB8 differs from CFB64, and
+//! [`crate::helpers::stream_mode_helpers`]. The key is the 16-byte `KEY1 || KEY2`.
+
+use crate::helpers::block_mode_helpers::{DecryptOnlyAction, load_iv, load_key_object};
+use crate::helpers::stream_mode_helpers::decrypt_stream;
+use bouncycastle::cipher::modes::CFB8;
+use bouncycastle::tdes::{BLOCK_LEN, KEY_LEN_2KEY, TDES2Key};
+
+pub(crate) fn tdes2_cfb8_cmd(
+ action: &DecryptOnlyAction,
+ key: &Option,
+ key_file: &Option,
+ iv: &Option,
+ iv_file: &Option,
+ output_hex: bool,
+) {
+ let DecryptOnlyAction::Decrypt = action;
+ let key = load_key_object::, KEY_LEN_2KEY>(key, key_file, "two-key TDES");
+ decrypt_stream::<_, KEY_LEN_2KEY, BLOCK_LEN>(&key, load_iv(iv, iv_file), output_hex)
+}
diff --git a/cli/src/tdes2_cfb_cmd.rs b/cli/src/tdes2_cfb_cmd.rs
new file mode 100644
index 00000000..677db994
--- /dev/null
+++ b/cli/src/tdes2_cfb_cmd.rs
@@ -0,0 +1,26 @@
+//! Two-key TDES-CFB64 decryption, streaming stdin to stdout.
+//!
+//! Decryption only: NIST SP 800-131A Rev 2 Table 1 disallows two-key TDEA for encryption,
+//! `TDES2Key::create_encryptor` does not compile, and
+//! [`DecryptOnlyAction`] has no `encrypt`. Everything else is `tdes-cfb decrypt` -- the first 8
+//! bytes of input are the IV unless `--iv` supplies it, the rest any length -- see
+//! [`crate::tdes_cfb_cmd`] and
+//! [`crate::helpers::stream_mode_helpers`]. The key is the 16-byte `KEY1 || KEY2`.
+
+use crate::helpers::block_mode_helpers::{DecryptOnlyAction, load_iv, load_key_object};
+use crate::helpers::stream_mode_helpers::decrypt_stream;
+use bouncycastle::cipher::modes::CFB;
+use bouncycastle::tdes::{BLOCK_LEN, KEY_LEN_2KEY, TDES2Key};
+
+pub(crate) fn tdes2_cfb_cmd(
+ action: &DecryptOnlyAction,
+ key: &Option,
+ key_file: &Option,
+ iv: &Option,
+ iv_file: &Option,
+ output_hex: bool,
+) {
+ let DecryptOnlyAction::Decrypt = action;
+ let key = load_key_object::, KEY_LEN_2KEY>(key, key_file, "two-key TDES");
+ decrypt_stream::<_, KEY_LEN_2KEY, BLOCK_LEN>(&key, load_iv(iv, iv_file), output_hex)
+}
diff --git a/cli/src/tdes2_ctr_cmd.rs b/cli/src/tdes2_ctr_cmd.rs
new file mode 100644
index 00000000..0240790e
--- /dev/null
+++ b/cli/src/tdes2_ctr_cmd.rs
@@ -0,0 +1,28 @@
+//! Two-key TDES-CTR decryption, streaming stdin to stdout.
+//!
+//! Decryption only: NIST SP 800-131A Rev 2 Table 1 disallows two-key TDEA for encryption,
+//! `TDES2Key::create_encryptor` does not compile, and
+//! [`DecryptOnlyAction`] has no `encrypt`. Everything else is `tdes-ctr decrypt` -- the first 6
+//! bytes of input are the nonce unless `--iv` supplies it, the counter starts at zero, at most
+//! 512 KiB of data -- see [`crate::tdes_ctr_cmd`] and [`crate::helpers::stream_mode_helpers`].
+//! The key is the 16-byte `KEY1 || KEY2`.
+
+use crate::helpers::block_mode_helpers::{DecryptOnlyAction, load_iv, load_key_object};
+use crate::helpers::stream_mode_helpers::decrypt_stream;
+use bouncycastle::cipher::modes::CTR;
+use bouncycastle::tdes::{BLOCK_LEN, CTR_NONCE_LEN, KEY_LEN_2KEY, TDES2Key};
+
+pub(crate) fn tdes2_ctr_cmd(
+ action: &DecryptOnlyAction,
+ key: &Option,
+ key_file: &Option,
+ iv: &Option,
+ iv_file: &Option,
+ output_hex: bool,
+) {
+ let DecryptOnlyAction::Decrypt = action;
+ let key = load_key_object::>, KEY_LEN_2KEY>(
+ key, key_file, "two-key TDES",
+ );
+ decrypt_stream::<_, KEY_LEN_2KEY, CTR_NONCE_LEN>(&key, load_iv(iv, iv_file), output_hex)
+}
diff --git a/cli/src/tdes2_ecb_cmd.rs b/cli/src/tdes2_ecb_cmd.rs
new file mode 100644
index 00000000..e722fd80
--- /dev/null
+++ b/cli/src/tdes2_ecb_cmd.rs
@@ -0,0 +1,31 @@
+//! Two-key TDES-ECB decryption, streaming stdin to stdout.
+//!
+//! Decryption only: NIST SP 800-131A Rev 2 Table 1 disallows two-key TDEA for encryption,
+//! `TDES2Key::create_encryptor` does not compile, and
+//! [`DecryptOnlyAction`] has no `encrypt`. Everything else is `tdes-ecb decrypt` -- no IV, input a
+//! whole number of 8-byte blocks, no unpadding -- see [`crate::tdes_ecb_cmd`] for the ECB warning
+//! and [`crate::helpers::block_mode_helpers`] for the framing. The key is the 16-byte
+//! `KEY1 || KEY2`.
+
+use crate::helpers::block_mode_helpers::{DecryptOnlyAction, decrypt_stream, load_key_object};
+use bouncycastle::cipher::modes::hazmat::ecb::ECB;
+use bouncycastle::cipher::padding::NoPadding;
+use bouncycastle::core::symmetric_key::SymmetricDecryptionKey;
+use bouncycastle::tdes::{BLOCK_LEN, KEY_LEN_2KEY, TDES2Key};
+
+pub(crate) fn tdes2_ecb_cmd(
+ action: &DecryptOnlyAction,
+ key: &Option,
+ key_file: &Option,
+ output_hex: bool,
+) {
+ let DecryptOnlyAction::Decrypt = action;
+ let key =
+ load_key_object::>, KEY_LEN_2KEY>(key, key_file, "two-key TDES");
+ decrypt_stream::<_, 0, BLOCK_LEN>(
+ None,
+ |no_iv| key.create_decryptor(no_iv),
+ output_hex,
+ Some("ECB"),
+ )
+}
diff --git a/cli/src/tdes_cbc_cmd.rs b/cli/src/tdes_cbc_cmd.rs
new file mode 100644
index 00000000..4cc7a0b8
--- /dev/null
+++ b/cli/src/tdes_cbc_cmd.rs
@@ -0,0 +1,59 @@
+//! TDES-CBC encryption and decryption, streaming stdin to stdout.
+//!
+//! Only the mode wiring lives here: the IV convention, key loading and stdin framing are all in
+//! [`crate::helpers::block_mode_helpers`], shared with the AES commands and `tdes-ecb`. See that
+//! module for the command-line contract. The block, and so the IV, is 8 bytes, and input is
+//! padded with PKCS7, so it may be any length.
+//!
+//! CBC (NIST SP 800-38A Sec 6.2; TCBC in its Appendix E) provides confidentiality only. It does not
+//! detect tampering, and neither the ciphertext nor the IV is authenticated -- a flipped ciphertext
+//! bit flips the same bit of the *next* block's plaintext (Appendix D). Do not decrypt data you
+//! have not authenticated separately.
+//!
+//! TDEA is a legacy algorithm, disallowed for encryption by NIST SP 800-131A Rev 2 after 2023; see
+//! the `bouncycastle-tdes` crate docs. One key bundle must not protect more than 2^20 blocks
+//! (8 MiB) in total (SP 800-67 Rev 2 Sec 3.4): `encrypt` refuses input past that in one
+//! invocation, and nothing is counted across invocations, which is the caller's to track.
+
+use crate::helpers::block_mode_helpers::{
+ CipherDirection, TDEA_LIMIT_PADDED, decrypt_stream, encrypt_stream_bounded, load_iv,
+ load_key_object, start_encryptor,
+};
+use bouncycastle::cipher::modes::CBC;
+use bouncycastle::cipher::padding::PKCS7;
+use bouncycastle::core::symmetric_key::{SymmetricDecryptionKey, SymmetricEncryptionKey};
+use bouncycastle::tdes::{BLOCK_LEN, KEY_LEN, TDES3Key};
+
+pub(crate) fn tdes_cbc_cmd(
+ action: &CipherDirection,
+ key: &Option,
+ key_file: &Option,
+ iv: &Option,
+ iv_file: &Option,
+ output_hex: bool,
+) {
+ let key = load_key_object::>, KEY_LEN>(key, key_file, "TDES");
+ let iv = load_iv::(iv, iv_file);
+ match action {
+ CipherDirection::Encrypt => {
+ let (enc, generated_iv) = start_encryptor(
+ iv,
+ |rng| key.create_encryptor(rng),
+ |iv| key.create_encryptor_nonce(iv),
+ );
+ encrypt_stream_bounded::<_, BLOCK_LEN, BLOCK_LEN>(
+ enc,
+ generated_iv.as_ref(),
+ output_hex,
+ None,
+ Some(&TDEA_LIMIT_PADDED),
+ )
+ }
+ CipherDirection::Decrypt => decrypt_stream::<_, BLOCK_LEN, BLOCK_LEN>(
+ iv,
+ |iv| key.create_decryptor(iv),
+ output_hex,
+ None,
+ ),
+ }
+}
diff --git a/cli/src/tdes_cfb8_cmd.rs b/cli/src/tdes_cfb8_cmd.rs
new file mode 100644
index 00000000..b7b8615c
--- /dev/null
+++ b/cli/src/tdes_cfb8_cmd.rs
@@ -0,0 +1,46 @@
+//! TDES-CFB8 encryption and decryption, streaming stdin to stdout.
+//!
+//! Only the mode wiring lives here: the IV convention, key loading and stdin framing are in
+//! [`crate::helpers::stream_mode_helpers`] (and [`crate::helpers::block_mode_helpers`] for the
+//! key and IV loaders), shared with the
+//! AES stream commands and `tdes-cfb` / `tdes-ctr`. See those modules for the command-line
+//! contract. The block, and so the IV, is 8 bytes.
+//!
+//! CFB8 (SP 800-38A Sec 6.3 with `s = 8`; TCFB with `s = 8` in Appendix E) is a **different,
+//! non-interoperable mode** from `tdes-cfb`: the two ciphertexts agree only on their first byte. It
+//! also costs one TDES call per byte, eight times the work of `tdes-cfb`, so prefer that unless a
+//! byte-granular mode is specifically required. The SP 800-67 Rev 2 Sec 3.4 bound counts the
+//! blocks TDEA processes, so `encrypt` here refuses input past 2^20 bytes, 1 MiB, where the modes
+//! that process one block per 8 bytes allow 8 MiB.
+//!
+//! # Warning
+//!
+//! CFB8 provides confidentiality only. It does not detect tampering, and neither the ciphertext nor
+//! the IV is authenticated. Do not decrypt data you have not authenticated separately.
+//!
+//! TDEA is a legacy algorithm, disallowed for encryption by NIST SP 800-131A Rev 2 after 2023; see
+//! the `bouncycastle-tdes` crate docs.
+
+use crate::helpers::block_mode_helpers::TDEA_LIMIT_CFB8;
+use crate::helpers::block_mode_helpers::{CipherDirection, load_iv, load_key_object};
+use crate::helpers::stream_mode_helpers::run_stream_mode_bounded;
+use bouncycastle::cipher::modes::CFB8;
+use bouncycastle::tdes::{BLOCK_LEN, KEY_LEN, TDES3Key};
+
+pub(crate) fn tdes_cfb8_cmd(
+ action: &CipherDirection,
+ key: &Option,
+ key_file: &Option,
+ iv: &Option,
+ iv_file: &Option,
+ output_hex: bool,
+) {
+ let key = load_key_object::, KEY_LEN>(key, key_file, "TDES");
+ run_stream_mode_bounded::<_, KEY_LEN, BLOCK_LEN>(
+ action,
+ &key,
+ load_iv(iv, iv_file),
+ output_hex,
+ Some(&TDEA_LIMIT_CFB8),
+ )
+}
diff --git a/cli/src/tdes_cfb_cmd.rs b/cli/src/tdes_cfb_cmd.rs
new file mode 100644
index 00000000..1f3edfe4
--- /dev/null
+++ b/cli/src/tdes_cfb_cmd.rs
@@ -0,0 +1,45 @@
+//! TDES-CFB64 encryption and decryption, streaming stdin to stdout.
+//!
+//! Only the mode wiring lives here: the IV convention, key loading and stdin framing are in
+//! [`crate::helpers::stream_mode_helpers`] (and [`crate::helpers::block_mode_helpers`] for the
+//! key and IV loaders), shared with the
+//! AES stream commands and `tdes-cfb8` / `tdes-ctr`. See those modules for the command-line
+//! contract. The block, and so the IV, is 8 bytes; the segment is the full block, so this is CFB64
+//! -- the TCFB mode of SP 800-38A Appendix E with `s = 64`.
+//!
+//! # Any length
+//!
+//! CFB is a stream cipher: input of any length is accepted, nothing is padded, and the output is
+//! exactly as long as the input.
+//!
+//! # Warning
+//!
+//! CFB provides confidentiality only. It does not detect tampering, and neither the ciphertext nor
+//! the IV is authenticated. Do not decrypt data you have not authenticated separately.
+//!
+//! TDEA is a legacy algorithm, disallowed for encryption by NIST SP 800-131A Rev 2 after 2023; see
+//! the `bouncycastle-tdes` crate docs.
+
+use crate::helpers::block_mode_helpers::TDEA_LIMIT;
+use crate::helpers::block_mode_helpers::{CipherDirection, load_iv, load_key_object};
+use crate::helpers::stream_mode_helpers::run_stream_mode_bounded;
+use bouncycastle::cipher::modes::CFB;
+use bouncycastle::tdes::{BLOCK_LEN, KEY_LEN, TDES3Key};
+
+pub(crate) fn tdes_cfb_cmd(
+ action: &CipherDirection,
+ key: &Option,
+ key_file: &Option,
+ iv: &Option,
+ iv_file: &Option,
+ output_hex: bool,
+) {
+ let key = load_key_object::, KEY_LEN>(key, key_file, "TDES");
+ run_stream_mode_bounded::<_, KEY_LEN, BLOCK_LEN>(
+ action,
+ &key,
+ load_iv(iv, iv_file),
+ output_hex,
+ Some(&TDEA_LIMIT),
+ )
+}
diff --git a/cli/src/tdes_ctr_cmd.rs b/cli/src/tdes_ctr_cmd.rs
new file mode 100644
index 00000000..2802f903
--- /dev/null
+++ b/cli/src/tdes_ctr_cmd.rs
@@ -0,0 +1,65 @@
+//! TDES-CTR encryption and decryption, streaming stdin to stdout.
+//!
+//! Only the mode wiring lives here: the nonce convention, key loading and stdin framing are in
+//! [`crate::helpers::stream_mode_helpers`] (and [`crate::helpers::block_mode_helpers`] for the
+//! key and nonce loaders), shared with the
+//! AES stream commands and `tdes-cfb` / `tdes-cfb8`. See those modules for the command-line
+//! contract.
+//!
+//! # The nonce is 6 bytes and the counter is 2
+//!
+//! NIST SP 800-38A Sec 6.5 builds CTR on a sequence of counter blocks, and Appendix B.2's second
+//! approach makes each one a message nonce followed by a counter; Appendix E allows TDEA as the
+//! underlying cipher. With an 8-byte block the split is tight. This command uses the `TDES_CTR`
+//! alias: a **6-byte** nonce and a 2-byte counter, so a single message is limited to 65 536 blocks
+//! (512 KiB), past which the command fails rather than repeat a counter block. The
+//! `bouncycastle-tdes` crate docs explain the trade-off against nonce collisions.
+//!
+//! `encrypt` writes that 6-byte nonce as the first bytes of its output and `decrypt` reads it back,
+//! exactly as the other modes do with their IVs; note that it is 6 bytes here, not 8.
+//!
+//! # Any length (up to the counter limit)
+//!
+//! CTR is a stream cipher: nothing is padded, and the output is exactly as long as the input.
+//!
+//! # Warning
+//!
+//! CTR provides confidentiality only. It does not detect tampering, and neither the ciphertext nor
+//! the nonce is authenticated. It is the most malleable of the modes here: flipping any ciphertext
+//! bit flips exactly the corresponding plaintext bit and affects nothing else (SP 800-38A
+//! Appendix D). Do not decrypt data you have not authenticated separately.
+//!
+//! A repeated nonce is fatal here rather than merely unwise: the same nonce under the same key
+//! gives the same keystream. The nonce is drawn from the OS-backed DRBG unless `--iv` /
+//! `--iv-file` supplies one, and then its uniqueness under the key is the caller's to keep; with
+//! only 48 bits of nonce the number of messages under one key bundle must stay small either way
+//! -- which SP 800-67 Rev 2 Sec 3.4's limit of 2^20 blocks per bundle already demands.
+//!
+//! TDEA is a legacy algorithm, disallowed for encryption by NIST SP 800-131A Rev 2 after 2023; see
+//! the `bouncycastle-tdes` crate docs.
+
+use crate::helpers::block_mode_helpers::TDEA_LIMIT;
+use crate::helpers::block_mode_helpers::{CipherDirection, load_iv, load_key_object};
+use crate::helpers::stream_mode_helpers::run_stream_mode_bounded;
+use bouncycastle::cipher::modes::CTR;
+use bouncycastle::tdes::{BLOCK_LEN, CTR_NONCE_LEN, KEY_LEN, TDES3Key};
+
+pub(crate) fn tdes_ctr_cmd(
+ action: &CipherDirection,
+ key: &Option,
+ key_file: &Option,
+ iv: &Option,
+ iv_file: &Option,
+ output_hex: bool,
+) {
+ let key =
+ load_key_object::>, KEY_LEN>(key, key_file, "TDES");
+ let nonce = load_iv::(iv, iv_file);
+ run_stream_mode_bounded::<_, KEY_LEN, CTR_NONCE_LEN>(
+ action,
+ &key,
+ nonce,
+ output_hex,
+ Some(&TDEA_LIMIT),
+ )
+}
diff --git a/cli/src/tdes_ecb_cmd.rs b/cli/src/tdes_ecb_cmd.rs
new file mode 100644
index 00000000..cfec5415
--- /dev/null
+++ b/cli/src/tdes_ecb_cmd.rs
@@ -0,0 +1,64 @@
+//! TDES-ECB encryption and decryption, streaming stdin to stdout.
+//!
+//! Only the mode wiring lives here: key loading, stdin framing and block-alignment enforcement are
+//! all in [`crate::helpers::block_mode_helpers`], shared with the AES commands and `tdes-cbc`. See
+//! that module for the command-line contract. ECB has no IV (`INIT_DATA_LEN = 0`), so nothing is
+//! prepended to
+//! the output or consumed from the input: the ciphertext is exactly as long as the plaintext. The
+//! block is 8 bytes.
+//!
+//! # Warning
+//!
+//! ECB (NIST SP 800-38A Sec 6.1; TECB in its Appendix E) is **not a confidentiality mode for
+//! data**. Under a given key every plaintext block maps to the same ciphertext block, so equal
+//! blocks stay visibly equal, the structure of the plaintext shows through, and blocks can be
+//! reordered, repeated or removed with nothing to detect it. The same plaintext encrypts to the
+//! same ciphertext every time. This command exists for interoperability with systems that use ECB
+//! and for driving test vectors.
+//!
+//! TDEA is a legacy algorithm, disallowed for encryption by NIST SP 800-131A Rev 2 after 2023; see
+//! the `bouncycastle-tdes` crate docs.
+
+use crate::helpers::block_mode_helpers::{
+ CipherDirection, TDEA_LIMIT, decrypt_stream, encrypt_stream_bounded, load_key_object,
+ start_encryptor,
+};
+use bouncycastle::cipher::modes::hazmat::ecb::ECB;
+use bouncycastle::cipher::padding::NoPadding;
+use bouncycastle::core::symmetric_key::{SymmetricDecryptionKey, SymmetricEncryptionKey};
+use bouncycastle::tdes::{BLOCK_LEN, KEY_LEN, TDES3Key};
+
+/// Names the mode in error messages.
+const MODE: &str = "ECB";
+
+pub(crate) fn tdes_ecb_cmd(
+ action: &CipherDirection,
+ key: &Option,
+ key_file: &Option,
+ output_hex: bool,
+) {
+ let key = load_key_object::>, KEY_LEN>(key, key_file, "TDES");
+ match action {
+ CipherDirection::Encrypt => {
+ // ECB has no IV: the constructor's RNG draws nothing, and nothing is written.
+ let (enc, _) = start_encryptor(
+ None,
+ |rng| key.create_encryptor(rng),
+ |no_iv| key.create_encryptor_nonce(no_iv),
+ );
+ encrypt_stream_bounded::<_, 0, BLOCK_LEN>(
+ enc,
+ None,
+ output_hex,
+ Some(MODE),
+ Some(&TDEA_LIMIT),
+ )
+ }
+ CipherDirection::Decrypt => decrypt_stream::<_, 0, BLOCK_LEN>(
+ None,
+ |no_iv| key.create_decryptor(no_iv),
+ output_hex,
+ Some(MODE),
+ ),
+ }
+}
diff --git a/cli/src/tdes_tkw_cmd.rs b/cli/src/tdes_tkw_cmd.rs
new file mode 100644
index 00000000..586b980e
--- /dev/null
+++ b/cli/src/tdes_tkw_cmd.rs
@@ -0,0 +1,46 @@
+//! TDEA key wrap: `tdes-tkw -d encrypt|decrypt` (three-key, both directions) and
+//! `tdes2-tkw -d decrypt` (two-key, unwrapping only), stdin to stdout.
+//!
+//! They are the `aes*-kw` command over TDEA (NIST SP 800-38F Sec 7, TKW), so everything in
+//! [`crate::kw_cmd`] -- the whole-input reading, the absence of an IV, the fail-closed unwrap
+//! -- applies unchanged, at half the width: the input is a whole number of 4-byte semiblocks, at
+//! least 8 bytes, and the output is 4 bytes longer. `encrypt` has the SP 800-67 Rev 2 Sec 3.4
+//! bound the other `tdes-*` encrypting commands have, counted as blocks TDEA processes: TW makes
+//! six calls per 4-byte semiblock, so the input may be at most 699,048 bytes
+//! ([`TDEA_LIMIT_TKW`]). TKW is approved for legacy systems only (SP 800-38F Sec 8), and two-key
+//! TDEA may not wrap at all (SP 800-131A Rev 2 Table 6), so `tdes2-tkw` has no `encrypt`, as the
+//! other `tdes2-*` commands have none.
+
+use crate::helpers::block_mode_helpers::{
+ CipherDirection, DecryptOnlyAction, TDEA_LIMIT_TKW, load_key_object,
+};
+use crate::kw_cmd::{run, run_with};
+use bouncycastle::cipher::modes::TKW;
+use bouncycastle::core::symmetric_key::KeyUnwrappingKey;
+use bouncycastle::tdes::{KEY_LEN, KEY_LEN_2KEY, TDES2Key, TDES3Key};
+
+pub(crate) fn tdes_tkw_cmd(
+ direction: &CipherDirection,
+ key: &Option,
+ key_file: &Option,
+ output_hex: bool,
+) {
+ run::<_, KEY_LEN>(
+ direction,
+ &load_key_object::, KEY_LEN>(key, key_file, "TDES"),
+ Some(&TDEA_LIMIT_TKW),
+ output_hex,
+ "TDES-TKW",
+ );
+}
+
+pub(crate) fn tdes2_tkw_cmd(
+ action: &DecryptOnlyAction,
+ key: &Option,
+ key_file: &Option,
+ output_hex: bool,
+) {
+ let DecryptOnlyAction::Decrypt = action;
+ let kek = load_key_object::, KEY_LEN_2KEY>(key, key_file, "two-key TDES");
+ run_with(|input| kek.unwrap(input), None, output_hex, "two-key TDES-TKW");
+}
diff --git a/cli/tests/tdes_cli_tests.rs b/cli/tests/tdes_cli_tests.rs
new file mode 100644
index 00000000..7358d0af
--- /dev/null
+++ b/cli/tests/tdes_cli_tests.rs
@@ -0,0 +1,380 @@
+//! Tests for the `tdes-*` and `tdes2-*` subcommands.
+//!
+//! They share their key and IV loaders, streaming loops and error paths with the AES commands
+//! (`cli/src/helpers/`), and `test_aes_*.sh` cover those exhaustively. This file pins what is
+//! specific to TDEA: the 8-byte block and IV, the 6-byte CTR nonce, the 24- and 16-byte bundles,
+//! the decrypt-only two-key commands, and the known-answer vectors in both directions.
+//!
+//! The vectors are `COUNT = 0` of each NIST CAVP Multi-block Message Test file the crate's own
+//! suite uses (`TECBMMT3`, `TCBCMMT3`, `TCFB64MMT3`, `TCFB8MMT3` `[ENCRYPT]`, and the two-key
+//! `[DECRYPT]` files), read from `../bc-test-data` at test time; without it those tests print a
+//! warning and pass, as the crate's suite does. The CBC vectors are unpadded, so under the
+//! commands' PKCS7 framing the ciphertext is followed by one block of padding, computed here from
+//! the engine.
+
+use std::io::{ErrorKind, Write};
+use std::path::Path;
+use std::process::{Command, Output, Stdio};
+
+/// The path to the binary under test, resolved by cargo.
+const BC_RUST: &str = env!("CARGO_BIN_EXE_bc-rust");
+
+/// A three-key bundle of distinct, non-weak components, for the tests that need no vector.
+const KEY_3: &str = "0123456789abcdef23456789abcdef01456789abcdef0123";
+
+/// Runs `bc-rust ` with `stdin_bytes` on stdin and returns the completed output.
+fn run(args: &[&str], stdin_bytes: &[u8]) -> Output {
+ let mut child = Command::new(BC_RUST)
+ .args(args)
+ .stdin(Stdio::piped())
+ .stdout(Stdio::piped())
+ .stderr(Stdio::piped())
+ .spawn()
+ .expect("failed to spawn bc-rust");
+
+ // The error-path tests hand a rejected key to a command that `exit`s before it ever reads
+ // stdin, so this write races the child's exit and sometimes loses. That is an expected
+ // outcome: `wait_with_output` still returns the exit status and stderr, which is all those
+ // tests assert on. Any other write error is a real problem and still panics.
+ match child.stdin.as_mut().expect("stdin piped").write_all(stdin_bytes) {
+ Ok(()) => {}
+ Err(e) if e.kind() == ErrorKind::BrokenPipe => {}
+ Err(e) => panic!("failed to write to stdin: {e}"),
+ }
+
+ child.wait_with_output().expect("failed to wait for bc-rust")
+}
+
+/// Runs a command that is expected to succeed, returning stdout.
+fn run_ok(args: &[&str], stdin_bytes: &[u8]) -> Vec {
+ let out = run(args, stdin_bytes);
+ assert!(
+ out.status.success(),
+ "expected success from {args:?}, got {:?}\nstderr: {}",
+ out.status,
+ String::from_utf8_lossy(&out.stderr)
+ );
+ out.stdout
+}
+
+/// Runs a command that is expected to fail, returning stderr as a string.
+fn run_err(args: &[&str], stdin_bytes: &[u8]) -> String {
+ let out = run(args, stdin_bytes);
+ assert!(
+ !out.status.success(),
+ "expected failure from {args:?}, but it succeeded\nstdout: {:?}",
+ String::from_utf8_lossy(&out.stdout)
+ );
+ String::from_utf8_lossy(&out.stderr).into_owned()
+}
+
+fn unhex(s: &str) -> Vec {
+ assert!(s.len().is_multiple_of(2), "hex string must have even length");
+ (0..s.len())
+ .step_by(2)
+ .map(|i| u8::from_str_radix(&s[i..i + 2], 16).expect("valid hex"))
+ .collect()
+}
+
+fn tohex(bytes: &[u8]) -> String {
+ bytes.iter().map(|b| format!("{b:02x}")).collect()
+}
+
+/// Deterministic pseudo-random bytes, so the tests do not depend on an RNG.
+fn pseudo_random(len: usize, seed: u32) -> Vec {
+ let mut state = seed.wrapping_mul(2_654_435_761).wrapping_add(1);
+ (0..len)
+ .map(|_| {
+ state ^= state << 13;
+ state ^= state >> 17;
+ state ^= state << 5;
+ (state >> 24) as u8
+ })
+ .collect()
+}
+
+// ---- the CAVP vectors ------------------------------------------------------------------------
+
+/// `COUNT = 0` of one section of a CAVP MMT response file: key bundle, IV (empty for ECB),
+/// plaintext and ciphertext, all as hex.
+struct Vector {
+ key: String,
+ iv: String,
+ plaintext: String,
+ ciphertext: String,
+}
+
+/// The text of a TDES CAVP response file, or `None` (with a warning) when `bc-test-data` is not
+/// cloned beside this repository. When it is and the file is missing, this panics rather than
+/// letting the test pass vacuously, as the framework's `bc_test_data` loader does.
+fn cavp_file(file: &str) -> Option {
+ let root = Path::new(env!("CARGO_MANIFEST_DIR")).join("../../bc-test-data");
+ if !root.is_dir() {
+ println!(
+ "WARNING: bc-test-data not found at {}; the CAVP vector tests are skipped",
+ root.display()
+ );
+ return None;
+ }
+ let path = root.join("crypto/aes_tdes_vectors/TDES").join(file);
+ Some(std::fs::read_to_string(&path).unwrap_or_else(|e| panic!("{}: {e}", path.display())))
+}
+
+/// `COUNT = 0` of `[section]` in `file`, or `None` without the data. The key is `KEY1 || KEY2`
+/// for a two-key file (whose `KEY3 = KEY1`) and `KEY1 || KEY2 || KEY3` otherwise.
+fn vector(file: &str, section: &str) -> Option {
+ let text = cavp_file(file)?;
+ let body = text.split(&format!("[{section}]")).nth(1).expect("the section");
+ let case = body.split("COUNT = 0").nth(1).expect("COUNT = 0");
+ let case = case.split("COUNT = 1").next().expect("one case");
+ let field = |name: &str| -> String {
+ case.lines()
+ .map(str::trim)
+ .find_map(|l| l.strip_prefix(&format!("{name} = ")))
+ .unwrap_or_default()
+ .to_lowercase()
+ };
+ let (k1, k2, k3) = (field("KEY1"), field("KEY2"), field("KEY3"));
+ let key = if file.ends_with("MMT2.rsp") {
+ assert_eq!(k1, k3, "a two-key vector has KEY3 = KEY1");
+ k1 + &k2
+ } else {
+ k1 + &k2 + &k3
+ };
+ Some(Vector {
+ key,
+ iv: field("IV"),
+ plaintext: field("PLAINTEXT"),
+ ciphertext: field("CIPHERTEXT"),
+ })
+}
+
+/// The CBC ciphertext block that a full block of PKCS7 padding (eight `0x08` bytes) encrypts to
+/// under `key_hex` after the ciphertext block `prev_hex`: `E_K(prev xor 08..08)`, from the engine
+/// of the bundle's length. Appended to an unpadded known-answer ciphertext, it gives the PKCS7
+/// ciphertext of the same plaintext, which is how the commands frame it.
+fn pkcs7_block(key_hex: &str, prev_hex: &str) -> String {
+ use bouncycastle::core::hazmat::{BlockPermutation, KeyExpansion};
+ use bouncycastle::core::key_material::{KeyMaterial, KeyType};
+ use bouncycastle::tdes::hazmat::{TDES2Internal, TDESInternal};
+
+ fn material(key_hex: &str) -> KeyMaterial {
+ let key_bytes: [u8; N] = unhex(key_hex).try_into().expect("the right key length");
+ KeyMaterial::::from_bytes_as_type(&key_bytes, KeyType::SymmetricCipherKey)
+ .expect("a valid symmetric cipher key")
+ }
+ let mut block: [u8; 8] = unhex(prev_hex).try_into().expect("an 8-byte block");
+ block.iter_mut().for_each(|b| *b ^= 0x08);
+ match key_hex.len() / 2 {
+ 24 => TDESInternal::new(&material::<24>(key_hex)).unwrap().encrypt_block(&mut block),
+ 16 => TDES2Internal::new(&material::<16>(key_hex)).unwrap().encrypt_block(&mut block),
+ _ => panic!("not a TDEA bundle length"),
+ }
+ tohex(&block)
+}
+
+/// The last 16 hex characters: the final ciphertext block.
+fn last_block(ct: &str) -> &str {
+ &ct[ct.len() - 16..]
+}
+
+/// `tdes-cbc encrypt --iv` reproduces TCBCMMT3 followed by the PKCS7 block, `decrypt --iv` takes
+/// it back, and `decrypt` with the IV in band gives the same answer.
+#[test]
+fn tdes_cbc_matches_the_cavp_vector() {
+ let Some(v) = vector("TCBCMMT3.rsp", "ENCRYPT") else { return };
+ let want = format!("{}{}", v.ciphertext, pkcs7_block(&v.key, last_block(&v.ciphertext)));
+
+ let out = run_ok(
+ &["tdes-cbc", "-d", "encrypt", "--key", &v.key, "--iv", &v.iv],
+ &unhex(&v.plaintext),
+ );
+ assert_eq!(tohex(&out), want, "encrypt --iv");
+
+ let back = run_ok(&["tdes-cbc", "-d", "decrypt", "--key", &v.key, "--iv", &v.iv], &out);
+ assert_eq!(tohex(&back), v.plaintext, "decrypt --iv");
+
+ let back =
+ run_ok(&["tdes-cbc", "-d", "decrypt", "--key", &v.key], &unhex(&format!("{}{want}", v.iv)));
+ assert_eq!(tohex(&back), v.plaintext, "decrypt with the IV in band");
+}
+
+/// `tdes-cfb encrypt --iv` and `tdes-cfb8 encrypt --iv` reproduce TCFB64MMT3 and TCFB8MMT3
+/// exactly, and `decrypt --iv` takes them back.
+#[test]
+fn tdes_cfb_and_cfb8_match_the_cavp_vectors() {
+ for (cmd, file) in [("tdes-cfb", "TCFB64MMT3.rsp"), ("tdes-cfb8", "TCFB8MMT3.rsp")] {
+ let Some(v) = vector(file, "ENCRYPT") else { return };
+ let out =
+ run_ok(&[cmd, "-d", "encrypt", "--key", &v.key, "--iv", &v.iv], &unhex(&v.plaintext));
+ assert_eq!(tohex(&out), v.ciphertext, "{cmd} encrypt --iv");
+ let back = run_ok(&[cmd, "-d", "decrypt", "--key", &v.key, "--iv", &v.iv], &out);
+ assert_eq!(tohex(&back), v.plaintext, "{cmd} decrypt --iv");
+ }
+}
+
+/// `tdes-ecb` reproduces TECBMMT3 in both directions; there is no IV and no padding.
+#[test]
+fn tdes_ecb_matches_the_cavp_vector() {
+ let Some(v) = vector("TECBMMT3.rsp", "ENCRYPT") else { return };
+ let out = run_ok(&["tdes-ecb", "-d", "encrypt", "--key", &v.key], &unhex(&v.plaintext));
+ assert_eq!(tohex(&out), v.ciphertext, "encrypt");
+ let back = run_ok(&["tdes-ecb", "-d", "decrypt", "--key", &v.key], &out);
+ assert_eq!(tohex(&back), v.plaintext, "decrypt");
+}
+
+/// The two-key commands decrypt the `[DECRYPT]` vectors of the two-key files: CBC with the PKCS7
+/// block appended, CFB64 and CFB8 exactly, ECB without an IV.
+#[test]
+fn tdes2_commands_decrypt_the_cavp_vectors() {
+ let Some(v) = vector("TCBCMMT2.rsp", "DECRYPT") else { return };
+ let padded = format!("{}{}", v.ciphertext, pkcs7_block(&v.key, last_block(&v.ciphertext)));
+ let out =
+ run_ok(&["tdes2-cbc", "-d", "decrypt", "--key", &v.key, "--iv", &v.iv], &unhex(&padded));
+ assert_eq!(tohex(&out), v.plaintext, "tdes2-cbc decrypt --iv");
+ let out = run_ok(
+ &["tdes2-cbc", "-d", "decrypt", "--key", &v.key],
+ &unhex(&format!("{}{padded}", v.iv)),
+ );
+ assert_eq!(tohex(&out), v.plaintext, "tdes2-cbc decrypt with the IV in band");
+
+ for (cmd, file) in [("tdes2-cfb", "TCFB64MMT2.rsp"), ("tdes2-cfb8", "TCFB8MMT2.rsp")] {
+ let Some(v) = vector(file, "DECRYPT") else { return };
+ let out =
+ run_ok(&[cmd, "-d", "decrypt", "--key", &v.key, "--iv", &v.iv], &unhex(&v.ciphertext));
+ assert_eq!(tohex(&out), v.plaintext, "{cmd} decrypt --iv");
+ }
+
+ let Some(v) = vector("TECBMMT2.rsp", "DECRYPT") else { return };
+ let out = run_ok(&["tdes2-ecb", "-d", "decrypt", "--key", &v.key], &unhex(&v.ciphertext));
+ assert_eq!(tohex(&out), v.plaintext, "tdes2-ecb decrypt");
+}
+
+// ---- the contract ----------------------------------------------------------------------------
+
+/// `encrypt | decrypt` composes for every three-key mode: the 8-byte IV (6-byte nonce for CTR)
+/// rides at the front, CBC pads with PKCS7, the stream modes and ECB do not.
+#[test]
+fn every_three_key_mode_round_trips() {
+ let plaintext = pseudo_random(4096, 0xC0FFEE);
+ for (cmd, init_len, padded_len) in [
+ ("tdes-cbc", 8, 4096 + 8),
+ ("tdes-cfb", 8, 4096),
+ ("tdes-cfb8", 8, 4096),
+ ("tdes-ctr", 6, 4096),
+ ("tdes-ecb", 0, 4096),
+ ] {
+ let ciphertext = run_ok(&[cmd, "-d", "encrypt", "--key", KEY_3], &plaintext);
+ assert_eq!(ciphertext.len(), init_len + padded_len, "{cmd}: init data plus the body");
+ assert_ne!(&ciphertext[init_len..init_len + 64], &plaintext[..64], "{cmd}: encrypted");
+ let recovered = run_ok(&[cmd, "-d", "decrypt", "--key", KEY_3], &ciphertext);
+ assert_eq!(recovered, plaintext, "{cmd}: round trip");
+ }
+}
+
+/// CBC accepts any length and pads to the next whole 8-byte block; ECB does not pad and rejects
+/// unaligned input.
+#[test]
+fn cbc_pads_and_ecb_does_not() {
+ for len in [0usize, 1, 7, 8, 9, 17] {
+ let plaintext = vec![0x5Au8; len];
+ let ciphertext = run_ok(&["tdes-cbc", "-d", "encrypt", "--key", KEY_3], &plaintext);
+ assert_eq!(ciphertext.len(), 8 + (len / 8 + 1) * 8, "len {len}: IV plus padded body");
+ let recovered = run_ok(&["tdes-cbc", "-d", "decrypt", "--key", KEY_3], &ciphertext);
+ assert_eq!(recovered, plaintext, "len {len}: round trip");
+ }
+ let err = run_err(&["tdes-ecb", "-d", "encrypt", "--key", KEY_3], &[0u8; 9]);
+ assert!(err.contains("whole number of 8-byte blocks"), "stderr was: {err}");
+}
+
+/// With `--iv` the output is the ciphertext alone, and it is still CTR over TDEA under that
+/// 6-byte nonce: the library's key object decrypts it.
+#[test]
+fn tdes_ctr_under_a_supplied_nonce_agrees_with_the_library() {
+ use bouncycastle::cipher::modes::CTR;
+ use bouncycastle::core::key_material::{KeyMaterial, KeyType};
+ use bouncycastle::core::symmetric_key::{FromKeyMaterial, SymmetricDecryptionKey};
+ use bouncycastle::tdes::{BLOCK_LEN, CTR_NONCE_LEN, TDES3Key};
+
+ let nonce = "000102030405";
+ let plaintext = pseudo_random(37, 5);
+ let out = run_ok(&["tdes-ctr", "-d", "encrypt", "--key", KEY_3, "--iv", nonce], &plaintext);
+ assert_eq!(out.len(), plaintext.len(), "ciphertext only, no nonce in band");
+
+ let key_bytes: [u8; 24] = unhex(KEY_3).try_into().unwrap();
+ let material = KeyMaterial::<24>::from_bytes_as_type(&key_bytes, KeyType::SymmetricCipherKey)
+ .expect("a valid symmetric cipher key");
+ let key = TDES3Key::>::from_key_material(&material).unwrap();
+ let mut recovered = out.clone();
+ let nonce_bytes: [u8; CTR_NONCE_LEN] = unhex(nonce).try_into().unwrap();
+ key.decrypt_inplace(&nonce_bytes, &mut recovered).expect("decryption");
+ assert_eq!(recovered, plaintext, "the CLI should agree with the library under that nonce");
+
+ let back = run_ok(&["tdes-ctr", "-d", "decrypt", "--key", KEY_3, "--iv", nonce], &out);
+ assert_eq!(back, plaintext);
+}
+
+/// The same with `-x`: identical answer in hex plus a trailing newline.
+#[test]
+fn hex_output_matches_binary_output() {
+ let plaintext = pseudo_random(32, 3);
+ let ciphertext = run_ok(&["tdes-cbc", "-d", "encrypt", "--key", KEY_3], &plaintext);
+ let binary = run_ok(&["tdes-cbc", "-d", "decrypt", "--key", KEY_3], &ciphertext);
+ let hex_out = run_ok(&["tdes-cbc", "-d", "decrypt", "--key", KEY_3, "-x"], &ciphertext);
+ assert_eq!(String::from_utf8_lossy(&hex_out), format!("{}\n", tohex(&binary)));
+ assert_eq!(binary, plaintext);
+}
+
+/// The two-key commands have no `encrypt`: the parser refuses it, naming the one value.
+#[test]
+fn two_key_commands_refuse_to_encrypt() {
+ let key_2 = &KEY_3[..32];
+ for cmd in ["tdes2-cbc", "tdes2-cfb", "tdes2-cfb8", "tdes2-ctr", "tdes2-ecb"] {
+ let err = run_err(&[cmd, "-d", "encrypt", "--key", key_2], &[0u8; 16]);
+ assert!(
+ err.contains("decrypt"),
+ "{cmd}: stderr should list the one valid value, was: {err}"
+ );
+ }
+}
+
+/// Each command wants exactly its bundle length, and a bundle that repeats a component or holds
+/// a weak DEA key is rejected by the key object.
+#[test]
+fn bad_bundles_are_rejected() {
+ let err = run_err(&["tdes-cbc", "-d", "encrypt", "--key", &KEY_3[..32]], &[0u8; 16]);
+ assert!(err.contains("TDES needs a 24-byte key, got 16 bytes"), "stderr was: {err}");
+ let err = run_err(&["tdes2-cbc", "-d", "decrypt", "--key", KEY_3], &[0u8; 16]);
+ assert!(err.contains("two-key TDES needs a 16-byte key, got 24 bytes"), "stderr was: {err}");
+
+ // Key1 = Key2: two of the three transformations cancel.
+ let repeated = "0123456789abcdef0123456789abcdef456789abcdef0123";
+ let err = run_err(&["tdes-cbc", "-d", "encrypt", "--key", repeated], &[0u8; 16]);
+ assert!(err.contains("WeakKey"), "stderr was: {err}");
+ // A weak DEA key as Key1.
+ let weak = "010101010101010123456789abcdef01456789abcdef0123";
+ let err = run_err(&["tdes-cfb", "-d", "encrypt", "--key", weak], &[0u8; 16]);
+ assert!(err.contains("WeakKey"), "stderr was: {err}");
+}
+
+/// The harness above must survive a write that loses the race with the child's exit: the key is
+/// rejected so the command exits before reading a byte, and the payload cannot fit in a pipe
+/// buffer, so the write is certain to get EPIPE.
+#[test]
+fn a_large_payload_on_an_error_path_does_not_break_the_harness() {
+ let err =
+ run_err(&["tdes-cbc", "-d", "encrypt", "--key", &KEY_3[..32]], &vec![0u8; 4 * 1024 * 1024]);
+ assert!(err.contains("TDES needs a 24-byte key"), "stderr was: {err}");
+}
+
+/// The subcommands are discoverable.
+#[test]
+fn the_subcommands_are_listed_in_help() {
+ let out = run_ok(&["--help"], &[]);
+ let help = String::from_utf8_lossy(&out);
+ for cmd in
+ ["tdes-cbc", "tdes-cfb", "tdes-cfb8", "tdes-ctr", "tdes-ecb", "tdes2-cbc", "tdes2-ecb"]
+ {
+ assert!(help.contains(cmd), "`--help` should list {cmd}");
+ }
+}
diff --git a/cli/tests/tdes_tkw_cli_tests.rs b/cli/tests/tdes_tkw_cli_tests.rs
new file mode 100644
index 00000000..7a3944c0
--- /dev/null
+++ b/cli/tests/tdes_tkw_cli_tests.rs
@@ -0,0 +1,163 @@
+//! Tests for the `tdes-tkw` and `tdes2-tkw` subcommands.
+//!
+//! They share everything but the key type and the semiblock width with the `aes*-kw` commands,
+//! whose `test_aes_kw.sh` covers the command-line contract exhaustively. This file pins what is
+//! specific to TKW: the CAVP known answers in both directions, a CAVP forgery, the 4-byte
+//! alignment rule, and that the two-key command unwraps only.
+//!
+//! The known answers are `COUNT = 0` of the 64- and 128-bit sections of the NIST CAVP `TKW_AE.txt`
+//! sample file, and the first `FAIL` of `TKW_AD.txt`, read from `../bc-test-data` at test time;
+//! without it those tests print a warning and pass, as the crate's suite does.
+
+use std::io::{ErrorKind, Write};
+use std::path::Path;
+use std::process::{Command, Output, Stdio};
+
+/// The path to the binary under test, resolved by cargo.
+const BC_RUST: &str = env!("CARGO_BIN_EXE_bc-rust");
+
+/// A three-key bundle of distinct, non-weak components, for the tests that need no vector.
+const KEY_3: &str = "0123456789abcdef23456789abcdef01456789abcdef0123";
+/// A two-key bundle of distinct, non-weak components.
+const KEY_2: &str = "0123456789abcdef23456789abcdef01";
+
+/// Runs `bc-rust ` with `stdin_bytes` on stdin and returns the completed output.
+fn run(args: &[&str], stdin_bytes: &[u8]) -> Output {
+ let mut child = Command::new(BC_RUST)
+ .args(args)
+ .stdin(Stdio::piped())
+ .stdout(Stdio::piped())
+ .stderr(Stdio::piped())
+ .spawn()
+ .expect("failed to spawn bc-rust");
+ // A command that exits before reading stdin makes this write race its exit; that is the
+ // expected outcome for the error-path tests, which assert on the status and stderr only.
+ match child.stdin.as_mut().expect("stdin piped").write_all(stdin_bytes) {
+ Ok(()) => {}
+ Err(e) if e.kind() == ErrorKind::BrokenPipe => {}
+ Err(e) => panic!("failed to write to stdin: {e}"),
+ }
+ child.wait_with_output().expect("failed to wait for bc-rust")
+}
+
+fn run_ok(args: &[&str], stdin_bytes: &[u8]) -> Vec {
+ let out = run(args, stdin_bytes);
+ assert!(
+ out.status.success(),
+ "expected success from {args:?}, got {:?}\nstderr: {}",
+ out.status,
+ String::from_utf8_lossy(&out.stderr)
+ );
+ out.stdout
+}
+
+fn run_err(args: &[&str], stdin_bytes: &[u8]) -> String {
+ let out = run(args, stdin_bytes);
+ assert!(
+ !out.status.success(),
+ "expected failure from {args:?}, but it succeeded\nstdout: {:?}",
+ String::from_utf8_lossy(&out.stdout)
+ );
+ assert!(out.stdout.is_empty(), "a rejected command must write nothing: {args:?}");
+ String::from_utf8_lossy(&out.stderr).into_owned()
+}
+
+fn unhex(s: &str) -> Vec {
+ (0..s.len()).step_by(2).map(|i| u8::from_str_radix(&s[i..i + 2], 16).expect("hex")).collect()
+}
+
+fn tohex(bytes: &[u8]) -> String {
+ bytes.iter().map(|b| format!("{b:02x}")).collect()
+}
+
+/// The text of a CAVP sample file, or `None` (with a warning) when `bc-test-data` is not cloned
+/// beside this repository.
+fn cavp_file(file: &str) -> Option {
+ let root = Path::new(env!("CARGO_MANIFEST_DIR")).join("../../bc-test-data");
+ let path = root.join("crypto/aes_tdes_vectors/TDES").join(file);
+ if !root.exists() {
+ println!(
+ "WARNING: bc-test-data not found at {}; the CAVP tests are skipped",
+ root.display()
+ );
+ return None;
+ }
+ let text = std::fs::read_to_string(&path).unwrap_or_else(|e| panic!("{}: {e}", path.display()));
+ // The CAVS files have CRLF line ends.
+ Some(text.replace('\r', ""))
+}
+
+/// `(K, P, C)` of `COUNT = 0` in the `[PLAINTEXT LENGTH = bits]` section of `file`; `P` is empty
+/// for a `FAIL` case.
+fn case(file: &str, bits: u32, count: u32) -> Option<(String, String, String)> {
+ let text = cavp_file(file)?;
+ let section = text.split(&format!("[PLAINTEXT LENGTH = {bits}]")).nth(1).expect("the section");
+ let body = section.split(&format!("COUNT = {count}\n")).nth(1).expect("the case");
+ let body = body.split("COUNT = ").next().unwrap();
+ let field = |name: &str| -> String {
+ body.lines()
+ .map(str::trim)
+ .find_map(|l| l.strip_prefix(&format!("{name} = ")))
+ .unwrap_or_default()
+ .to_lowercase()
+ };
+ Some((field("K"), field("P"), field("C")))
+}
+
+#[test]
+fn tdes_tkw_matches_the_cavp_vectors_in_both_directions() {
+ for bits in [64, 128] {
+ let Some((k, p, c)) = case("TKW_AE.txt", bits, 0) else { return };
+ let wrapped = run_ok(&["tdes-tkw", "-d", "encrypt", "--key", &k], &unhex(&p));
+ assert_eq!(tohex(&wrapped), c, "{bits}-bit wrap");
+ let hex = run_ok(&["tdes-tkw", "-d", "encrypt", "--key", &k, "-x"], &unhex(&p));
+ assert_eq!(String::from_utf8_lossy(&hex).trim(), c, "{bits}-bit wrap -x");
+ let unwrapped = run_ok(&["tdes-tkw", "-d", "decrypt", "--key", &k], &unhex(&c));
+ assert_eq!(tohex(&unwrapped), p, "{bits}-bit unwrap");
+ }
+}
+
+#[test]
+fn tdes_tkw_rejects_a_cavp_forgery() {
+ let Some(text) = cavp_file("TKW_AD.txt") else { return };
+ // The first FAIL: its K and C are the two `NAME = value` lines just above it.
+ let before = text.split("\nFAIL").next().expect("a FAIL line");
+ let mut lines = before.lines().rev().map(str::trim);
+ let c = lines.next().unwrap().strip_prefix("C = ").expect("C before FAIL").to_lowercase();
+ let k = lines.next().unwrap().strip_prefix("K = ").expect("K before C").to_lowercase();
+ let err = run_err(&["tdes-tkw", "-d", "decrypt", "--key", &k], &unhex(&c));
+ assert!(err.contains("not an authentic"), "{err}");
+}
+
+#[test]
+fn tkw_takes_whole_4_byte_semiblocks_and_at_least_two() {
+ let err = run_err(&["tdes-tkw", "-d", "encrypt", "--key", KEY_3], &[0x5Au8; 4]);
+ assert!(err.contains("4 bytes rejected"), "{err}");
+ let err = run_err(&["tdes-tkw", "-d", "encrypt", "--key", KEY_3], &[0x5Au8; 10]);
+ assert!(err.contains("10 bytes rejected"), "{err}");
+ let wrapped = run_ok(&["tdes-tkw", "-d", "encrypt", "--key", KEY_3], &[0x5Au8; 12]);
+ assert_eq!(wrapped.len(), 16, "12 bytes wrap to 16");
+ let back = run_ok(&["tdes-tkw", "-d", "decrypt", "--key", KEY_3], &wrapped);
+ assert_eq!(back, [0x5Au8; 12]);
+}
+
+#[test]
+fn tdes2_tkw_unwraps_only() {
+ // `encrypt` is not a value of the two-key direction at all.
+ let err = run_err(&["tdes2-tkw", "-d", "encrypt", "--key", KEY_2], &[0x5Au8; 8]);
+ assert!(err.contains("encrypt"), "{err}");
+ // A ciphertext this key never made is rejected, not unwrapped to garbage.
+ let err = run_err(&["tdes2-tkw", "-d", "decrypt", "--key", KEY_2], &[0x5Au8; 12]);
+ assert!(err.contains("not an authentic"), "{err}");
+ // A three-key bundle is not a two-key one.
+ let err = run_err(&["tdes2-tkw", "-d", "decrypt", "--key", KEY_3], &[0x5Au8; 12]);
+ assert!(err.contains("16-byte key"), "{err}");
+}
+
+#[test]
+fn the_subcommands_are_listed_in_help() {
+ let help = String::from_utf8(run_ok(&["--help"], b"")).unwrap();
+ for cmd in ["tdes-tkw", "tdes2-tkw"] {
+ assert!(help.contains(cmd), "--help should list {cmd}");
+ }
+}
diff --git a/cli/tests/test_tdes.sh b/cli/tests/test_tdes.sh
new file mode 100755
index 00000000..22a9a1bf
--- /dev/null
+++ b/cli/tests/test_tdes.sh
@@ -0,0 +1,91 @@
+#!/usr/bin/env bash
+# The tdes-* subcommands' data limit, end to end through the binary. SP 800-67 Rev 2 Sec 3.4
+# allows one key bundle 2^20 64-bit blocks (8 MiB) of protection; `encrypt` refuses input past
+# that with the usual `Error:` line, before any byte past the bound is processed. CBC's PKCS7
+# padding adds up to a block, so its bound is one byte lower; CFB64 takes exactly 8 MiB. The
+# bound counts the blocks TDEA processes, so CFB8 (one block per byte) stops at 1 MiB and TKW
+# (six calls per 4-byte semiblock) at 699,048 bytes. CTR never reaches it: its 6-byte nonce
+# leaves a 16-bit counter, so the library's own keystream limit (2^16 blocks, 512 KiB) binds
+# first, as `DataLimitExceeded`. Decryption is not limited. This lives here rather than in
+# `tdes_cli_tests.rs` because 8 MiB through a debug build of the bit-sliced engine takes a minute
+# or two per run.
+
+source "$(dirname "${BASH_SOURCE[0]}")/lib.sh"
+
+KEY=0123456789abcdef23456789abcdef01456789abcdef0123
+KEY2=0123456789abcdef23456789abcdef01
+LIMIT=$((1 << 23))
+
+# `zeros N` writes N zero bytes.
+zeros() { head -c "$1" /dev/zero; }
+
+test_cbc_refuses_a_padded_message_past_the_limit() {
+ expect_fail "8 MiB pads to 2^20 + 1 blocks" \
+ "$BC_RUST" tdes-cbc -d encrypt --key "$KEY" < <(zeros "$LIMIT")
+ assert_stderr_has "Error: TDEA: one key bundle may protect at most 2^20 blocks"
+}
+
+test_cbc_takes_a_message_that_pads_to_the_limit() {
+ expect_ok "8 MiB less one byte pads to exactly 2^20 blocks" \
+ "$BC_RUST" tdes-cbc -d encrypt --key "$KEY" < <(zeros $((LIMIT - 1))) >/dev/null
+}
+
+test_cfb_refuses_one_byte_past_the_limit() {
+ expect_fail "tdes-cfb: 2^20 blocks plus a byte" \
+ "$BC_RUST" tdes-cfb -d encrypt --key "$KEY" < <(zeros $((LIMIT + 1)))
+ assert_stderr_has "Error: TDEA: one key bundle may protect at most 2^20 blocks"
+}
+
+test_cfb8_counts_a_block_per_byte() {
+ expect_ok "tdes-cfb8: 2^20 bytes is 2^20 blocks" \
+ "$BC_RUST" tdes-cfb8 -d encrypt --key "$KEY" < <(zeros $((1 << 20))) >/dev/null
+ expect_fail "tdes-cfb8: 2^20 bytes plus one" \
+ "$BC_RUST" tdes-cfb8 -d encrypt --key "$KEY" < <(zeros $(((1 << 20) + 1)))
+ assert_stderr_has "Error: TDEA: one key bundle may protect at most 2^20 blocks"
+}
+
+test_tkw_counts_six_blocks_per_semiblock() {
+ local bound=$(((1 << 20) / 6 * 4))
+ expect_ok "tdes-tkw: $bound bytes is 2^20 blocks" \
+ "$BC_RUST" tdes-tkw -d encrypt --key "$KEY" < <(zeros "$bound") >/dev/null
+ expect_fail "tdes-tkw: one semiblock more" \
+ "$BC_RUST" tdes-tkw -d encrypt --key "$KEY" < <(zeros $((bound + 4)))
+ assert_stderr_has "Error: TDEA: one key bundle may protect at most 2^20 blocks"
+}
+
+test_ctr_runs_out_of_counter_first() {
+ expect_fail "tdes-ctr: 2^16 blocks plus a byte exhausts the 16-bit counter" \
+ "$BC_RUST" tdes-ctr -d encrypt --key "$KEY" < <(zeros $(((1 << 19) + 1)))
+ assert_stderr_has "DataLimitExceeded"
+}
+
+test_ecb_takes_the_limit_and_refuses_a_block_more() {
+ expect_ok "tdes-ecb: exactly 2^20 blocks" \
+ "$BC_RUST" tdes-ecb -d encrypt --key "$KEY" < <(zeros "$LIMIT") >/dev/null
+ expect_fail "tdes-ecb: 2^20 blocks plus one" \
+ "$BC_RUST" tdes-ecb -d encrypt --key "$KEY" < <(zeros $((LIMIT + 8)))
+ assert_stderr_has "Error: TDEA: one key bundle may protect at most 2^20 blocks"
+}
+
+test_cfb_takes_exactly_the_limit() {
+ expect_ok "tdes-cfb: exactly 2^20 blocks" \
+ "$BC_RUST" tdes-cfb -d encrypt --key "$KEY" < <(zeros "$LIMIT") >/dev/null
+}
+
+test_ctr_takes_its_whole_counter_space() {
+ expect_ok "tdes-ctr: exactly 2^16 blocks" \
+ "$BC_RUST" tdes-ctr -d encrypt --key "$KEY" < <(zeros $((1 << 19))) >/dev/null
+}
+
+test_decrypt_is_not_limited() {
+ # 2^20 + 1 blocks of ciphertext decrypt (ECB, no padding; CFB with the IV read from the
+ # input), under either bundle, since the limit is on protecting.
+ expect_ok "tdes-ecb decrypt past the limit" \
+ "$BC_RUST" tdes-ecb -d decrypt --key "$KEY" < <(zeros $((LIMIT + 8))) >/dev/null
+ expect_ok "tdes2-ecb decrypt past the limit" \
+ "$BC_RUST" tdes2-ecb -d decrypt --key "$KEY2" < <(zeros $((LIMIT + 8))) >/dev/null
+ expect_ok "tdes2-cfb decrypt past the limit" \
+ "$BC_RUST" tdes2-cfb -d decrypt --key "$KEY2" < <(zeros $((LIMIT + 16))) >/dev/null
+}
+
+run_all
diff --git a/crypto/aes/src/kw.rs b/crypto/aes/src/kw.rs
index d5036e85..2e9c8257 100644
--- a/crypto/aes/src/kw.rs
+++ b/crypto/aes/src/kw.rs
@@ -102,27 +102,27 @@ use bouncycastle_cipher::modes::{Kw, Kwp};
/// [`KeyUnwrappingKey`]: bouncycastle_core::symmetric_key::KeyUnwrappingKey
/// [`KeyType::SymmetricCipherKey`]: bouncycastle_core::key_material::KeyType::SymmetricCipherKey
#[allow(non_camel_case_types)]
-pub type AES_KW_128<'k> = Kw<'k, AES128Internal>;
+pub type AES_KW_128<'k, Dir> = Kw<'k, AES128Internal, Dir>;
/// AES-192 Key Wrap (SP 800-38F KW; RFC 3394 with a 192-bit KEK). See [`AES_KW_128`].
#[allow(non_camel_case_types)]
-pub type AES_KW_192<'k> = Kw<'k, AES192Internal>;
+pub type AES_KW_192<'k, Dir> = Kw<'k, AES192Internal, Dir>;
/// AES-256 Key Wrap (SP 800-38F KW; RFC 3394 with a 256-bit KEK). See [`AES_KW_128`].
#[allow(non_camel_case_types)]
-pub type AES_KW_256<'k> = Kw<'k, AES256Internal>;
+pub type AES_KW_256<'k, Dir> = Kw<'k, AES256Internal, Dir>;
/// AES-128 Key Wrap with Padding (SP 800-38F KWP; RFC 5649 with a 128-bit KEK): the worker an
/// `AES128Key` hands out.
#[allow(non_camel_case_types)]
-pub type AES_KWP_128<'k> = Kwp<'k, AES128Internal>;
+pub type AES_KWP_128<'k, Dir> = Kwp<'k, AES128Internal, Dir>;
/// AES-192 Key Wrap with Padding (SP 800-38F KWP; RFC 5649 with a 192-bit KEK). See
/// [`AES_KWP_128`].
#[allow(non_camel_case_types)]
-pub type AES_KWP_192<'k> = Kwp<'k, AES192Internal>;
+pub type AES_KWP_192<'k, Dir> = Kwp<'k, AES192Internal, Dir>;
/// AES-256 Key Wrap with Padding (SP 800-38F KWP; RFC 5649 with a 256-bit KEK). See
/// [`AES_KWP_128`].
#[allow(non_camel_case_types)]
-pub type AES_KWP_256<'k> = Kwp<'k, AES256Internal>;
+pub type AES_KWP_256<'k, Dir> = Kwp<'k, AES256Internal, Dir>;
diff --git a/crypto/aes/tests/alg_name_tests.rs b/crypto/aes/tests/alg_name_tests.rs
index 595084b6..8e775423 100644
--- a/crypto/aes/tests/alg_name_tests.rs
+++ b/crypto/aes/tests/alg_name_tests.rs
@@ -149,25 +149,20 @@ fn cmac() {
check::, AES_CMAC_256<'_, Decrypting>>("AES_CMAC_256", _256bit);
}
-/// One worker serves both halves of a key wrap, so there is one name per alias to check.
+/// A key wrap's two directions report the one name and strength.
#[test]
fn kw_kwp() {
use SecurityStrength::*;
- assert_eq!((AES_KW_128::ALG_NAME, AES_KW_128::MAX_SECURITY_STRENGTH), ("AES_KW_128", _128bit));
- assert_eq!((AES_KW_192::ALG_NAME, AES_KW_192::MAX_SECURITY_STRENGTH), ("AES_KW_192", _192bit));
- assert_eq!((AES_KW_256::ALG_NAME, AES_KW_256::MAX_SECURITY_STRENGTH), ("AES_KW_256", _256bit));
- assert_eq!(
- (AES_KWP_128::ALG_NAME, AES_KWP_128::MAX_SECURITY_STRENGTH),
- ("AES_KWP_128", _128bit)
- );
- assert_eq!(
- (AES_KWP_192::ALG_NAME, AES_KWP_192::MAX_SECURITY_STRENGTH),
- ("AES_KWP_192", _192bit)
- );
- assert_eq!(
- (AES_KWP_256::ALG_NAME, AES_KWP_256::MAX_SECURITY_STRENGTH),
- ("AES_KWP_256", _256bit)
- );
+ fn check(name: &str, strength: SecurityStrength) {
+ assert_eq!((Enc::ALG_NAME, Enc::MAX_SECURITY_STRENGTH), (name, strength));
+ assert_eq!((Dec::ALG_NAME, Dec::MAX_SECURITY_STRENGTH), (name, strength));
+ }
+ check::, AES_KW_128<'_, Decrypting>>("AES_KW_128", _128bit);
+ check::, AES_KW_192<'_, Decrypting>>("AES_KW_192", _192bit);
+ check::, AES_KW_256<'_, Decrypting>>("AES_KW_256", _256bit);
+ check::, AES_KWP_128<'_, Decrypting>>("AES_KWP_128", _128bit);
+ check::, AES_KWP_192<'_, Decrypting>>("AES_KWP_192", _192bit);
+ check::, AES_KWP_256<'_, Decrypting>>("AES_KWP_256", _256bit);
}
fn key_for>() -> AES128Key {
diff --git a/crypto/aes/tests/kw_tests.rs b/crypto/aes/tests/kw_tests.rs
index 032c6460..6ba63e10 100644
--- a/crypto/aes/tests/kw_tests.rs
+++ b/crypto/aes/tests/kw_tests.rs
@@ -15,6 +15,7 @@ use bouncycastle_aes::{
AES192Key, AES256Key,
};
use bouncycastle_cipher::modes::{KW, KWP, ModeNames};
+use bouncycastle_cipher::{Decrypting, Encrypting};
use bouncycastle_core::hazmat::Mode;
use bouncycastle_core::key_material::{KeyMaterial, KeyType};
use bouncycastle_core::security_strength::SecurityStrength;
@@ -210,18 +211,18 @@ fn the_three_key_lengths_are_not_interchangeable() {
#[test]
fn the_keys_hand_out_the_aliased_workers() {
let kek = key128::(&RFC3394_KEK[..32]);
- let _: AES_KW_128<'_> = kek.create_wrapper();
- let _: AES_KW_128<'_> = kek.create_unwrapper();
+ let _: AES_KW_128<'_, Encrypting> = kek.create_wrapper();
+ let _: AES_KW_128<'_, Decrypting> = kek.create_unwrapper();
let kek = key192::(&RFC3394_KEK[..48]);
- let _: AES_KW_192<'_> = kek.create_wrapper();
+ let _: AES_KW_192<'_, Encrypting> = kek.create_wrapper();
let kek = key256::(RFC3394_KEK);
- let _: AES_KW_256<'_> = kek.create_unwrapper();
+ let _: AES_KW_256<'_, Decrypting> = kek.create_unwrapper();
let kek = key128::(&RFC3394_KEK[..32]);
- let _: AES_KWP_128<'_> = kek.create_wrapper();
+ let _: AES_KWP_128<'_, Encrypting> = kek.create_wrapper();
let kek = key192::(&RFC3394_KEK[..48]);
- let _: AES_KWP_192<'_> = kek.create_unwrapper();
+ let _: AES_KWP_192<'_, Decrypting> = kek.create_unwrapper();
let kek = key256::(RFC3394_KEK);
- let _: AES_KWP_256<'_> = kek.create_wrapper();
+ let _: AES_KWP_256<'_, Encrypting> = kek.create_wrapper();
}
/// The sizes the docs quote: the key is the schedule, the worker is the borrow.
@@ -233,8 +234,8 @@ fn sizes() {
[size_of::(), size_of::(), size_of::()]
);
assert_eq!(size_of::>(), size_of::>());
- assert_eq!(size_of::(), size_of::<&AES128Internal>());
- assert_eq!(size_of::(), size_of::<&AES256Internal>());
+ assert_eq!(size_of::>(), size_of::<&AES128Internal>());
+ assert_eq!(size_of::>(), size_of::<&AES256Internal>());
}
/// Equality follows the material: the same bytes compare equal, as does a clone, and different
diff --git a/crypto/aria/src/kw.rs b/crypto/aria/src/kw.rs
index f2ee6d13..6951a399 100644
--- a/crypto/aria/src/kw.rs
+++ b/crypto/aria/src/kw.rs
@@ -48,25 +48,25 @@ use bouncycastle_cipher::modes::{Kw, Kwp};
/// is the borrow of it, one pointer, and the wrapping function's scratch is one block on the
/// stack; the data is wrapped and unwrapped in the caller's buffers.
#[allow(non_camel_case_types)]
-pub type ARIA_KW_128<'k> = Kw<'k, ARIA128Internal>;
+pub type ARIA_KW_128<'k, Dir> = Kw<'k, ARIA128Internal, Dir>;
/// ARIA-192 Key Wrap. See [`ARIA_KW_128`].
#[allow(non_camel_case_types)]
-pub type ARIA_KW_192<'k> = Kw<'k, ARIA192Internal>;
+pub type ARIA_KW_192<'k, Dir> = Kw<'k, ARIA192Internal, Dir>;
/// ARIA-256 Key Wrap. See [`ARIA_KW_128`].
#[allow(non_camel_case_types)]
-pub type ARIA_KW_256<'k> = Kw<'k, ARIA256Internal>;
+pub type ARIA_KW_256<'k, Dir> = Kw<'k, ARIA256Internal, Dir>;
/// ARIA-128 Key Wrap with Padding: the `Kwp` worker over the ARIA permutation, from an
/// `ARIA128Key`. See [`ARIA_KW_128`].
#[allow(non_camel_case_types)]
-pub type ARIA_KWP_128<'k> = Kwp<'k, ARIA128Internal>;
+pub type ARIA_KWP_128<'k, Dir> = Kwp<'k, ARIA128Internal, Dir>;
/// ARIA-192 Key Wrap with Padding. See [`ARIA_KW_128`].
#[allow(non_camel_case_types)]
-pub type ARIA_KWP_192<'k> = Kwp<'k, ARIA192Internal>;
+pub type ARIA_KWP_192<'k, Dir> = Kwp<'k, ARIA192Internal, Dir>;
/// ARIA-256 Key Wrap with Padding. See [`ARIA_KW_128`].
#[allow(non_camel_case_types)]
-pub type ARIA_KWP_256<'k> = Kwp<'k, ARIA256Internal>;
+pub type ARIA_KWP_256<'k, Dir> = Kwp<'k, ARIA256Internal, Dir>;
diff --git a/crypto/aria/tests/alg_name_tests.rs b/crypto/aria/tests/alg_name_tests.rs
index 0b94cf2d..5996da72 100644
--- a/crypto/aria/tests/alg_name_tests.rs
+++ b/crypto/aria/tests/alg_name_tests.rs
@@ -69,12 +69,12 @@ fn cfb_cfb8_ctr() {
#[test]
fn kw_kwp() {
use SecurityStrength::*;
- check::, ARIA_KW_128<'_>>("ARIA_KW_128", _128bit);
- check::, ARIA_KW_192<'_>>("ARIA_KW_192", _192bit);
- check::, ARIA_KW_256<'_>>("ARIA_KW_256", _256bit);
- check::, ARIA_KWP_128<'_>>("ARIA_KWP_128", _128bit);
- check::, ARIA_KWP_192<'_>>("ARIA_KWP_192", _192bit);
- check::, ARIA_KWP_256<'_>>("ARIA_KWP_256", _256bit);
+ check::, ARIA_KW_128<'_, Decrypting>>("ARIA_KW_128", _128bit);
+ check::, ARIA_KW_192<'_, Decrypting>>("ARIA_KW_192", _192bit);
+ check::, ARIA_KW_256<'_, Decrypting>>("ARIA_KW_256", _256bit);
+ check::, ARIA_KWP_128<'_, Decrypting>>("ARIA_KWP_128", _128bit);
+ check::, ARIA_KWP_192<'_, Decrypting>>("ARIA_KWP_192", _192bit);
+ check::, ARIA_KWP_256<'_, Decrypting>>("ARIA_KWP_256", _256bit);
}
#[test]
diff --git a/crypto/camellia/src/kw.rs b/crypto/camellia/src/kw.rs
index c3215a38..b3b5f01f 100644
--- a/crypto/camellia/src/kw.rs
+++ b/crypto/camellia/src/kw.rs
@@ -45,12 +45,12 @@ use bouncycastle_cipher::modes::Kw;
/// worker is the borrow of it, one pointer, and the wrapping function's scratch is one block on
/// the stack; the data is wrapped and unwrapped in the caller's buffers.
#[allow(non_camel_case_types)]
-pub type Camellia_KW_128<'k> = Kw<'k, Camellia128Internal>;
+pub type Camellia_KW_128<'k, Dir> = Kw<'k, Camellia128Internal, Dir>;
/// Camellia-192 Key Wrap. See [`Camellia_KW_128`].
#[allow(non_camel_case_types)]
-pub type Camellia_KW_192<'k> = Kw<'k, Camellia192Internal>;
+pub type Camellia_KW_192<'k, Dir> = Kw<'k, Camellia192Internal, Dir>;
/// Camellia-256 Key Wrap. See [`Camellia_KW_128`].
#[allow(non_camel_case_types)]
-pub type Camellia_KW_256<'k> = Kw<'k, Camellia256Internal>;
+pub type Camellia_KW_256<'k, Dir> = Kw<'k, Camellia256Internal, Dir>;
diff --git a/crypto/camellia/tests/alg_name_tests.rs b/crypto/camellia/tests/alg_name_tests.rs
index 679d2013..55fdad28 100644
--- a/crypto/camellia/tests/alg_name_tests.rs
+++ b/crypto/camellia/tests/alg_name_tests.rs
@@ -90,9 +90,15 @@ fn cfb_cfb8_ctr() {
#[test]
fn kw() {
use SecurityStrength::*;
- check::, Camellia_KW_128<'_>>("Camellia_KW_128", _128bit);
- check::, Camellia_KW_192<'_>>("Camellia_KW_192", _192bit);
- check::, Camellia_KW_256<'_>>("Camellia_KW_256", _256bit);
+ check::, Camellia_KW_128<'_, Decrypting>>(
+ "Camellia_KW_128", _128bit,
+ );
+ check::, Camellia_KW_192<'_, Decrypting>>(
+ "Camellia_KW_192", _192bit,
+ );
+ check::, Camellia_KW_256<'_, Decrypting>>(
+ "Camellia_KW_256", _256bit,
+ );
}
#[test]
diff --git a/crypto/chacha20-poly1305-aead/src/lib.rs b/crypto/chacha20-poly1305-aead/src/lib.rs
index d49cc57c..6142fa2a 100644
--- a/crypto/chacha20-poly1305-aead/src/lib.rs
+++ b/crypto/chacha20-poly1305-aead/src/lib.rs
@@ -105,6 +105,7 @@
use bouncycastle_chacha20::hazmat::{ChaCha20KeyStream, keystream_at};
use bouncycastle_chacha20::{ChaCha20, ChaCha20Key};
+use bouncycastle_cipher::stream::hazmat::stream_cipher_over;
use bouncycastle_cipher::{Decrypting, Encrypting};
use bouncycastle_core::errors::SymmetricCipherError;
use bouncycastle_core::hazmat::KeyStream;
@@ -231,7 +232,7 @@ where
// already enforced on the parent cipher key; no entropy heuristic applies here.
let mac = Poly1305::from_key(key_from_bytes(poly1305_key_gen(&mut keystream, &mut block)));
Self {
- cipher: ChaCha20::from_keystream(keystream),
+ cipher: stream_cipher_over(keystream),
mac,
aad_len: 0,
data_len: 0,
@@ -550,7 +551,7 @@ mod tests {
let mut cipher = fresh(key);
// `check_data_len` relies on MAX_MESSAGE_LEN being exactly the data keystream's capacity.
assert_eq!(cipher.cipher.keystream().remaining_blocks() * 64, MAX_MESSAGE_LEN);
- cipher.cipher = ChaCha20::from_keystream(keystream_at(key, &[9; 12], u32::MAX));
+ cipher.cipher = stream_cipher_over(keystream_at(key, &[9; 12], u32::MAX));
cipher.data_len = MAX_MESSAGE_LEN - 64;
cipher
}
diff --git a/crypto/chacha20/src/hazmat.rs b/crypto/chacha20/src/hazmat.rs
index e7843a95..d83a061b 100644
--- a/crypto/chacha20/src/hazmat.rs
+++ b/crypto/chacha20/src/hazmat.rs
@@ -8,6 +8,7 @@
//! and is the cipher to use.
use crate::{BLOCK_LEN, ChaCha20Key, KEY_LEN, NONCE_LEN};
+use bouncycastle_cipher::stream::hazmat::PermutationFreeKeyStream;
use bouncycastle_core::errors::{KeyMaterialError, SymmetricCipherError};
use bouncycastle_core::hazmat::KeyStream;
use bouncycastle_core::key_material::{KeyMaterial, KeyMaterialTrait, KeyType};
@@ -123,6 +124,9 @@ pub fn keystream_at<'k>(
ChaCha20KeyStream::start_at(&key.state, nonce, initial_counter)
}
+// The block function is all there is: no block permutation, so no decrypt-only one.
+impl PermutationFreeKeyStream for ChaCha20KeyStream<'_> {}
+
impl Algorithm for ChaCha20KeyStream<'_> {
const ALG_NAME: &'static str = "ChaCha20";
const MAX_SECURITY_STRENGTH: SecurityStrength = SecurityStrength::_256bit;
diff --git a/crypto/chacha20/src/lib.rs b/crypto/chacha20/src/lib.rs
index 81700f1e..af8fdd2a 100644
--- a/crypto/chacha20/src/lib.rs
+++ b/crypto/chacha20/src/lib.rs
@@ -83,6 +83,7 @@
pub mod hazmat;
use bouncycastle_cipher::stream::StreamCipher;
+use bouncycastle_cipher::stream::hazmat::stream_cipher_over;
use bouncycastle_cipher::{Decrypting, Encrypting};
use bouncycastle_core::errors::SymmetricCipherError;
use bouncycastle_core::key_material::{KeyMaterial, KeyType};
@@ -154,14 +155,14 @@ impl SymmetricEncryptionKey for ChaCha20Key {
) -> Result<(Self::Encryptor<'k>, [u8; NONCE_LEN]), SymmetricCipherError> {
let mut nonce = [0u8; NONCE_LEN];
rng.next_bytes_out(&mut nonce)?;
- Ok((ChaCha20::from_keystream(ChaCha20KeyStream::start_at(&self.state, &nonce, 0)), nonce))
+ Ok((stream_cipher_over(ChaCha20KeyStream::start_at(&self.state, &nonce, 0)), nonce))
}
/// Under a nonce the caller supplies, for the protocols RFC 8439 Sec 2.4 has in mind ("In some
/// protocols, this is known as the Initialization Vector"); it "MUST not be repeated for the
/// same key", which is then the caller's to ensure.
fn create_encryptor_nonce<'k>(&'k self, nonce: &[u8; NONCE_LEN]) -> Self::Encryptor<'k> {
- ChaCha20::from_keystream(ChaCha20KeyStream::start_at(&self.state, nonce, 0))
+ stream_cipher_over(ChaCha20KeyStream::start_at(&self.state, nonce, 0))
}
}
@@ -172,6 +173,6 @@ impl SymmetricDecryptionKey for ChaCha20Key {
Self: 'k;
fn create_decryptor<'k>(&'k self, nonce: &[u8; NONCE_LEN]) -> Self::Decryptor<'k> {
- ChaCha20::from_keystream(ChaCha20KeyStream::start_at(&self.state, nonce, 0))
+ stream_cipher_over(ChaCha20KeyStream::start_at(&self.state, nonce, 0))
}
}
diff --git a/crypto/chacha20/tests/chacha20_bc-test-data.rs b/crypto/chacha20/tests/chacha20_bc-test-data.rs
index 2081b61c..086a2ad5 100644
--- a/crypto/chacha20/tests/chacha20_bc-test-data.rs
+++ b/crypto/chacha20/tests/chacha20_bc-test-data.rs
@@ -2,6 +2,7 @@
use bouncycastle_chacha20::hazmat::keystream_at;
use bouncycastle_chacha20::{ChaCha20, ChaCha20Key};
use bouncycastle_cipher::Encrypting;
+use bouncycastle_cipher::stream::hazmat::stream_cipher_over;
use bouncycastle_core::hazmat::do_hazardous_operations;
use bouncycastle_core::key_material::{KeyMaterial, KeyMaterialTrait, KeyType};
use bouncycastle_core::security_strength::SecurityStrength;
@@ -45,5 +46,5 @@ fn rfc8439_blocks_encryption_and_one_time_keys() {
/// The RFC's vectors start at counters other than 0, which only the hazmat keystream takes.
fn at<'k>(key: &'k ChaCha20Key, nonce: &[u8; 12], counter: u32) -> ChaCha20<'k, Encrypting> {
- ChaCha20::from_keystream(keystream_at(key, nonce, counter))
+ stream_cipher_over(keystream_at(key, nonce, counter))
}
diff --git a/crypto/chacha20/tests/chacha20_tests.rs b/crypto/chacha20/tests/chacha20_tests.rs
index e8dc97df..9a40e1d6 100644
--- a/crypto/chacha20/tests/chacha20_tests.rs
+++ b/crypto/chacha20/tests/chacha20_tests.rs
@@ -1,5 +1,6 @@
use bouncycastle_chacha20::hazmat::{ChaCha20KeyStream, keystream_at};
use bouncycastle_chacha20::{ChaCha20, ChaCha20Key};
+use bouncycastle_cipher::stream::hazmat::stream_cipher_over;
use bouncycastle_cipher::{Decrypting, Encrypting};
use bouncycastle_core::errors::{KeyMaterialError, SymmetricCipherError};
use bouncycastle_core::hazmat::KeyStream;
@@ -23,7 +24,7 @@ fn key() -> ChaCha20Key {
}
fn at<'k>(key: &'k ChaCha20Key, nonce: &[u8; 12], counter: u32) -> ChaCha20<'k, Encrypting> {
- ChaCha20::from_keystream(keystream_at(key, nonce, counter))
+ stream_cipher_over(keystream_at(key, nonce, counter))
}
#[test]
@@ -98,7 +99,7 @@ fn a_keystream_at_its_last_counter_has_no_blocks_left() {
ks.apply_blocks(&mut [[0u8; 64]; 1]);
assert_eq!(ks.remaining_blocks(), 0);
assert!(matches!(
- ChaCha20::::from_keystream(ks).do_encrypt_inplace(&mut [0u8; 1]),
+ stream_cipher_over::<_, Encrypting, 12, 64>(ks).do_encrypt_inplace(&mut [0u8; 1]),
Err(SymmetricCipherError::DataLimitExceeded)
));
}
diff --git a/crypto/cipher/src/lib.rs b/crypto/cipher/src/lib.rs
index 0a2f6e8f..ecc33e31 100644
--- a/crypto/cipher/src/lib.rs
+++ b/crypto/cipher/src/lib.rs
@@ -42,3 +42,9 @@ pub use key::BlockCipherKey;
// `bouncycastle_cipher::{Encrypting, Decrypting, Direction}` stays the path the cipher crates
// use; the MAC crates take them from `core`, which does not depend on this crate.
pub use bouncycastle_core::direction::{Decrypting, Direction, Encrypting};
+
+pub(crate) mod sealed {
+ /// Private supertrait of [`KeyStreamPolicy`](crate::stream::KeyStreamPolicy): only this
+ /// crate's keystream types implement it, beside their definitions.
+ pub trait Sealed {}
+}
diff --git a/crypto/cipher/src/modes/cbc.rs b/crypto/cipher/src/modes/cbc.rs
index ef805b26..e52d70d7 100644
--- a/crypto/cipher/src/modes/cbc.rs
+++ b/crypto/cipher/src/modes/cbc.rs
@@ -147,6 +147,12 @@ where
state: &'k Self::KeyState,
rng: &mut dyn RNG,
) -> Result<(Self::Encryptor<'k>, [u8; BLOCK_LEN]), SymmetricCipherError> {
+ const {
+ assert!(
+ !P::DECRYPT_ONLY,
+ "this permutation decrypts only (BlockPermutation::DECRYPT_ONLY): no encrypting worker may be made over it"
+ )
+ };
let iv = random_iv::(rng)?;
Ok((PaddedBlockCipherEncryptor::from_inner(Cbc::from_perm(state, iv)), iv))
}
@@ -155,6 +161,12 @@ where
state: &'k Self::KeyState,
iv: &[u8; BLOCK_LEN],
) -> Self::Encryptor<'k> {
+ const {
+ assert!(
+ !P::DECRYPT_ONLY,
+ "this permutation decrypts only (BlockPermutation::DECRYPT_ONLY): no encrypting worker may be made over it"
+ )
+ };
PaddedBlockCipherEncryptor::from_inner(Cbc::from_perm(state, *iv))
}
}
@@ -192,6 +204,12 @@ where
state: &'k Self::KeyState,
rng: &mut dyn RNG,
) -> Result<(Self::Encryptor<'k>, [u8; BLOCK_LEN]), SymmetricCipherError> {
+ const {
+ assert!(
+ !P::DECRYPT_ONLY,
+ "this permutation decrypts only (BlockPermutation::DECRYPT_ONLY): no encrypting worker may be made over it"
+ )
+ };
let iv = random_iv::(rng)?;
Ok((Cbc::from_perm(state, iv), iv))
}
@@ -200,6 +218,12 @@ where
state: &'k Self::KeyState,
iv: &[u8; BLOCK_LEN],
) -> Self::Encryptor<'k> {
+ const {
+ assert!(
+ !P::DECRYPT_ONLY,
+ "this permutation decrypts only (BlockPermutation::DECRYPT_ONLY): no encrypting worker may be made over it"
+ )
+ };
Cbc::from_perm(state, *iv)
}
}
diff --git a/crypto/cipher/src/modes/ccm.rs b/crypto/cipher/src/modes/ccm.rs
index 80f4b163..78fb82bb 100644
--- a/crypto/cipher/src/modes/ccm.rs
+++ b/crypto/cipher/src/modes/ccm.rs
@@ -98,7 +98,7 @@
use crate::modes::ModeNames;
use crate::modes::ctr::apply_counter_blocks;
use crate::modes::iv::random_iv;
-use crate::stream::StreamCipher;
+use crate::stream::{KeyStreamPolicy, StreamCipher};
use bouncycastle_core::errors::SymmetricCipherError;
use bouncycastle_core::hazmat::{
AeadDeclaredDecryptMode, AeadDeclaredEncryptMode, AeadDecryptMode, AeadEncryptMode,
@@ -114,7 +114,7 @@ use bouncycastle_utils::ct::ct_eq_bytes;
use bouncycastle_utils::secret::Secret;
use core::marker::PhantomData;
-use crate::{Decrypting, Encrypting};
+use crate::{Decrypting, Direction, Encrypting};
/// CCM (SP 800-38C) over any [`ElectronicCodeBook`] with a 128-bit block, for Sec 3's "packet
/// environment, i.e., when all of the data is available in storage before CCM is applied": the
@@ -167,6 +167,7 @@ impl<'k, P, Dir, const BLOCK_LEN: usize, const NONCE_LEN: usize, const TAG_LEN:
Ccm<'k, P, Dir, BLOCK_LEN, NONCE_LEN, TAG_LEN>
where
P: BlockPermutation + ModeNames,
+ Dir: Direction,
{
/// The spec's `q`: the octet length of the payload-length field `Q`. A.1 requires `n + q = 15`.
const Q_LEN: usize = CcmKeyStream::::Q_LEN;
@@ -621,6 +622,7 @@ impl<'k, P, Dir, const BLOCK_LEN: usize, const NONCE_LEN: usize, const TAG_LEN:
for Ccm<'k, P, Dir, BLOCK_LEN, NONCE_LEN, TAG_LEN>
where
P: BlockPermutation + ModeNames,
+ Dir: Direction,
{
/// The permutation's name for this mode, [`ModeNames::CCM_ALG_NAME`].
const ALG_NAME: &'static str = P::CCM_ALG_NAME;
@@ -717,6 +719,21 @@ where
const MAX_SECURITY_STRENGTH: SecurityStrength = P::MAX_SECURITY_STRENGTH;
}
+impl<'k, P, const BLOCK_LEN: usize, const NONCE_LEN: usize> crate::sealed::Sealed
+ for CcmKeyStream<'k, P, BLOCK_LEN, NONCE_LEN>
+where
+ P: BlockPermutation + ModeNames,
+{
+}
+
+impl<'k, P, const BLOCK_LEN: usize, const NONCE_LEN: usize> KeyStreamPolicy
+ for CcmKeyStream<'k, P, BLOCK_LEN, NONCE_LEN>
+where
+ P: BlockPermutation + ModeNames,
+{
+ const DECRYPT_ONLY: bool = P::DECRYPT_ONLY;
+}
+
impl<'k, P, const BLOCK_LEN: usize, const NONCE_LEN: usize> KeyStream
for CcmKeyStream<'k, P, BLOCK_LEN, NONCE_LEN>
where
@@ -788,6 +805,7 @@ impl<
> CcmAdapter<'k, P, Dir, BLOCK_LEN, NONCE_LEN, TAG_LEN, AAD_LEN, DATA_LEN>
where
P: BlockPermutation + ModeNames,
+ Dir: Direction,
{
/// The compile-time check for the trait adapters, run from both [`CcmPacketEncryptor`]'s and
/// [`CcmPacketDecryptor`]'s constructors and from their one-shots, which never build an adapter, so
diff --git a/crypto/cipher/src/modes/cfb.rs b/crypto/cipher/src/modes/cfb.rs
index 1b34b971..4147af96 100644
--- a/crypto/cipher/src/modes/cfb.rs
+++ b/crypto/cipher/src/modes/cfb.rs
@@ -184,6 +184,12 @@ where
state: &'k Self::KeyState,
rng: &mut dyn RNG,
) -> Result<(Self::Encryptor<'k>, [u8; BLOCK_LEN]), SymmetricCipherError> {
+ const {
+ assert!(
+ !P::DECRYPT_ONLY,
+ "this permutation decrypts only (BlockPermutation::DECRYPT_ONLY): no encrypting worker may be made over it"
+ )
+ };
// `I1 = IV`.
let iv = random_iv::(rng)?;
Ok((Cfb::start(state, iv), iv))
@@ -193,6 +199,12 @@ where
state: &'k Self::KeyState,
iv: &[u8; BLOCK_LEN],
) -> Self::Encryptor<'k> {
+ const {
+ assert!(
+ !P::DECRYPT_ONLY,
+ "this permutation decrypts only (BlockPermutation::DECRYPT_ONLY): no encrypting worker may be made over it"
+ )
+ };
Cfb::start(state, *iv)
}
}
diff --git a/crypto/cipher/src/modes/cfb8.rs b/crypto/cipher/src/modes/cfb8.rs
index 6e543848..34be4968 100644
--- a/crypto/cipher/src/modes/cfb8.rs
+++ b/crypto/cipher/src/modes/cfb8.rs
@@ -93,6 +93,12 @@ where
state: &'k Self::KeyState,
rng: &mut dyn RNG,
) -> Result<(Self::Encryptor<'k>, [u8; BLOCK_LEN]), SymmetricCipherError> {
+ const {
+ assert!(
+ !P::DECRYPT_ONLY,
+ "this permutation decrypts only (BlockPermutation::DECRYPT_ONLY): no encrypting worker may be made over it"
+ )
+ };
// `I1 = IV`.
let iv = random_iv::(rng)?;
Ok((Cfb8 { perm: state, chain: iv, _dir: PhantomData }, iv))
@@ -102,6 +108,12 @@ where
state: &'k Self::KeyState,
iv: &[u8; BLOCK_LEN],
) -> Self::Encryptor<'k> {
+ const {
+ assert!(
+ !P::DECRYPT_ONLY,
+ "this permutation decrypts only (BlockPermutation::DECRYPT_ONLY): no encrypting worker may be made over it"
+ )
+ };
Cfb8 { perm: state, chain: *iv, _dir: PhantomData }
}
}
diff --git a/crypto/cipher/src/modes/cmac.rs b/crypto/cipher/src/modes/cmac.rs
index c7d73279..703827bd 100644
--- a/crypto/cipher/src/modes/cmac.rs
+++ b/crypto/cipher/src/modes/cmac.rs
@@ -83,7 +83,10 @@ use core::marker::PhantomData;
/// block length, 16 by default and 8 for a 64-bit block cipher; it is a parameter because stable
/// Rust cannot read it off the permutation from inside the mode impl, as for `CTR`. It is also
/// the tag length. The impls below are generic over any [`BlockPermutation`] of that block
-/// length.
+/// length. A permutation that decrypts only (`BlockPermutation::DECRYPT_ONLY`) gets a verifier
+/// and no generator: `generate_init` refuses it at compile time, as the encrypting constructors
+/// of the cipher modes do, so a key over it can check tags and not produce them (SP 800-131A
+/// Rev 2 Table 9: two-key TDEA CMAC generation "Disallowed", verification "Legacy use").
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct CMAC;
@@ -113,6 +116,12 @@ where
P: 'k;
fn generate_init<'k>(state: &'k Self::KeyState) -> Self::Generator<'k> {
+ const {
+ assert!(
+ !P::DECRYPT_ONLY,
+ "this permutation decrypts only (BlockPermutation::DECRYPT_ONLY): no MAC generator may be made over it"
+ )
+ };
Cmac::from_key_state(state)
}
diff --git a/crypto/cipher/src/modes/ctr.rs b/crypto/cipher/src/modes/ctr.rs
index b79663c4..962f9baf 100644
--- a/crypto/cipher/src/modes/ctr.rs
+++ b/crypto/cipher/src/modes/ctr.rs
@@ -163,6 +163,12 @@ where
state: &'k Self::KeyState,
rng: &mut dyn RNG,
) -> Result<(Self::Encryptor<'k>, [u8; NONCE_LEN]), SymmetricCipherError> {
+ const {
+ assert!(
+ !P::DECRYPT_ONLY,
+ "this permutation decrypts only (BlockPermutation::DECRYPT_ONLY): no encrypting worker may be made over it"
+ )
+ };
let nonce = random_iv::(rng)?;
Ok((StreamCipher::from_keystream(CtrKeyStream::from_perm(state, nonce)), nonce))
}
diff --git a/crypto/cipher/src/modes/gcm.rs b/crypto/cipher/src/modes/gcm.rs
index bae9c324..c57da701 100644
--- a/crypto/cipher/src/modes/gcm.rs
+++ b/crypto/cipher/src/modes/gcm.rs
@@ -183,7 +183,7 @@
use crate::modes::Ctr;
use crate::modes::ModeNames;
use crate::modes::hazmat::ctr_key_stream::CtrKeyStream;
-use crate::{Decrypting, Encrypting};
+use crate::{Decrypting, Direction, Encrypting};
use bouncycastle_core::errors::SymmetricCipherError;
use bouncycastle_core::hazmat::{
AeadDecryptMode, AeadEncryptMode, BlockPermutation, ElectronicCodeBook, Mode,
@@ -351,6 +351,7 @@ where
impl<'k, P, Dir, const TAG_LEN: usize> Gcm<'k, P, Dir, TAG_LEN>
where
P: BlockPermutation<16> + ModeNames,
+ Dir: Direction,
{
/// The compile-time shape check: `TAG_LEN` must be one of Sec 5.2.1.2's five recommended tag
/// lengths in bytes (96, 104, 112, 120, 128 bits -- Appendix C's 32- and 64-bit tags are a
@@ -490,6 +491,7 @@ where
impl<'k, P, Dir, const TAG_LEN: usize> Algorithm for Gcm<'k, P, Dir, TAG_LEN>
where
P: BlockPermutation<16> + ModeNames,
+ Dir: Direction,
{
const ALG_NAME: &'static str = P::GCM_ALG_NAME;
const MAX_SECURITY_STRENGTH: SecurityStrength = P::MAX_SECURITY_STRENGTH;
@@ -1233,7 +1235,7 @@ mod tests {
/// The CTR half positioned at the last counter block under `nonce`: 16 bytes of keystream
/// left, as a worker that had encrypted `2^32 - 3` blocks would have.
- fn ctr_at_the_last_block(
+ fn ctr_at_the_last_block(
state: &GcmKeyState,
nonce: [u8; GCM_NONCE_LEN],
) -> Ctr<'_, Toy, Dir, 16, GCM_NONCE_LEN> {
diff --git a/crypto/cipher/src/modes/hazmat/ctr_key_stream.rs b/crypto/cipher/src/modes/hazmat/ctr_key_stream.rs
index 18d7f040..409588e6 100644
--- a/crypto/cipher/src/modes/hazmat/ctr_key_stream.rs
+++ b/crypto/cipher/src/modes/hazmat/ctr_key_stream.rs
@@ -11,7 +11,7 @@ use bouncycastle_core::traits::Algorithm;
#[allow(unused_imports)]
use crate::modes::Ctr;
#[allow(unused_imports)]
-use crate::stream::StreamCipher;
+use crate::stream::{KeyStreamPolicy, StreamCipher};
// end of imports needed for docs
/// The CTR keystream `Oj = CIPH_K(Tj)` (SP 800-38A Sec 6.5) over any [`BlockPermutation`], with
@@ -126,6 +126,21 @@ where
const MAX_SECURITY_STRENGTH: SecurityStrength = P::MAX_SECURITY_STRENGTH;
}
+impl<'k, P, const BLOCK_LEN: usize, const INIT_DATA_LEN: usize> crate::sealed::Sealed
+ for CtrKeyStream<'k, P, BLOCK_LEN, INIT_DATA_LEN>
+where
+ P: BlockPermutation + ModeNames,
+{
+}
+
+impl<'k, P, const BLOCK_LEN: usize, const INIT_DATA_LEN: usize> KeyStreamPolicy
+ for CtrKeyStream<'k, P, BLOCK_LEN, INIT_DATA_LEN>
+where
+ P: BlockPermutation + ModeNames,
+{
+ const DECRYPT_ONLY: bool = P::DECRYPT_ONLY;
+}
+
impl<'k, P, const BLOCK_LEN: usize, const INIT_DATA_LEN: usize> KeyStream
for CtrKeyStream<'k, P, BLOCK_LEN, INIT_DATA_LEN>
where
diff --git a/crypto/cipher/src/modes/hazmat/ecb.rs b/crypto/cipher/src/modes/hazmat/ecb.rs
index 952ca536..7941fcf0 100644
--- a/crypto/cipher/src/modes/hazmat/ecb.rs
+++ b/crypto/cipher/src/modes/hazmat/ecb.rs
@@ -117,6 +117,12 @@ where
P: 'k;
fn encrypt_init<'k>(state: &'k Self::KeyState) -> Self::Encryptor<'k> {
+ const {
+ assert!(
+ !P::DECRYPT_ONLY,
+ "this permutation decrypts only (BlockPermutation::DECRYPT_ONLY): no encrypting worker may be made over it"
+ )
+ };
Ecb::from_perm(state)
}
}
@@ -153,10 +159,22 @@ where
state: &'k Self::KeyState,
_rng: &mut dyn RNG,
) -> Result<(Self::Encryptor<'k>, [u8; 0]), SymmetricCipherError> {
+ const {
+ assert!(
+ !P::DECRYPT_ONLY,
+ "this permutation decrypts only (BlockPermutation::DECRYPT_ONLY): no encrypting worker may be made over it"
+ )
+ };
Ok((PaddedBlockCipherEncryptor::from_inner(Ecb::from_perm(state)), []))
}
fn encrypt_init_nonce<'k>(state: &'k Self::KeyState, _: &[u8; 0]) -> Self::Encryptor<'k> {
+ const {
+ assert!(
+ !P::DECRYPT_ONLY,
+ "this permutation decrypts only (BlockPermutation::DECRYPT_ONLY): no encrypting worker may be made over it"
+ )
+ };
PaddedBlockCipherEncryptor::from_inner(Ecb::from_perm(state))
}
}
diff --git a/crypto/cipher/src/modes/kw.rs b/crypto/cipher/src/modes/kw.rs
index 60efc6a6..95758e3c 100644
--- a/crypto/cipher/src/modes/kw.rs
+++ b/crypto/cipher/src/modes/kw.rs
@@ -73,12 +73,13 @@
//! ));
//! ```
//!
-//! # No direction marker
+//! # The direction is in the type
//!
-//! Unlike [`Ecb`](crate::modes::hazmat::ecb::Ecb) and the other modes, [`Kw`] has no `Dir`
-//! parameter. The wrapping and unwrapping halves are already separate traits ([`KeyWrapper`] /
-//! [`KeyUnwrapper`]), so a policy can import one trait and not the other, and there is no
-//! per-direction state for a marker type to select.
+//! [`Kw<'k, P, Dir>`](Kw) carries [`Encrypting`] or [`Decrypting`] as the cipher modes do:
+//! [`KeyWrapper`] is implemented for the encrypting worker alone and [`KeyUnwrapper`] for the
+//! decrypting one, so an unwrapper has no wrapping method to call, and a permutation that
+//! decrypts only ([`BlockPermutation::DECRYPT_ONLY`]) is refused a wrapper at compile time in
+//! `wrap_init`. The worker has no per-direction state; the marker is zero-sized.
//!
//! # The wrapping function runs in place, without the shift register
//!
@@ -120,6 +121,7 @@
//! [`KeyUnwrappingKey`]: bouncycastle_core::symmetric_key::KeyUnwrappingKey
use super::ModeNames;
+use crate::{Decrypting, Encrypting};
use bouncycastle_core::errors::SymmetricCipherError;
use bouncycastle_core::hazmat::{
BlockPermutation, ElectronicCodeBook, KeyUnwrapMode, KeyWrapMode, Mode,
@@ -129,6 +131,7 @@ use bouncycastle_core::security_strength::SecurityStrength;
use bouncycastle_core::traits::{Algorithm, KeyUnwrapper, KeyWrapper};
use bouncycastle_utils::ct::ct_eq_bytes;
use bouncycastle_utils::secret::Secret;
+use core::marker::PhantomData;
/// The block length, in bytes, of the permutation under KW and KWP. SP 800-38F Sec 5.1: "For KW
/// and KWP, the underlying block cipher shall be approved, and the block size shall be 128 bits."
@@ -167,71 +170,87 @@ pub(crate) const fn kw_wrapped_len(len: usize) -> usize {
len.saturating_add(SEMIBLOCK_LEN)
}
-/// The wrapping function W (SP 800-38F Algorithm 1), in place over `S = a || r`.
+/// The wrapping function W (SP 800-38F Algorithm 1), in place over `S = a || r`, with
+/// `SEMI`-byte semiblocks over a `BLOCK`-byte permutation: 8 and 16 for KW and KWP, 4 and 8 for
+/// TKW, whose TW (Algorithm 7) is this same loop with `[t]32` in place of `[t]64`.
///
/// `a` holds `S1` and `r` holds `S2 .. Sn`, so `r.len() == n - 1`, which must be at least 2
/// (Algorithm 1 is defined for `n >= 3`). On return `a` holds `C1` and `r` holds `C2 .. Cn`.
///
/// Runs in place rather than through the shift register of the spec's step 2; see the module
/// docs for why the two are the same computation.
-pub(crate) fn w(perm: &P, a: &mut [u8; SEMIBLOCK_LEN], r: &mut [[u8; SEMIBLOCK_LEN]])
-where
- P: BlockPermutation,
+pub(crate) fn w(
+ perm: &P,
+ a: &mut [u8; SEMI],
+ r: &mut [[u8; SEMI]],
+) where
+ P: BlockPermutation,
{
+ const { assert!(2 * SEMI == BLOCK, "a semiblock is half a block (SP 800-38F Sec 4.1)") };
debug_assert!(r.len() >= 2, "Algorithm 1 is defined on n >= 3 semiblocks");
// Everything that passes through `block` is derived from the key being wrapped, so it is
// scrubbed when this function returns.
- let mut block: Secret<[u8; KW_BLOCK_LEN]> = Secret::new();
+ let mut block: Secret<[u8; BLOCK]> = Secret::new();
// Step 1a: s = 6(n-1) steps, indexed by t = 1, ..., s.
let mut t: u64 = 0;
for _ in 0..6 {
for r_i in r.iter_mut() {
t += 1;
// Step 2: CIPH_K(A_{t-1} || R2_{t-1}), where R2_{t-1} is this register (module docs).
- let (halves, _) = block.as_chunks_mut::();
+ let (halves, _) = block.as_chunks_mut::();
halves[0] = *a;
halves[1] = *r_i;
perm.encrypt_block(&mut block);
- let (halves, _) = block.as_chunks::();
- // Step 2a: A_t = MSB64(CIPH_K(...)) xor [t]64.
+ let (halves, _) = block.as_chunks::();
+ // Step 2a: A_t = MSB(CIPH_K(...)) xor [t]: the counter as a big-endian semiblock, the
+ // low SEMI bytes of its 8-byte form.
+ let t_bytes = t.to_be_bytes();
for (a_byte, (c_byte, t_byte)) in
- a.iter_mut().zip(halves[0].iter().zip(t.to_be_bytes()))
+ a.iter_mut().zip(halves[0].iter().zip(&t_bytes[8 - SEMI..]))
{
*a_byte = c_byte ^ t_byte;
}
- // Step 2c: R_n_t = LSB64(CIPH_K(...)), which lands back in this register.
+ // Step 2c: R_n_t = LSB(CIPH_K(...)), which lands back in this register.
*r_i = halves[1];
}
}
debug_assert_eq!(t as usize, 6 * r.len(), "Algorithm 1 step 1a: s = 6(n-1)");
}
-/// The unwrapping function W⁻¹ (SP 800-38F Algorithm 2), in place over `C = a || r`.
+/// The unwrapping function W⁻¹ (SP 800-38F Algorithm 2), in place over `C = a || r`, with the
+/// same `BLOCK` / `SEMI` parameters as [`w`] (TW⁻¹, Algorithm 8, is the 4-byte-semiblock form).
///
/// `a` holds `C1` and `r` holds `C2 .. Cn`, with `r.len() == n - 1 >= 2`. On return `a` holds
/// `S1` and `r` holds `S2 .. Sn`. The registers are visited in the reverse of the order [`w`]
/// visits them, so that step `t` here undoes step `t` there.
-pub(crate) fn w_inv(perm: &P, a: &mut [u8; SEMIBLOCK_LEN], r: &mut [[u8; SEMIBLOCK_LEN]])
-where
- P: BlockPermutation,
+pub(crate) fn w_inv(
+ perm: &P,
+ a: &mut [u8; SEMI],
+ r: &mut [[u8; SEMI]],
+) where
+ P: BlockPermutation,
{
+ const { assert!(2 * SEMI == BLOCK, "a semiblock is half a block (SP 800-38F Sec 4.1)") };
debug_assert!(r.len() >= 2, "Algorithm 2 is defined on n >= 3 semiblocks");
- let mut block: Secret<[u8; KW_BLOCK_LEN]> = Secret::new();
+ let mut block: Secret<[u8; BLOCK]> = Secret::new();
// Step 1a: s = 6(n-1); step 2 runs t = s, s-1, ..., 1.
let mut t: u64 = 6 * r.len() as u64;
for _ in 0..6 {
for r_i in r.iter_mut().rev() {
- // Steps 2a/2b: CIPH⁻¹_K((A_t xor [t]64) || R_n_t), where R_n_t is this register.
- let (halves, _) = block.as_chunks_mut::();
- for (b, (a_byte, t_byte)) in halves[0].iter_mut().zip(a.iter().zip(t.to_be_bytes())) {
+ // Steps 2a/2b: CIPH⁻¹_K((A_t xor [t]) || R_n_t), where R_n_t is this register.
+ let t_bytes = t.to_be_bytes();
+ let (halves, _) = block.as_chunks_mut::();
+ for (b, (a_byte, t_byte)) in
+ halves[0].iter_mut().zip(a.iter().zip(&t_bytes[8 - SEMI..]))
+ {
*b = a_byte ^ t_byte;
}
halves[1] = *r_i;
perm.decrypt_block(&mut block);
- let (halves, _) = block.as_chunks::();
- // Step 2a: A_{t-1} = MSB64(...).
+ let (halves, _) = block.as_chunks::();
+ // Step 2a: A_{t-1} = MSB(...).
*a = halves[0];
- // Step 2b: R2_{t-1} = LSB64(...), which lands back in this register.
+ // Step 2b: R2_{t-1} = LSB(...), which lands back in this register.
*r_i = halves[1];
t -= 1;
}
@@ -261,11 +280,17 @@ where
P: ElectronicCodeBook + ModeNames + Clone,
{
type Wrapper<'k>
- = Kw<'k, P>
+ = Kw<'k, P, Encrypting>
where
P: 'k;
fn wrap_init<'k>(state: &'k Self::KeyState) -> Self::Wrapper<'k> {
+ const {
+ assert!(
+ !P::DECRYPT_ONLY,
+ "this permutation decrypts only (BlockPermutation::DECRYPT_ONLY): no wrapper may be made over it"
+ )
+ };
Kw::from_perm(state)
}
}
@@ -275,7 +300,7 @@ where
P: ElectronicCodeBook + ModeNames + Clone,
{
type Unwrapper<'k>
- = Kw<'k, P>
+ = Kw<'k, P, Decrypting>
where
P: 'k;
@@ -287,28 +312,29 @@ where
/// KW over any 128-bit permutation that impls [`BlockPermutation`]: the one-shot worker a
/// [`KW`]-bound key hands out, borrowing the keyed permutation for `'k`.
///
-/// There is no state beyond the borrow and no direction marker: both halves of the algorithm are
-/// the [`KeyWrapper`] and [`KeyUnwrapper`] traits, which this type implements together. See the
-/// module docs for usage and the security notes.
-pub struct Kw<'k, P>
+/// There is no state beyond the borrow; `Dir` is [`Encrypting`] for the wrapper, which alone
+/// implements [`KeyWrapper`], and [`Decrypting`] for the unwrapper, which alone implements
+/// [`KeyUnwrapper`]. See the module docs for usage and the security notes.
+pub struct Kw<'k, P, Dir>
where
P: BlockPermutation + ModeNames,
{
perm: &'k P,
+ _dir: PhantomData,
}
-impl<'k, P> Kw<'k, P>
+impl<'k, P, Dir> Kw<'k, P, Dir>
where
P: BlockPermutation + ModeNames,
{
/// Over an already-keyed permutation, which the worker borrows: what [`KW`]'s mode impls
/// build for a key's roles.
pub(crate) fn from_perm(perm: &'k P) -> Self {
- Self { perm }
+ Self { perm, _dir: PhantomData }
}
}
-impl<'k, P> Algorithm for Kw<'k, P>
+impl<'k, P, Dir> Algorithm for Kw<'k, P, Dir>
where
P: BlockPermutation + ModeNames,
{
@@ -318,7 +344,7 @@ where
const MAX_SECURITY_STRENGTH: SecurityStrength = P::MAX_SECURITY_STRENGTH;
}
-impl<'k, P> KeyWrapper for Kw<'k, P>
+impl<'k, P> KeyWrapper for Kw<'k, P, Encrypting>
where
P: BlockPermutation + ModeNames,
{
@@ -374,12 +400,12 @@ where
r.copy_from_slice(plaintext);
let (r, _) = r.as_chunks_mut::();
// Step 3: C = W(S).
- w(self.perm, a, r);
+ w::(self.perm, a, r);
Ok(ct_len)
}
}
-impl<'k, P> KeyUnwrapper for Kw<'k, P>
+impl<'k, P> KeyUnwrapper for Kw<'k, P, Decrypting>
where
P: BlockPermutation + ModeNames,
{
@@ -437,7 +463,7 @@ where
let r = &mut plaintext[..pt_len];
r.copy_from_slice(&ciphertext[SEMIBLOCK_LEN..]);
let (r, _) = r.as_chunks_mut::();
- w_inv(self.perm, &mut a, r);
+ w_inv::(self.perm, &mut a, r);
// Step 3: if MSB64(S) != ICV1, FAIL. Compared in constant time, and the buffer is scrubbed
// so that a caller who ignores the `Result` is not left holding the unauthenticated bytes.
diff --git a/crypto/cipher/src/modes/kwp.rs b/crypto/cipher/src/modes/kwp.rs
index 2266f383..1026730e 100644
--- a/crypto/cipher/src/modes/kwp.rs
+++ b/crypto/cipher/src/modes/kwp.rs
@@ -61,6 +61,7 @@
use super::ModeNames;
use super::kw::{KW_BLOCK_LEN, SEMIBLOCK_LEN, w, w_inv};
+use crate::{Decrypting, Encrypting};
use bouncycastle_core::errors::SymmetricCipherError;
use bouncycastle_core::hazmat::{
BlockPermutation, ElectronicCodeBook, KeyUnwrapMode, KeyWrapMode, Mode,
@@ -70,6 +71,7 @@ use bouncycastle_core::security_strength::SecurityStrength;
use bouncycastle_core::traits::{Algorithm, KeyUnwrapper, KeyWrapper};
use bouncycastle_utils::ct::{ct_eq_bytes, ct_eq_zero_bytes};
use bouncycastle_utils::secret::Secret;
+use core::marker::PhantomData;
/// ICV2, the integrity check value of KWP (Algorithm 5, step 1): `0xA65959A6`.
const ICV2: [u8; 4] = [0xA6, 0x59, 0x59, 0xA6];
@@ -124,11 +126,17 @@ where
P: ElectronicCodeBook + ModeNames + Clone,
{
type Wrapper<'k>
- = Kwp<'k, P>
+ = Kwp<'k, P, Encrypting>
where
P: 'k;
fn wrap_init<'k>(state: &'k Self::KeyState) -> Self::Wrapper<'k> {
+ const {
+ assert!(
+ !P::DECRYPT_ONLY,
+ "this permutation decrypts only (BlockPermutation::DECRYPT_ONLY): no wrapper may be made over it"
+ )
+ };
Kwp::from_perm(state)
}
}
@@ -138,7 +146,7 @@ where
P: ElectronicCodeBook + ModeNames + Clone,
{
type Unwrapper<'k>
- = Kwp<'k, P>
+ = Kwp<'k, P, Decrypting>
where
P: 'k;
@@ -148,27 +156,28 @@ where
}
/// KWP over any 128-bit permutation that impls [`BlockPermutation`]: the one-shot worker a
-/// [`KWP`]-bound key hands out, borrowing the keyed permutation for `'k`, as
-/// [`Kw`](super::kw::Kw) does. See the module docs.
-pub struct Kwp<'k, P>
+/// [`KWP`]-bound key hands out, borrowing the keyed permutation for `'k` and carrying its
+/// direction in `Dir`, as [`Kw`](super::kw::Kw) does. See the module docs.
+pub struct Kwp<'k, P, Dir>
where
P: BlockPermutation + ModeNames,
{
perm: &'k P,
+ _dir: PhantomData,
}
-impl<'k, P> Kwp<'k, P>
+impl<'k, P, Dir> Kwp<'k, P, Dir>
where
P: BlockPermutation + ModeNames,
{
/// Over an already-keyed permutation, which the worker borrows: what [`KWP`]'s mode impls
/// build for a key's roles.
pub(crate) fn from_perm(perm: &'k P) -> Self {
- Self { perm }
+ Self { perm, _dir: PhantomData }
}
}
-impl<'k, P> Algorithm for Kwp<'k, P>
+impl<'k, P, Dir> Algorithm for Kwp<'k, P, Dir>
where
P: BlockPermutation + ModeNames,
{
@@ -178,7 +187,7 @@ where
const MAX_SECURITY_STRENGTH: SecurityStrength = P::MAX_SECURITY_STRENGTH;
}
-impl<'k, P> KeyWrapper for Kwp<'k, P>
+impl<'k, P> KeyWrapper for Kwp<'k, P, Encrypting>
where
P: BlockPermutation + ModeNames,
{
@@ -245,13 +254,13 @@ where
let (a, r) = s.split_at_mut(SEMIBLOCK_LEN);
let (a, _) = a.as_chunks_mut::