Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
55 commits
Select commit Hold shift + click to select a range
6746a41
core: KeyMaterialError::WeakKey, for a key an algorithm's specificati…
dghgit Sep 8, 2026
4e573e6
cli: block-mode plumbing takes the block length as a const parameter …
dghgit Sep 8, 2026
3ce0987
core: ElectronicCodeBook::ENCRYPTION_APPROVED (default true) marks a …
dghgit Sep 8, 2026
7a0e425
modes: the Encrypting direction of Ecb, Cbc, Cfb, Cfb8 and Ctr assert…
dghgit Sep 8, 2026
6d1656c
tdes: add bouncycastle-tdes, a constant-time table-free TDEA engine (…
dghgit Sep 8, 2026
b2d327e
tdes: drop the summary.md reviewer-orientation doc
dghgit Sep 19, 2026
eeebbf2
mem_usage_benches: fence bench_tdes_mem_usage's shell recipes as ```text
dghgit Sep 19, 2026
b931d49
tdes: fix the three CFB/CFB8/CTR doctests broken by StreamCipherEncry…
dghgit Sep 20, 2026
84015ab
tdes: adapt to feature/simple-ciphers -- the API changes this branch …
dghgit Sep 28, 2026
af64b54
tdes: adapt to feature/simple-ciphers 0fb4e79 -- the TDES_CFB/CFB8/CT…
dghgit Sep 29, 2026
ae476ea
tdes: adopt the hazmat layout (#156 step 5)
dghgit Oct 1, 2026
27a5856
tdes: project TDES_CBC and TDES_ECB through core's sealed Direction::…
dghgit Oct 1, 2026
7d74ee3
tdes: the adaptations the dropped merges carried -- bouncycastle-ciph…
dghgit Oct 24, 2026
cb57079
tdes: onto the key objects -- TDESKey<P, M> hands out the mode worker…
dghgit Oct 24, 2026
7d1e7cc
tdes: the two engines and the keys compare in constant time
dghgit Oct 25, 2026
3604a59
tdes: review fixes -- the keys' redundant key-type check goes, the st…
dghgit Oct 28, 2026
a9fb3dc
cli: the tdes commands take the aes contract -- PKCS7, --iv/--iv-file…
dghgit Oct 28, 2026
0b195ae
tdes: the stack table sums the frame chain, as the AES table does
dghgit Oct 30, 2026
620b86e
tdes: a key checks the key type its mode asks for before the engine does
dghgit Oct 30, 2026
ec4eb5c
tdes: the clippy nits from the camellia round
dghgit Oct 30, 2026
3b920bb
tdes: the PR #142 findings that apply here -- the mode and key docs s…
dghgit Nov 3, 2026
a83f737
tdes: the merge-time adaptations to feature/key-rework-memory, carrie…
dghgit Nov 3, 2026
f3f1515
core, cipher, tdes: the decryption-only gate is BlockPermutation::DEC…
dghgit Nov 4, 2026
657f758
tdes: spread goes through ct::value_barrier off x86-64 and aarch64, s…
dghgit Nov 4, 2026
fd55fc5
cli: the tdes-* encrypt commands refuse input past SP 800-67 Rev 2 Se…
dghgit Nov 4, 2026
79a2c34
Merge release/0.1.4alpha 1bee29d8 (cipher workers no longer implement…
dghgit Nov 4, 2026
a4289b2
Merge release/0.1.4alpha 8ea9d6c2 (PR #157: ChaCha20, Poly1305 and Ch…
dghgit Nov 5, 2026
1b83492
Merge release/0.1.4alpha 27b83ede (PR #160: AES Key Wrap, KW and KWP)…
dghgit Nov 5, 2026
9a00e1a
cipher: TKW, the TDEA key wrap of SP 800-38F Sec 7, as a mode over an…
dghgit Nov 5, 2026
e3622a3
tdes, cli: TDES3Key<TKW> wraps keys and TDES2Key<TKW> unwraps them; t…
dghgit Nov 5, 2026
becb91a
Merge release/0.1.4alpha bbb31d5f (PR #143: ECDSA, SM2 and the ec cra…
dghgit Nov 6, 2026
cf6e5a4
cipher, aes: Kw and Kwp carry their direction in the type
dghgit Nov 6, 2026
3509db5
cipher, tdes: Tkw carries its direction in the type, so a two-key unw…
dghgit Nov 6, 2026
608642a
cli, tdes: tdes-tkw and tdes-cfb8 encrypt count the blocks TDEA proce…
dghgit Nov 6, 2026
c028af9
cipher, core, cli, tdes, dev_scripts: the round-3 nits of the PR #139…
dghgit Nov 6, 2026
e719c94
Release notes: TDES
dghgit Nov 6, 2026
8c49c33
Merge release/0.1.4alpha 11bf46c1 (ec, ecdsa, sm2 rustdoc links) into…
dghgit Nov 7, 2026
56544ee
Merge release/0.1.4alpha a801bc74 (PRs #141 and #140: Camellia and SM…
dghgit Nov 7, 2026
4de6f85
Merge release/0.1.4alpha 3f130f67 (fix/block-cipher-key: BlockCipherK…
dghgit Nov 7, 2026
4b29ecf
tdes: the ElectronicCodeBook conformance test names its framework run…
dghgit Nov 7, 2026
100e0bd
Merge release/0.1.4alpha 0193cb22 (fix/shared-bitslice: utils::bitsli…
dghgit Nov 7, 2026
bb6bddc
Merge release/0.1.4alpha c2db8107 (fix/signature-workers-dyn: the sig…
dghgit Nov 7, 2026
9e40efe
Merge release/0.1.4alpha f3fdb8bf (PR #192 squash: KEM encapsulation …
dghgit Nov 8, 2026
0a4184f
Merge release/0.1.4alpha 563978a7 (fix/supplied-nonce squash: create_…
dghgit Nov 8, 2026
7cb618d
Merge release/0.1.4alpha 61442241 (PR #194 squash: the MAC worker tra…
dghgit Nov 10, 2026
eb647cc
cipher: CMAC's generating constructor refuses a decrypt-only permutation
dghgit Nov 10, 2026
dcf0ded
core: the DECRYPT_ONLY contract names MAC generators and Table 9
dghgit Nov 10, 2026
0bf4d98
tdes: CMAC over TDEA stated and tested, and the data limit given per …
dghgit Nov 10, 2026
9249570
release notes: two-key TDEA verifies CMAC only, and the ARIA, Camelli…
dghgit Nov 10, 2026
3c8c1f1
cipher, tdes: the supplied-IV constructors carry the DECRYPT_ONLY gat…
dghgit Nov 11, 2026
e14b150
tdes: the CMAC tests, the NIST samples and the ACVP CMAC-TDES sets
dghgit Nov 11, 2026
3c7fa45
tdes: CMAC over TDEA reports a name
dghgit Nov 11, 2026
67ae72d
Merge release/0.1.4alpha 7cb54e02 (PR #193 squash: two-party key agre…
dghgit Nov 11, 2026
7c0683c
Merge release/0.1.4alpha f87a69e1 (fix/ec-keygen squash: one key pair…
dghgit Nov 11, 2026
7d60a21
Merge release/0.1.4alpha f213c9e4 (fix/ec-curve-markers, fix/ec-curve…
dghgit Nov 13, 2026
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -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" }
Expand Down Expand Up @@ -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
12 changes: 12 additions & 0 deletions alpha_0.1.4_release_notes.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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.
Expand Down
17 changes: 11 additions & 6 deletions cli/src/cbc_cmd.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand All @@ -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<P, const KEY_LEN: usize>(
Expand Down Expand Up @@ -60,10 +62,13 @@ fn run<K, const KEY_LEN: usize>(
|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,
),
}
}
5 changes: 4 additions & 1 deletion cli/src/cfb8_cmd.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand All @@ -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<P, const KEY_LEN: usize>(
Expand Down
5 changes: 4 additions & 1 deletion cli/src/cfb_cmd.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand All @@ -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<P, const KEY_LEN: usize>(
Expand Down
5 changes: 4 additions & 1 deletion cli/src/ctr_cmd.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand All @@ -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
Expand Down
9 changes: 6 additions & 3 deletions cli/src/ecb_cmd.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand All @@ -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
Expand Down Expand Up @@ -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,
Expand Down
90 changes: 81 additions & 9 deletions cli/src/helpers/block_mode_helpers.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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.
///
Expand Down Expand Up @@ -232,11 +236,70 @@ pub(crate) fn start_encryptor<E, const INIT_DATA_LEN: usize>(
/// 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<E, const INIT_DATA_LEN: usize>(
pub(crate) fn encrypt_stream<E, const INIT_DATA_LEN: usize, const BLOCK_LEN: usize>(
enc: E,
generated_iv: Option<&[u8; INIT_DATA_LEN]>,
output_hex: bool,
aligned_mode: Option<&str>,
) where
E: SymmetricCipherEncryptor<INIT_DATA_LEN, BLOCK_LEN>,
{
encrypt_stream_bounded::<E, INIT_DATA_LEN, BLOCK_LEN>(
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<E, const INIT_DATA_LEN: usize, const BLOCK_LEN: usize>(
mut enc: E,
generated_iv: Option<&[u8; INIT_DATA_LEN]>,
output_hex: bool,
aligned_mode: Option<&str>,
limit: Option<&InputLimit>,
) where
E: SymmetricCipherEncryptor<INIT_DATA_LEN, BLOCK_LEN>,
{
Expand All @@ -246,8 +309,17 @@ pub(crate) fn encrypt_stream<E, const INIT_DATA_LEN: usize>(
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.
Expand All @@ -256,7 +328,7 @@ pub(crate) fn encrypt_stream<E, const INIT_DATA_LEN: usize>(
});

if let Some(mode) = aligned_mode {
check_aligned(mode, total);
check_aligned::<BLOCK_LEN>(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| {
Expand All @@ -271,7 +343,7 @@ pub(crate) fn encrypt_stream<E, const INIT_DATA_LEN: usize>(
/// 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<D, const INIT_DATA_LEN: usize>(
pub(crate) fn decrypt_stream<D, const INIT_DATA_LEN: usize, const BLOCK_LEN: usize>(
iv: Option<[u8; INIT_DATA_LEN]>,
make_decryptor: impl FnOnce(&[u8; INIT_DATA_LEN]) -> D,
output_hex: bool,
Expand Down Expand Up @@ -306,7 +378,7 @@ pub(crate) fn decrypt_stream<D, const INIT_DATA_LEN: usize>(
});

if let Some(mode) = aligned_mode {
check_aligned(mode, total);
check_aligned::<BLOCK_LEN>(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.
Expand Down Expand Up @@ -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<const BLOCK_LEN: usize>(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
Expand Down
33 changes: 30 additions & 3 deletions cli/src/helpers/stream_mode_helpers.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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};
Expand All @@ -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<KEY_LEN, INIT_DATA_LEN, 0>,
K::Encryptor<'k>: StreamCipherEncryptor<INIT_DATA_LEN>,
Expand All @@ -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.
Expand Down Expand Up @@ -152,10 +163,26 @@ pub(crate) fn run_stream_mode<'k, K, const KEY_LEN: usize, const INIT_DATA_LEN:
+ SymmetricDecryptionKey<KEY_LEN, INIT_DATA_LEN, 0>,
K::Encryptor<'k>: StreamCipherEncryptor<INIT_DATA_LEN>,
K::Decryptor<'k>: StreamCipherDecryptor<INIT_DATA_LEN>,
{
run_stream_mode_bounded::<K, KEY_LEN, INIT_DATA_LEN>(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<KEY_LEN, INIT_DATA_LEN, 0>
+ SymmetricDecryptionKey<KEY_LEN, INIT_DATA_LEN, 0>,
K::Encryptor<'k>: StreamCipherEncryptor<INIT_DATA_LEN>,
K::Decryptor<'k>: StreamCipherDecryptor<INIT_DATA_LEN>,
{
match action {
CipherDirection::Encrypt => {
encrypt_stream::<K, KEY_LEN, INIT_DATA_LEN>(key, iv, output_hex)
encrypt_stream::<K, KEY_LEN, INIT_DATA_LEN>(key, iv, output_hex, limit)
}
CipherDirection::Decrypt => {
decrypt_stream::<K, KEY_LEN, INIT_DATA_LEN>(key, iv, output_hex)
Expand Down
Loading
Loading