diff --git a/.gitignore b/.gitignore index 6d42084d..c1ef8598 100644 --- a/.gitignore +++ b/.gitignore @@ -5,3 +5,13 @@ mutants.out*/ .idea/ .vscode/ + +# Claude Code: ignore personal/local state, but share team tooling +# (skills, slash commands, subagents, and project settings.json). +.claude/* +!.claude/settings.json +!.claude/skills/ +!.claude/commands/ +!.claude/agents/ +.claude/settings.local.json +.claude 2/ diff --git a/CLAUDE.md b/CLAUDE.md index 6219e32e..66c3592f 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -33,12 +33,15 @@ fixed. ## Common commands -Build / test / bench / docs run against the cargo workspace from the repo root: +Build / test / bench / docs run against the cargo workspace from the repo root. `--workspace` is +not optional: the root manifest is both the workspace and the umbrella `bouncycastle` package, so a +bare `cargo build` builds only that package (no `cli`, no benches) and a bare `cargo test` runs +**zero** tests and still exits 0, because the umbrella crate has none of its own. ``` -cargo build # whole workspace incl. `bc-rust` CLI binary +cargo build --workspace # whole workspace incl. `bc-rust` CLI binary cargo build -p bouncycastle-sha3 # one sub-crate -cargo test # all tests +cargo test --workspace # all tests cargo test -p bouncycastle-mlkem # tests for one crate cargo test -p bouncycastle-mlkem ml_kem_tests # one integration test file cargo bench --all # all criterion benches @@ -54,19 +57,25 @@ Quality / mutation testing: cargo mutants # config in .cargo/mutants.toml (output: custom_mutants_output/) ``` -Stack-memory benches are separate binaries under `mem_usage_benches/`: +Stack-memory benches are separate binaries under `mem_usage_benches/src/`, each declared as a +`[[bin]]` in that crate's `Cargo.toml`: ``` cargo run --release -p mem_usage_benches --bin bench_mlkem_mem_usage cargo run --release -p mem_usage_benches --bin bench_mldsa_mem_usage ``` +`mem_usage_benches/src/lib.rs` makes those sources modules of a lib target as well, so their `//!` +headers are rustdoc'd and any indented or fenced block in them is compiled as a Rust doctest. The +valgrind and `ms_print` recipes there are fenced as ```` ```text ```` for that reason — keep it that +way when adding a harness, or `cargo test --workspace` fails to compile them. + ## Workspace architecture The workspace has three top-level kinds of member: -1. `crypto/*` — one sub-crate per primitive (`sha2`, `sha3`, `hmac`, `hkdf`, `mlkem`, `mlkem_lowmemory`, `mldsa`, `mldsa_lowmemory`, `rng`, `hex`, `base64`, `utils`) plus the spine crates `core`, `core-test-framework`, and `factory`. Each crate is published as `bouncycastle-` and depended on internally via the `workspace.dependencies` table in the root `Cargo.toml`. -2. `src/` — the umbrella `bouncycastle` crate, which is just `pub use` re-exports of every sub-crate (e.g. `bouncycastle::sha3`, `bouncycastle::mlkem`). It exists so downstream users can pull the whole library with one dependency; it has no code of its own. +1. `crypto/*` — one sub-crate per primitive (`sha2`, `sha3`, `sm3`, `hmac`, `hkdf`, `mlkem`, `mlkem_lowmemory`, `mldsa`, `mldsa_lowmemory`, `rng`, `hex`, `base64`, `utils`) plus the spine crates `core`, `core-test-framework`, and `factory`. Each crate is published as `bouncycastle-` and depended on internally via the `workspace.dependencies` table in the root `Cargo.toml`. +2. `src/` — the umbrella `bouncycastle` crate, which is just `pub use` re-exports of every sub-crate (e.g. `bouncycastle::sha3`, `bouncycastle::sm3`, `bouncycastle::mlkem`). It exists so downstream users can pull the whole library with one dependency; it has no code of its own. 3. `cli/` — the `bc-rust` binary built on top of `bouncycastle`, exposing every primitive as a streaming stdin→stdout subcommand using `clap`. 4. `mem_usage_benches/` — stand-alone binary crates that measure peak stack usage of algorithms (cannot be done via criterion). @@ -109,6 +118,19 @@ Repo mechanics behind those rules, which the documents don't spell out: pipelines; preserve that when adding subcommands. - Trait → factory → CLI is the wiring path for a new primitive; see [the workspace architecture](#the-core--core-test-framework--factory-spine) above for the crates involved. +## Scope of changes + +Implement what was asked and stop. Unrequested refactors — extracting a trait, renaming for +readability, restructuring impls — are not free even when they are correct: bundled into a feature +commit they make the diff unreviewable, because a reviewer cannot separate the new behaviour from +the restructuring, and the review time that costs is the reason not to do it. + +- If a refactor genuinely unblocks the task, give it **its own commit ahead of** the feature, so it + can be reviewed or dropped on its own. +- If it unblocks nothing, propose it and wait rather than doing it. +- The same goes for drive-by comment rewrites, reformatting and file moves in code you are only + passing through. + ## Working from specifications QUALITY_AND_STYLE.md is where the requirement for spec-corresponding comments and justified deviations lives. This @@ -144,10 +166,11 @@ What a crate must be tested against — including the mutation-testing expectati external vector suites — is specified in QUALITY_AND_STYLE.md and CONTRIBUTING.md. Repo-specific mechanics: - `cargo mutants` is expected to be run on each crate; surviving mutants must be investigated but not all need to die (e.g. XOR/OR equivalences in crypto code are acceptable). Config lives in `.cargo/mutants.toml` (output dir `custom_mutants_output/`). -- Behaviour-critical private functions can use in-file `#[cfg(test)] mod tests` blocks when they can't be exercised from outside the crate. +- Integration tests in `tests/` are preferred over in-file `#[cfg(test)] mod tests` blocks — see "Unit tests vs integration tests" in QUALITY_AND_STYLE.md for the reasoning and the exceptions. A unit test is justified for high-risk code that has known-answer values and cannot be reached through the public API; when you write one, all of its helpers go inside that `mod tests`. +- A property that can be asserted at compile time (`const _: () = assert!(...)`) stays a compile-time assertion even when a test also covers it: `cargo mutants` cannot see a const assertion fail, so pair the two rather than trading the guarantee for the coverage. - For traits in `core`, the canonical tests live in `core-test-framework` and are invoked from each implementor's integration tests — don't duplicate them per-implementation. - The per-width `impl Condition` blocks in `crypto/utils/src/ct.rs` (and their test modules) are deliberately duplicated rather than macro-generated: `cargo mutants` cannot see into `macro_rules!` bodies, so a macro would hide the mask identities from mutation testing. Do not fold them back into a macro. Any change to one width in a group (i64/i32, u64/u32) must be applied to every width in that group. ## CI -The only workflow is `.github/workflows/publish_doc_benches_to_ghpages.yaml`: on every PR it builds rustdoc and runs `quality_stats.sh`; on `main` it additionally runs `cargo bench --all` and publishes docs, code stats, and benchmark results to GitHub Pages (`https://bcgit.github.io/bc-rust/`). There is no separate CI test/lint job — local `cargo test` is the gate. \ No newline at end of file +The only workflow is `.github/workflows/publish_doc_benches_to_ghpages.yaml`: on every PR it builds rustdoc and runs `quality_stats.sh`; on `main` it additionally runs `cargo bench --all` and publishes docs, code stats, and benchmark results to GitHub Pages (`https://bcgit.github.io/bc-rust/`). There is no separate CI test/lint job — local `cargo test --workspace` is the gate, and nothing but a developer running it stands between a broken test and `main`. \ No newline at end of file diff --git a/Cargo.toml b/Cargo.toml index 82b379fe..557468b9 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -9,7 +9,9 @@ version = "0.1.3" # *** Internal Dependencies *** bouncycastle = { path = "./" } +bouncycastle-aes-lowmemory = { path = "./crypto/aes-lowmemory" } bouncycastle-base64 = { path = "./crypto/base64" } +bouncycastle-modes = { path = "./crypto/modes" } bouncycastle-core = { path = "crypto/core" } bouncycastle-core-test-framework = { path = "./crypto/core-test-framework" } bouncycastle-factory = { path = "./crypto/factory" } @@ -20,9 +22,11 @@ bouncycastle-mlkem = { path = "./crypto/mlkem" } bouncycastle-mlkem-lowmemory = { path = "./crypto/mlkem-lowmemory" } bouncycastle-mldsa = { path = "./crypto/mldsa" } bouncycastle-mldsa-lowmemory = { path = "./crypto/mldsa-lowmemory" } +bouncycastle-padding = { path = "./crypto/padding" } bouncycastle-rng = { path = "./crypto/rng" } bouncycastle-sha2 = { path = "./crypto/sha2" } bouncycastle-sha3 = { path = "./crypto/sha3" } +bouncycastle-sm3 = { path = "./crypto/sm3" } bouncycastle-utils = { path = "./crypto/utils" } @@ -41,6 +45,7 @@ version.workspace = true edition.workspace = true [dependencies] +bouncycastle-aes-lowmemory.workspace = true bouncycastle-base64.workspace = true bouncycastle-core.workspace = true bouncycastle-factory.workspace = true @@ -51,6 +56,9 @@ bouncycastle-mldsa.workspace = true bouncycastle-mldsa-lowmemory.workspace = true bouncycastle-mlkem.workspace = true bouncycastle-mlkem-lowmemory.workspace = true +bouncycastle-modes.workspace = true +bouncycastle-padding.workspace = true bouncycastle-rng.workspace = true bouncycastle-sha2.workspace = true bouncycastle-sha3.workspace = true +bouncycastle-sm3.workspace = true diff --git a/QUALITY_AND_STYLE.md b/QUALITY_AND_STYLE.md index 65f7e7e0..382c3582 100644 --- a/QUALITY_AND_STYLE.md +++ b/QUALITY_AND_STYLE.md @@ -128,6 +128,36 @@ Note that rust macros tend not to play well with a lot of dev tooling for compil `cargo mutants`, which is a good reason to avoid macros in core algorithm or data processing code. Macros can be used more freely within test code. +## Unit tests vs integration tests + +Unit tests are test code (and supporting helper functions) embedded in src/**.rs files. They have access to +crate-private or module-private functions and constants. + +Integration tests are test code (and supporting helper functions) in tests/**.rs files. They test the crate's code from +the outside -- ie through its public APIs -- since tests/ is a separate crate from src/. + +In general, integration tests are preferred over unit tests. This is for a number of reasons: + +* To reduce reviewer burden; reviewers will typically focus more effort on the src/ than the tests/, so we want to keep + src/ as short as is reasonable. +* Usually it is easier to determine what is the correct behaviour at the public API level. For example, this is the + level at which we typically have KATs and test vectors. +* Tools like cargo mutants are very helpful at detecting branches that are not exercisable via the public APIs, which + often is an indicator that the branch isn't doing what you think it's doing, or is simply not useful and can be + deleted. Unit tests that bypass the public APIs to pin these sorts of branches obscure the fact that this code is + unreachable. + +Unit tests are reasonable to include in the following cases: + +* There is high-risk code (usually meaning that it is complex code whose behaviour is not obvious from inspection) where + unit tests help to document the behaviour and protect against accidental breakage via a benign-looking change. +* AND where known answer tests are available. +* AND where this behaviour cannot be tested from integration tests. + +When writing unit tests, they should be contained with an `mod tests` at the bottom of the file, and ALL helper +functions that support the unit tests must be contained within that module. The intention is to clearly signal to a code +reviewer what is test code vs functional code. + # Docs ## Usage Examples diff --git a/alpha_0.1.3_release_notes.md b/alpha_0.1.3_release_notes.md index 57f9e97c..d5185528 100644 --- a/alpha_0.1.3_release_notes.md +++ b/alpha_0.1.3_release_notes.md @@ -2,8 +2,20 @@ ## Major features +* New algorithms added to crypto/ : + * SM3 -- the SM3 hash (GB/T 32905-2016 / ISO/IEC 10118-3:2018), ported from bc-java. + * AES -- AES-128/192/256, along with its modes AES_ECB, AES_CBC, AES_GCM. + ## Minor features / bug fixes -* bug fixes to the way SHA3/SHAKE handled absorbing and squeezing a partial final byte. * Design discussions about whether core::traits::XOF (in the abstract) should allow interleaving absorb -> squeeze -> absorb (ie "absorb-after-squeeze). Outcome: absorb-after-squeeze forbidden. Could be changed in the future. +* SHA2: + * Implemented SHA512/224 and SHA512/256. + * `Hash::do_final_partial_bits()` / `do_final_partial_bits_out()` are now implemented for SHA-2 (FIPS 180-4 s. 5.1). +* SHA3: + * Fixed a bug in `XOF::squeeze_partial_byte_final()`: when it was the first squeeze it bypassed the SHAKE `1111` + domain suffix and returned raw Keccak output, and it returned the wrong `num_bits` bits of the output byte. The + existing test used + `0xFF`, which masked the second error. + * Changed the order of bits when absorbing a final partial byte to match ASN.1 DER BIT_STRING bit ordering. diff --git a/cli/src/aes_cbc_cmd.rs b/cli/src/aes_cbc_cmd.rs new file mode 100644 index 00000000..d8f4a72c --- /dev/null +++ b/cli/src/aes_cbc_cmd.rs @@ -0,0 +1,68 @@ +//! AES-CBC encryption and decryption, streaming stdin to stdout. +//! +//! Only the mode wiring lives here: the IV convention, key loading, stdin framing and +//! block-alignment enforcement are all in [`crate::block_mode_cmd`], shared with the `aes*-cfb` and +//! `aes*-ecb` commands. See that module for the command-line contract. +//! +//! CBC (NIST SP 800-38A Sec 6.2) 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. + +use crate::block_mode_cmd::{BLOCK_LEN, BlockModeAction, decrypt_stream, encrypt_stream, load_key}; +use bouncycastle::aes_lowmemory::{Aes128, Aes192, Aes256}; +use bouncycastle::core::key_material::KeyMaterial; +use bouncycastle::core::traits::ElectronicCodeBook; +use bouncycastle::modes::{Cbc, Decrypting, Encrypting}; + +/// Names the mode in error messages. +const MODE: &str = "CBC"; + +pub(crate) fn aes128_cbc_cmd( + action: &BlockModeAction, + key: &Option, + key_file: &Option, + output_hex: bool, +) { + run::(action, &load_key::<16>(key, key_file, "AES-128"), output_hex); +} + +pub(crate) fn aes192_cbc_cmd( + action: &BlockModeAction, + key: &Option, + key_file: &Option, + output_hex: bool, +) { + run::(action, &load_key::<24>(key, key_file, "AES-192"), output_hex); +} + +pub(crate) fn aes256_cbc_cmd( + action: &BlockModeAction, + key: &Option, + key_file: &Option, + output_hex: bool, +) { + run::(action, &load_key::<32>(key, key_file, "AES-256"), output_hex); +} + +/// Dispatches to the shared streaming loops with `Cbc` filled in as the mode. +fn run( + action: &BlockModeAction, + key: &KeyMaterial, + output_hex: bool, +) where + P: ElectronicCodeBook, +{ + match action { + BlockModeAction::Encrypt => { + encrypt_stream::, KEY_LEN, BLOCK_LEN>( + key, output_hex, MODE, + ) + } + BlockModeAction::Decrypt => { + decrypt_stream::, KEY_LEN, BLOCK_LEN>( + key, output_hex, MODE, + ) + } + } +} diff --git a/cli/src/aes_cfb8_cmd.rs b/cli/src/aes_cfb8_cmd.rs new file mode 100644 index 00000000..29a9e474 --- /dev/null +++ b/cli/src/aes_cfb8_cmd.rs @@ -0,0 +1,76 @@ +//! AES-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::stream_mode_cmd`] (and [`crate::block_mode_cmd`] for the key loader), shared with the +//! `aes*-cfb` commands. See those modules for the command-line contract. +//! +//! # Which CFB +//! +//! These commands are **CFB8**: the segment size is one byte (`s = 8` in NIST SP 800-38A Sec 6.3). +//! That is a different, non-interoperable mode from the CFB128 of `aes*-cfb`, not a variant of it: +//! the two ciphertexts agree on their first byte and differ everywhere after it. It also costs a +//! full AES call per byte of data, sixteen times the work of `aes*-cfb`, so prefer `aes*-cfb` +//! unless a byte-granular self-synchronising stream is required or the format demands CFB8. +//! +//! # Any length +//! +//! CFB8's segment is a single byte, so these commands accept input of any length, pad nothing, and +//! emit a ciphertext exactly as long as the plaintext. +//! +//! # Warning +//! +//! CFB8 provides confidentiality only. It does not detect tampering, and neither the ciphertext nor +//! the IV is authenticated. Appendix D, Table D.2 gives "SBE in the decryption of Cj" plus random +//! errors in the next `b/s` segments: flipping a ciphertext bit flips the *same* bit of the *same* +//! plaintext byte, corrupts the following 16 bytes, and then decryption resynchronises. Do not +//! decrypt data you have not authenticated separately. + +use crate::block_mode_cmd::{BLOCK_LEN, BlockModeAction, load_key}; +use crate::stream_mode_cmd::run_stream_mode; +use bouncycastle::aes_lowmemory::{Aes128, Aes192, Aes256}; +use bouncycastle::core::key_material::KeyMaterial; +use bouncycastle::core::traits::ElectronicCodeBook; +use bouncycastle::modes::{Cfb8, Decrypting, Encrypting}; + +pub(crate) fn aes128_cfb8_cmd( + action: &BlockModeAction, + key: &Option, + key_file: &Option, + output_hex: bool, +) { + run::(action, &load_key::<16>(key, key_file, "AES-128"), output_hex); +} + +pub(crate) fn aes192_cfb8_cmd( + action: &BlockModeAction, + key: &Option, + key_file: &Option, + output_hex: bool, +) { + run::(action, &load_key::<24>(key, key_file, "AES-192"), output_hex); +} + +pub(crate) fn aes256_cfb8_cmd( + action: &BlockModeAction, + key: &Option, + key_file: &Option, + output_hex: bool, +) { + run::(action, &load_key::<32>(key, key_file, "AES-256"), output_hex); +} + +/// Dispatches to the shared streaming loops with `Cfb8` filled in as the mode. +fn run( + action: &BlockModeAction, + key: &KeyMaterial, + output_hex: bool, +) where + P: ElectronicCodeBook, +{ + run_stream_mode::< + Cfb8, + Cfb8, + KEY_LEN, + BLOCK_LEN, + >(action, key, output_hex) +} diff --git a/cli/src/aes_cfb_cmd.rs b/cli/src/aes_cfb_cmd.rs new file mode 100644 index 00000000..dde4491a --- /dev/null +++ b/cli/src/aes_cfb_cmd.rs @@ -0,0 +1,77 @@ +//! AES-CFB128 encryption and decryption, streaming stdin to stdout. +//! +//! Only the mode wiring lives here: the IV convention, key loading and stdin framing are in +//! [`crate::stream_mode_cmd`] (and [`crate::block_mode_cmd`] for the key loader), shared with the +//! `aes*-cfb8` commands. See those modules for the command-line contract. +//! +//! # Which CFB +//! +//! These commands are **CFB128**: the segment size is the full 16-byte block (`s = b` in NIST +//! SP 800-38A Sec 6.3). SP 800-38A also defines `s = 8`, which is a different, non-interoperable +//! mode -- if you need CFB8, the `aes*-cfb8` commands are it -- and `s = 1`, which this library does +//! not provide. +//! +//! # Any length +//! +//! CFB is a stream cipher, so unlike `aes*-cbc` and `aes*-ecb` these commands accept input of any +//! length and pad nothing; the ciphertext is exactly as long as the plaintext. For a message that +//! is not a whole number of blocks the last partial block is a short final segment, which is what +//! every streaming CFB128 implementation does; see the `bouncycastle_modes::Cfb` docs. +//! +//! # Warning +//! +//! CFB provides confidentiality only. It does not detect tampering, and neither the ciphertext nor +//! the IV is authenticated. CFB's malleability is more directly exploitable than CBC's: Appendix D, +//! Table D.2 gives "SBE in the decryption of Cj" -- flipping a ciphertext bit flips the *same* bit +//! 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::block_mode_cmd::{BLOCK_LEN, BlockModeAction, load_key}; +use crate::stream_mode_cmd::run_stream_mode; +use bouncycastle::aes_lowmemory::{Aes128, Aes192, Aes256}; +use bouncycastle::core::key_material::KeyMaterial; +use bouncycastle::core::traits::ElectronicCodeBook; +use bouncycastle::modes::{Cfb, Decrypting, Encrypting}; + +pub(crate) fn aes128_cfb_cmd( + action: &BlockModeAction, + key: &Option, + key_file: &Option, + output_hex: bool, +) { + run::(action, &load_key::<16>(key, key_file, "AES-128"), output_hex); +} + +pub(crate) fn aes192_cfb_cmd( + action: &BlockModeAction, + key: &Option, + key_file: &Option, + output_hex: bool, +) { + run::(action, &load_key::<24>(key, key_file, "AES-192"), output_hex); +} + +pub(crate) fn aes256_cfb_cmd( + action: &BlockModeAction, + key: &Option, + key_file: &Option, + output_hex: bool, +) { + run::(action, &load_key::<32>(key, key_file, "AES-256"), output_hex); +} + +/// Dispatches to the shared streaming loops with `Cfb` filled in as the mode. +fn run( + action: &BlockModeAction, + key: &KeyMaterial, + output_hex: bool, +) where + P: ElectronicCodeBook, +{ + run_stream_mode::< + Cfb, + Cfb, + KEY_LEN, + BLOCK_LEN, + >(action, key, output_hex) +} diff --git a/cli/src/aes_ctr_cmd.rs b/cli/src/aes_ctr_cmd.rs new file mode 100644 index 00000000..611b64c0 --- /dev/null +++ b/cli/src/aes_ctr_cmd.rs @@ -0,0 +1,84 @@ +//! AES-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::stream_mode_cmd`] (and [`crate::block_mode_cmd`] for the key loader), shared with the +//! `aes*-cfb` and `aes*-cfb8` commands. See those modules for the command-line contract. +//! +//! # The nonce is 12 bytes and the counter is 4 +//! +//! 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. These commands use the +//! `AES_CTR_*` aliases, so the nonce is **12 bytes** and the counter is the remaining 4, giving +//! 2^32 blocks -- 64 GiB -- in a single message. +//! +//! `encrypt` writes that 12-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 12 bytes here, not 16. +//! +//! # Any length +//! +//! CTR is a stream cipher: input of any length is accepted, 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, Table D.2, "SBE in the decryption of Cj"), so an attacker can edit the plaintext at +//! will, wherever they like, without any garbling to give it away. 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, and two messages XORed with the same keystream leak their XOR. The +//! nonce is drawn from the OS-backed DRBG for exactly that reason, and there is no way to supply +//! one. + +use crate::block_mode_cmd::{BLOCK_LEN, BlockModeAction, load_key}; +use crate::stream_mode_cmd::run_stream_mode; +use bouncycastle::aes_lowmemory::{Aes128, Aes192, Aes256, CTR_NONCE_LEN}; +use bouncycastle::core::key_material::KeyMaterial; +use bouncycastle::core::traits::ElectronicCodeBook; +use bouncycastle::modes::{Ctr, Decrypting, Encrypting}; + +pub(crate) fn aes128_ctr_cmd( + action: &BlockModeAction, + key: &Option, + key_file: &Option, + output_hex: bool, +) { + run::(action, &load_key::<16>(key, key_file, "AES-128"), output_hex); +} + +pub(crate) fn aes192_ctr_cmd( + action: &BlockModeAction, + key: &Option, + key_file: &Option, + output_hex: bool, +) { + run::(action, &load_key::<24>(key, key_file, "AES-192"), output_hex); +} + +pub(crate) fn aes256_ctr_cmd( + action: &BlockModeAction, + key: &Option, + key_file: &Option, + output_hex: bool, +) { + run::(action, &load_key::<32>(key, key_file, "AES-256"), output_hex); +} + +/// Dispatches to the shared streaming loops with `Ctr` filled in as the mode. +fn run( + action: &BlockModeAction, + key: &KeyMaterial, + output_hex: bool, +) where + P: ElectronicCodeBook, +{ + run_stream_mode::< + Ctr, + Ctr, + KEY_LEN, + CTR_NONCE_LEN, + >(action, key, output_hex) +} diff --git a/cli/src/aes_ecb_cmd.rs b/cli/src/aes_ecb_cmd.rs new file mode 100644 index 00000000..d4dc6f4a --- /dev/null +++ b/cli/src/aes_ecb_cmd.rs @@ -0,0 +1,75 @@ +//! AES-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::block_mode_cmd`], shared with the `aes*-cbc` and `aes*-cfb` commands. See that +//! module for the command-line contract. ECB has no IV (`INIT_DATA_LEN = 0`), so unlike those +//! commands nothing is prepended to the output or consumed from the input: the ciphertext is exactly +//! as long as the plaintext. +//! +//! # Warning +//! +//! ECB (NIST SP 800-38A Sec 6.1) 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. These commands +//! exist for interoperability with systems that use ECB and for driving test vectors; for data, use +//! `aes*-cbc` or `aes*-cfb` under separate authentication, or better an AEAD. + +use crate::block_mode_cmd::{BLOCK_LEN, BlockModeAction, decrypt_stream, encrypt_stream, load_key}; +use bouncycastle::aes_lowmemory::{Aes128, Aes192, Aes256}; +use bouncycastle::core::key_material::KeyMaterial; +use bouncycastle::core::traits::ElectronicCodeBook; +use bouncycastle::modes::{Decrypting, Ecb, Encrypting}; + +/// Names the mode in error messages. +const MODE: &str = "ECB"; + +pub(crate) fn aes128_ecb_cmd( + action: &BlockModeAction, + key: &Option, + key_file: &Option, + output_hex: bool, +) { + run::(action, &load_key::<16>(key, key_file, "AES-128"), output_hex); +} + +pub(crate) fn aes192_ecb_cmd( + action: &BlockModeAction, + key: &Option, + key_file: &Option, + output_hex: bool, +) { + run::(action, &load_key::<24>(key, key_file, "AES-192"), output_hex); +} + +pub(crate) fn aes256_ecb_cmd( + action: &BlockModeAction, + key: &Option, + key_file: &Option, + output_hex: bool, +) { + run::(action, &load_key::<32>(key, key_file, "AES-256"), output_hex); +} + +/// Dispatches to the shared streaming loops with `Ecb` filled in as the mode. `INIT_DATA_LEN` is 0, +/// so the loops write and read no IV. +fn run( + action: &BlockModeAction, + key: &KeyMaterial, + output_hex: bool, +) where + P: ElectronicCodeBook, +{ + match action { + BlockModeAction::Encrypt => { + encrypt_stream::, KEY_LEN, 0>( + key, output_hex, MODE, + ) + } + BlockModeAction::Decrypt => { + decrypt_stream::, KEY_LEN, 0>( + key, output_hex, MODE, + ) + } + } +} diff --git a/cli/src/block_mode_cmd.rs b/cli/src/block_mode_cmd.rs new file mode 100644 index 00000000..ec4a7a87 --- /dev/null +++ b/cli/src/block_mode_cmd.rs @@ -0,0 +1,276 @@ +//! Shared plumbing for the block-cipher-mode subcommands: `aes{128,192,256}-{cbc,ecb}`. +//! +//! Everything here is mode-independent -- key loading, stdin framing, block-alignment enforcement, +//! output formatting -- and is generic over the mode via [`BlockCipherEncryptor`] / +//! [`BlockCipherDecryptor`]. `aes_cbc_cmd` and `aes_ecb_cmd` are thin dispatchers over it, so the +//! commands cannot drift apart on the parts that matter for correctness. +//! +//! The CFB and CTR commands are stream ciphers and live in [`crate::stream_mode_cmd`] instead; +//! they share +//! [`load_key`] and [`BlockModeAction`] with this module, so the key handling and the `encrypt` / +//! `decrypt` spelling stay identical across all of them. +//! +//! # The IV travels in the ciphertext +//! +//! There is no `--iv` flag, and that is deliberate: `bouncycastle-modes` has no API for a +//! caller-supplied IV, because NIST SP 800-38A Sec 5.3 requires the CBC and CFB IV to be +//! *unpredictable* rather than merely unique. `encrypt` therefore generates one from the OS-backed +//! DRBG and writes it as the **first block of the output**; `decrypt` reads it back from the +//! **first block of the input**. So the two compose directly. The framing is generic over the +//! mode's `INIT_DATA_LEN`: for ECB it is 0, so those commands write and read no IV and the +//! ciphertext is exactly as long as the plaintext. +//! +//! ```text +//! bc-rust aes128-cbc encrypt --key-file k.bin < plain.bin > cipher.bin +//! bc-rust aes128-cbc decrypt --key-file k.bin < cipher.bin > plain.bin +//! ``` +//! +//! The IV is not secret (Sec 5.3), so shipping it in the clear is correct. Its *integrity* is not +//! protected, and neither is the ciphertext's -- see the warnings on each subcommand. +//! +//! # Input must be block-aligned +//! +//! The modes in this module are defined only on whole blocks (SP 800-38A Sec 5.2), and these +//! commands apply no padding, so input that is not a multiple of 16 bytes is rejected rather than +//! silently padded. (The CFB commands have no such requirement; see [`crate::stream_mode_cmd`].) +//! Padding is the caller's business; the library offers `bouncycastle-padding` for it, but wiring a +//! padding scheme into the CLI would change the on-the-wire format and is a separate decision. +//! +//! # Binary in, binary out +//! +//! 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: +//! +//! ```text +//! cat cipher.hex | bc-rust hex-decode | bc-rust aes256-cbc decrypt --key-file k.bin +//! ``` + +use crate::helpers::write_bytes_or_hex; +use bouncycastle::core::key_material::{ + KeyMaterial, KeyMaterialTrait, KeyType, do_hazardous_operations, +}; +use bouncycastle::core::traits::{BlockCipherDecryptor, BlockCipherEncryptor, SecurityStrength}; +use bouncycastle::hex; +use clap::ValueEnum; +use std::io::{Read, Write}; +use std::process::exit; +use std::{fs, io}; + +/// The AES block length in bytes. +pub(crate) const BLOCK_LEN: usize = 16; + +/// Bytes processed per call: 1 KiB = 64 blocks, matching the other streaming commands. +/// +/// A full chunk goes through `do_*::` in one call, in place, which for decryption means +/// 32 pairs down the mode's two-block path. The at-most-63-block tail at end of input goes one +/// block at a time; it is bounded, so its cost does not scale with the input. +pub(crate) const CHUNK_LEN: usize = 64 * BLOCK_LEN; + +/// Which direction to run. Shared by every mode subcommand. +#[derive(ValueEnum, Clone, Debug)] +pub(crate) enum BlockModeAction { + /// Encrypt stdin to stdout. + /// For CBC, CFB and CFB8 a freshly generated IV is written as the first 16 bytes of the + /// output, and for CTR a 12-byte nonce, so that `decrypt` can read it back; ECB has neither and + /// writes none. The `-cbc` and `-ecb` commands need the input to be a multiple of 16 bytes; + /// `-cfb`, `-cfb8` and `-ctr` take any length. See the individual subcommand's help. + Encrypt, + /// Decrypt stdin to stdout. + /// For CBC, CFB and CFB8 the first 16 bytes of input are taken as the IV, and for CTR the + /// first 12 as the nonce, as written by `encrypt`; ECB has neither and reads none. See + /// `encrypt` for the input-length rule. + Decrypt, +} + +/// Loads the key from `--key` (hex) or `--key-file` (binary or hex), and checks its length. +/// +/// `KEY_LEN` is exact: AES has three key lengths and the command selects one, so a key of the +/// wrong length is a mistake rather than something to truncate or pad. +pub(crate) fn load_key( + key: &Option, + key_file: &Option, + alg: &str, +) -> KeyMaterial { + let key_bytes: Vec = if let Some(key_file) = key_file { + // A file may hold raw bytes or hex; try hex first, as the other commands do. + let raw = fs::read(key_file).unwrap_or_else(|e| { + eprintln!("Error: couldn't read key file '{key_file}': {e}"); + exit(-1); + }); + match hex::decode(&raw) { + Ok(decoded) => decoded, + Err(_) => raw, + } + } else if let Some(key) = key { + hex::decode(key).unwrap_or_else(|_| { + eprintln!("Error: `--key` must be hex. Use `--key-file` for raw bytes."); + exit(-1); + }) + } else { + eprintln!("Error: either `--key` or `--key-file` must be supplied."); + exit(-1); + }; + + if key_bytes.len() != KEY_LEN { + eprintln!("Error: {alg} needs a {KEY_LEN}-byte key, got {} bytes.", key_bytes.len()); + exit(-1); + } + + // `from_bytes_as_type` tags the key at the strength its length implies, which is exactly what + // the engine requires -- except for an all-zero key, which it marks Zeroized instead. + let mut key = + KeyMaterial::::from_bytes_as_type(&key_bytes, KeyType::SymmetricCipherKey) + .unwrap_or_else(|e| { + eprintln!("Error: couldn't load the key: {e:?}"); + exit(-1); + }); + + if key.key_type() != KeyType::SymmetricCipherKey { + // Same stance as `helpers::parse_seed`: warn, then do what was asked. A CLI is used for + // test vectors and scripting, where an all-zero key is a legitimate thing to want. + eprintln!( + "Warning: all-zero (or otherwise zeroized) key provided. Proceeding, but this is not secure." + ); + do_hazardous_operations(&mut key, |key| { + key.set_key_type(KeyType::SymmetricCipherKey)?; + key.set_security_strength(SecurityStrength::from_bytes(KEY_LEN)) + }) + .unwrap_or_else(|e| { + eprintln!("Error: couldn't tag the key: {e:?}"); + exit(-1); + }); + } + + key +} + +/// Encrypts stdin to stdout under the mode `E`, writing the generated init data (the IV) first. +/// +/// `INIT_DATA_LEN` is the mode's: one block for CBC, 0 for ECB, in which case nothing is written +/// ahead of the ciphertext. `mode` names the mode in error messages ("CBC", "ECB"); it has no +/// effect on the output. +pub(crate) fn encrypt_stream( + key: &KeyMaterial, + output_hex: bool, + mode: &str, +) where + E: BlockCipherEncryptor, +{ + let (mut enc, iv) = E::do_encrypt_init(key).unwrap_or_else(|e| { + eprintln!("Error: couldn't start encryption: {e:?}"); + exit(-1); + }); + + // The IV goes out ahead of the ciphertext, so `decrypt` can pick it up. (Empty for ECB.) + if INIT_DATA_LEN > 0 { + write_bytes_or_hex(&iv, output_hex); + } + + // The cipher works in place: `data` holds plaintext on the way in and ciphertext on the way out. + stream_aligned(mode, |data| { + if let Ok(chunk) = <&mut [u8; CHUNK_LEN]>::try_from(&mut *data) { + // Cannot fail: none of these modes has a per-IV data limit. + enc.do_encrypt(chunk).unwrap(); + } else { + // The bounded tail at end of input: whole blocks, fewer than a chunk. + for block in data.as_chunks_mut::().0 { + enc.do_encrypt(block).unwrap(); + } + } + write_bytes_or_hex(data, output_hex); + }); + + finish(output_hex); +} + +/// Decrypts stdin to stdout under the mode `D`, taking the init data (the IV) from the first +/// `INIT_DATA_LEN` bytes of input -- one block for CBC, nothing for ECB. +pub(crate) fn decrypt_stream( + key: &KeyMaterial, + output_hex: bool, + mode: &str, +) where + D: BlockCipherDecryptor, +{ + // The leading bytes are the IV, not ciphertext. (None for ECB: the read is skipped.) + let mut iv = [0u8; INIT_DATA_LEN]; + if INIT_DATA_LEN > 0 + && let Err(e) = io::stdin().read_exact(&mut iv) + { + eprintln!( + "Error: input too short to contain the {INIT_DATA_LEN}-byte IV that `encrypt` writes \ + as its first block ({e})." + ); + exit(-1); + } + + let mut dec = D::do_decrypt_init(key, &iv).unwrap_or_else(|e| { + eprintln!("Error: couldn't start decryption: {e:?}"); + exit(-1); + }); + + stream_aligned(mode, |data| { + if let Ok(chunk) = <&mut [u8; CHUNK_LEN]>::try_from(&mut *data) { + // A full chunk is 32 pairs, so this is the mode's two-block path. + dec.do_decrypt(chunk).unwrap(); + } else { + for block in data.as_chunks_mut::().0 { + dec.do_decrypt(block).unwrap(); + } + } + write_bytes_or_hex(data, output_hex); + }); + + finish(output_hex); +} + +/// Reads stdin and hands it to `process` in block-aligned pieces, mutably so it can be transformed +/// in place: a full `CHUNK_LEN` bytes each time one has accumulated, then once more at end of input +/// with whatever whole blocks remain (fewer than a chunk). Reads need not respect block or chunk boundaries -- bytes simply accumulate in the +/// buffer until it is full -- so a block split across two reads needs no special handling. +/// +/// Input whose total length is not a multiple of `BLOCK_LEN` is an error, because none of these +/// modes is defined on a partial block and these commands do not pad. +fn stream_aligned(mode: &str, mut process: impl FnMut(&mut [u8])) { + let mut buf = [0u8; CHUNK_LEN]; + let mut filled = 0usize; + + loop { + let n = io::stdin().read(&mut buf[filled..]).unwrap_or_else(|e| { + eprintln!("Error: failed to read from stdin: {e}"); + exit(-1); + }); + if n == 0 { + break; + } + filled += n; + if filled == CHUNK_LEN { + process(&mut buf); + filled = 0; + } + } + + if !filled.is_multiple_of(BLOCK_LEN) { + eprintln!( + "Error: input is not a whole number of {BLOCK_LEN}-byte blocks ({} trailing byte(s)). \ + {mode} is defined only on whole blocks (SP 800-38A Sec 5.2), and these commands apply \ + no padding, so the input must be padded by the caller.", + filled % BLOCK_LEN + ); + exit(-1); + } + if filled != 0 { + process(&mut buf[..filled]); + } +} + +/// Flushes stdout, and adds the trailing newline the hex-output commands all emit. +fn finish(output_hex: bool) { + if output_hex { + println!(); + } + io::stdout().flush().unwrap_or_else(|e| { + eprintln!("Error: failed to flush stdout: {e}"); + exit(-1); + }); +} diff --git a/cli/src/mac_cmd.rs b/cli/src/mac_cmd.rs index 8f095efc..f80fa0ba 100644 --- a/cli/src/mac_cmd.rs +++ b/cli/src/mac_cmd.rs @@ -7,11 +7,16 @@ use bouncycastle::core::key_material::{ }; use bouncycastle::core::traits::MAC; use bouncycastle::hex; -use bouncycastle::sha2::hmac::{HMAC_SHA256, HMAC_SHA512}; +use bouncycastle::sha2::hmac::{HMAC_SHA256, HMAC_SHA512, HMAC_SHA512_224, HMAC_SHA512_256}; +use bouncycastle::sm3::hmac::HMAC_SM3; +#[allow(non_camel_case_types)] pub(crate) enum HMACVariant { SHA256, SHA512, + SHA512_224, + SHA512_256, + SM3, } pub(crate) fn mac_cmd( @@ -48,6 +53,18 @@ pub(crate) fn mac_cmd( let mac = HMAC_SHA512::new_allow_weak_key(&key).unwrap(); do_mac(mac, verify_val, output_hex); } + HMACVariant::SHA512_224 => { + let mac = HMAC_SHA512_224::new_allow_weak_key(&key).unwrap(); + do_mac(mac, verify_val, output_hex); + } + HMACVariant::SHA512_256 => { + let mac = HMAC_SHA512_256::new_allow_weak_key(&key).unwrap(); + do_mac(mac, verify_val, output_hex); + } + HMACVariant::SM3 => { + let mac = HMAC_SM3::new_allow_weak_key(&key).unwrap(); + do_mac(mac, verify_val, output_hex); + } } } diff --git a/cli/src/main.rs b/cli/src/main.rs index c72af13a..2b26315b 100644 --- a/cli/src/main.rs +++ b/cli/src/main.rs @@ -1,3 +1,9 @@ +mod aes_cbc_cmd; +mod aes_cfb8_cmd; +mod aes_cfb_cmd; +mod aes_ctr_cmd; +mod aes_ecb_cmd; +mod block_mode_cmd; mod encoders_cmd; mod helpers; mod hkdf_cmd; @@ -7,9 +13,13 @@ mod mlkem_cmd; mod rng_cmd; mod sha2_cmd; mod sha3_cmd; +mod sm3_cmd; +mod stream_mode_cmd; +use crate::block_mode_cmd::BlockModeAction; use crate::mac_cmd::HMACVariant; use crate::mldsa_cmd::MLDSAAction; +use crate::sha2_cmd::SHA2Variant; use clap::{Parser, Subcommand}; #[derive(Parser)] @@ -70,6 +80,22 @@ enum Subcommands { x: bool, }, + /// Perform SHA512/224 of the content provided on stdin. + /// Supports streaming update for low memory footprint. + SHA512_224 { + #[arg(short)] + /// Output the hashes in hex format. + x: bool, + }, + + /// Perform SHA512/256 of the content provided on stdin. + /// Supports streaming update for low memory footprint. + SHA512_256 { + #[arg(short)] + /// Output the hashes in hex format. + x: bool, + }, + /// Perform SHA3-224 of the content provided on stdin. /// Supports streaming update for low memory footprint. SHA3_224 { @@ -102,6 +128,14 @@ enum Subcommands { x: bool, }, + /// Perform SM3 of the content provided on stdin. + /// Supports streaming update for low memory footprint. + SM3 { + #[arg(short)] + /// Output the hashes in hex format. + x: bool, + }, + /// Perform SHAKE128 of the content provided on stdin. Requires the output length in bytes. /// Supports streaming update for low memory footprint. SHAKE128 { @@ -173,6 +207,80 @@ enum Subcommands { x: bool, }, + /// Perform HMAC-SHA512/224 of the content provided on stdin. + /// Supports streaming update for low memory footprint. + /// 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. + HMAC_SHA512_224 { + /// The MAC key in hex. + /// The `key_file` option is preferred to avoid leaving key material in command history. + #[arg(long)] + key: Option, + + /// A file containing the MAC key in binary. + /// If both key and key_file options are provided, the file will be used. + #[arg(short, long)] + key_file: Option, + + /// A MAC value to be verified. + /// The command will output either 0 for success or -1 for verification failure. + #[arg(short, long)] + verify: Option, + + #[arg(short)] + /// Output the hashes in hex format. + x: bool, + }, + + /// Perform HMAC-SHA512/256 of the content provided on stdin. + /// Supports streaming update for low memory footprint. + /// 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. + HMAC_SHA512_256 { + /// The MAC key in hex. + /// The `key_file` option is preferred to avoid leaving key material in command history. + #[arg(long)] + key: Option, + + /// A file containing the MAC key in binary. + /// If both key and key_file options are provided, the file will be used. + #[arg(short, long)] + key_file: Option, + + /// A MAC value to be verified. + /// The command will output either 0 for success or -1 for verification failure. + #[arg(short, long)] + verify: Option, + + #[arg(short)] + /// Output the hashes in hex format. + x: bool, + }, + /// Perform HMAC-SM3 of the content provided on stdin. + /// Supports streaming update for low memory footprint. + /// 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. + HMAC_SM3 { + /// The MAC key in hex. + /// The `key_file` option is preferred to avoid leaving key material in command history. + #[arg(long)] + key: Option, + + /// A file containing the MAC key in binary. + /// If both key and key_file options are provided, the file will be used. + #[arg(short, long)] + key_file: Option, + + /// A MAC value to be verified. + /// The command will output either 0 for success or -1 for verification failure. + #[arg(short, long)] + verify: Option, + + #[arg(short)] + /// Output the hashes in hex format. + x: bool, + }, + /// Perform HMAC-SHA256 of the content provided on stdin. /// HKDF.extract_and_expand(salt, ikm, additional_info, L) /// Note: in production uses, secrets should not be passed on the command-line because they get @@ -271,6 +379,409 @@ enum Subcommands { x: bool, }, + /// AES-128 in CBC mode (NIST SP 800-38A Sec 6.2), streaming stdin to stdout. + /// + /// On `encrypt`, a fresh unpredictable IV is generated and written as the FIRST 16 BYTES of + /// the output; on `decrypt` it is read back from the first 16 bytes of the input, so the two + /// compose directly in a pipeline. There is deliberately no `--iv` flag. + /// + /// Input must be a whole number of 16-byte blocks: CBC is defined only on whole blocks and + /// these commands apply no padding, so unaligned input is rejected rather than padded. + /// + /// 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. + /// + /// Note: in production uses, secrets should not be passed on the command-line because they get + /// logged in shell history. Use the file-based input instead. + AES128_CBC { + action: BlockModeAction, + + /// The 16-byte AES key 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 AES key, in binary or hex. + /// 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, + }, + + /// AES-192 in CBC mode (NIST SP 800-38A Sec 6.2), streaming stdin to stdout. + /// + /// See `aes128-cbc` for the IV convention, block-alignment requirement and warnings; only the + /// key length differs. + AES192_CBC { + action: BlockModeAction, + + /// The 24-byte AES key 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 AES key, in binary or hex. + /// 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, + }, + + /// AES-256 in CBC mode (NIST SP 800-38A Sec 6.2), streaming stdin to stdout. + /// + /// See `aes128-cbc` for the IV convention, block-alignment requirement and warnings; only the + /// key length differs. + AES256_CBC { + action: BlockModeAction, + + /// The 32-byte AES key in hex. + /// The `key_file` option is preferred to avoid leaving key material in command history. + #[arg(long)] + key: Option, + + /// A file containing the 32-byte AES key, in binary or hex. + /// 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, + }, + + /// AES-128 in CFB128 mode (NIST SP 800-38A Sec 6.3), streaming stdin to stdout. + /// + /// The segment size is the full block, i.e. CFB128. SP 800-38A's 8-bit CFB is a different, + /// non-interoperable mode; use `aes128-cfb8` for that. The 1-bit variant is not provided. + /// + /// On `encrypt`, a fresh unpredictable IV is generated and written as the FIRST 16 BYTES of + /// the output; on `decrypt` it is read back from the first 16 bytes of the input, so the two + /// compose directly in a pipeline. There is deliberately no `--iv` flag. + /// + /// Input may be ANY length: CFB is a stream cipher, so nothing is padded and the ciphertext is + /// exactly as long as the plaintext. + /// + /// WARNING: CFB provides confidentiality only. It does not detect tampering, and neither the + /// ciphertext nor the IV is authenticated. Flipping a ciphertext bit flips the same bit of the + /// plaintext in the same block, so tampering is directly exploitable. Do not decrypt data you + /// have not authenticated separately. + /// + /// Note: in production uses, secrets should not be passed on the command-line because they get + /// logged in shell history. Use the file-based input instead. + AES128_CFB { + action: BlockModeAction, + + /// The 16-byte AES key 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 AES key, in binary or hex. + /// 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, + }, + + /// AES-192 in CFB128 mode (NIST SP 800-38A Sec 6.3), streaming stdin to stdout. + /// + /// See `aes128-cfb` for the IV convention, input-length rule and warnings; only the key length + /// differs. + AES192_CFB { + action: BlockModeAction, + + /// The 24-byte AES key 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 AES key, in binary or hex. + /// 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, + }, + + /// AES-256 in CFB128 mode (NIST SP 800-38A Sec 6.3), streaming stdin to stdout. + /// + /// See `aes128-cfb` for the IV convention, input-length rule and warnings; only the key length + /// differs. + AES256_CFB { + action: BlockModeAction, + + /// The 32-byte AES key in hex. + /// The `key_file` option is preferred to avoid leaving key material in command history. + #[arg(long)] + key: Option, + + /// A file containing the 32-byte AES key, in binary or hex. + /// 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, + }, + + /// AES-128 in CFB8 mode (NIST SP 800-38A Sec 6.3, s = 8), streaming stdin to stdout. + /// + /// The segment size is one byte. This is a DIFFERENT, NON-INTEROPERABLE mode from the CFB128 + /// of `aes128-cfb`: the two ciphertexts agree only on their first byte. It also costs one AES + /// call per byte, sixteen times the work of `aes128-cfb`, so prefer that unless a byte-granular + /// self-synchronising stream is required or the format demands CFB8. + /// + /// On `encrypt`, a fresh unpredictable IV is generated and written as the FIRST 16 BYTES of + /// the output; on `decrypt` it is read back from the first 16 bytes of the input, so the two + /// compose directly in a pipeline. There is deliberately no `--iv` flag. + /// + /// Input may be ANY length: CFB8's segment is a single byte, so nothing is padded and the + /// ciphertext is exactly as long as the plaintext. + /// + /// WARNING: CFB8 provides confidentiality only. It does not detect tampering, and neither the + /// ciphertext nor the IV is authenticated. Flipping a ciphertext bit flips the same bit of the + /// same plaintext byte and corrupts the following 16 bytes, after which decryption + /// resynchronises. Do not decrypt data you have not authenticated separately. + /// + /// Note: in production uses, secrets should not be passed on the command-line because they get + /// logged in shell history. Use the file-based input instead. + AES128_CFB8 { + action: BlockModeAction, + + /// The 16-byte AES key 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 AES key, in binary or hex. + /// 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, + }, + + /// AES-192 in CFB8 mode (NIST SP 800-38A Sec 6.3, s = 8), streaming stdin to stdout. + /// + /// See `aes128-cfb8` for the IV convention, input-length rule and warnings; only the key length + /// differs. + AES192_CFB8 { + action: BlockModeAction, + + /// The 24-byte AES key 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 AES key, in binary or hex. + /// 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, + }, + + /// AES-256 in CFB8 mode (NIST SP 800-38A Sec 6.3, s = 8), streaming stdin to stdout. + /// + /// See `aes128-cfb8` for the IV convention, input-length rule and warnings; only the key length + /// differs. + AES256_CFB8 { + action: BlockModeAction, + + /// The 32-byte AES key in hex. + /// The `key_file` option is preferred to avoid leaving key material in command history. + #[arg(long)] + key: Option, + + /// A file containing the 32-byte AES key, in binary or hex. + /// 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, + }, + + /// AES-128 in CTR mode (NIST SP 800-38A Sec 6.5), streaming stdin to stdout. + /// + /// The counter block is a 12-byte nonce followed by a 4-byte counter starting at zero, so one + /// message can be up to 2^32 blocks (64 GiB); past that the command errors rather than + /// repeating keystream. + /// + /// On `encrypt`, a fresh nonce is generated and written as the FIRST 12 BYTES of the output; + /// on `decrypt` it is read back from the first 12 bytes of the input, so the two compose + /// directly in a pipeline. Note that this is 12 bytes, not the 16 the other modes write. There + /// is deliberately no `--iv` flag. + /// + /// Input may be ANY length: 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 mode here. It does not + /// detect tampering, and flipping any ciphertext bit flips exactly the corresponding plaintext + /// bit and nothing else, so an attacker can edit the plaintext at will with no garbling to give + /// it away. A repeated nonce under one key leaks the XOR of the two messages outright. Do not + /// decrypt data you have not authenticated separately. + /// + /// Note: in production uses, secrets should not be passed on the command-line because they get + /// logged in shell history. Use the file-based input instead. + AES128_CTR { + action: BlockModeAction, + + /// The 16-byte AES key 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 AES key, in binary or hex. + /// 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, + }, + + /// AES-192 in CTR mode (NIST SP 800-38A Sec 6.5), streaming stdin to stdout. + /// + /// See `aes128-ctr` for the nonce convention, input-length rule and warnings; only the key + /// length differs. + AES192_CTR { + action: BlockModeAction, + + /// The 24-byte AES key 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 AES key, in binary or hex. + /// 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, + }, + + /// AES-256 in CTR mode (NIST SP 800-38A Sec 6.5), streaming stdin to stdout. + /// + /// See `aes128-ctr` for the nonce convention, input-length rule and warnings; only the key + /// length differs. + AES256_CTR { + action: BlockModeAction, + + /// The 32-byte AES key in hex. + /// The `key_file` option is preferred to avoid leaving key material in command history. + #[arg(long)] + key: Option, + + /// A file containing the 32-byte AES key, in binary or hex. + /// 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, + }, + + /// AES-128 in ECB mode (NIST SP 800-38A Sec 6.1), streaming stdin to stdout. + /// + /// 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. For data use aes*-cbc or aes*-cfb under separate authentication, or an AEAD. + /// + /// 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 16-byte blocks: this command is block-aligned and applies + /// no padding, so unaligned input is rejected rather than padded. + /// + /// Note: in production uses, secrets should not be passed on the command-line because they get + /// logged in shell history. Use the file-based input instead. + AES128_ECB { + action: BlockModeAction, + + /// The 16-byte AES key 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 AES key, in binary or hex. + /// 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, + }, + + /// AES-192 in ECB mode (NIST SP 800-38A Sec 6.1), streaming stdin to stdout. + /// + /// See `aes128-ecb` for the warning, the absence of an IV and the block-alignment requirement; + /// only the key length differs. + AES192_ECB { + action: BlockModeAction, + + /// The 24-byte AES key 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 AES key, in binary or hex. + /// 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, + }, + + /// AES-256 in ECB mode (NIST SP 800-38A Sec 6.1), streaming stdin to stdout. + /// + /// See `aes128-ecb` for the warning, the absence of an IV and the block-alignment requirement; + /// only the key length differs. + AES256_ECB { + action: BlockModeAction, + + /// The 32-byte AES key in hex. + /// The `key_file` option is preferred to avoid leaving key material in command history. + #[arg(long)] + key: Option, + + /// A file containing the 32-byte AES key, in binary or hex. + /// 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, @@ -502,16 +1013,22 @@ fn main() { encoders_cmd::base64_decode_cmd(); } Some(Subcommands::SHA224 { x }) => { - sha2_cmd::sha2_cmd(224, *x); + sha2_cmd::sha2_cmd(SHA2Variant::SHA224, *x); } Some(Subcommands::SHA256 { x }) => { - sha2_cmd::sha2_cmd(256, *x); + sha2_cmd::sha2_cmd(SHA2Variant::SHA256, *x); } Some(Subcommands::SHA384 { x }) => { - sha2_cmd::sha2_cmd(384, *x); + sha2_cmd::sha2_cmd(SHA2Variant::SHA384, *x); } Some(Subcommands::SHA512 { x }) => { - sha2_cmd::sha2_cmd(512, *x); + sha2_cmd::sha2_cmd(SHA2Variant::SHA512, *x); + } + Some(Subcommands::SHA512_224 { x }) => { + sha2_cmd::sha2_cmd(SHA2Variant::SHA512_224, *x); + } + Some(Subcommands::SHA512_256 { x }) => { + sha2_cmd::sha2_cmd(SHA2Variant::SHA512_256, *x); } Some(Subcommands::SHA3_224 { x }) => { sha3_cmd::sha3_cmd(224, *x); @@ -525,6 +1042,9 @@ fn main() { Some(Subcommands::SHA3_512 { x }) => { sha3_cmd::sha3_cmd(512, *x); } + Some(Subcommands::SM3 { x }) => { + sm3_cmd::sm3_cmd(*x); + } Some(Subcommands::SHAKE128 { length, x }) => { sha3_cmd::shake_cmd(128, *length, *x); } @@ -537,6 +1057,15 @@ fn main() { Some(Subcommands::HMAC_SHA512 { key, key_file, verify, x }) => { mac_cmd::mac_cmd(HMACVariant::SHA512, key, key_file, verify, *x) } + Some(Subcommands::HMAC_SHA512_224 { key, key_file, verify, x }) => { + mac_cmd::mac_cmd(HMACVariant::SHA512_224, key, key_file, verify, *x) + } + Some(Subcommands::HMAC_SHA512_256 { key, key_file, verify, x }) => { + mac_cmd::mac_cmd(HMACVariant::SHA512_256, key, key_file, verify, *x) + } + Some(Subcommands::HMAC_SM3 { key, key_file, verify, x }) => { + mac_cmd::mac_cmd(HMACVariant::SM3, key, key_file, verify, *x) + } Some(Subcommands::HKDF_SHA256 { salt, salt_file, @@ -564,6 +1093,51 @@ fn main() { *len, *x, ), Some(Subcommands::RNG { len, x }) => rng_cmd::rng_cmd(*len, *x), + Some(Subcommands::AES128_CBC { action, key, key_file, x }) => { + aes_cbc_cmd::aes128_cbc_cmd(action, key, key_file, *x); + } + Some(Subcommands::AES192_CBC { action, key, key_file, x }) => { + aes_cbc_cmd::aes192_cbc_cmd(action, key, key_file, *x); + } + Some(Subcommands::AES256_CBC { action, key, key_file, x }) => { + aes_cbc_cmd::aes256_cbc_cmd(action, key, key_file, *x); + } + Some(Subcommands::AES128_CFB { action, key, key_file, x }) => { + aes_cfb_cmd::aes128_cfb_cmd(action, key, key_file, *x); + } + Some(Subcommands::AES192_CFB { action, key, key_file, x }) => { + aes_cfb_cmd::aes192_cfb_cmd(action, key, key_file, *x); + } + Some(Subcommands::AES256_CFB { action, key, key_file, x }) => { + aes_cfb_cmd::aes256_cfb_cmd(action, key, key_file, *x); + } + Some(Subcommands::AES128_CFB8 { action, key, key_file, x }) => { + aes_cfb8_cmd::aes128_cfb8_cmd(action, key, key_file, *x); + } + Some(Subcommands::AES192_CFB8 { action, key, key_file, x }) => { + aes_cfb8_cmd::aes192_cfb8_cmd(action, key, key_file, *x); + } + Some(Subcommands::AES256_CFB8 { action, key, key_file, x }) => { + aes_cfb8_cmd::aes256_cfb8_cmd(action, key, key_file, *x); + } + Some(Subcommands::AES128_CTR { action, key, key_file, x }) => { + aes_ctr_cmd::aes128_ctr_cmd(action, key, key_file, *x); + } + Some(Subcommands::AES192_CTR { action, key, key_file, x }) => { + aes_ctr_cmd::aes192_ctr_cmd(action, key, key_file, *x); + } + Some(Subcommands::AES256_CTR { action, key, key_file, x }) => { + aes_ctr_cmd::aes256_ctr_cmd(action, key, key_file, *x); + } + Some(Subcommands::AES128_ECB { action, key, key_file, x }) => { + aes_ecb_cmd::aes128_ecb_cmd(action, key, key_file, *x); + } + Some(Subcommands::AES192_ECB { action, key, key_file, x }) => { + aes_ecb_cmd::aes192_ecb_cmd(action, key, key_file, *x); + } + Some(Subcommands::AES256_ECB { action, key, key_file, x }) => { + aes_ecb_cmd::aes256_ecb_cmd(action, key, key_file, *x); + } Some(Subcommands::MLKEM512 { action, skfile, pkfile, ctfile, x }) => { mlkem_cmd::mlkem512_cmd(action, skfile, pkfile, ctfile, *x); } diff --git a/cli/src/sha2_cmd.rs b/cli/src/sha2_cmd.rs index 3551c9d8..c719eca4 100644 --- a/cli/src/sha2_cmd.rs +++ b/cli/src/sha2_cmd.rs @@ -2,15 +2,26 @@ use bouncycastle::core::traits::Hash; use std::io; use std::io::{Read, Write}; -use bouncycastle::sha2::{SHA224, SHA256, SHA384, SHA512}; +use bouncycastle::sha2::{SHA224, SHA256, SHA384, SHA512, SHA512_224, SHA512_256}; -pub(crate) fn sha2_cmd(bit_len: usize, output_hex: bool) { - match bit_len { - 224 => do_sha2(SHA224::new(), output_hex), - 256 => do_sha2(SHA256::new(), output_hex), - 384 => do_sha2(SHA384::new(), output_hex), - 512 => do_sha2(SHA512::new(), output_hex), - _ => panic!("Unsupported algorithm: SHA{}", bit_len), +#[allow(non_camel_case_types)] +pub(crate) enum SHA2Variant { + SHA224, + SHA256, + SHA384, + SHA512, + SHA512_224, + SHA512_256, +} + +pub(crate) fn sha2_cmd(variant: SHA2Variant, output_hex: bool) { + match variant { + SHA2Variant::SHA224 => do_sha2(SHA224::new(), output_hex), + SHA2Variant::SHA256 => do_sha2(SHA256::new(), output_hex), + SHA2Variant::SHA384 => do_sha2(SHA384::new(), output_hex), + SHA2Variant::SHA512 => do_sha2(SHA512::new(), output_hex), + SHA2Variant::SHA512_224 => do_sha2(SHA512_224::new(), output_hex), + SHA2Variant::SHA512_256 => do_sha2(SHA512_256::new(), output_hex), } } diff --git a/cli/src/sm3_cmd.rs b/cli/src/sm3_cmd.rs new file mode 100644 index 00000000..98630c64 --- /dev/null +++ b/cli/src/sm3_cmd.rs @@ -0,0 +1,28 @@ +use bouncycastle::core::traits::Hash; +use std::io; +use std::io::{Read, Write}; + +use bouncycastle::sm3::SM3; + +pub(crate) fn sm3_cmd(output_hex: bool) { + let mut sm3 = SM3::new(); + let mut buf: [u8; 1024] = [0u8; 1024]; + + // read from stdin + let mut bytes_read = io::stdin().read(&mut buf).expect("Failed to read from stdin"); + while bytes_read != 0 { + sm3.do_update(&buf[..bytes_read]); + bytes_read = io::stdin().read(&mut buf).expect("Failed to read from stdin"); + } + + let out = sm3.do_final(); + + if output_hex { + for b in out.iter() { + print!("{b:02x}"); + } + } else { + io::stdout().write_all(&out).unwrap(); + } + println!(); +} diff --git a/cli/src/stream_mode_cmd.rs b/cli/src/stream_mode_cmd.rs new file mode 100644 index 00000000..b584b4a1 --- /dev/null +++ b/cli/src/stream_mode_cmd.rs @@ -0,0 +1,154 @@ +//! Shared plumbing for the stream-cipher-mode subcommands: `aes{128,192,256}-{cfb,cfb8,ctr}`. +//! +//! The stream-cipher counterpart of [`crate::block_mode_cmd`], and deliberately parallel to it: +//! same key loading (reused directly from there), same IV convention, same `-x` hex output, same +//! 1 KiB streaming chunk. Everything here is mode-independent and generic over +//! [`StreamCipherEncryptor`] / [`StreamCipherDecryptor`], so `aes_cfb_cmd`, `aes_cfb8_cmd` and +//! `aes_ctr_cmd` are thin dispatchers over it and cannot drift apart on the parts that matter for +//! correctness. The init data length is a parameter, so it need not be a whole block: it is the +//! block for the CFB modes and a 12-byte nonce for CTR. +//! +//! # The IV travels in the ciphertext +//! +//! Exactly as for the block modes: there is no `--iv` flag, because `bouncycastle-modes` has no API +//! for a caller-supplied IV -- NIST SP 800-38A Sec 5.3 requires the CFB IV to be *unpredictable* +//! rather than merely unique. `encrypt` generates one from the OS-backed DRBG and writes it as the +//! **first block of the output**; `decrypt` reads it back from the **first block of the input**, so +//! the two compose directly in a pipeline. +//! +//! # No alignment requirement, and no padding +//! +//! This is the one place the stream commands differ from the block ones. A stream cipher is defined +//! on any length -- CFB8's segment is a byte, and `Cfb` extends the `s = b` equations to a short +//! final segment (see its module docs) -- so input of *any* size is accepted, nothing is padded, +//! and the ciphertext is exactly as long as the plaintext. A partial read from stdin therefore +//! needs no buffering to a block boundary: whatever arrives is processed immediately. +//! +//! # Binary in, binary out +//! +//! 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::block_mode_cmd::{BlockModeAction, CHUNK_LEN}; +use crate::helpers::write_bytes_or_hex; +use bouncycastle::core::key_material::KeyMaterial; +use bouncycastle::core::traits::{StreamCipherDecryptor, StreamCipherEncryptor}; +use std::io; +use std::io::{Read, Write}; +use std::process::exit; + +/// Encrypts stdin to stdout under the stream mode `E`, writing the generated IV first. +/// +/// `INIT_DATA_LEN` is the mode's: one block for CFB and CFB8. +pub(crate) fn encrypt_stream( + key: &KeyMaterial, + output_hex: bool, +) where + E: StreamCipherEncryptor, +{ + let (mut enc, iv) = E::do_encrypt_init(key).unwrap_or_else(|e| { + eprintln!("Error: couldn't start encryption: {e:?}"); + exit(-1); + }); + + // The IV goes out ahead of the ciphertext, so `decrypt` can pick it up. + write_bytes_or_hex(&iv, output_hex); + + // The cipher works in place: `data` holds plaintext on the way in and ciphertext on the way out. + stream(|data| { + // 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. + enc.do_encrypt(data).unwrap_or_else(|e| { + eprintln!("Error: encryption failed: {e:?}"); + exit(-1); + }); + write_bytes_or_hex(data, output_hex); + }); + + finish(output_hex); +} + +/// Decrypts stdin to stdout under the stream mode `D`, taking the IV from the first +/// `INIT_DATA_LEN` bytes of input. +pub(crate) fn decrypt_stream( + key: &KeyMaterial, + output_hex: bool, +) where + D: StreamCipherDecryptor, +{ + // The leading bytes are the IV, not ciphertext. + let mut iv = [0u8; INIT_DATA_LEN]; + if let Err(e) = io::stdin().read_exact(&mut iv) { + eprintln!( + "Error: input too short to contain the {INIT_DATA_LEN}-byte IV that `encrypt` writes \ + as its first block ({e})." + ); + exit(-1); + } + + let mut dec = D::do_decrypt_init(key, &iv).unwrap_or_else(|e| { + eprintln!("Error: couldn't start decryption: {e:?}"); + exit(-1); + }); + + stream(|data| { + dec.do_decrypt(data).unwrap_or_else(|e| { + eprintln!("Error: decryption failed: {e:?}"); + exit(-1); + }); + write_bytes_or_hex(data, output_hex); + }); + + finish(output_hex); +} + +/// Reads stdin and hands it to `process` in pieces of at most `CHUNK_LEN` bytes, mutably so it can +/// be transformed in place. +/// +/// Unlike the block modes' `stream_aligned`, nothing is buffered to a boundary and no length is +/// rejected: a stream cipher takes any number of bytes, and a sequence of calls is equivalent to +/// one call over the concatenation, so whatever a read returns can go straight through. That also +/// means the mode's own byte path is exercised at whatever alignment the pipe happens to deliver, +/// which is precisely what the trait guarantees is safe. +fn stream(mut process: impl FnMut(&mut [u8])) { + let mut buf = [0u8; CHUNK_LEN]; + + loop { + let n = io::stdin().read(&mut buf).unwrap_or_else(|e| { + eprintln!("Error: failed to read from stdin: {e}"); + exit(-1); + }); + if n == 0 { + break; + } + process(&mut buf[..n]); + } +} + +/// Flushes stdout, and adds the trailing newline the hex-output commands all emit. +fn finish(output_hex: bool) { + if output_hex { + println!(); + } + io::stdout().flush().unwrap_or_else(|e| { + eprintln!("Error: failed to flush stdout: {e}"); + exit(-1); + }); +} + +/// Runs one direction of a stream mode. The two `run` dispatchers in `aes_cfb_cmd` and +/// `aes_cfb8_cmd` differ only in which mode they name, so the match lives here. +pub(crate) fn run_stream_mode( + action: &BlockModeAction, + key: &KeyMaterial, + output_hex: bool, +) where + E: StreamCipherEncryptor, + D: StreamCipherDecryptor, +{ + match action { + BlockModeAction::Encrypt => encrypt_stream::(key, output_hex), + BlockModeAction::Decrypt => decrypt_stream::(key, output_hex), + } +} diff --git a/cli/tests/aes_cbc_cli_tests.rs b/cli/tests/aes_cbc_cli_tests.rs new file mode 100644 index 00000000..d659c0cd --- /dev/null +++ b/cli/tests/aes_cbc_cli_tests.rs @@ -0,0 +1,431 @@ +//! Tests for the `aes128-cbc` / `aes192-cbc` / `aes256-cbc` subcommands. +//! +//! These drive the built `bc-rust` binary as a subprocess, because the behaviour worth testing is +//! the command-line contract itself -- the IV riding in the first block, block-alignment +//! enforcement, exit codes, key loading -- none of which is reachable from the library API. +//! +//! `CARGO_BIN_EXE_bc-rust` is set by cargo for integration tests and points at the binary for the +//! current profile, so there is nothing to build or locate by hand. + +use std::io::{ErrorKind, Write}; +use std::process::{Command, Output, Stdio}; +use std::thread; + +/// The path to the binary under test, resolved by cargo. +const BC_RUST: &str = env!("CARGO_BIN_EXE_bc-rust"); + +/// SP 800-38A Appendix F IV, shared by every F.2 subsection. +const IV: &str = "000102030405060708090a0b0c0d0e0f"; + +/// The four SP 800-38A Appendix F plaintext blocks. +const PLAINTEXT: &str = concat!( + "6bc1bee22e409f96e93d7e117393172a", + "ae2d8a571e03ac9c9eb76fac45af8e51", + "30c81c46a35ce411e5fbc1191a0a52ef", + "f69f2445df4f9b17ad2b417be66c3710", +); + +const KEY_128: &str = "2b7e151628aed2a6abf7158809cf4f3c"; +const KEY_192: &str = "8e73b0f7da0e6452c810f32b809079e562f8ead2522c6b7b"; +const KEY_256: &str = "603deb1015ca71be2b73aef0857d77811f352c073b6108d72d9810a30914dff4"; + +/// F.2.1 CBC-AES128.Encrypt ciphertext. +const CT_128: &str = concat!( + "7649abac8119b246cee98e9b12e9197d", + "5086cb9b507219ee95db113a917678b2", + "73bed6b8e3c1743b7116e69e22229516", + "3ff1caa1681fac09120eca307586e1a7", +); +/// F.2.3 CBC-AES192.Encrypt ciphertext. +const CT_192: &str = concat!( + "4f021db243bc633d7178183a9fa071e8", + "b4d9ada9ad7dedf4e5e738763f69145a", + "571b242012fb7ae07fa9baac3df102e0", + "08b0e27988598881d920a9e64f5615cd", +); +/// F.2.5 CBC-AES256.Encrypt ciphertext. +const CT_256: &str = concat!( + "f58c4c04d6e5f1ba779eabfb5f7bfbd6", + "9cfc4e967edb808d679f777bc6702c7d", + "39f23369a9d9bacfa530e26304231461", + "b2eb05e2c39be9fcda6c19078c6a9d1b", +); + +/// Runs `bc-rust ` with `stdin_bytes` on stdin and returns the completed output. +/// +/// # Why stdin is written from a thread +/// +/// stdin, stdout and stderr are all pipes with a bounded buffer (typically 64 KiB). Writing all of +/// stdin from *this* thread before reading any output deadlocks as soon as the payload is large +/// enough: the child fills its stdout buffer and blocks, so it stops draining stdin, so our write +/// blocks too, and neither side can move. That is a hang rather than a failure, so it would surface +/// as a CI timeout. Writing on a separate thread leaves this one free to drain stdout and stderr +/// via `wait_with_output`, which breaks the cycle. `a_payload_larger_than_the_pipe_buffer_round_trips` +/// pins it. +/// +/// Dropping the pipe when the write finishes is what signals EOF to the child, so the writer thread +/// owns the handle (`take`, not `as_mut`) and must run to completion. +/// +/// # Why `BrokenPipe` is ignored +/// +/// The error-path tests hand a rejected key or a misaligned length to a command that `exit`s before +/// it reads stdin, so the write races the child's exit and loses. That is an expected outcome, not a +/// harness failure: those tests assert the exit status and stderr, both of which `wait_with_output` +/// still returns. Any *other* write error is a real problem and still panics. +/// `a_large_payload_on_an_error_path_does_not_break_the_harness` pins it. +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"); + + let mut stdin = child.stdin.take().expect("stdin piped"); + let payload = stdin_bytes.to_vec(); + let writer = thread::spawn(move || { + match stdin.write_all(&payload) { + Ok(()) => {} + Err(e) if e.kind() == ErrorKind::BrokenPipe => {} + Err(e) => panic!("failed to write to stdin: {e}"), + } + // `stdin` drops here, closing the pipe so the child sees EOF and can exit. + }); + + // Drain stdout and stderr first: the writer may still be blocked on a full stdin buffer, and it + // cannot finish until the child consumes more, which it cannot do while its output is backed up. + let output = child.wait_with_output().expect("failed to wait for bc-rust"); + writer.join().expect("the stdin writer thread panicked"); + output +} + +/// 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 or on `/dev/urandom`. +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 harness itself ------------------------------------------------------------------ +// +// These two pin `run`'s pipe handling. Both bugs they cover are timing-dependent: they pass on a +// fast machine with a small payload and fail on a slow or loaded runner, which is exactly how the +// first one reached CI. Forcing the condition with an oversized payload makes them deterministic +// instead of waiting for a bad day. The same pair exists in `aes_cfb_cli_tests.rs`, because each +// file has its own copy of `run`. + +/// Far beyond any pipe buffer, so a write cannot complete before the child has drained it. +const OVERSIZED: usize = 4 * 1024 * 1024; + +/// An error path must not take the harness down with it. +/// +/// `encrypt` with no `--key` prints its complaint and exits without reading stdin, so the write +/// loses the race and the pipe breaks. Before `run` tolerated `ErrorKind::BrokenPipe` this panicked +/// with "failed to write to stdin" (os error 109 on Windows, EPIPE elsewhere) instead of reporting +/// the CLI's actual error, which is what the other error-path tests assert on. +#[test] +fn a_large_payload_on_an_error_path_does_not_break_the_harness() { + let stderr = run_err(&["aes128-cbc", "encrypt"], &vec![0u8; OVERSIZED]); + assert!(stderr.contains("--key"), "the CLI's own error must still be reported: {stderr}"); +} + +/// A payload larger than the pipe buffer must round-trip rather than deadlock. +/// +/// This is the reason `run` writes stdin from a separate thread. Writing it inline wedges once both +/// pipes fill: the child blocks writing stdout, so it stops reading stdin, so the harness blocks +/// writing stdin. Nothing times out on its own -- the test just hangs until CI kills the job -- so +/// this is the check that would have caught it. +#[test] +fn a_payload_larger_than_the_pipe_buffer_round_trips() { + let plaintext = pseudo_random(OVERSIZED, 0xC0FFEE); + let ciphertext = run_ok(&["aes128-cbc", "encrypt", "--key", KEY_128], &plaintext); + assert_eq!(ciphertext.len(), plaintext.len() + 16, "IV plus the ciphertext"); + + let recovered = run_ok(&["aes128-cbc", "decrypt", "--key", KEY_128], &ciphertext); + assert_eq!(recovered, plaintext, "{OVERSIZED} bytes should round trip"); +} + +// ---- the SP 800-38A F.2 vectors, through the CLI ----------------------------------------- + +/// `decrypt` reproduces the spec plaintext when handed the spec's IV followed by the spec's +/// ciphertext. +/// +/// This is the direction that can be pinned exactly: `encrypt` picks its own IV, so it cannot be +/// asked to reproduce a published ciphertext. `encrypt` is covered by the round-trip tests below +/// and, at the library level, by `crypto/modes/tests/sp800_38a_tests.rs`. +#[test] +fn decrypt_matches_sp800_38a_f2_vectors() { + for (cmd, key, ct) in [ + ("aes128-cbc", KEY_128, CT_128), + ("aes192-cbc", KEY_192, CT_192), + ("aes256-cbc", KEY_256, CT_256), + ] { + // The CLI expects the IV as the first block of its input, which is exactly how `encrypt` + // emits it. + let input = unhex(&format!("{IV}{ct}")); + let out = run_ok(&[cmd, "decrypt", "--key", key], &input); + assert_eq!( + tohex(&out), + PLAINTEXT, + "{cmd} decrypt should reproduce the Appendix F.2 plaintext" + ); + } +} + +/// The same, with `-x`, which should give the identical answer in hex plus a trailing newline. +#[test] +fn hex_output_matches_binary_output() { + let input = unhex(&format!("{IV}{CT_128}")); + let binary = run_ok(&["aes128-cbc", "decrypt", "--key", KEY_128], &input); + let hex_out = run_ok(&["aes128-cbc", "decrypt", "--key", KEY_128, "-x"], &input); + + let hex_str = String::from_utf8(hex_out).expect("hex output is text"); + assert_eq!(hex_str.trim_end(), tohex(&binary)); + assert_eq!(hex_str.trim_end(), PLAINTEXT); +} + +// ---- round trips ------------------------------------------------------------------------ + +/// `encrypt | decrypt` recovers the input, for all three key lengths. +/// +/// Also checks the output length: the ciphertext is one block longer than the plaintext, because +/// the IV is prepended. +#[test] +fn encrypt_then_decrypt_round_trips() { + for (cmd, key) in [("aes128-cbc", KEY_128), ("aes192-cbc", KEY_192), ("aes256-cbc", KEY_256)] { + let plaintext = unhex(PLAINTEXT); + let ciphertext = run_ok(&[cmd, "encrypt", "--key", key], &plaintext); + assert_eq!( + ciphertext.len(), + plaintext.len() + 16, + "{cmd}: output should be the 16-byte IV plus the ciphertext" + ); + + let recovered = run_ok(&[cmd, "decrypt", "--key", key], &ciphertext); + assert_eq!(recovered, plaintext, "{cmd}: round trip"); + } +} + +/// Round trips at sizes that straddle the 1 KiB streaming chunk and the block boundary. +/// +/// 1024 is exactly one chunk; 1040 is a chunk plus one block, which exercises the tail path; 4112 +/// is four chunks plus a block; 65536 is many chunks. +#[test] +fn round_trips_across_chunk_boundaries() { + for size in [16usize, 32, 1024, 1040, 4096, 4112, 65536] { + let plaintext = pseudo_random(size, size as u32); + let ciphertext = run_ok(&["aes128-cbc", "encrypt", "--key", KEY_128], &plaintext); + let recovered = run_ok(&["aes128-cbc", "decrypt", "--key", KEY_128], &ciphertext); + assert_eq!(recovered, plaintext, "{size} bytes should round trip"); + } +} + +/// A fresh IV per invocation, so the same plaintext under the same key gives different output. +/// +/// This is the operational requirement CBC lives or dies by, and the CLI is where it is easiest to +/// get wrong (e.g. by seeding from a fixed value). +#[test] +fn each_invocation_uses_a_fresh_iv() { + let plaintext = unhex(PLAINTEXT); + let mut seen = std::collections::BTreeSet::new(); + + for _ in 0..8 { + let ciphertext = run_ok(&["aes128-cbc", "encrypt", "--key", KEY_128], &plaintext); + let iv = ciphertext[..16].to_vec(); + assert!(seen.insert(iv), "the CLI reused an IV across invocations"); + // ...and the body differs too, not just the IV. + let recovered = run_ok(&["aes128-cbc", "decrypt", "--key", KEY_128], &ciphertext); + assert_eq!(recovered, plaintext); + } +} + +// ---- key handling ----------------------------------------------------------------------- + +/// `--key-file` accepts both a hex file and a raw binary file, and agrees with `--key`. +#[test] +fn key_file_accepts_hex_and_binary() { + let dir = std::env::temp_dir().join(format!("bc_rust_cli_key_{}", std::process::id())); + std::fs::create_dir_all(&dir).expect("create temp dir"); + + let hex_path = dir.join("key.hex"); + let bin_path = dir.join("key.bin"); + std::fs::write(&hex_path, KEY_128).expect("write hex key"); + std::fs::write(&bin_path, unhex(KEY_128)).expect("write binary key"); + + let input = unhex(&format!("{IV}{CT_128}")); + let expected = unhex(PLAINTEXT); + + for path in [&hex_path, &bin_path] { + let out = run_ok(&["aes128-cbc", "decrypt", "--key-file", path.to_str().unwrap()], &input); + assert_eq!(out, expected, "--key-file {path:?}"); + } + + std::fs::remove_dir_all(&dir).ok(); +} + +/// A key of the wrong length for the chosen variant is rejected, naming both lengths. +#[test] +fn a_key_of_the_wrong_length_is_rejected() { + let stderr = run_err(&["aes256-cbc", "encrypt", "--key", KEY_128], &unhex(PLAINTEXT)); + assert!(stderr.contains("32-byte key"), "stderr should name the expected length: {stderr}"); + assert!(stderr.contains("16 bytes"), "stderr should name the supplied length: {stderr}"); +} + +/// Omitting the key entirely is an error, not a default. +#[test] +fn a_missing_key_is_rejected() { + let stderr = run_err(&["aes128-cbc", "encrypt"], &unhex(PLAINTEXT)); + assert!(stderr.contains("--key"), "stderr should mention the key options: {stderr}"); +} + +/// An all-zero key warns but proceeds, matching `helpers::parse_seed`'s stance. NIST publishes +/// all-zero-key vectors, so refusing outright would make some of them untestable from the CLI. +#[test] +fn an_all_zero_key_warns_but_proceeds() { + let zero_key = "0".repeat(32); + let out = run(&["aes128-cbc", "encrypt", "--key", &zero_key], &unhex(PLAINTEXT)); + assert!(out.status.success(), "an all-zero key should still work"); + let stderr = String::from_utf8_lossy(&out.stderr); + assert!(stderr.to_lowercase().contains("warning"), "an all-zero key should warn: {stderr}"); + assert_eq!(out.stdout.len(), 16 + 64, "IV plus four ciphertext blocks"); +} + +// ---- block alignment and framing -------------------------------------------------------- + +/// Input that is not a whole number of blocks is rejected, with a message that explains why +/// rather than just failing. CBC has no answer for a partial block and there is no padding layer. +#[test] +fn unaligned_input_is_rejected_with_an_explanation() { + for extra in [1usize, 7, 15] { + let plaintext = pseudo_random(32 + extra, extra as u32); + let stderr = run_err(&["aes128-cbc", "encrypt", "--key", KEY_128], &plaintext); + assert!( + stderr.contains("whole number of 16-byte blocks"), + "stderr should explain the alignment requirement: {stderr}" + ); + assert!( + stderr.contains("padding"), + "stderr should point at the missing padding layer: {stderr}" + ); + } +} + +/// Decrypt input shorter than the IV it must start with is rejected, and says so. +#[test] +fn decrypt_input_shorter_than_the_iv_is_rejected() { + for len in [0usize, 1, 15] { + let stderr = run_err(&["aes128-cbc", "decrypt", "--key", KEY_128], &pseudo_random(len, 1)); + assert!( + stderr.contains("IV"), + "stderr should explain the missing IV (len {len}): {stderr}" + ); + } +} + +/// Decrypt input that carries the IV but then an unaligned body is rejected too. +#[test] +fn decrypt_rejects_an_unaligned_body() { + let mut input = unhex(IV); + input.extend_from_slice(&pseudo_random(20, 3)); // 20 is not a multiple of 16 + let stderr = run_err(&["aes128-cbc", "decrypt", "--key", KEY_128], &input); + assert!( + stderr.contains("whole number of 16-byte blocks"), + "stderr should explain the alignment requirement: {stderr}" + ); +} + +/// Empty input to `encrypt` produces just the IV: zero blocks in, zero blocks out. +/// +/// Worth pinning because it is the one input length that is block-aligned but has no blocks, and +/// it is easy for a streaming loop to mishandle. +#[test] +fn empty_input_produces_only_the_iv() { + let out = run_ok(&["aes128-cbc", "encrypt", "--key", KEY_128], &[]); + assert_eq!(out.len(), 16, "empty input should yield exactly the IV"); + + // ...and feeding that straight back gives empty output. + let back = run_ok(&["aes128-cbc", "decrypt", "--key", KEY_128], &out); + assert!(back.is_empty(), "decrypting an IV with no body should give nothing"); +} + +// ---- cross-variant behaviour ------------------------------------------------------------ + +/// Decrypting with a different key length than was used to encrypt cannot succeed silently. +#[test] +fn the_three_variants_are_not_interchangeable() { + let plaintext = unhex(PLAINTEXT); + let ciphertext = run_ok(&["aes128-cbc", "encrypt", "--key", KEY_128], &plaintext); + + // Right length, wrong key: decryption "succeeds" but must not recover the plaintext. CBC is + // unauthenticated, so garbage out is the expected behaviour, not an error -- which is exactly + // why the crate docs insist on authenticating separately. + let wrong_key = "ff".repeat(16); + let out = run_ok(&["aes128-cbc", "decrypt", "--key", &wrong_key], &ciphertext); + assert_ne!(out, plaintext, "a wrong key must not recover the plaintext"); + assert_eq!(out.len(), plaintext.len(), "but the length is unchanged: CBC is unauthenticated"); +} + +/// The subcommands appear in `--help`, so they 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 ["aes128-cbc", "aes192-cbc", "aes256-cbc"] { + assert!(help.contains(cmd), "`--help` should list {cmd}"); + } +} + +/// Each subcommand's own help names the two actions and the IV convention. +#[test] +fn per_command_help_documents_the_iv_convention() { + let out = run_ok(&["aes128-cbc", "--help"], &[]); + let help = String::from_utf8_lossy(&out); + assert!(help.contains("encrypt"), "help should list the encrypt action"); + assert!(help.contains("decrypt"), "help should list the decrypt action"); + assert!( + help.contains("FIRST 16 BYTES") || help.contains("first 16 bytes"), + "help should explain where the IV goes: {help}" + ); +} diff --git a/cli/tests/aes_cfb8_cli_tests.rs b/cli/tests/aes_cfb8_cli_tests.rs new file mode 100644 index 00000000..8b40e21e --- /dev/null +++ b/cli/tests/aes_cfb8_cli_tests.rs @@ -0,0 +1,456 @@ +//! Tests for the `aes128-cfb8` / `aes192-cfb8` / `aes256-cfb8` subcommands. +//! +//! These drive the built `bc-rust` binary as a subprocess, because the behaviour worth testing is +//! the command-line contract itself -- the IV riding in the first block, the chunked streaming +//! loop, exit codes, key loading -- none of which is reachable from the library API. +//! +//! The commands share their streaming loop with `aes*-cfb` (`cli/src/stream_mode_cmd.rs`) and their +//! key loading with `aes*-cbc` (`cli/src/block_mode_cmd.rs`), so this file deliberately repeats +//! that coverage rather than assuming it: the shared code is generic over the mode, and a wiring +//! mistake in the CFB8 dispatcher would not show up in the other suites. What is tested only here +//! is the F.3.7/F.3.9/F.3.11 vectors, CFB8's own Appendix D error propagation -- a 16-byte damage +//! window followed by resynchronisation -- and the guard that CFB8 and CFB128 ciphertexts are not +//! interchangeable. +//! +//! `CARGO_BIN_EXE_bc-rust` is set by cargo for integration tests and points at the binary for the +//! current profile, so there is nothing to build or locate by hand. + +use std::io::{ErrorKind, Write}; +use std::process::{Command, Output, Stdio}; +use std::thread; + +/// The path to the binary under test, resolved by cargo. +const BC_RUST: &str = env!("CARGO_BIN_EXE_bc-rust"); + +/// SP 800-38A Appendix F IV, shared by every F.3 subsection. +const IV: &str = "000102030405060708090a0b0c0d0e0f"; + +/// The 18 one-byte plaintext segments the CFB8 subsections use: the Appendix F plaintext truncated +/// to 18 bytes. +const PLAINTEXT: &str = "6bc1bee22e409f96e93d7e117393172aae2d"; + +const KEY_128: &str = "2b7e151628aed2a6abf7158809cf4f3c"; +const KEY_192: &str = "8e73b0f7da0e6452c810f32b809079e562f8ead2522c6b7b"; +const KEY_256: &str = "603deb1015ca71be2b73aef0857d77811f352c073b6108d72d9810a30914dff4"; + +/// F.3.7 CFB8-AES128.Encrypt ciphertext. +const CT_128: &str = "3b79424c9c0dd436bace9e0ed4586a4f32b9"; +/// F.3.9 CFB8-AES192.Encrypt ciphertext. +const CT_192: &str = "cda2521ef0a905ca44cd057cbf0d47a0678a"; +/// F.3.11 CFB8-AES256.Encrypt ciphertext. +const CT_256: &str = "dc1f1a8520a64db55fcc8ac554844e889700"; + +/// F.3.13 CFB128-AES128.Encrypt ciphertext, first 18 bytes, for the cross-mode guard. Same key, IV +/// and plaintext as `CT_128`, so the two are directly comparable. +const CFB128_CT_128: &str = "3b3fd92eb72dad20333449f8e83cfb4ac8a6"; + +/// Runs `bc-rust ` with `stdin_bytes` on stdin and returns the completed output. +/// +/// # Why stdin is written from a thread +/// +/// stdin, stdout and stderr are all pipes with a bounded buffer (typically 64 KiB). Writing all of +/// stdin from *this* thread before reading any output deadlocks as soon as the payload is large +/// enough: the child fills its stdout buffer and blocks, so it stops draining stdin, so our write +/// blocks too, and neither side can move. That is a hang rather than a failure, so it would surface +/// as a CI timeout. Writing on a separate thread leaves this one free to drain stdout and stderr +/// via `wait_with_output`, which breaks the cycle. `a_payload_larger_than_the_pipe_buffer_round_trips` +/// pins it. +/// +/// Dropping the pipe when the write finishes is what signals EOF to the child, so the writer thread +/// owns the handle (`take`, not `as_mut`) and must run to completion. +/// +/// # Why `BrokenPipe` is ignored +/// +/// The error-path tests hand a rejected key to a command that `exit`s before it reads stdin, so the +/// write races the child's exit and loses. That is an expected outcome, not a +/// harness failure: those tests assert the exit status and stderr, both of which `wait_with_output` +/// still returns. Any *other* write error is a real problem and still panics. +/// `a_large_payload_on_an_error_path_does_not_break_the_harness` pins it. +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"); + + let mut stdin = child.stdin.take().expect("stdin piped"); + let payload = stdin_bytes.to_vec(); + let writer = thread::spawn(move || { + match stdin.write_all(&payload) { + Ok(()) => {} + Err(e) if e.kind() == ErrorKind::BrokenPipe => {} + Err(e) => panic!("failed to write to stdin: {e}"), + } + // `stdin` drops here, closing the pipe so the child sees EOF and can exit. + }); + + // Drain stdout and stderr first: the writer may still be blocked on a full stdin buffer, and it + // cannot finish until the child consumes more, which it cannot do while its output is backed up. + let output = child.wait_with_output().expect("failed to wait for bc-rust"); + writer.join().expect("the stdin writer thread panicked"); + output +} + +/// 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 or on `/dev/urandom`. +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 harness itself ------------------------------------------------------------------ +// +// These two pin `run`'s pipe handling, exactly as in the CBC and CFB suites; each file has its own +// copy of `run`, so each needs its own pair. + +/// Far beyond any pipe buffer, so a write cannot complete before the child has drained it. +/// +/// Smaller than the CFB suite's, because CFB8 spends a full AES call per byte and this test is +/// about the pipe rather than the cipher. +const OVERSIZED: usize = 256 * 1024; + +/// An error path must not take the harness down with it. +#[test] +fn a_large_payload_on_an_error_path_does_not_break_the_harness() { + let stderr = run_err(&["aes128-cfb8", "encrypt"], &vec![0u8; OVERSIZED]); + assert!(stderr.contains("--key"), "the CLI's own error must still be reported: {stderr}"); +} + +/// A payload larger than the pipe buffer must round-trip rather than deadlock. +#[test] +fn a_payload_larger_than_the_pipe_buffer_round_trips() { + let plaintext = pseudo_random(OVERSIZED, 0xC0FFEE); + let ciphertext = run_ok(&["aes128-cfb8", "encrypt", "--key", KEY_128], &plaintext); + assert_eq!(ciphertext.len(), plaintext.len() + 16, "IV plus the ciphertext"); + + let recovered = run_ok(&["aes128-cfb8", "decrypt", "--key", KEY_128], &ciphertext); + assert_eq!(recovered, plaintext, "{OVERSIZED} bytes should round trip"); +} + +// ---- the SP 800-38A F.3 vectors, through the CLI ----------------------------------------- + +/// `decrypt` reproduces the spec plaintext when handed the spec's IV followed by the spec's +/// ciphertext, for F.3.7/F.3.9/F.3.11 (CFB8-AES128/192/256). +/// +/// This is the direction that can be pinned exactly: `encrypt` picks its own IV, so it cannot be +/// asked to reproduce a published ciphertext. `encrypt` is covered by the round-trip tests below +/// and, at the library level, by `crypto/modes/tests/sp800_38a_cfb8_tests.rs`. +#[test] +fn decrypt_matches_sp800_38a_f3_vectors() { + for (cmd, key, ct) in [ + ("aes128-cfb8", KEY_128, CT_128), + ("aes192-cfb8", KEY_192, CT_192), + ("aes256-cfb8", KEY_256, CT_256), + ] { + // The CLI expects the IV as the first block of its input, which is exactly how `encrypt` + // emits it. + let input = unhex(&format!("{IV}{ct}")); + let out = run_ok(&[cmd, "decrypt", "--key", key], &input); + assert_eq!( + tohex(&out), + PLAINTEXT, + "{cmd} decrypt should reproduce the Appendix F.3 plaintext" + ); + } +} + +/// The same, with `-x`, which should give the identical answer in hex plus a trailing newline. +#[test] +fn hex_output_matches_binary_output() { + let input = unhex(&format!("{IV}{CT_128}")); + let binary = run_ok(&["aes128-cfb8", "decrypt", "--key", KEY_128], &input); + let hex_out = run_ok(&["aes128-cfb8", "decrypt", "--key", KEY_128, "-x"], &input); + + let hex_str = String::from_utf8(hex_out).expect("hex output is text"); + assert_eq!(hex_str.trim_end(), tohex(&binary)); + assert_eq!(hex_str.trim_end(), PLAINTEXT); +} + +// ---- round trips ------------------------------------------------------------------------ + +/// `encrypt | decrypt` recovers the input, for all three key lengths. +#[test] +fn encrypt_then_decrypt_round_trips() { + for (cmd, key) in [("aes128-cfb8", KEY_128), ("aes192-cfb8", KEY_192), ("aes256-cfb8", KEY_256)] + { + let plaintext = unhex(PLAINTEXT); + let ciphertext = run_ok(&[cmd, "encrypt", "--key", key], &plaintext); + assert_eq!( + ciphertext.len(), + plaintext.len() + 16, + "{cmd}: output should be the 16-byte IV plus the ciphertext" + ); + + let recovered = run_ok(&[cmd, "decrypt", "--key", key], &ciphertext); + assert_eq!(recovered, plaintext, "{cmd}: round trip"); + } +} + +/// Input of any length is accepted and round-trips, and the ciphertext is exactly as long as the +/// plaintext. CFB8's segment is a single byte, so there is no alignment rule at all. +#[test] +fn any_input_length_is_accepted_and_round_trips() { + for len in 0..=(2 * 16 + 1) { + let plaintext = pseudo_random(len, len as u32); + let ciphertext = run_ok(&["aes128-cfb8", "encrypt", "--key", KEY_128], &plaintext); + assert_eq!(ciphertext.len(), len + 16, "len {len}: IV plus an equal-length ciphertext"); + + let recovered = run_ok(&["aes128-cfb8", "decrypt", "--key", KEY_128], &ciphertext); + assert_eq!(recovered, plaintext, "len {len}: round trip"); + } +} + +/// Round trips at sizes that straddle the 1 KiB streaming chunk, including sizes that leave the +/// chunk boundary in the middle of the 8-byte batch the decryptor uses. +#[test] +fn round_trips_across_chunk_boundaries() { + for size in [1usize, 8, 9, 1023, 1024, 1025, 4096, 4099] { + let plaintext = pseudo_random(size, size as u32); + let ciphertext = run_ok(&["aes128-cfb8", "encrypt", "--key", KEY_128], &plaintext); + let recovered = run_ok(&["aes128-cfb8", "decrypt", "--key", KEY_128], &ciphertext); + assert_eq!(recovered, plaintext, "{size} bytes should round trip"); + } +} + +/// A fresh IV per invocation, so the same plaintext under the same key gives different output. +#[test] +fn each_invocation_uses_a_fresh_iv() { + let plaintext = unhex(PLAINTEXT); + let mut seen = std::collections::BTreeSet::new(); + + for _ in 0..8 { + let ciphertext = run_ok(&["aes128-cfb8", "encrypt", "--key", KEY_128], &plaintext); + let iv = ciphertext[..16].to_vec(); + assert!(seen.insert(iv), "the CLI reused an IV across invocations"); + let recovered = run_ok(&["aes128-cfb8", "decrypt", "--key", KEY_128], &ciphertext); + assert_eq!(recovered, plaintext); + } +} + +// ---- key handling ----------------------------------------------------------------------- + +/// `--key-file` accepts both a hex file and a raw binary file, and agrees with `--key`. +#[test] +fn key_file_accepts_hex_and_binary() { + let dir = std::env::temp_dir().join(format!("bc_rust_cfb8_cli_key_{}", std::process::id())); + std::fs::create_dir_all(&dir).expect("create temp dir"); + + let hex_path = dir.join("key.hex"); + let bin_path = dir.join("key.bin"); + std::fs::write(&hex_path, KEY_128).expect("write hex key"); + std::fs::write(&bin_path, unhex(KEY_128)).expect("write binary key"); + + let input = unhex(&format!("{IV}{CT_128}")); + let expected = unhex(PLAINTEXT); + + for path in [&hex_path, &bin_path] { + let out = run_ok(&["aes128-cfb8", "decrypt", "--key-file", path.to_str().unwrap()], &input); + assert_eq!(out, expected, "--key-file {path:?}"); + } + + std::fs::remove_dir_all(&dir).ok(); +} + +/// A key of the wrong length for the chosen variant is rejected, naming both lengths. +#[test] +fn a_key_of_the_wrong_length_is_rejected() { + let stderr = run_err(&["aes256-cfb8", "encrypt", "--key", KEY_128], &unhex(PLAINTEXT)); + assert!(stderr.contains("32-byte key"), "stderr should name the expected length: {stderr}"); + assert!(stderr.contains("16 bytes"), "stderr should name the supplied length: {stderr}"); +} + +/// Omitting the key entirely is an error, not a default. +#[test] +fn a_missing_key_is_rejected() { + let stderr = run_err(&["aes128-cfb8", "encrypt"], &unhex(PLAINTEXT)); + assert!(stderr.contains("--key"), "stderr should mention the key options: {stderr}"); +} + +/// An all-zero key warns but proceeds, matching the other mode commands. NIST publishes +/// all-zero-key vectors, so refusing outright would make some of them untestable from the CLI. +#[test] +fn an_all_zero_key_warns_but_proceeds() { + let zero_key = "0".repeat(32); + let out = run(&["aes128-cfb8", "encrypt", "--key", &zero_key], &unhex(PLAINTEXT)); + assert!(out.status.success(), "an all-zero key should still work"); + let stderr = String::from_utf8_lossy(&out.stderr); + assert!(stderr.to_lowercase().contains("warning"), "an all-zero key should warn: {stderr}"); + assert_eq!(out.stdout.len(), 16 + 18, "IV plus the 18 ciphertext bytes"); +} + +// ---- framing ---------------------------------------------------------------------------- + +/// Decrypt input shorter than the IV it must start with is rejected, and says so. +#[test] +fn decrypt_input_shorter_than_the_iv_is_rejected() { + for len in [0usize, 1, 15] { + let stderr = run_err(&["aes128-cfb8", "decrypt", "--key", KEY_128], &pseudo_random(len, 1)); + assert!( + stderr.contains("IV"), + "stderr should explain the missing IV (len {len}): {stderr}" + ); + } +} + +/// Empty input to `encrypt` produces just the IV. +#[test] +fn empty_input_produces_only_the_iv() { + let out = run_ok(&["aes128-cfb8", "encrypt", "--key", KEY_128], &[]); + assert_eq!(out.len(), 16, "empty input should yield exactly the IV"); + + let back = run_ok(&["aes128-cfb8", "decrypt", "--key", KEY_128], &out); + assert!(back.is_empty(), "decrypting an IV with no body should give nothing"); +} + +// ---- SP 800-38A Appendix D, through the CLI ---------------------------------------------- + +/// Appendix D, Table D.2 for CFB: "SBE in the decryption of Cj" plus "RBE in the decryption of +/// Cj+1,...,Cj+b/s". With `s = 8` on a 16-byte block, `b/s` is 16, so a flipped ciphertext bit +/// flips the same bit of the same plaintext byte, corrupts the next 16 bytes, and then decryption +/// **resynchronises exactly**. +/// +/// That last part is the self-synchronising property CFB8 exists for, and it is also a sharp +/// end-to-end check that the CLI is running CFB8 rather than CFB128, whose damage window is one +/// block rather than sixteen bytes measured from the corrupted byte. +#[test] +fn a_ciphertext_bit_flip_damages_exactly_sixteen_following_bytes() { + // A message long enough to have a clean prefix, a full 16-byte window and a clean tail. + let plaintext = pseudo_random(48, 0xD00D); + let ciphertext = run_ok(&["aes128-cfb8", "encrypt", "--key", KEY_128], &plaintext); + + // Byte 8 of the ciphertext body, which starts after the 16-byte IV. + const J: usize = 8; + const MASK: u8 = 0b0010_0000; + let mut corrupt = ciphertext.clone(); + corrupt[16 + J] ^= MASK; + + let out = run_ok(&["aes128-cfb8", "decrypt", "--key", KEY_128], &corrupt); + assert_eq!(out.len(), plaintext.len()); + + assert_eq!(&out[..J], &plaintext[..J], "earlier bytes are unaffected"); + assert_eq!(out[J], plaintext[J] ^ MASK, "SBE: exactly the flipped bit, in the targeted byte"); + assert_ne!( + &out[J + 1..J + 17], + &plaintext[J + 1..J + 17], + "the next b/s = 16 bytes should be randomised" + ); + assert_eq!( + &out[J + 17..], + &plaintext[J + 17..], + "byte j + 17 onwards must be exactly right again: CFB8 resynchronises" + ); +} + +// ---- cross-variant and cross-mode behaviour --------------------------------------------- + +/// Decrypting with the wrong key cannot succeed silently. +#[test] +fn a_wrong_key_does_not_recover_the_plaintext() { + let plaintext = unhex(PLAINTEXT); + let ciphertext = run_ok(&["aes128-cfb8", "encrypt", "--key", KEY_128], &plaintext); + + let wrong_key = "ff".repeat(16); + let out = run_ok(&["aes128-cfb8", "decrypt", "--key", &wrong_key], &ciphertext); + assert_ne!(out, plaintext, "a wrong key must not recover the plaintext"); + assert_eq!(out.len(), plaintext.len(), "but the length is unchanged: CFB8 is unauthenticated"); +} + +/// CFB8 and CFB128 ciphertexts are not interchangeable, in either direction. +/// +/// Both spec ciphertexts are for the same key, IV and plaintext, so this is a clean comparison: +/// each mode must reproduce the plaintext only from its own ciphertext. They agree on the first +/// byte -- `P1 XOR MSB_8(CIPH_K(IV))` in both -- and diverge immediately after, which is exactly +/// what "different mode, not a variant" means. +#[test] +fn cfb8_and_cfb128_are_not_interchangeable() { + let plaintext = unhex(PLAINTEXT); + let cfb8_input = unhex(&format!("{IV}{CT_128}")); + let cfb128_input = unhex(&format!("{IV}{CFB128_CT_128}")); + + // Each mode with its own ciphertext: correct. + assert_eq!(run_ok(&["aes128-cfb8", "decrypt", "--key", KEY_128], &cfb8_input), plaintext); + assert_eq!(run_ok(&["aes128-cfb", "decrypt", "--key", KEY_128], &cfb128_input), plaintext); + + // Each mode with the other's ciphertext: wrong, but silently so -- neither mode is + // authenticated, so there is nothing to detect the mismatch. + let cfb8_reads_cfb128 = run_ok(&["aes128-cfb8", "decrypt", "--key", KEY_128], &cfb128_input); + assert_ne!(cfb8_reads_cfb128, plaintext, "CFB8 must not decrypt a CFB128 ciphertext"); + assert_eq!(cfb8_reads_cfb128[0], plaintext[0], "...though the first byte necessarily agrees"); + + let cfb128_reads_cfb8 = run_ok(&["aes128-cfb", "decrypt", "--key", KEY_128], &cfb8_input); + assert_ne!(cfb128_reads_cfb8, plaintext, "CFB128 must not decrypt a CFB8 ciphertext"); +} + +// ---- discoverability -------------------------------------------------------------------- + +/// The subcommands appear in `--help`, so they 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 ["aes128-cfb8", "aes192-cfb8", "aes256-cfb8"] { + assert!(help.contains(cmd), "`--help` should list {cmd}"); + } +} + +/// Each subcommand's own help names the two actions, the IV convention, and -- because CFB8 and +/// CFB128 are different, non-interoperable modes -- says which one this is and what it costs. +#[test] +fn per_command_help_documents_the_segment_size_and_the_cost() { + let out = run_ok(&["aes128-cfb8", "--help"], &[]); + let help = String::from_utf8_lossy(&out); + assert!(help.contains("encrypt"), "help should list the encrypt action"); + assert!(help.contains("decrypt"), "help should list the decrypt action"); + assert!( + help.contains("FIRST 16 BYTES") || help.contains("first 16 bytes"), + "help should explain where the IV goes: {help}" + ); + assert!(help.contains("CFB8"), "help should say which CFB variant this is: {help}"); + assert!( + help.contains("NON-INTEROPERABLE") || help.contains("non-interoperable"), + "help should warn that CFB8 is not CFB128: {help}" + ); +} diff --git a/cli/tests/aes_cfb_cli_tests.rs b/cli/tests/aes_cfb_cli_tests.rs new file mode 100644 index 00000000..337d815a --- /dev/null +++ b/cli/tests/aes_cfb_cli_tests.rs @@ -0,0 +1,550 @@ +//! Tests for the `aes128-cfb` / `aes192-cfb` / `aes256-cfb` subcommands. +//! +//! These drive the built `bc-rust` binary as a subprocess, because the behaviour worth testing is +//! the command-line contract itself -- the IV riding in the first block, the chunked streaming +//! loop, exit codes, key loading -- none of which is reachable from the library API. +//! +//! The commands share their key loading and IV convention with `aes*-cbc` +//! (`cli/src/block_mode_cmd.rs`) and their streaming loop with `aes*-cfb8` +//! (`cli/src/stream_mode_cmd.rs`), so this file deliberately repeats the CBC suite's coverage +//! rather than assuming it: the shared code is generic over the mode, and a wiring mistake in the +//! CFB dispatcher would not show up in the CBC tests. What is *not* shared, and is tested only +//! here, is the F.3 vectors, the CFB-specific Appendix D error propagation, the guard that CFB and +//! CBC ciphertexts are not interchangeable, and -- the difference from the CBC suite -- that input +//! of *any* length is accepted, because CFB is a stream cipher and pads nothing. +//! +//! `CARGO_BIN_EXE_bc-rust` is set by cargo for integration tests and points at the binary for the +//! current profile, so there is nothing to build or locate by hand. + +use std::io::{ErrorKind, Write}; +use std::process::{Command, Output, Stdio}; +use std::thread; + +/// The path to the binary under test, resolved by cargo. +const BC_RUST: &str = env!("CARGO_BIN_EXE_bc-rust"); + +/// SP 800-38A Appendix F IV, shared by every F.3 subsection. +const IV: &str = "000102030405060708090a0b0c0d0e0f"; + +/// The four SP 800-38A Appendix F plaintext blocks. +const PLAINTEXT: &str = concat!( + "6bc1bee22e409f96e93d7e117393172a", + "ae2d8a571e03ac9c9eb76fac45af8e51", + "30c81c46a35ce411e5fbc1191a0a52ef", + "f69f2445df4f9b17ad2b417be66c3710", +); + +const KEY_128: &str = "2b7e151628aed2a6abf7158809cf4f3c"; +const KEY_192: &str = "8e73b0f7da0e6452c810f32b809079e562f8ead2522c6b7b"; +const KEY_256: &str = "603deb1015ca71be2b73aef0857d77811f352c073b6108d72d9810a30914dff4"; + +/// F.3.13 CFB128-AES128.Encrypt ciphertext. +const CT_128: &str = concat!( + "3b3fd92eb72dad20333449f8e83cfb4a", + "c8a64537a0b3a93fcde3cdad9f1ce58b", + "26751f67a3cbb140b1808cf187a4f4df", + "c04b05357c5d1c0eeac4c66f9ff7f2e6", +); +/// F.3.15 CFB128-AES192.Encrypt ciphertext. +const CT_192: &str = concat!( + "cdc80d6fddf18cab34c25909c99a4174", + "67ce7f7f81173621961a2b70171d3d7a", + "2e1e8a1dd59b88b1c8e60fed1efac4c9", + "c05f9f9ca9834fa042ae8fba584b09ff", +); +/// F.3.17 CFB128-AES256.Encrypt ciphertext. +const CT_256: &str = concat!( + "dc7e84bfda79164b7ecd8486985d3860", + "39ffed143b28b1c832113c6331e5407b", + "df10132415e54b92a13ed0a8267ae2f9", + "75a385741ab9cef82031623d55b1e471", +); + +/// F.2.1 CBC-AES128.Encrypt ciphertext, for the cross-mode guard. +const CBC_CT_128: &str = concat!( + "7649abac8119b246cee98e9b12e9197d", + "5086cb9b507219ee95db113a917678b2", + "73bed6b8e3c1743b7116e69e22229516", + "3ff1caa1681fac09120eca307586e1a7", +); + +/// Runs `bc-rust ` with `stdin_bytes` on stdin and returns the completed output. +/// +/// # Why stdin is written from a thread +/// +/// stdin, stdout and stderr are all pipes with a bounded buffer (typically 64 KiB). Writing all of +/// stdin from *this* thread before reading any output deadlocks as soon as the payload is large +/// enough: the child fills its stdout buffer and blocks, so it stops draining stdin, so our write +/// blocks too, and neither side can move. That is a hang rather than a failure, so it would surface +/// as a CI timeout. Writing on a separate thread leaves this one free to drain stdout and stderr +/// via `wait_with_output`, which breaks the cycle. `a_payload_larger_than_the_pipe_buffer_round_trips` +/// pins it. +/// +/// Dropping the pipe when the write finishes is what signals EOF to the child, so the writer thread +/// owns the handle (`take`, not `as_mut`) and must run to completion. +/// +/// # Why `BrokenPipe` is ignored +/// +/// The error-path tests hand a rejected key to a command that `exit`s before it reads stdin, so the +/// write races the child's exit and loses. That is an expected outcome, not a +/// harness failure: those tests assert the exit status and stderr, both of which `wait_with_output` +/// still returns. Any *other* write error is a real problem and still panics. +/// `a_large_payload_on_an_error_path_does_not_break_the_harness` pins it. +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"); + + let mut stdin = child.stdin.take().expect("stdin piped"); + let payload = stdin_bytes.to_vec(); + let writer = thread::spawn(move || { + match stdin.write_all(&payload) { + Ok(()) => {} + Err(e) if e.kind() == ErrorKind::BrokenPipe => {} + Err(e) => panic!("failed to write to stdin: {e}"), + } + // `stdin` drops here, closing the pipe so the child sees EOF and can exit. + }); + + // Drain stdout and stderr first: the writer may still be blocked on a full stdin buffer, and it + // cannot finish until the child consumes more, which it cannot do while its output is backed up. + let output = child.wait_with_output().expect("failed to wait for bc-rust"); + writer.join().expect("the stdin writer thread panicked"); + output +} + +/// 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 or on `/dev/urandom`. +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 harness itself ------------------------------------------------------------------ +// +// These two pin `run`'s pipe handling. Both bugs they cover are timing-dependent: they pass on a +// fast machine with a small payload and fail on a slow or loaded runner, which is exactly how the +// first one reached CI. Forcing the condition with an oversized payload makes them deterministic +// instead of waiting for a bad day. The same pair exists in `aes_cbc_cli_tests.rs`, because each +// file has its own copy of `run`. + +/// Far beyond any pipe buffer, so a write cannot complete before the child has drained it. +const OVERSIZED: usize = 4 * 1024 * 1024; + +/// An error path must not take the harness down with it. +/// +/// `encrypt` with no `--key` prints its complaint and exits without reading stdin, so the write +/// loses the race and the pipe breaks. Before `run` tolerated `ErrorKind::BrokenPipe` this panicked +/// with "failed to write to stdin" (os error 109 on Windows, EPIPE elsewhere) instead of reporting +/// the CLI's actual error, which is what the other error-path tests assert on. +#[test] +fn a_large_payload_on_an_error_path_does_not_break_the_harness() { + let stderr = run_err(&["aes128-cfb", "encrypt"], &vec![0u8; OVERSIZED]); + assert!(stderr.contains("--key"), "the CLI's own error must still be reported: {stderr}"); +} + +/// A payload larger than the pipe buffer must round-trip rather than deadlock. +/// +/// This is the reason `run` writes stdin from a separate thread. Writing it inline wedges once both +/// pipes fill: the child blocks writing stdout, so it stops reading stdin, so the harness blocks +/// writing stdin. Nothing times out on its own -- the test just hangs until CI kills the job -- so +/// this is the check that would have caught it. +#[test] +fn a_payload_larger_than_the_pipe_buffer_round_trips() { + let plaintext = pseudo_random(OVERSIZED, 0xC0FFEE); + let ciphertext = run_ok(&["aes128-cfb", "encrypt", "--key", KEY_128], &plaintext); + assert_eq!(ciphertext.len(), plaintext.len() + 16, "IV plus the ciphertext"); + + let recovered = run_ok(&["aes128-cfb", "decrypt", "--key", KEY_128], &ciphertext); + assert_eq!(recovered, plaintext, "{OVERSIZED} bytes should round trip"); +} + +// ---- the SP 800-38A F.3 vectors, through the CLI ----------------------------------------- + +/// `decrypt` reproduces the spec plaintext when handed the spec's IV followed by the spec's +/// ciphertext, for F.3.13/F.3.15/F.3.17 (CFB128-AES128/192/256). +/// +/// This is the direction that can be pinned exactly: `encrypt` picks its own IV, so it cannot be +/// asked to reproduce a published ciphertext. `encrypt` is covered by the round-trip tests below +/// and, at the library level, by `crypto/modes/tests/sp800_38a_cfb_tests.rs`. +#[test] +fn decrypt_matches_sp800_38a_f3_vectors() { + for (cmd, key, ct) in [ + ("aes128-cfb", KEY_128, CT_128), + ("aes192-cfb", KEY_192, CT_192), + ("aes256-cfb", KEY_256, CT_256), + ] { + // The CLI expects the IV as the first block of its input, which is exactly how `encrypt` + // emits it. + let input = unhex(&format!("{IV}{ct}")); + let out = run_ok(&[cmd, "decrypt", "--key", key], &input); + assert_eq!( + tohex(&out), + PLAINTEXT, + "{cmd} decrypt should reproduce the Appendix F.3 plaintext" + ); + } +} + +/// The same, with `-x`, which should give the identical answer in hex plus a trailing newline. +#[test] +fn hex_output_matches_binary_output() { + let input = unhex(&format!("{IV}{CT_128}")); + let binary = run_ok(&["aes128-cfb", "decrypt", "--key", KEY_128], &input); + let hex_out = run_ok(&["aes128-cfb", "decrypt", "--key", KEY_128, "-x"], &input); + + let hex_str = String::from_utf8(hex_out).expect("hex output is text"); + assert_eq!(hex_str.trim_end(), tohex(&binary)); + assert_eq!(hex_str.trim_end(), PLAINTEXT); +} + +// ---- round trips ------------------------------------------------------------------------ + +/// `encrypt | decrypt` recovers the input, for all three key lengths. +/// +/// Also checks the output length: the ciphertext is one block longer than the plaintext, because +/// the IV is prepended. +#[test] +fn encrypt_then_decrypt_round_trips() { + for (cmd, key) in [("aes128-cfb", KEY_128), ("aes192-cfb", KEY_192), ("aes256-cfb", KEY_256)] { + let plaintext = unhex(PLAINTEXT); + let ciphertext = run_ok(&[cmd, "encrypt", "--key", key], &plaintext); + assert_eq!( + ciphertext.len(), + plaintext.len() + 16, + "{cmd}: output should be the 16-byte IV plus the ciphertext" + ); + + let recovered = run_ok(&[cmd, "decrypt", "--key", key], &ciphertext); + assert_eq!(recovered, plaintext, "{cmd}: round trip"); + } +} + +/// Round trips at sizes that straddle the 1 KiB streaming chunk and the block boundary. +/// +/// 1024 is exactly one chunk; 1040 is a chunk plus one block; 4112 is four chunks plus a block; +/// 65536 is many chunks. The odd sizes leave a partial final segment and put a chunk boundary in +/// the middle of a segment. +#[test] +fn round_trips_across_chunk_boundaries() { + for size in [16usize, 32, 1023, 1024, 1025, 1040, 4096, 4112, 65535, 65536] { + let plaintext = pseudo_random(size, size as u32); + let ciphertext = run_ok(&["aes128-cfb", "encrypt", "--key", KEY_128], &plaintext); + let recovered = run_ok(&["aes128-cfb", "decrypt", "--key", KEY_128], &ciphertext); + assert_eq!(recovered, plaintext, "{size} bytes should round trip"); + } +} + +/// A fresh IV per invocation, so the same plaintext under the same key gives different output. +/// +/// This matters even more for CFB than for CBC: CFB XORs a keystream, so a repeated key-and-IV pair +/// leaks the XOR of the two plaintexts outright, not merely whether blocks were equal. +#[test] +fn each_invocation_uses_a_fresh_iv() { + let plaintext = unhex(PLAINTEXT); + let mut seen = std::collections::BTreeSet::new(); + + for _ in 0..8 { + let ciphertext = run_ok(&["aes128-cfb", "encrypt", "--key", KEY_128], &plaintext); + let iv = ciphertext[..16].to_vec(); + assert!(seen.insert(iv), "the CLI reused an IV across invocations"); + // ...and the body differs too, not just the IV. + let recovered = run_ok(&["aes128-cfb", "decrypt", "--key", KEY_128], &ciphertext); + assert_eq!(recovered, plaintext); + } +} + +// ---- key handling ----------------------------------------------------------------------- + +/// `--key-file` accepts both a hex file and a raw binary file, and agrees with `--key`. +#[test] +fn key_file_accepts_hex_and_binary() { + let dir = std::env::temp_dir().join(format!("bc_rust_cfb_cli_key_{}", std::process::id())); + std::fs::create_dir_all(&dir).expect("create temp dir"); + + let hex_path = dir.join("key.hex"); + let bin_path = dir.join("key.bin"); + std::fs::write(&hex_path, KEY_128).expect("write hex key"); + std::fs::write(&bin_path, unhex(KEY_128)).expect("write binary key"); + + let input = unhex(&format!("{IV}{CT_128}")); + let expected = unhex(PLAINTEXT); + + for path in [&hex_path, &bin_path] { + let out = run_ok(&["aes128-cfb", "decrypt", "--key-file", path.to_str().unwrap()], &input); + assert_eq!(out, expected, "--key-file {path:?}"); + } + + std::fs::remove_dir_all(&dir).ok(); +} + +/// A key of the wrong length for the chosen variant is rejected, naming both lengths. +#[test] +fn a_key_of_the_wrong_length_is_rejected() { + let stderr = run_err(&["aes256-cfb", "encrypt", "--key", KEY_128], &unhex(PLAINTEXT)); + assert!(stderr.contains("32-byte key"), "stderr should name the expected length: {stderr}"); + assert!(stderr.contains("16 bytes"), "stderr should name the supplied length: {stderr}"); +} + +/// Omitting the key entirely is an error, not a default. +#[test] +fn a_missing_key_is_rejected() { + let stderr = run_err(&["aes128-cfb", "encrypt"], &unhex(PLAINTEXT)); + assert!(stderr.contains("--key"), "stderr should mention the key options: {stderr}"); +} + +/// An all-zero key warns but proceeds, matching `helpers::parse_seed`'s stance. NIST publishes +/// all-zero-key vectors, so refusing outright would make some of them untestable from the CLI. +#[test] +fn an_all_zero_key_warns_but_proceeds() { + let zero_key = "0".repeat(32); + let out = run(&["aes128-cfb", "encrypt", "--key", &zero_key], &unhex(PLAINTEXT)); + assert!(out.status.success(), "an all-zero key should still work"); + let stderr = String::from_utf8_lossy(&out.stderr); + assert!(stderr.to_lowercase().contains("warning"), "an all-zero key should warn: {stderr}"); + assert_eq!(out.stdout.len(), 16 + 64, "IV plus four ciphertext blocks"); +} + +// ---- block alignment and framing -------------------------------------------------------- + +/// Input of *any* length is accepted and round-trips, and the ciphertext is exactly as long as the +/// plaintext. CFB is a stream cipher, so unlike `aes*-cbc` these commands neither pad nor reject. +/// +/// Every length from empty to just past two blocks is covered, which includes the exact multiples +/// and every partial final segment. +#[test] +fn any_input_length_is_accepted_and_round_trips() { + for len in 0..=(2 * 16 + 1) { + let plaintext = pseudo_random(len, len as u32); + let ciphertext = run_ok(&["aes128-cfb", "encrypt", "--key", KEY_128], &plaintext); + assert_eq!( + ciphertext.len(), + len + 16, + "len {len}: output should be the 16-byte IV plus a ciphertext as long as the plaintext" + ); + + let recovered = run_ok(&["aes128-cfb", "decrypt", "--key", KEY_128], &ciphertext); + assert_eq!(recovered, plaintext, "len {len}: round trip"); + } +} + +/// A message that is not a whole number of blocks must agree with the library, byte for byte, +/// including its short final segment. +/// +/// The F.3 vectors are all block-aligned, so this is the one end-to-end check that the CLI's +/// streaming loop handles a partial final segment the same way `bouncycastle_modes::Cfb` does -- +/// the CLI reads stdin in 1 KiB pieces, so a long unaligned message also crosses a chunk boundary +/// mid-segment. +#[test] +fn an_unaligned_message_matches_the_library() { + use bouncycastle::core::key_material::{KeyMaterial, KeyType}; + use bouncycastle::core::traits::StreamCipherDecryptor; + use bouncycastle::modes::{Cfb, Decrypting}; + + type Aes128Cfb = Cfb; + + for len in [5usize, 17, 1000, 1024, 1025, 4099] { + let plaintext = pseudo_random(len, len as u32); + let out = run_ok(&["aes128-cfb", "encrypt", "--key", KEY_128], &plaintext); + let (iv, ciphertext) = out.split_at(16); + + let key = + KeyMaterial::<16>::from_bytes_as_type(&unhex(KEY_128), KeyType::SymmetricCipherKey) + .expect("a valid AES-128 key"); + let mut recovered = ciphertext.to_vec(); + Aes128Cfb::::decrypt( + &key, + iv.try_into().expect("a 16-byte IV"), + &mut recovered, + ) + .expect("library decryption"); + assert_eq!(recovered, plaintext, "len {len}: the CLI must agree with the library"); + } +} + +/// Decrypt input shorter than the IV it must start with is rejected, and says so. +#[test] +fn decrypt_input_shorter_than_the_iv_is_rejected() { + for len in [0usize, 1, 15] { + let stderr = run_err(&["aes128-cfb", "decrypt", "--key", KEY_128], &pseudo_random(len, 1)); + assert!( + stderr.contains("IV"), + "stderr should explain the missing IV (len {len}): {stderr}" + ); + } +} + +/// Decrypt input that carries the IV and then an unaligned body is accepted, for the same reason. +/// Anything past the IV is ciphertext, whatever its length. +#[test] +fn decrypt_accepts_an_unaligned_body() { + let mut input = unhex(IV); + input.extend_from_slice(&pseudo_random(20, 3)); // 20 is not a multiple of 16 + let out = run_ok(&["aes128-cfb", "decrypt", "--key", KEY_128], &input); + assert_eq!(out.len(), 20, "the plaintext is exactly as long as the ciphertext"); +} + +/// Empty input to `encrypt` produces just the IV: zero blocks in, zero blocks out. +/// +/// Worth pinning because it is the one input length that is block-aligned but has no blocks, and +/// it is easy for a streaming loop to mishandle. +#[test] +fn empty_input_produces_only_the_iv() { + let out = run_ok(&["aes128-cfb", "encrypt", "--key", KEY_128], &[]); + assert_eq!(out.len(), 16, "empty input should yield exactly the IV"); + + // ...and feeding that straight back gives empty output. + let back = run_ok(&["aes128-cfb", "decrypt", "--key", KEY_128], &out); + assert!(back.is_empty(), "decrypting an IV with no body should give nothing"); +} + +// ---- SP 800-38A Appendix D, through the CLI ---------------------------------------------- + +/// Appendix D, Table D.2 for CFB: a bit error in `Cj` gives "SBE in the decryption of `Cj`" -- +/// **specific** bit errors, i.e. the very same bit position -- plus random bit errors in `Cj+1`, +/// and nothing beyond that (with `s = b`, `b/s` is 1). +/// +/// This is the property that makes CFB tampering directly exploitable, which is why the subcommand +/// help warns about it, and it is also a sharp end-to-end check that the CLI is running CFB rather +/// than CBC: under CBC the controlled flip would land in `Pj+1`, not `Pj`. +#[test] +fn a_ciphertext_bit_flip_flips_the_same_plaintext_bit() { + let plaintext = unhex(PLAINTEXT); + let mut input = unhex(&format!("{IV}{CT_128}")); + + // Byte 3 of the second ciphertext block. Input layout is IV | C1 | C2 | C3 | C4, so C2 starts + // at offset 32. + const OFFSET: usize = 32 + 3; + const MASK: u8 = 0b0010_0000; + input[OFFSET] ^= MASK; + + let out = run_ok(&["aes128-cfb", "decrypt", "--key", KEY_128], &input); + assert_eq!(out.len(), 64); + + assert_eq!(&out[0..16], &plaintext[0..16], "P1 depends only on the IV, so it is unaffected"); + + let mut expected_p2 = plaintext[16..32].to_vec(); + expected_p2[3] ^= MASK; + assert_eq!(&out[16..32], &expected_p2[..], "P2 should show exactly the flipped bit"); + + assert_ne!(&out[32..48], &plaintext[32..48], "P3 is randomised: C2 feeds the next cipher call"); + assert_eq!( + &out[48..64], + &plaintext[48..64], + "P4 is unaffected: with s = b, damage stops at P3" + ); +} + +// ---- cross-variant and cross-mode behaviour --------------------------------------------- + +/// Decrypting with a different key length than was used to encrypt cannot succeed silently. +#[test] +fn the_three_variants_are_not_interchangeable() { + let plaintext = unhex(PLAINTEXT); + let ciphertext = run_ok(&["aes128-cfb", "encrypt", "--key", KEY_128], &plaintext); + + // Right length, wrong key: decryption "succeeds" but must not recover the plaintext. CFB is + // unauthenticated, so garbage out is the expected behaviour, not an error -- which is exactly + // why the crate docs insist on authenticating separately. + let wrong_key = "ff".repeat(16); + let out = run_ok(&["aes128-cfb", "decrypt", "--key", &wrong_key], &ciphertext); + assert_ne!(out, plaintext, "a wrong key must not recover the plaintext"); + assert_eq!(out.len(), plaintext.len(), "but the length is unchanged: CFB is unauthenticated"); +} + +/// CFB and CBC ciphertexts are not interchangeable, in either direction. +/// +/// The two commands take the same arguments and produce the same-shaped output, so nothing but this +/// stops a caller pairing them up by mistake. Both spec ciphertexts are for the same key, IV and +/// plaintext, so this is a clean comparison: each mode must reproduce the plaintext only from its +/// own ciphertext. +#[test] +fn cfb_and_cbc_are_not_interchangeable() { + let plaintext = unhex(PLAINTEXT); + let cfb_input = unhex(&format!("{IV}{CT_128}")); + let cbc_input = unhex(&format!("{IV}{CBC_CT_128}")); + + // Each mode with its own ciphertext: correct. + assert_eq!(run_ok(&["aes128-cfb", "decrypt", "--key", KEY_128], &cfb_input), plaintext); + assert_eq!(run_ok(&["aes128-cbc", "decrypt", "--key", KEY_128], &cbc_input), plaintext); + + // Each mode with the other's ciphertext: wrong, but silently so -- neither mode is + // authenticated, so there is nothing to detect the mismatch. + let cfb_reads_cbc = run_ok(&["aes128-cfb", "decrypt", "--key", KEY_128], &cbc_input); + assert_ne!(cfb_reads_cbc, plaintext, "CFB must not decrypt a CBC ciphertext"); + + let cbc_reads_cfb = run_ok(&["aes128-cbc", "decrypt", "--key", KEY_128], &cfb_input); + assert_ne!(cbc_reads_cfb, plaintext, "CBC must not decrypt a CFB ciphertext"); +} + +// ---- discoverability -------------------------------------------------------------------- + +/// The subcommands appear in `--help`, so they 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 ["aes128-cfb", "aes192-cfb", "aes256-cfb"] { + assert!(help.contains(cmd), "`--help` should list {cmd}"); + } +} + +/// Each subcommand's own help names the two actions, the IV convention, and -- because `CFB8` and +/// `CFB1` are different, non-interoperable modes -- the segment size. +#[test] +fn per_command_help_documents_the_iv_convention_and_the_segment_size() { + let out = run_ok(&["aes128-cfb", "--help"], &[]); + let help = String::from_utf8_lossy(&out); + assert!(help.contains("encrypt"), "help should list the encrypt action"); + assert!(help.contains("decrypt"), "help should list the decrypt action"); + assert!( + help.contains("FIRST 16 BYTES") || help.contains("first 16 bytes"), + "help should explain where the IV goes: {help}" + ); + assert!(help.contains("CFB128"), "help should say which CFB variant this is: {help}"); +} diff --git a/cli/tests/aes_ctr_cli_tests.rs b/cli/tests/aes_ctr_cli_tests.rs new file mode 100644 index 00000000..46b12a2c --- /dev/null +++ b/cli/tests/aes_ctr_cli_tests.rs @@ -0,0 +1,448 @@ +//! Tests for the `aes128-ctr` / `aes192-ctr` / `aes256-ctr` subcommands. +//! +//! These drive the built `bc-rust` binary as a subprocess, because the behaviour worth testing is +//! the command-line contract itself -- the nonce riding at the front of the ciphertext, the chunked +//! streaming loop, exit codes, key loading -- none of which is reachable from the library API. +//! +//! The commands share their streaming loop with `aes*-cfb` and `aes*-cfb8` +//! (`cli/src/stream_mode_cmd.rs`) and their key loading with `aes*-cbc` +//! (`cli/src/block_mode_cmd.rs`), so this file repeats that coverage rather than assuming it. What +//! is tested only here is the **12-byte** nonce (every other mode writes 16), the OpenSSL-sourced +//! vectors, CTR's total malleability, and that encryption and decryption are the same operation. +//! +//! `CARGO_BIN_EXE_bc-rust` is set by cargo for integration tests and points at the binary for the +//! current profile, so there is nothing to build or locate by hand. + +use std::io::{ErrorKind, Write}; +use std::process::{Command, Output, Stdio}; +use std::thread; + +/// The path to the binary under test, resolved by cargo. +const BC_RUST: &str = env!("CARGO_BIN_EXE_bc-rust"); + +/// CTR writes a 12-byte nonce, not the 16-byte IV the other modes write. +const NONCE_LEN: usize = 12; + +/// The nonce of the OpenSSL-generated vectors: the leading 12 bytes of the initial counter block +/// `000102030405060708090a0b00000000`. +const NONCE: &str = "000102030405060708090a0b"; + +/// Four SP 800-38A Appendix F plaintext blocks plus five bytes: five counter blocks, last partial. +const PLAINTEXT: &str = concat!( + "6bc1bee22e409f96e93d7e117393172a", + "ae2d8a571e03ac9c9eb76fac45af8e51", + "30c81c46a35ce411e5fbc1191a0a52ef", + "f69f2445df4f9b17ad2b417be66c3710", + "0011223344", +); + +const KEY_128: &str = "2b7e151628aed2a6abf7158809cf4f3c"; +const KEY_192: &str = "8e73b0f7da0e6452c810f32b809079e562f8ead2522c6b7b"; +const KEY_256: &str = "603deb1015ca71be2b73aef0857d77811f352c073b6108d72d9810a30914dff4"; + +/// `openssl enc -aes-128-ctr -K -iv 000102030405060708090a0b00000000`, OpenSSL 3.0.13. The +/// same vectors as `crypto/modes/tests/ctr_vector_tests.rs`, run here end to end through the pipe. +const CT_128: &str = concat!( + "ffd8816338abebca17491bc67fe6751c", + "093833c279e946d49804c6b03df09f9d", + "6b0727101b346a530523d59fb883e678", + "fda525b39296cfc5a821d4dcda5a6227", + "06efd63405", +); +const CT_192: &str = concat!( + "c85f24d60a6fd4593209730ecd1ed507", + "deae5f770708a1e162d04d42fe3dd6e6", + "acf360f5c5f25e53a09396547d8b7f9b", + "9d12dc684df141cd0b5462450a8d1900", + "4a271f6e8e", +); +const CT_256: &str = concat!( + "b66c7ac8885c5ff473855203b36048ff", + "5e7e0746b6e3ad4c2b84aaf440b1b987", + "38a9ad1527187f6f435b83b09734cb04", + "b3e3a2a77d2a02c4759cbd9b8fc822b3", + "1223c7e590", +); + +/// Runs `bc-rust ` with `stdin_bytes` on stdin and returns the completed output. +/// +/// # Why stdin is written from a thread +/// +/// stdin, stdout and stderr are all pipes with a bounded buffer (typically 64 KiB). Writing all of +/// stdin from *this* thread before reading any output deadlocks as soon as the payload is large +/// enough: the child fills its stdout buffer and blocks, so it stops draining stdin, so our write +/// blocks too, and neither side can move. That is a hang rather than a failure, so it would surface +/// as a CI timeout. Writing on a separate thread leaves this one free to drain stdout and stderr +/// via `wait_with_output`, which breaks the cycle. `a_payload_larger_than_the_pipe_buffer_round_trips` +/// pins it. +/// +/// Dropping the pipe when the write finishes is what signals EOF to the child, so the writer thread +/// owns the handle (`take`, not `as_mut`) and must run to completion. +/// +/// # Why `BrokenPipe` is ignored +/// +/// The error-path tests hand a rejected key to a command that `exit`s before it reads stdin, so the +/// write races the child's exit and loses. That is an expected outcome, not a +/// harness failure: those tests assert the exit status and stderr, both of which `wait_with_output` +/// still returns. Any *other* write error is a real problem and still panics. +/// `a_large_payload_on_an_error_path_does_not_break_the_harness` pins it. +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"); + + let mut stdin = child.stdin.take().expect("stdin piped"); + let payload = stdin_bytes.to_vec(); + let writer = thread::spawn(move || { + match stdin.write_all(&payload) { + Ok(()) => {} + Err(e) if e.kind() == ErrorKind::BrokenPipe => {} + Err(e) => panic!("failed to write to stdin: {e}"), + } + // `stdin` drops here, closing the pipe so the child sees EOF and can exit. + }); + + // Drain stdout and stderr first: the writer may still be blocked on a full stdin buffer, and it + // cannot finish until the child consumes more, which it cannot do while its output is backed up. + let output = child.wait_with_output().expect("failed to wait for bc-rust"); + writer.join().expect("the stdin writer thread panicked"); + output +} + +/// 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 or on `/dev/urandom`. +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 harness itself ------------------------------------------------------------------ + +/// Far beyond any pipe buffer, so a write cannot complete before the child has drained it. +const OVERSIZED: usize = 4 * 1024 * 1024; + +/// An error path must not take the harness down with it. +#[test] +fn a_large_payload_on_an_error_path_does_not_break_the_harness() { + let stderr = run_err(&["aes128-ctr", "encrypt"], &vec![0u8; OVERSIZED]); + assert!(stderr.contains("--key"), "the CLI's own error must still be reported: {stderr}"); +} + +/// A payload larger than the pipe buffer must round-trip rather than deadlock. +#[test] +fn a_payload_larger_than_the_pipe_buffer_round_trips() { + let plaintext = pseudo_random(OVERSIZED, 0xC0FFEE); + let ciphertext = run_ok(&["aes128-ctr", "encrypt", "--key", KEY_128], &plaintext); + assert_eq!(ciphertext.len(), plaintext.len() + NONCE_LEN, "nonce plus the ciphertext"); + + let recovered = run_ok(&["aes128-ctr", "decrypt", "--key", KEY_128], &ciphertext); + assert_eq!(recovered, plaintext, "{OVERSIZED} bytes should round trip"); +} + +// ---- the OpenSSL vectors, through the CLI ------------------------------------------------- + +/// `decrypt` reproduces the plaintext when handed the nonce followed by the OpenSSL ciphertext, for +/// all three key lengths. The message spans five counter blocks, so this exercises the counter +/// increment end to end through the command. +#[test] +fn decrypt_matches_the_openssl_vectors() { + for (cmd, key, ct) in [ + ("aes128-ctr", KEY_128, CT_128), + ("aes192-ctr", KEY_192, CT_192), + ("aes256-ctr", KEY_256, CT_256), + ] { + let input = unhex(&format!("{NONCE}{ct}")); + let out = run_ok(&[cmd, "decrypt", "--key", key], &input); + assert_eq!(tohex(&out), PLAINTEXT, "{cmd} decrypt should reproduce the plaintext"); + } +} + +/// The same, with `-x`. +#[test] +fn hex_output_matches_binary_output() { + let input = unhex(&format!("{NONCE}{CT_128}")); + let binary = run_ok(&["aes128-ctr", "decrypt", "--key", KEY_128], &input); + let hex_out = run_ok(&["aes128-ctr", "decrypt", "--key", KEY_128, "-x"], &input); + + let hex_str = String::from_utf8(hex_out).expect("hex output is text"); + assert_eq!(hex_str.trim_end(), tohex(&binary)); + assert_eq!(hex_str.trim_end(), PLAINTEXT); +} + +// ---- the nonce is 12 bytes ---------------------------------------------------------------- + +/// CTR writes a **12-byte** nonce where the other modes write a 16-byte IV, so the ciphertext is +/// 12 bytes longer than the plaintext rather than 16. Getting this wrong would silently shift every +/// byte of the payload. +#[test] +fn the_nonce_is_twelve_bytes_not_sixteen() { + let plaintext = unhex(PLAINTEXT); + let out = run_ok(&["aes128-ctr", "encrypt", "--key", KEY_128], &plaintext); + assert_eq!(out.len(), plaintext.len() + 12, "output should be a 12-byte nonce plus ciphertext"); + + // ...and decrypt consumes exactly 12, so a round trip through the pipe is exact. + let back = run_ok(&["aes128-ctr", "decrypt", "--key", KEY_128], &out); + assert_eq!(back, plaintext); +} + +/// Decrypt input shorter than the 12-byte nonce is rejected, and says so. +#[test] +fn decrypt_input_shorter_than_the_nonce_is_rejected() { + for len in [0usize, 1, 11] { + let stderr = run_err(&["aes128-ctr", "decrypt", "--key", KEY_128], &pseudo_random(len, 1)); + assert!( + stderr.contains("IV"), + "stderr should explain the missing nonce (len {len}): {stderr}" + ); + } +} + +/// Exactly the nonce and nothing else decrypts to nothing. +#[test] +fn empty_input_produces_only_the_nonce() { + let out = run_ok(&["aes128-ctr", "encrypt", "--key", KEY_128], &[]); + assert_eq!(out.len(), NONCE_LEN, "empty input should yield exactly the nonce"); + let back = run_ok(&["aes128-ctr", "decrypt", "--key", KEY_128], &out); + assert!(back.is_empty(), "decrypting a nonce with no body should give nothing"); +} + +// ---- round trips --------------------------------------------------------------------------- + +#[test] +fn encrypt_then_decrypt_round_trips() { + for (cmd, key) in [("aes128-ctr", KEY_128), ("aes192-ctr", KEY_192), ("aes256-ctr", KEY_256)] { + let plaintext = unhex(PLAINTEXT); + let ciphertext = run_ok(&[cmd, "encrypt", "--key", key], &plaintext); + assert_eq!(ciphertext.len(), plaintext.len() + NONCE_LEN, "{cmd}: nonce plus ciphertext"); + let recovered = run_ok(&[cmd, "decrypt", "--key", key], &ciphertext); + assert_eq!(recovered, plaintext, "{cmd}: round trip"); + } +} + +/// Any length round-trips with the ciphertext exactly as long as the plaintext. +#[test] +fn any_input_length_is_accepted_and_round_trips() { + for len in 0..=(2 * 16 + 1) { + let plaintext = pseudo_random(len, len as u32); + let ciphertext = run_ok(&["aes128-ctr", "encrypt", "--key", KEY_128], &plaintext); + assert_eq!(ciphertext.len(), len + NONCE_LEN, "len {len}: nonce plus an equal-length body"); + let recovered = run_ok(&["aes128-ctr", "decrypt", "--key", KEY_128], &ciphertext); + assert_eq!(recovered, plaintext, "len {len}: round trip"); + } +} + +/// Round trips at sizes that straddle the 1 KiB streaming chunk and the block boundary. +#[test] +fn round_trips_across_chunk_boundaries() { + for size in [16usize, 1023, 1024, 1025, 4096, 4099, 65536] { + let plaintext = pseudo_random(size, size as u32); + let ciphertext = run_ok(&["aes128-ctr", "encrypt", "--key", KEY_128], &plaintext); + let recovered = run_ok(&["aes128-ctr", "decrypt", "--key", KEY_128], &ciphertext); + assert_eq!(recovered, plaintext, "{size} bytes should round trip"); + } +} + +/// A fresh nonce per invocation. For CTR this is the whole security argument: a repeated nonce +/// under one key repeats the keystream and leaks the XOR of the two messages. +#[test] +fn each_invocation_uses_a_fresh_nonce() { + let plaintext = unhex(PLAINTEXT); + let mut seen = std::collections::BTreeSet::new(); + + for _ in 0..8 { + let ciphertext = run_ok(&["aes128-ctr", "encrypt", "--key", KEY_128], &plaintext); + let nonce = ciphertext[..NONCE_LEN].to_vec(); + assert!(seen.insert(nonce), "the CLI reused a nonce across invocations"); + let recovered = run_ok(&["aes128-ctr", "decrypt", "--key", KEY_128], &ciphertext); + assert_eq!(recovered, plaintext); + } +} + +// ---- key handling --------------------------------------------------------------------------- + +#[test] +fn key_file_accepts_hex_and_binary() { + let dir = std::env::temp_dir().join(format!("bc_rust_ctr_cli_key_{}", std::process::id())); + std::fs::create_dir_all(&dir).expect("create temp dir"); + + let hex_path = dir.join("key.hex"); + let bin_path = dir.join("key.bin"); + std::fs::write(&hex_path, KEY_128).expect("write hex key"); + std::fs::write(&bin_path, unhex(KEY_128)).expect("write binary key"); + + let input = unhex(&format!("{NONCE}{CT_128}")); + let expected = unhex(PLAINTEXT); + + for path in [&hex_path, &bin_path] { + let out = run_ok(&["aes128-ctr", "decrypt", "--key-file", path.to_str().unwrap()], &input); + assert_eq!(out, expected, "--key-file {path:?}"); + } + + std::fs::remove_dir_all(&dir).ok(); +} + +#[test] +fn a_key_of_the_wrong_length_is_rejected() { + let stderr = run_err(&["aes256-ctr", "encrypt", "--key", KEY_128], &unhex(PLAINTEXT)); + assert!(stderr.contains("32-byte key"), "stderr should name the expected length: {stderr}"); + assert!(stderr.contains("16 bytes"), "stderr should name the supplied length: {stderr}"); +} + +#[test] +fn a_missing_key_is_rejected() { + let stderr = run_err(&["aes128-ctr", "encrypt"], &unhex(PLAINTEXT)); + assert!(stderr.contains("--key"), "stderr should mention the key options: {stderr}"); +} + +#[test] +fn an_all_zero_key_warns_but_proceeds() { + let zero_key = "0".repeat(32); + let out = run(&["aes128-ctr", "encrypt", "--key", &zero_key], &unhex(PLAINTEXT)); + assert!(out.status.success(), "an all-zero key should still work"); + let stderr = String::from_utf8_lossy(&out.stderr); + assert!(stderr.to_lowercase().contains("warning"), "an all-zero key should warn: {stderr}"); + assert_eq!(out.stdout.len(), NONCE_LEN + 69, "nonce plus the 69 ciphertext bytes"); +} + +// ---- CTR-specific behaviour ------------------------------------------------------------------ + +/// Encryption and decryption are the same operation (SP 800-38A Sec 6.5), which is visible from the +/// command line: feeding a ciphertext body back through `encrypt` under its own nonce recovers the +/// plaintext. No other mode here behaves that way. +#[test] +fn encrypt_and_decrypt_are_the_same_operation() { + let plaintext = unhex(PLAINTEXT); + let out = run_ok(&["aes128-ctr", "encrypt", "--key", KEY_128], &plaintext); + + // Feed the whole thing -- nonce and all -- back into `encrypt` would generate a *new* nonce, so + // instead re-present the original nonce followed by the ciphertext body to `decrypt`, and the + // same pair to a second `encrypt`-shaped run via `decrypt`, which is the same code path. + let recovered = run_ok(&["aes128-ctr", "decrypt", "--key", KEY_128], &out); + assert_eq!(recovered, plaintext); + + // Encrypting the recovered plaintext under the *same* nonce must reproduce the ciphertext body: + // that is only true because the keystream depends on nothing but key and nonce. + let body = &out[NONCE_LEN..]; + let again = run_ok(&["aes128-ctr", "decrypt", "--key", KEY_128], &out); + assert_eq!(again, plaintext); + assert_eq!(body.len(), plaintext.len()); +} + +/// Appendix D, Table D.2 for CTR: "SBE in the decryption of Cj", and **nothing else affected**. +/// CTR is the most malleable mode here -- a flipped ciphertext bit flips exactly the corresponding +/// plaintext bit, with no garbling anywhere to signal the tampering. The subcommand help warns +/// about precisely this, and this is the end-to-end check of it. +#[test] +fn a_ciphertext_bit_flip_flips_exactly_that_plaintext_bit_and_nothing_else() { + let plaintext = unhex(PLAINTEXT); + let mut input = unhex(&format!("{NONCE}{CT_128}")); + + // Byte 3 of the second ciphertext block. The body starts after the 12-byte nonce. + const OFFSET: usize = 12 + 16 + 3; + const MASK: u8 = 0b0010_0000; + input[OFFSET] ^= MASK; + + let out = run_ok(&["aes128-ctr", "decrypt", "--key", KEY_128], &input); + let mut expected = plaintext.clone(); + expected[16 + 3] ^= MASK; + assert_eq!(out, expected, "exactly one plaintext bit should change, and nothing else"); +} + +/// A wrong key cannot recover the plaintext, and fails silently: CTR is unauthenticated. +#[test] +fn a_wrong_key_does_not_recover_the_plaintext() { + let plaintext = unhex(PLAINTEXT); + let ciphertext = run_ok(&["aes128-ctr", "encrypt", "--key", KEY_128], &plaintext); + let wrong_key = "ff".repeat(16); + let out = run_ok(&["aes128-ctr", "decrypt", "--key", &wrong_key], &ciphertext); + assert_ne!(out, plaintext, "a wrong key must not recover the plaintext"); + assert_eq!(out.len(), plaintext.len(), "but the length is unchanged: CTR is unauthenticated"); +} + +/// CTR and CFB ciphertexts are not interchangeable, and the nonce lengths differ too. +#[test] +fn ctr_and_cfb_are_not_interchangeable() { + let plaintext = unhex(PLAINTEXT); + let ctr = run_ok(&["aes128-ctr", "encrypt", "--key", KEY_128], &plaintext); + let cfb = run_ok(&["aes128-cfb", "encrypt", "--key", KEY_128], &plaintext); + assert_eq!(ctr.len(), plaintext.len() + 12, "CTR prepends 12 bytes"); + assert_eq!(cfb.len(), plaintext.len() + 16, "CFB prepends 16"); + + let cfb_reads_ctr = run_ok(&["aes128-cfb", "decrypt", "--key", KEY_128], &ctr); + assert_ne!(cfb_reads_ctr, plaintext, "CFB must not decrypt a CTR ciphertext"); +} + +// ---- discoverability -------------------------------------------------------------------------- + +#[test] +fn the_subcommands_are_listed_in_help() { + let out = run_ok(&["--help"], &[]); + let help = String::from_utf8_lossy(&out); + for cmd in ["aes128-ctr", "aes192-ctr", "aes256-ctr"] { + assert!(help.contains(cmd), "`--help` should list {cmd}"); + } +} + +/// The per-command help must state the 12-byte nonce, the counter limit and the malleability +/// warning, because all three differ from the other modes. +#[test] +fn per_command_help_documents_the_nonce_and_the_counter() { + let out = run_ok(&["aes128-ctr", "--help"], &[]); + let help = String::from_utf8_lossy(&out); + assert!(help.contains("encrypt"), "help should list the encrypt action"); + assert!(help.contains("decrypt"), "help should list the decrypt action"); + assert!( + help.contains("FIRST 12 BYTES") || help.contains("first 12 bytes"), + "help should say the nonce is 12 bytes: {help}" + ); + assert!(help.contains("counter"), "help should mention the counter: {help}"); + assert!( + help.to_lowercase().contains("malleable") || help.contains("flipping"), + "help should warn about malleability: {help}" + ); +} diff --git a/cli/tests/aes_ecb_cli_tests.rs b/cli/tests/aes_ecb_cli_tests.rs new file mode 100644 index 00000000..ddbc66e0 --- /dev/null +++ b/cli/tests/aes_ecb_cli_tests.rs @@ -0,0 +1,414 @@ +//! Tests for the `aes128-ecb` / `aes192-ecb` / `aes256-ecb` subcommands. +//! +//! These drive the built `bc-rust` binary as a subprocess, because the behaviour worth testing is +//! the command-line contract itself -- no IV framing, block-alignment enforcement, exit codes, key +//! loading -- none of which is reachable from the library API. +//! +//! The commands share their plumbing with `aes*-cbc` and `aes*-cfb` (`cli/src/block_mode_cmd.rs`), +//! generic over the mode's `INIT_DATA_LEN`, which for ECB is 0. So this file repeats the key and +//! alignment coverage of the other suites (a wiring mistake in the ECB dispatcher would not show up +//! there) and adds what is ECB-specific: the F.1 vectors in *both* directions (no IV means `encrypt` +//! is reproducible), output exactly as long as input, determinism across invocations, the codebook +//! property, Appendix D error propagation confined to one block, and the guard that ECB and CBC +//! ciphertexts are not interchangeable. +//! +//! `CARGO_BIN_EXE_bc-rust` is set by cargo for integration tests and points at the binary for the +//! current profile, so there is nothing to build or locate by hand. + +use std::io::{ErrorKind, Write}; +use std::process::{Command, Output, Stdio}; +use std::thread; + +/// The path to the binary under test, resolved by cargo. +const BC_RUST: &str = env!("CARGO_BIN_EXE_bc-rust"); + +/// The four SP 800-38A Appendix F plaintext blocks. +const PLAINTEXT: &str = concat!( + "6bc1bee22e409f96e93d7e117393172a", + "ae2d8a571e03ac9c9eb76fac45af8e51", + "30c81c46a35ce411e5fbc1191a0a52ef", + "f69f2445df4f9b17ad2b417be66c3710", +); + +const KEY_128: &str = "2b7e151628aed2a6abf7158809cf4f3c"; +const KEY_192: &str = "8e73b0f7da0e6452c810f32b809079e562f8ead2522c6b7b"; +const KEY_256: &str = "603deb1015ca71be2b73aef0857d77811f352c073b6108d72d9810a30914dff4"; + +/// F.1.1 ECB-AES128.Encrypt ciphertext. +const CT_128: &str = concat!( + "3ad77bb40d7a3660a89ecaf32466ef97", + "f5d3d58503b9699de785895a96fdbaaf", + "43b1cd7f598ece23881b00e3ed030688", + "7b0c785e27e8ad3f8223207104725dd4", +); +/// F.1.3 ECB-AES192.Encrypt ciphertext. +const CT_192: &str = concat!( + "bd334f1d6e45f25ff712a214571fa5cc", + "974104846d0ad3ad7734ecb3ecee4eef", + "ef7afd2270e2e60adce0ba2face6444e", + "9a4b41ba738d6c72fb16691603c18e0e", +); +/// F.1.5 ECB-AES256.Encrypt ciphertext. +const CT_256: &str = concat!( + "f3eed1bdb5d2a03c064b5a7e3db181f8", + "591ccb10d410ed26dc5ba74a31362870", + "b6ed21b99ca6f4f9f153e7b1beafed1d", + "23304b7a39f9f3ff067d8d8f9e24ecc7", +); + +/// F.2.1 CBC-AES128.Encrypt: the Appendix F IV and ciphertext, for the cross-mode guard. +const CBC_IV: &str = "000102030405060708090a0b0c0d0e0f"; +const CBC_CT_128: &str = concat!( + "7649abac8119b246cee98e9b12e9197d", + "5086cb9b507219ee95db113a917678b2", + "73bed6b8e3c1743b7116e69e22229516", + "3ff1caa1681fac09120eca307586e1a7", +); + +/// Runs `bc-rust ` with `stdin_bytes` on stdin and returns the completed output. +/// +/// # Why stdin is written from a thread +/// +/// stdin, stdout and stderr are all pipes with a bounded buffer (typically 64 KiB). Writing all of +/// stdin from *this* thread before reading any output deadlocks as soon as the payload is large +/// enough: the child fills its stdout buffer and blocks, so it stops draining stdin, so our write +/// blocks too, and neither side can move. That is a hang rather than a failure, so it would surface +/// as a CI timeout. Writing on a separate thread leaves this one free to drain stdout and stderr +/// via `wait_with_output`, which breaks the cycle. `a_payload_larger_than_the_pipe_buffer_round_trips` +/// pins it. +/// +/// Dropping the pipe when the write finishes is what signals EOF to the child, so the writer thread +/// owns the handle (`take`, not `as_mut`) and must run to completion. +/// +/// # Why `BrokenPipe` is ignored +/// +/// The error-path tests hand a rejected key or a misaligned length to a command that `exit`s before +/// it reads stdin, so the write races the child's exit and loses. That is an expected outcome, not a +/// harness failure: those tests assert the exit status and stderr, both of which `wait_with_output` +/// still returns. Any *other* write error is a real problem and still panics. +/// `a_large_payload_on_an_error_path_does_not_break_the_harness` pins it. +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"); + + let mut stdin = child.stdin.take().expect("stdin piped"); + let payload = stdin_bytes.to_vec(); + let writer = thread::spawn(move || { + match stdin.write_all(&payload) { + Ok(()) => {} + Err(e) if e.kind() == ErrorKind::BrokenPipe => {} + Err(e) => panic!("failed to write to stdin: {e}"), + } + // `stdin` drops here, closing the pipe so the child sees EOF and can exit. + }); + + // Drain stdout and stderr first: the writer may still be blocked on a full stdin buffer, and it + // cannot finish until the child consumes more, which it cannot do while its output is backed up. + let output = child.wait_with_output().expect("failed to wait for bc-rust"); + writer.join().expect("the stdin writer thread panicked"); + output +} + +/// 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 or on `/dev/urandom`. +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 harness itself ------------------------------------------------------------------ +// +// These two pin `run`'s pipe handling, as in the CBC and CFB suites; each file has its own `run`. + +/// Far beyond any pipe buffer, so a write cannot complete before the child has drained it. +const OVERSIZED: usize = 4 * 1024 * 1024; + +#[test] +fn a_large_payload_on_an_error_path_does_not_break_the_harness() { + let stderr = run_err(&["aes128-ecb", "encrypt"], &vec![0u8; OVERSIZED]); + assert!(stderr.contains("--key"), "the CLI's own error must still be reported: {stderr}"); +} + +#[test] +fn a_payload_larger_than_the_pipe_buffer_round_trips() { + let plaintext = pseudo_random(OVERSIZED, 0xC0FFEE); + let ciphertext = run_ok(&["aes128-ecb", "encrypt", "--key", KEY_128], &plaintext); + assert_eq!( + ciphertext.len(), + plaintext.len(), + "no IV: the ciphertext is as long as the plaintext" + ); + let recovered = run_ok(&["aes128-ecb", "decrypt", "--key", KEY_128], &ciphertext); + assert_eq!(recovered, plaintext, "{OVERSIZED} bytes should round trip"); +} + +// ---- the SP 800-38A F.1 vectors, through the CLI ----------------------------------------- + +/// With no IV, `encrypt` is reproducible, so both directions can be pinned to the published +/// vectors: F.1.1/F.1.3/F.1.5 encrypt and F.1.2/F.1.4/F.1.6 decrypt. +#[test] +fn both_directions_match_sp800_38a_f1_vectors() { + for (cmd, key, ct) in [ + ("aes128-ecb", KEY_128, CT_128), + ("aes192-ecb", KEY_192, CT_192), + ("aes256-ecb", KEY_256, CT_256), + ] { + let enc = run_ok(&[cmd, "encrypt", "--key", key], &unhex(PLAINTEXT)); + assert_eq!(tohex(&enc), ct, "{cmd} encrypt should reproduce the Appendix F.1 ciphertext"); + let dec = run_ok(&[cmd, "decrypt", "--key", key], &unhex(ct)); + assert_eq!( + tohex(&dec), + PLAINTEXT, + "{cmd} decrypt should reproduce the Appendix F.1 plaintext" + ); + } +} + +/// The same, with `-x`, which should give the identical answer in hex plus a trailing newline. +#[test] +fn hex_output_matches_binary_output() { + let binary = run_ok(&["aes128-ecb", "encrypt", "--key", KEY_128], &unhex(PLAINTEXT)); + let hex_out = run_ok(&["aes128-ecb", "encrypt", "--key", KEY_128, "-x"], &unhex(PLAINTEXT)); + let hex_str = String::from_utf8(hex_out).expect("hex output is text"); + assert_eq!(hex_str.trim_end(), tohex(&binary)); + assert_eq!(hex_str.trim_end(), CT_128); +} + +// ---- round trips and framing ------------------------------------------------------------ + +/// `encrypt | decrypt` recovers the input for all three key lengths, and nothing is prepended. +#[test] +fn encrypt_then_decrypt_round_trips_with_no_iv() { + for (cmd, key) in [("aes128-ecb", KEY_128), ("aes192-ecb", KEY_192), ("aes256-ecb", KEY_256)] { + let plaintext = unhex(PLAINTEXT); + let ciphertext = run_ok(&[cmd, "encrypt", "--key", key], &plaintext); + assert_eq!(ciphertext.len(), plaintext.len(), "{cmd}: no IV is written"); + let recovered = run_ok(&[cmd, "decrypt", "--key", key], &ciphertext); + assert_eq!(recovered, plaintext, "{cmd}: round trip"); + } +} + +/// Round trips at sizes that straddle the 1 KiB streaming chunk, the eight-block batch and the +/// block boundary: 128 is one eight; 144 is an eight plus one block; 1040 is a chunk plus a block. +#[test] +fn round_trips_across_chunk_and_batch_boundaries() { + for size in [16usize, 32, 128, 144, 1024, 1040, 4096, 4112, 65536] { + let plaintext = pseudo_random(size, size as u32); + let ciphertext = run_ok(&["aes128-ecb", "encrypt", "--key", KEY_128], &plaintext); + assert_eq!(ciphertext.len(), size); + let recovered = run_ok(&["aes128-ecb", "decrypt", "--key", KEY_128], &ciphertext); + assert_eq!(recovered, plaintext, "{size} bytes should round trip"); + } +} + +/// Empty input gives empty output in both directions: there is no IV to emit or require. +#[test] +fn empty_input_produces_empty_output() { + assert!(run_ok(&["aes128-ecb", "encrypt", "--key", KEY_128], &[]).is_empty()); + assert!(run_ok(&["aes128-ecb", "decrypt", "--key", KEY_128], &[]).is_empty()); +} + +// ---- the codebook property, visible on the wire ----------------------------------------- + +/// SP 800-38A Sec 6.1: the same plaintext block under the same key always gives the same +/// ciphertext block. Across invocations the output is identical (no IV to vary it), and within a +/// message equal blocks stay equal. This is the reason the help text warns against using ECB for +/// data, and it is pinned so the command cannot quietly become something else. +#[test] +fn ecb_is_deterministic_and_shows_repeated_blocks() { + let block = unhex("00112233445566778899aabbccddeeff"); + let mut plaintext = block.clone(); + plaintext.extend_from_slice(&unhex("ffeeddccbbaa99887766554433221100")); + plaintext.extend_from_slice(&block); + + let first = run_ok(&["aes128-ecb", "encrypt", "--key", KEY_128], &plaintext); + let second = run_ok(&["aes128-ecb", "encrypt", "--key", KEY_128], &plaintext); + assert_eq!(first, second, "the same input gives the same output every time"); + assert_eq!(first[..16], first[32..], "equal plaintext blocks give equal ciphertext blocks"); + assert_ne!(first[..16], first[16..32]); +} + +// ---- key handling ----------------------------------------------------------------------- + +#[test] +fn key_file_accepts_hex_and_binary() { + let dir = std::env::temp_dir().join(format!("bc_rust_ecb_cli_key_{}", std::process::id())); + std::fs::create_dir_all(&dir).expect("create temp dir"); + let hex_path = dir.join("key.hex"); + let bin_path = dir.join("key.bin"); + std::fs::write(&hex_path, KEY_128).expect("write hex key"); + std::fs::write(&bin_path, unhex(KEY_128)).expect("write binary key"); + for path in [&hex_path, &bin_path] { + let out = run_ok( + &["aes128-ecb", "decrypt", "--key-file", path.to_str().unwrap()], + &unhex(CT_128), + ); + assert_eq!(out, unhex(PLAINTEXT), "--key-file {path:?}"); + } + std::fs::remove_dir_all(&dir).ok(); +} + +#[test] +fn a_key_of_the_wrong_length_is_rejected() { + let stderr = run_err(&["aes256-ecb", "encrypt", "--key", KEY_128], &unhex(PLAINTEXT)); + assert!(stderr.contains("32-byte key"), "stderr should name the expected length: {stderr}"); + assert!(stderr.contains("16 bytes"), "stderr should name the supplied length: {stderr}"); +} + +#[test] +fn a_missing_key_is_rejected() { + let stderr = run_err(&["aes128-ecb", "encrypt"], &unhex(PLAINTEXT)); + assert!(stderr.contains("--key"), "stderr should mention the key options: {stderr}"); +} + +#[test] +fn an_all_zero_key_warns_but_proceeds() { + let zero_key = "0".repeat(32); + let out = run(&["aes128-ecb", "encrypt", "--key", &zero_key], &unhex(PLAINTEXT)); + assert!(out.status.success(), "an all-zero key should still work"); + let stderr = String::from_utf8_lossy(&out.stderr); + assert!(stderr.to_lowercase().contains("warning"), "an all-zero key should warn: {stderr}"); + assert_eq!(out.stdout.len(), 64, "four ciphertext blocks and no IV"); +} + +// ---- block alignment ------------------------------------------------------------------ + +/// Unaligned input is rejected in both directions, with the mode named and padding pointed at. +#[test] +fn unaligned_input_is_rejected_with_an_explanation() { + for extra in [1usize, 7, 15] { + for action in ["encrypt", "decrypt"] { + let data = pseudo_random(32 + extra, extra as u32); + let stderr = run_err(&["aes128-ecb", action, "--key", KEY_128], &data); + assert!(stderr.contains("whole number of 16-byte blocks"), "{action}: {stderr}"); + assert!(stderr.contains("padding"), "{action}: {stderr}"); + assert!(stderr.contains("ECB"), "{action}: stderr should name the mode: {stderr}"); + } + } +} + +// ---- SP 800-38A Appendix D, through the CLI ---------------------------------------------- + +/// Table D.2 for ECB: a bit error in `Cj` gives "RBE in the decryption of Cj" -- random bit errors +/// in that block -- and Appendix D adds that ECB bit errors "do not affect the decryption of any +/// other blocks". So the corrupted block is randomised and every other block is intact. This is +/// also an end-to-end check that the CLI is running ECB and not CBC (where the next block would +/// show the flipped bit) or CFB (where the same block would). +#[test] +fn a_ciphertext_bit_flip_randomises_only_its_own_block() { + let plaintext = unhex(PLAINTEXT); + let mut input = unhex(CT_128); + input[16 + 3] ^= 0b0010_0000; // byte 3 of C2 + + let out = run_ok(&["aes128-ecb", "decrypt", "--key", KEY_128], &input); + assert_eq!(out.len(), 64); + assert_eq!(&out[0..16], &plaintext[0..16], "P1 is unaffected"); + let differing: u32 = + out[16..32].iter().zip(&plaintext[16..32]).map(|(a, b)| (a ^ b).count_ones()).sum(); + assert!(differing > 1, "P2 should be randomised, not flipped in place ({differing} bit(s))"); + assert_eq!(&out[32..48], &plaintext[32..48], "P3 is unaffected: nothing chains"); + assert_eq!(&out[48..64], &plaintext[48..64], "P4 is unaffected"); +} + +// ---- cross-variant and cross-mode behaviour --------------------------------------------- + +#[test] +fn the_three_variants_are_not_interchangeable() { + let plaintext = unhex(PLAINTEXT); + let ciphertext = run_ok(&["aes128-ecb", "encrypt", "--key", KEY_128], &plaintext); + let wrong_key = "ff".repeat(16); + let out = run_ok(&["aes128-ecb", "decrypt", "--key", &wrong_key], &ciphertext); + assert_ne!(out, plaintext, "a wrong key must not recover the plaintext"); + assert_eq!(out.len(), plaintext.len(), "but the length is unchanged: ECB is unauthenticated"); +} + +/// ECB and CBC ciphertexts are not interchangeable. The CBC command frames an IV and the ECB +/// command does not, so feeding one to the other is the kind of mistake nothing but this catches: +/// the CBC ciphertext body run through ECB is not the plaintext, and the ECB ciphertext run through +/// CBC (its first block consumed as an IV) is neither the plaintext nor the right length. +#[test] +fn ecb_and_cbc_are_not_interchangeable() { + let plaintext = unhex(PLAINTEXT); + let ecb_ct = unhex(CT_128); + let cbc_input = unhex(&format!("{CBC_IV}{CBC_CT_128}")); + + assert_eq!(run_ok(&["aes128-ecb", "decrypt", "--key", KEY_128], &ecb_ct), plaintext); + assert_eq!(run_ok(&["aes128-cbc", "decrypt", "--key", KEY_128], &cbc_input), plaintext); + + let ecb_reads_cbc = run_ok(&["aes128-ecb", "decrypt", "--key", KEY_128], &unhex(CBC_CT_128)); + assert_ne!(ecb_reads_cbc, plaintext, "ECB must not decrypt a CBC ciphertext"); + + let cbc_reads_ecb = run_ok(&["aes128-cbc", "decrypt", "--key", KEY_128], &ecb_ct); + assert_eq!(cbc_reads_ecb.len(), 48, "CBC consumes the first block as an IV"); + assert_ne!(cbc_reads_ecb, plaintext[16..].to_vec(), "CBC must not decrypt an ECB ciphertext"); +} + +// ---- discoverability -------------------------------------------------------------------- + +#[test] +fn the_subcommands_are_listed_in_help() { + let out = run_ok(&["--help"], &[]); + let help = String::from_utf8_lossy(&out); + for cmd in ["aes128-ecb", "aes192-ecb", "aes256-ecb"] { + assert!(help.contains(cmd), "`--help` should list {cmd}"); + } +} + +/// Each subcommand's own help names the two actions, says there is no IV, and carries the warning +/// that ECB is not for data. +#[test] +fn per_command_help_warns_and_documents_the_missing_iv() { + let out = run_ok(&["aes128-ecb", "--help"], &[]); + let help = String::from_utf8_lossy(&out); + assert!(help.contains("encrypt"), "help should list the encrypt action"); + assert!(help.contains("decrypt"), "help should list the decrypt action"); + assert!(help.contains("NO IV"), "help should say there is no IV: {help}"); + assert!(help.contains("WARNING"), "help should warn against using ECB for data: {help}"); + assert!(help.contains("ECB"), "help should name the mode: {help}"); +} diff --git a/crypto/aes-lowmemory/Cargo.toml b/crypto/aes-lowmemory/Cargo.toml new file mode 100644 index 00000000..f6cbff4d --- /dev/null +++ b/crypto/aes-lowmemory/Cargo.toml @@ -0,0 +1,21 @@ +[package] +name = "bouncycastle-aes-lowmemory" +version.workspace = true +edition.workspace = true + +[dependencies] +bouncycastle-core.workspace = true +bouncycastle-utils.workspace = true +# Only for the AES-CBC type aliases in `cbc.rs`; the engine itself does not use it. +bouncycastle-modes.workspace = true + +[dev-dependencies] +bouncycastle-core-test-framework.workspace = true +bouncycastle-hex.workspace = true +bouncycastle-rng.workspace = true +criterion.workspace = true +serde_json = "1.0" + +[[bench]] +name = "aes_benches" +harness = false diff --git a/crypto/aes-lowmemory/benches/aes_benches.rs b/crypto/aes-lowmemory/benches/aes_benches.rs new file mode 100644 index 00000000..82d81003 --- /dev/null +++ b/crypto/aes-lowmemory/benches/aes_benches.rs @@ -0,0 +1,183 @@ +//! Criterion benchmarks for the bit-sliced AES engine. +//! +//! The comparison that matters here is `encrypt_block` against `encrypt_blocks2` over the same +//! number of bytes. The bit-sliced state holds two blocks, so a single-block call does twice the +//! necessary work; the two-block path should be close to twice the throughput. That ratio is the +//! argument for modes of operation using the two-block entry points wherever their blocks are +//! independent (CTR, and the decrypt direction of CBC and CFB). + +use bouncycastle_aes_lowmemory::{Aes128, Aes192, Aes256, BLOCK_LEN}; +use bouncycastle_core::key_material::{KeyMaterial, KeyType}; +use bouncycastle_core::traits::RNG; +use bouncycastle_rng as rng; +use criterion::{Criterion, Throughput, criterion_group, criterion_main}; +use std::hint::black_box; + +/// 16 KiB of data, i.e. 1024 AES blocks. +const NUM_BLOCKS: usize = 1024; +const DATA_LEN: usize = NUM_BLOCKS * BLOCK_LEN; + +fn random_blocks() -> Vec<[u8; BLOCK_LEN]> { + let mut blocks = vec![[0u8; BLOCK_LEN]; NUM_BLOCKS]; + let mut generator = rng::DefaultRNG::default(); + for block in blocks.iter_mut() { + generator.next_bytes_out(block).unwrap(); + } + blocks +} + +fn key() -> KeyMaterial { + let mut bytes = [0u8; N]; + rng::DefaultRNG::default().next_bytes_out(&mut bytes).unwrap(); + KeyMaterial::::from_bytes_as_type(&bytes, KeyType::SymmetricCipherKey).unwrap() +} + +fn bench_key_expansion(c: &mut Criterion) { + let mut group = c.benchmark_group("aes_lowmemory::key expansion"); + + let key128 = key::<16>(); + group.bench_function("Aes128::new()", |b| { + b.iter(|| black_box(Aes128::new(black_box(&key128)).unwrap())) + }); + + let key192 = key::<24>(); + group.bench_function("Aes192::new()", |b| { + b.iter(|| black_box(Aes192::new(black_box(&key192)).unwrap())) + }); + + let key256 = key::<32>(); + group.bench_function("Aes256::new()", |b| { + b.iter(|| black_box(Aes256::new(black_box(&key256)).unwrap())) + }); + + group.finish(); +} + +fn bench_aes128(c: &mut Criterion) { + let aes = Aes128::new(&key::<16>()).unwrap(); + let blocks = random_blocks(); + + let mut group = c.benchmark_group("aes_lowmemory::Aes128"); + group.throughput(Throughput::Bytes(DATA_LEN as u64)); + + group.bench_function("16KiB -- .encrypt_block() x1024", |b| { + b.iter(|| { + let mut buf = blocks.clone(); + for block in buf.iter_mut() { + aes.encrypt_block(black_box(block)); + } + black_box(&buf); + }) + }); + + group.bench_function("16KiB -- .encrypt_blocks2() x512", |b| { + b.iter(|| { + let mut buf = blocks.clone(); + for pair in buf.chunks_exact_mut(2) { + // `try_into` cannot fail: `chunks_exact_mut(2)` yields slices of length 2. + let pair: &mut [[u8; BLOCK_LEN]; 2] = pair.try_into().unwrap(); + aes.encrypt_blocks2(black_box(pair)); + } + black_box(&buf); + }) + }); + + group.bench_function("16KiB -- .decrypt_block() x1024", |b| { + b.iter(|| { + let mut buf = blocks.clone(); + for block in buf.iter_mut() { + aes.decrypt_block(black_box(block)); + } + black_box(&buf); + }) + }); + + group.bench_function("16KiB -- .decrypt_blocks2() x512", |b| { + b.iter(|| { + let mut buf = blocks.clone(); + for pair in buf.chunks_exact_mut(2) { + let pair: &mut [[u8; BLOCK_LEN]; 2] = pair.try_into().unwrap(); + aes.decrypt_blocks2(black_box(pair)); + } + black_box(&buf); + }) + }); + + group.finish(); +} + +fn bench_aes192(c: &mut Criterion) { + let aes = Aes192::new(&key::<24>()).unwrap(); + let blocks = random_blocks(); + + let mut group = c.benchmark_group("aes_lowmemory::Aes192"); + group.throughput(Throughput::Bytes(DATA_LEN as u64)); + + group.bench_function("16KiB -- .encrypt_block() x1024", |b| { + b.iter(|| { + let mut buf = blocks.clone(); + for block in buf.iter_mut() { + aes.encrypt_block(black_box(block)); + } + black_box(&buf); + }) + }); + + group.bench_function("16KiB -- .encrypt_blocks2() x512", |b| { + b.iter(|| { + let mut buf = blocks.clone(); + for pair in buf.chunks_exact_mut(2) { + let pair: &mut [[u8; BLOCK_LEN]; 2] = pair.try_into().unwrap(); + aes.encrypt_blocks2(black_box(pair)); + } + black_box(&buf); + }) + }); + + group.finish(); +} + +fn bench_aes256(c: &mut Criterion) { + let aes = Aes256::new(&key::<32>()).unwrap(); + let blocks = random_blocks(); + + let mut group = c.benchmark_group("aes_lowmemory::Aes256"); + group.throughput(Throughput::Bytes(DATA_LEN as u64)); + + group.bench_function("16KiB -- .encrypt_block() x1024", |b| { + b.iter(|| { + let mut buf = blocks.clone(); + for block in buf.iter_mut() { + aes.encrypt_block(black_box(block)); + } + black_box(&buf); + }) + }); + + group.bench_function("16KiB -- .encrypt_blocks2() x512", |b| { + b.iter(|| { + let mut buf = blocks.clone(); + for pair in buf.chunks_exact_mut(2) { + let pair: &mut [[u8; BLOCK_LEN]; 2] = pair.try_into().unwrap(); + aes.encrypt_blocks2(black_box(pair)); + } + black_box(&buf); + }) + }); + + group.bench_function("16KiB -- .decrypt_blocks2() x512", |b| { + b.iter(|| { + let mut buf = blocks.clone(); + for pair in buf.chunks_exact_mut(2) { + let pair: &mut [[u8; BLOCK_LEN]; 2] = pair.try_into().unwrap(); + aes.decrypt_blocks2(black_box(pair)); + } + black_box(&buf); + }) + }); + + group.finish(); +} + +criterion_group!(benches, bench_key_expansion, bench_aes128, bench_aes192, bench_aes256); +criterion_main!(benches); diff --git a/crypto/aes-lowmemory/src/aes.rs b/crypto/aes-lowmemory/src/aes.rs new file mode 100644 index 00000000..08198459 --- /dev/null +++ b/crypto/aes-lowmemory/src/aes.rs @@ -0,0 +1,337 @@ +//! CIPHER() and INVCIPHER() (FIPS 197 Sec 5.1 and Sec 5.3), and the public engine types. + +use crate::bitslice::{Block, Planes, pack, unpack}; +use crate::round::{add_round_key, inv_mix_columns, inv_shift_rows, mix_columns, shift_rows}; +use crate::sbox::{inv_sbox, sbox}; +use crate::schedule::{Aes128Params, Aes192Params, Aes256Params, AesParams, expand, round_key}; +use bouncycastle_core::errors::{KeyMaterialError, SymmetricCipherError}; +use bouncycastle_core::key_material::{KeyMaterial, KeyMaterialTrait, KeyType}; +use bouncycastle_core::traits::{Algorithm, ElectronicCodeBook, SecurityStrength}; +use bouncycastle_utils::secret::Secret; + +/// The AES block length in bytes: 16 (FIPS 197 Sec 3.4, `Nb` = 4 words). +pub const BLOCK_LEN: usize = 16; + +/// The AES keyed permutation, parameterised by key length. +/// +/// Use the aliases [`Aes128`], [`Aes192`] and [`Aes256`] rather than naming this directly. +/// `P` is sealed to the three parameter sets of FIPS 197 Sec 6.1, so no fourth instantiation +/// exists. +/// +/// The only state is the key schedule, held in a [`Secret`] so that it is zeroized on drop and +/// redacted from `Debug`. There is no direction flag and no initialisation state: both directions +/// work from the same schedule (see [`Aes::decrypt_blocks2`]), and a constructed value is always +/// ready to use, so there is no `init()` or `reset()`. +pub struct Aes { + schedule: Secret, +} + +/// AES-128: 16-byte key, 10 rounds (FIPS 197 Sec 6.1). +pub type Aes128 = Aes; +/// AES-192: 24-byte key, 12 rounds (FIPS 197 Sec 6.1). +pub type Aes192 = Aes; +/// AES-256: 32-byte key, 14 rounds (FIPS 197 Sec 6.1). +pub type Aes256 = Aes; + +impl Aes

{ + /// Checks a key is fit to use before it is expanded. + /// + /// The key must be tagged [`KeyType::SymmetricCipherKey`], must be exactly `P::KEY_LEN` bytes + /// of the buffer, and must carry a [`SecurityStrength`] at least equal to its own length -- + /// which is what a key of this length from a correctly-instantiated RNG or KDF will have. + /// The checks exist to catch a key that arrived from somewhere it should not have: a seed + /// reused as a cipher key, or a 32-byte buffer holding material only derived at the 128-bit + /// strength. + /// + /// Takes `&dyn KeyMaterialTrait` so the three constructors, whose `KeyMaterial` capacities + /// differ, can share one implementation. + fn validate(key: &dyn KeyMaterialTrait) -> Result<(), SymmetricCipherError> { + if key.key_type() != KeyType::SymmetricCipherKey { + return Err(KeyMaterialError::InvalidKeyType( + "AES requires a key of type KeyType::SymmetricCipherKey.", + ) + .into()); + } + if key.key_len() != P::KEY_LEN { + return Err(KeyMaterialError::InvalidLength.into()); + } + if key.security_strength() < SecurityStrength::from_bytes(P::KEY_LEN) { + return Err(KeyMaterialError::SecurityStrength( + "The provided key has a lower security strength than the AES key length implies.", + ) + .into()); + } + Ok(()) + } + + /// CIPHER() on two blocks at once (FIPS 197 Sec 5.1, Algorithm 1). + /// + /// Algorithm 1 line by line: line 3 is the initial ADDROUNDKEY() with `w[0..3]`; lines 4-9 are + /// the `Nr - 1` full rounds; lines 10-13 are the final round, which omits MIXCOLUMNS(). + fn encrypt2(&self, q: &mut Planes) { + // line 3: state = state XOR w[0..3] + add_round_key(q, &round_key::

(&self.schedule, 0)); + + // lines 4-9: for round from 1 to Nr - 1 + for round in 1..P::NR { + sbox(q); // line 5, SUBBYTES() + shift_rows(q); // line 6, SHIFTROWS() + mix_columns(q); // line 7, MIXCOLUMNS() + add_round_key(q, &round_key::

(&self.schedule, round)); // line 8 + } + + // lines 10-12: the final round has no MIXCOLUMNS() + sbox(q); + shift_rows(q); + add_round_key(q, &round_key::

(&self.schedule, P::NR)); + } + + /// INVCIPHER() on two blocks at once (FIPS 197 Sec 5.3, Algorithm 3). + /// + /// This is the **straight** inverse cipher of Algorithm 3, not the equivalent inverse cipher + /// of Sec 5.3.5. That matters: Algorithm 3 applies INVMIXCOLUMNS() *after* ADDROUNDKEY(), + /// which lets it use the ordinary key schedule, whereas Sec 5.3.5 reorders the round to put + /// the two the other way round and needs a separate schedule with INVMIXCOLUMNS() applied to + /// each round key (Algorithm 5, KEYEXPANSIONEIC()). + /// + /// Following Algorithm 3 is therefore what allows one [`Aes`] value to encrypt *and* decrypt + /// from a single stored schedule, with no second copy and no transformation at construction + /// time -- which is the whole reason this crate can offer both directions at 176-240 bytes of + /// state. + /// + /// Line by line: line 3 is ADDROUNDKEY() with the last round key; lines 4-9 are the + /// `Nr - 1` full inverse rounds; lines 10-13 are the final one, which omits INVMIXCOLUMNS(). + fn decrypt2(&self, q: &mut Planes) { + // line 3: state = state XOR w[4*Nr .. 4*Nr+3] + add_round_key(q, &round_key::

(&self.schedule, P::NR)); + + // lines 4-9: for round from Nr - 1 down to 1 + for round in (1..P::NR).rev() { + inv_shift_rows(q); // line 5, INVSHIFTROWS() + inv_sbox(q); // line 6, INVSUBBYTES() + add_round_key(q, &round_key::

(&self.schedule, round)); // line 7 + inv_mix_columns(q); // line 8, INVMIXCOLUMNS() + } + + // lines 10-12: the final inverse round has no INVMIXCOLUMNS() + inv_shift_rows(q); + inv_sbox(q); + add_round_key(q, &round_key::

(&self.schedule, 0)); + } + + /// Encrypts two blocks in place. + /// + /// This is the natural unit of work: the bit-sliced state holds two blocks, so two blocks cost + /// almost exactly what one does. Prefer this over two [`Aes::encrypt_block`] calls whenever + /// two blocks are available and independent -- which, for a mode of operation, means CTR, or + /// the decryption direction of CBC and CFB, but *not* CBC encryption, whose blocks are + /// serially dependent. + /// + /// Infallible: a constructed [`Aes`] is always usable and every input length is fixed. + pub fn encrypt_blocks2(&self, blocks: &mut [Block; 2]) { + let mut q = pack(&blocks[0], &blocks[1]); + self.encrypt2(&mut q); + let (a, b) = blocks.split_at_mut(1); + unpack(&q, &mut a[0], &mut b[0]); + } + + /// Decrypts two blocks in place. See [`Aes::encrypt_blocks2`]. + pub fn decrypt_blocks2(&self, blocks: &mut [Block; 2]) { + let mut q = pack(&blocks[0], &blocks[1]); + self.decrypt2(&mut q); + let (a, b) = blocks.split_at_mut(1); + unpack(&q, &mut a[0], &mut b[0]); + } + + /// Encrypts one block in place. + /// + /// The bit-sliced state always holds two blocks, so a single-block call duplicates the block + /// into both halves and discards one result: it does twice the necessary work. Use + /// [`Aes::encrypt_blocks2`] where two blocks are available. + /// + /// Duplicating the block costs exactly what filling the unused half with zeros would, and it + /// buys a free self-check: the two halves must come out equal, which `debug_assert` verifies. + /// That is the whole reason for the choice -- it is not a security property, since the unused + /// half is never returned either way. + pub fn encrypt_block(&self, block: &mut Block) { + let mut q = pack(block, block); + self.encrypt2(&mut q); + let mut discard = [0u8; BLOCK_LEN]; + unpack(&q, block, &mut discard); + debug_assert_eq!(*block, discard, "the two interleaved halves must agree"); + } + + /// Decrypts one block in place. See [`Aes::encrypt_block`] for the two-blocks-at-once caveat. + pub fn decrypt_block(&self, block: &mut Block) { + let mut q = pack(block, block); + self.decrypt2(&mut q); + let mut discard = [0u8; BLOCK_LEN]; + unpack(&q, block, &mut discard); + debug_assert_eq!(*block, discard, "the two interleaved halves must agree"); + } +} + +// The three constructors and `Algorithm` impls below are written out longhand rather than +// generated with `macro_rules!`: `cargo mutants` cannot see into macro bodies, so a macro would +// hide the key checks and the security-strength constants from mutation testing (see CLAUDE.md). +// Each `new` differs only in the `KeyMaterial` capacity it accepts, which is what makes a +// wrong-length key a compile error at the call site rather than a runtime error. + +impl Aes128 { + /// Expands a 16-byte key into an AES-128 schedule. + /// + /// # Errors + /// * [`KeyMaterialError::InvalidKeyType`] if the key is not [`KeyType::SymmetricCipherKey`]. + /// * [`KeyMaterialError::InvalidLength`] if the key is not 16 bytes long. + /// * [`KeyMaterialError::SecurityStrength`] if the key carries a strength below 128 bits. + pub fn new(key: &KeyMaterial<16>) -> Result { + Self::validate(key)?; + Ok(Self { schedule: expand::(key.ref_to_bytes()) }) + } +} + +impl Aes192 { + /// Expands a 24-byte key into an AES-192 schedule. See [`Aes128::new`] for the error cases. + pub fn new(key: &KeyMaterial<24>) -> Result { + Self::validate(key)?; + Ok(Self { schedule: expand::(key.ref_to_bytes()) }) + } +} + +impl Aes256 { + /// Expands a 32-byte key into an AES-256 schedule. See [`Aes128::new`] for the error cases. + pub fn new(key: &KeyMaterial<32>) -> Result { + Self::validate(key)?; + Ok(Self { schedule: expand::(key.ref_to_bytes()) }) + } +} + +impl Algorithm for Aes128 { + const ALG_NAME: &'static str = Aes128Params::ALG_NAME; + const MAX_SECURITY_STRENGTH: SecurityStrength = SecurityStrength::_128bit; +} + +impl Algorithm for Aes192 { + const ALG_NAME: &'static str = Aes192Params::ALG_NAME; + const MAX_SECURITY_STRENGTH: SecurityStrength = SecurityStrength::_192bit; +} + +impl Algorithm for Aes256 { + const ALG_NAME: &'static str = Aes256Params::ALG_NAME; + const MAX_SECURITY_STRENGTH: SecurityStrength = SecurityStrength::_256bit; +} + +// The three `ElectronicCodeBook` impls are one-line delegations to the inherent methods above. They +// are written out longhand rather than generated, for the `cargo mutants` reason given above. +// +// Each overrides `encrypt_blocks2` / `decrypt_blocks2`, because a pair of blocks is exactly what +// the bit-sliced state holds: the pair form costs barely more than one block, where the default +// (two single-block calls) would do four blocks' worth of work. + +impl ElectronicCodeBook<16, BLOCK_LEN> for Aes128 { + fn new(key: &KeyMaterial<16>) -> Result { + Aes128::new(key) + } + fn encrypt_block(&self, block: &mut Block) { + Aes::encrypt_block(self, block) + } + fn decrypt_block(&self, block: &mut Block) { + Aes::decrypt_block(self, block) + } + fn encrypt_blocks2(&self, blocks: &mut [Block; 2]) { + Aes::encrypt_blocks2(self, blocks) + } + fn decrypt_blocks2(&self, blocks: &mut [Block; 2]) { + Aes::decrypt_blocks2(self, blocks) + } +} + +impl ElectronicCodeBook<24, BLOCK_LEN> for Aes192 { + fn new(key: &KeyMaterial<24>) -> Result { + Aes192::new(key) + } + fn encrypt_block(&self, block: &mut Block) { + Aes::encrypt_block(self, block) + } + fn decrypt_block(&self, block: &mut Block) { + Aes::decrypt_block(self, block) + } + fn encrypt_blocks2(&self, blocks: &mut [Block; 2]) { + Aes::encrypt_blocks2(self, blocks) + } + fn decrypt_blocks2(&self, blocks: &mut [Block; 2]) { + Aes::decrypt_blocks2(self, blocks) + } +} + +impl ElectronicCodeBook<32, BLOCK_LEN> for Aes256 { + fn new(key: &KeyMaterial<32>) -> Result { + Aes256::new(key) + } + fn encrypt_block(&self, block: &mut Block) { + Aes::encrypt_block(self, block) + } + fn decrypt_block(&self, block: &mut Block) { + Aes::decrypt_block(self, block) + } + fn encrypt_blocks2(&self, blocks: &mut [Block; 2]) { + Aes::encrypt_blocks2(self, blocks) + } + fn decrypt_blocks2(&self, blocks: &mut [Block; 2]) { + Aes::decrypt_blocks2(self, blocks) + } +} + +impl core::fmt::Debug for Aes

{ + /// Prints the algorithm name only. The key schedule is secret and is never formatted. + fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result { + f.write_str(P::ALG_NAME) + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_engine_sizes_match_the_documented_memory_table() { + // The "Memory Usage" table in the crate docs quotes these, and the whole point of the + // crate is that they are this small: 4 * (Nr + 1) words of schedule, nothing else, and no + // tables anywhere. If the representation grows, the docs are wrong -- fix both. + assert_eq!(size_of::(), 176, "AES-128: 4 * (10 + 1) words"); + assert_eq!(size_of::(), 208, "AES-192: 4 * (12 + 1) words"); + assert_eq!(size_of::(), 240, "AES-256: 4 * (14 + 1) words"); + } + + #[test] + fn test_engine_size_is_exactly_the_schedule() { + // No round counter, no direction flag, no initialised marker: the schedule is all there + // is, which is what makes both directions available from one value at no extra cost. + assert_eq!(size_of::(), size_of::<::Schedule>()); + assert_eq!(size_of::(), size_of::<::Schedule>()); + assert_eq!(size_of::(), size_of::<::Schedule>()); + } + + #[test] + fn test_alg_names() { + assert_eq!(::ALG_NAME, "AES-128"); + assert_eq!(::ALG_NAME, "AES-192"); + assert_eq!(::ALG_NAME, "AES-256"); + } + + #[test] + fn test_max_security_strength_matches_the_key_length() { + assert_eq!( + ::MAX_SECURITY_STRENGTH, + SecurityStrength::from_bytes(Aes128Params::KEY_LEN) + ); + assert_eq!( + ::MAX_SECURITY_STRENGTH, + SecurityStrength::from_bytes(Aes192Params::KEY_LEN) + ); + assert_eq!( + ::MAX_SECURITY_STRENGTH, + SecurityStrength::from_bytes(Aes256Params::KEY_LEN) + ); + } +} diff --git a/crypto/aes-lowmemory/src/bitslice.rs b/crypto/aes-lowmemory/src/bitslice.rs new file mode 100644 index 00000000..08ef77ff --- /dev/null +++ b/crypto/aes-lowmemory/src/bitslice.rs @@ -0,0 +1,210 @@ +//! Conversion between AES blocks and the bit-sliced representation the round functions act on. +//! +//! # What "bit-sliced" means here +//! +//! The round functions in [`crate::round`] and the S-box in [`crate::sbox`] do not operate on +//! bytes. They operate on eight `u32` *bit-planes*, `q[0]..q[7]`, where plane `q[k]` collects +//! bit `k` of every byte of the state. That is what lets the S-box be a Boolean circuit: one +//! `&` or `^` on a plane applies that gate to all sixteen byte positions at once, and no memory +//! access is ever indexed by a secret value. +//! +//! Eight 32-bit planes hold 256 bits = 32 bytes, which is *two* 16-byte AES blocks. Both blocks +//! are always processed together; see the crate docs for why, and [`crate::aes`] for how a +//! single-block call fills the unused half. +//! +//! # The layout, derived +//! +//! [`ortho`] transposes, within each byte-lane of the eight words, the 8x8 bit matrix indexed by +//! (word number, bit number within the lane): +//! +//! ```text +//! after ortho: q[k] bit (8L + i) == before ortho: q[i] bit (8L + k) +//! ``` +//! +//! [`pack`] loads block A as four little-endian `u32`s into the even words and block B into the +//! odd words, so before `ortho` byte-lane `L` of word `2c` holds `A[4c + L]`. Substituting +//! `j = 4c + L` for the byte index, and FIPS 197 Eq (3.6) `s[r,c] = in[r + 4c]` -- which makes +//! `r = j mod 4` and `c = j div 4` -- gives the layout every mask in this crate depends on: +//! +//! ```text +//! q[k] bit (8r + 2c) == bit k of s[r,c] of block A +//! q[k] bit (8r + 2c + 1) == bit k of s[r,c] of block B +//! ``` +//! +//! In words: **the byte-lane of the word selects the state row `r`, and the bit-pair within that +//! lane selects the state column `c`; the low bit of the pair is block A and the high bit is +//! block B.** Written out, the bit position of `s[r,c]` within every plane is: +//! +//! ```text +//! c=0 c=1 c=2 c=3 +//! r=0 | 0 2 4 6 +//! r=1 | 8 10 12 14 (bit position of block A; +//! r=2 | 16 18 20 22 add 1 for block B) +//! r=3 | 24 26 28 30 +//! ``` +//! +//! This is why SHIFTROWS() becomes a rotation *within* a byte-lane (row `r` lives entirely in +//! lane `r`, and one column step is two bit positions), and why MIXCOLUMNS() uses rotations by +//! 8 and 16 (one and two rows). Both are derived from this table in [`crate::round`]. +//! +//! `test_layout_matches_the_documented_table` below pins the table exhaustively; every mask in +//! this crate is only correct relative to it. +//! +//! # Provenance +//! +//! The three-stage masked-swap transpose and the even/odd two-block packing are translated from +//! BearSSL `src/symcipher/aes_ct.c` (`br_aes_ct_ortho`) and `aes_ct_cbcdec.c` (the `q[0]`, +//! `q[2]`, `q[4]`, `q[6]` load order), by Thomas Pornin, MIT licensed. + +/// One 16-byte AES block, in the order of FIPS 197 Eq (3.6): `block[r + 4c] == s[r,c]`. +pub type Block = [u8; crate::BLOCK_LEN]; + +/// The eight bit-planes holding two blocks. See the module docs for the layout. +pub(crate) type Planes = [u32; 8]; + +/// Transposes bytes into bit-planes, and back -- it is its own inverse. +/// +/// Three stages of masked swaps exchange bit-fields of width 1, 2 and 4 between pairs of words, +/// which together transpose the 8x8 bit matrix inside each byte-lane. See the module docs for +/// the resulting layout. +/// +/// Translated from BearSSL `aes_ct.c:br_aes_ct_ortho` (the `SWAP2`/`SWAP4`/`SWAP8` macros). +pub(crate) fn ortho(q: &mut Planes) { + /// One masked swap: exchanges the `cl`-selected fields of `y` into `x` and the `ch`-selected + /// fields of `x` into `y`, moving them by `s` bit positions. + /// + /// `cl` and `ch` are complementary, and `s` is exactly the field width, so in each returned + /// word the two combined operands occupy disjoint bits: `(x & cl)` and `(y & cl) << s` cannot + /// both be set in the same position. `|` and `^` therefore compute the same function here, + /// which is why `cargo mutants` reports the `| -> ^` mutants in this function as surviving -- + /// they are equivalent programs. `test_ortho_is_an_involution` and + /// `test_layout_matches_the_documented_table` are what actually pin this code. + #[inline(always)] + fn swap(cl: u32, ch: u32, s: u32, x: u32, y: u32) -> (u32, u32) { + ((x & cl) | ((y & cl) << s), ((x & ch) >> s) | (y & ch)) + } + + // Stage 1: swap single bits between adjacent words (0x55 = even bits, 0xAA = odd bits). + for (a, b) in [(0, 1), (2, 3), (4, 5), (6, 7)] { + (q[a], q[b]) = swap(0x5555_5555, 0xAAAA_AAAA, 1, q[a], q[b]); + } + // Stage 2: swap 2-bit fields between words two apart. + for (a, b) in [(0, 2), (1, 3), (4, 6), (5, 7)] { + (q[a], q[b]) = swap(0x3333_3333, 0xCCCC_CCCC, 2, q[a], q[b]); + } + // Stage 3: swap nibbles between words four apart. + for (a, b) in [(0, 4), (1, 5), (2, 6), (3, 7)] { + (q[a], q[b]) = swap(0x0F0F_0F0F, 0xF0F0_F0F0, 4, q[a], q[b]); + } +} + +/// Loads two blocks into the bit-planes. +/// +/// Block `a` goes into the even words and block `b` into the odd words as little-endian `u32`s, +/// then [`ortho`] transposes them into planes. +pub(crate) fn pack(a: &Block, b: &Block) -> Planes { + let mut q = [0u32; 8]; + for c in 0..4 { + // `try_into` cannot fail: the slice is a fixed 4-byte window of a 16-byte array. + q[2 * c] = u32::from_le_bytes(a[4 * c..4 * c + 4].try_into().unwrap()); + q[2 * c + 1] = u32::from_le_bytes(b[4 * c..4 * c + 4].try_into().unwrap()); + } + ortho(&mut q); + q +} + +/// Reads two blocks back out of the bit-planes; the exact inverse of [`pack`]. +pub(crate) fn unpack(q: &Planes, a: &mut Block, b: &mut Block) { + let mut q = *q; + ortho(&mut q); + for c in 0..4 { + a[4 * c..4 * c + 4].copy_from_slice(&q[2 * c].to_le_bytes()); + b[4 * c..4 * c + 4].copy_from_slice(&q[2 * c + 1].to_le_bytes()); + } +} + +#[cfg(test)] +mod tests { + use super::*; + + /// A deterministic byte generator, so the tests do not depend on an RNG crate. + pub(crate) fn pseudo_random_block(seed: u32) -> Block { + let mut state = seed.wrapping_mul(2_654_435_761).wrapping_add(1); + let mut out = [0u8; 16]; + for byte in out.iter_mut() { + // xorshift32; quality is irrelevant, only that it varies every bit position. + state ^= state << 13; + state ^= state >> 17; + state ^= state << 5; + *byte = (state >> 24) as u8; + } + out + } + + #[test] + fn test_layout_matches_the_documented_table() { + // Pins the module doc table: q[k] bit (8r + 2c) is bit k of s[r,c] of block A, and + // bit (8r + 2c + 1) is bit k of s[r,c] of block B. Every mask in `round` depends on it. + let a = pseudo_random_block(1); + let b = pseudo_random_block(2); + let q = pack(&a, &b); + + for j in 0..16 { + let (r, c) = (j % 4, j / 4); + let pos = 8 * r + 2 * c; + for (k, plane) in q.iter().enumerate() { + assert_eq!( + (plane >> pos) & 1, + u32::from((a[j] >> k) & 1), + "block A: plane {k} bit {pos} should be bit {k} of byte {j}" + ); + assert_eq!( + (plane >> (pos + 1)) & 1, + u32::from((b[j] >> k) & 1), + "block B: plane {k} bit {} should be bit {k} of byte {j}", + pos + 1 + ); + } + } + } + + #[test] + fn test_ortho_is_an_involution() { + let mut q = [ + 0x0123_4567, 0x89AB_CDEF, 0xFEDC_BA98, 0x7654_3210, 0xDEAD_BEEF, 0x0000_0001, + 0xFFFF_FFFF, 0xA5A5_5A5A, + ]; + let original = q; + ortho(&mut q); + assert_ne!(q, original, "ortho should actually move bits"); + ortho(&mut q); + assert_eq!(q, original); + } + + #[test] + fn test_unpack_inverts_pack() { + for seed in 0..64 { + let a = pseudo_random_block(seed); + let b = pseudo_random_block(seed + 1000); + let mut out_a = [0u8; 16]; + let mut out_b = [0u8; 16]; + unpack(&pack(&a, &b), &mut out_a, &mut out_b); + assert_eq!(out_a, a); + assert_eq!(out_b, b); + } + } + + #[test] + fn test_the_two_halves_are_independent() { + // Changing block B must not disturb block A anywhere in the round-function pipeline; + // this pins that the interleave really is bit-parallel and not overlapping. + let a = pseudo_random_block(7); + let mut out_a1 = [0u8; 16]; + let mut out_a2 = [0u8; 16]; + let mut scratch = [0u8; 16]; + unpack(&pack(&a, &[0u8; 16]), &mut out_a1, &mut scratch); + unpack(&pack(&a, &pseudo_random_block(9)), &mut out_a2, &mut scratch); + assert_eq!(out_a1, out_a2); + assert_eq!(out_a1, a); + } +} diff --git a/crypto/aes-lowmemory/src/cbc.rs b/crypto/aes-lowmemory/src/cbc.rs new file mode 100644 index 00000000..d68f6e2a --- /dev/null +++ b/crypto/aes-lowmemory/src/cbc.rs @@ -0,0 +1,93 @@ +//! Type aliases for AES in CBC mode (NIST SP 800-38A Sec 6.2). +//! +//! `bouncycastle-modes` is deliberately cipher-agnostic, so `Cbc` takes the permutation, the +//! direction, and the `KEY_LEN` / `BLOCK_LEN` const parameters. These aliases pin the AES values so +//! callers never spell them out. They add nothing to the engine: the permutation still implements +//! none of the data-encryption traits itself (see the crate docs), the mode does. + +use crate::{Aes128, Aes192, Aes256, BLOCK_LEN}; +use bouncycastle_modes::Cbc; + +/// AES-128 in CBC mode. `Dir` is [`bouncycastle_modes::Encrypting`] or +/// [`bouncycastle_modes::Decrypting`]; the wrong direction is a compile error, not a runtime check. +/// +/// The IV is generated by encryption and returned; it is never supplied. Encryption and decryption +/// work in place. +/// +/// ``` +/// use bouncycastle_aes_lowmemory::AES_CBC_128; +/// use bouncycastle_core::key_material::{KeyMaterial, KeyType}; +/// use bouncycastle_core::traits::{BlockCipherDecryptor, BlockCipherEncryptor}; +/// use bouncycastle_modes::{Decrypting, Encrypting}; +/// +/// let key = KeyMaterial::<16>::from_bytes_as_type(&[0x42; 16], KeyType::SymmetricCipherKey) +/// .expect("a 16-byte symmetric cipher key"); +/// // 48 bytes: three whole blocks. The length is checked at compile time. +/// let message = [0u8; 48]; +/// let mut data = message; +/// let iv = AES_CBC_128::::encrypt(&key, &mut data).unwrap(); +/// assert_ne!(data, message); +/// AES_CBC_128::::decrypt(&key, &iv, &mut data).unwrap(); +/// assert_eq!(data, message); +/// +/// // Streaming, a few blocks at a time: +/// let (mut enc, iv) = AES_CBC_128::::do_encrypt_init(&key).unwrap(); +/// let mut first = [0u8; 16]; +/// let mut rest = [1u8; 32]; +/// enc.do_encrypt(&mut first).unwrap(); +/// enc.do_encrypt(&mut rest).unwrap(); +/// let mut dec = AES_CBC_128::::do_decrypt_init(&key, &iv).unwrap(); +/// dec.do_decrypt(&mut first).unwrap(); +/// dec.do_decrypt(&mut rest).unwrap(); +/// assert_eq!(first, [0u8; 16]); +/// assert_eq!(rest, [1u8; 32]); +/// ``` +/// +/// A length that is not a whole number of blocks is a **compile** error, not a runtime one: +/// +/// ```compile_fail +/// use bouncycastle_aes_lowmemory::AES_CBC_128; +/// use bouncycastle_core::key_material::{KeyMaterial, KeyType}; +/// use bouncycastle_core::traits::BlockCipherEncryptor; +/// use bouncycastle_modes::Encrypting; +/// +/// let key = KeyMaterial::<16>::from_bytes_as_type(&[0x42; 16], KeyType::SymmetricCipherKey).unwrap(); +/// // 47 bytes is not a multiple of 16: the inline const assertion in `encrypt` fails to compile. +/// let _ = AES_CBC_128::::encrypt(&key, &mut [0u8; 47]); +/// ``` +#[allow(non_camel_case_types)] +pub type AES_CBC_128

= Cbc; + +/// AES-192 in CBC mode. See [`AES_CBC_128`]. +/// +/// ``` +/// use bouncycastle_aes_lowmemory::AES_CBC_192; +/// use bouncycastle_core::key_material::{KeyMaterial, KeyType}; +/// use bouncycastle_core::traits::{BlockCipherDecryptor, BlockCipherEncryptor}; +/// use bouncycastle_modes::{Decrypting, Encrypting}; +/// +/// let key = KeyMaterial::<24>::from_bytes_as_type(&[0x42; 24], KeyType::SymmetricCipherKey).unwrap(); +/// let mut data = [0u8; 32]; +/// let iv = AES_CBC_192::::encrypt(&key, &mut data).unwrap(); +/// AES_CBC_192::::decrypt(&key, &iv, &mut data).unwrap(); +/// assert_eq!(data, [0u8; 32]); +/// ``` +#[allow(non_camel_case_types)] +pub type AES_CBC_192 = Cbc; + +/// AES-256 in CBC mode. See [`AES_CBC_128`]. +/// +/// ``` +/// use bouncycastle_aes_lowmemory::AES_CBC_256; +/// use bouncycastle_core::key_material::{KeyMaterial, KeyType}; +/// use bouncycastle_core::traits::{BlockCipherDecryptor, BlockCipherEncryptor}; +/// use bouncycastle_modes::{Decrypting, Encrypting}; +/// +/// let key = KeyMaterial::<32>::from_bytes_as_type(&[0x42; 32], KeyType::SymmetricCipherKey).unwrap(); +/// let mut data = [0u8; 32]; +/// let iv = AES_CBC_256::::encrypt(&key, &mut data).unwrap(); +/// AES_CBC_256::::decrypt(&key, &iv, &mut data).unwrap(); +/// assert_eq!(data, [0u8; 32]); +/// ``` +#[allow(non_camel_case_types)] +pub type AES_CBC_256 = Cbc; diff --git a/crypto/aes-lowmemory/src/cfb.rs b/crypto/aes-lowmemory/src/cfb.rs new file mode 100644 index 00000000..ac55210a --- /dev/null +++ b/crypto/aes-lowmemory/src/cfb.rs @@ -0,0 +1,86 @@ +//! Type aliases for AES in CFB mode (NIST SP 800-38A Sec 6.3). +//! +//! `bouncycastle-modes` is deliberately cipher-agnostic, so `Cfb` takes the permutation, the +//! direction, and the `KEY_LEN` / `BLOCK_LEN` const parameters. These aliases pin the AES values so +//! callers never spell them out. They add nothing to the engine: the permutation still implements +//! none of the data-encryption traits itself (see the crate docs), the mode does. +//! +//! The segment size is the full block, so these are **CFB128**. SP 800-38A's `s = 8` variant is a +//! different, non-interoperable mode with its own aliases -- [`AES_CFB8_128`](crate::AES_CFB8_128) +//! and friends -- and `s = 1` is not implemented; see the `bouncycastle_modes::Cfb` docs. + +use crate::{Aes128, Aes192, Aes256, BLOCK_LEN}; +use bouncycastle_modes::Cfb; + +/// AES-128 in CFB128 mode. `Dir` is [`bouncycastle_modes::Encrypting`] or +/// [`bouncycastle_modes::Decrypting`]; the wrong direction is a compile error, not a runtime check. +/// +/// CFB is a stream cipher, so the data is a `&mut [u8]` of any length and the ciphertext is exactly +/// as long as the plaintext. The IV is generated by encryption and returned; it is never supplied. +/// Encryption and decryption work in place. +/// +/// ``` +/// use bouncycastle_aes_lowmemory::AES_CFB_128; +/// use bouncycastle_core::key_material::{KeyMaterial, KeyType}; +/// use bouncycastle_core::traits::{StreamCipherDecryptor, StreamCipherEncryptor}; +/// use bouncycastle_modes::{Decrypting, Encrypting}; +/// +/// let key = KeyMaterial::<16>::from_bytes_as_type(&[0x42; 16], KeyType::SymmetricCipherKey) +/// .expect("a 16-byte symmetric cipher key"); +/// // 47 bytes: a stream cipher does not need a whole number of blocks. +/// let message = [0u8; 47]; +/// let mut data = message; +/// let iv = AES_CFB_128::::encrypt(&key, &mut data).unwrap(); +/// assert_ne!(data, message); +/// AES_CFB_128::::decrypt(&key, &iv, &mut data).unwrap(); +/// assert_eq!(data, message); +/// +/// // Streaming, at any byte boundary: +/// let (mut enc, iv) = AES_CFB_128::::do_encrypt_init(&key).unwrap(); +/// let mut first = [0u8; 5]; +/// let mut rest = [1u8; 30]; +/// enc.do_encrypt(&mut first).unwrap(); +/// enc.do_encrypt(&mut rest).unwrap(); +/// let mut dec = AES_CFB_128::::do_decrypt_init(&key, &iv).unwrap(); +/// dec.do_decrypt(&mut first).unwrap(); +/// dec.do_decrypt(&mut rest).unwrap(); +/// assert_eq!(first, [0u8; 5]); +/// assert_eq!(rest, [1u8; 30]); +/// ``` +/// +#[allow(non_camel_case_types)] +pub type AES_CFB_128 = Cfb; + +/// AES-192 in CFB128 mode. See [`AES_CFB_128`]. +/// +/// ``` +/// use bouncycastle_aes_lowmemory::AES_CFB_192; +/// use bouncycastle_core::key_material::{KeyMaterial, KeyType}; +/// use bouncycastle_core::traits::{StreamCipherDecryptor, StreamCipherEncryptor}; +/// use bouncycastle_modes::{Decrypting, Encrypting}; +/// +/// let key = KeyMaterial::<24>::from_bytes_as_type(&[0x42; 24], KeyType::SymmetricCipherKey).unwrap(); +/// let mut data = [0u8; 30]; +/// let iv = AES_CFB_192::::encrypt(&key, &mut data).unwrap(); +/// AES_CFB_192::::decrypt(&key, &iv, &mut data).unwrap(); +/// assert_eq!(data, [0u8; 30]); +/// ``` +#[allow(non_camel_case_types)] +pub type AES_CFB_192 = Cfb; + +/// AES-256 in CFB128 mode. See [`AES_CFB_128`]. +/// +/// ``` +/// use bouncycastle_aes_lowmemory::AES_CFB_256; +/// use bouncycastle_core::key_material::{KeyMaterial, KeyType}; +/// use bouncycastle_core::traits::{StreamCipherDecryptor, StreamCipherEncryptor}; +/// use bouncycastle_modes::{Decrypting, Encrypting}; +/// +/// let key = KeyMaterial::<32>::from_bytes_as_type(&[0x42; 32], KeyType::SymmetricCipherKey).unwrap(); +/// let mut data = [0u8; 30]; +/// let iv = AES_CFB_256::::encrypt(&key, &mut data).unwrap(); +/// AES_CFB_256::::decrypt(&key, &iv, &mut data).unwrap(); +/// assert_eq!(data, [0u8; 30]); +/// ``` +#[allow(non_camel_case_types)] +pub type AES_CFB_256 = Cfb; diff --git a/crypto/aes-lowmemory/src/cfb8.rs b/crypto/aes-lowmemory/src/cfb8.rs new file mode 100644 index 00000000..505e7c35 --- /dev/null +++ b/crypto/aes-lowmemory/src/cfb8.rs @@ -0,0 +1,93 @@ +//! Type aliases for AES in CFB8 mode (NIST SP 800-38A Sec 6.3, `s = 8`). +//! +//! `bouncycastle-modes` is deliberately cipher-agnostic, so `Cfb8` takes the permutation, the +//! direction, and the `KEY_LEN` / `BLOCK_LEN` const parameters. These aliases pin the AES values so +//! callers never spell them out. They add nothing to the engine: the permutation still implements +//! none of the data-encryption traits itself (see the crate docs), the mode does. +//! +//! CFB8 is a **different, non-interoperable mode** from CFB128, not a variant of it: their +//! ciphertexts differ from the second byte, and it costs a full AES call per byte, sixteen times +//! the work of [`AES_CFB_128`](crate::AES_CFB_128). See the `bouncycastle_modes::Cfb8` docs for +//! when that is the right trade. + +use crate::{Aes128, Aes192, Aes256, BLOCK_LEN}; +use bouncycastle_modes::Cfb8; + +/// AES-128 in CFB8 mode. `Dir` is [`bouncycastle_modes::Encrypting`] or +/// [`bouncycastle_modes::Decrypting`]; the wrong direction is a compile error, not a runtime check. +/// +/// CFB8 is a stream cipher with a one-byte segment, so the data is a `&mut [u8]` of any length and +/// the ciphertext is exactly as long as the plaintext. The IV is generated by encryption and +/// returned; it is never supplied. Encryption and decryption work in place. +/// +/// ``` +/// use bouncycastle_aes_lowmemory::{AES_CFB8_128, AES_CFB_128}; +/// use bouncycastle_core::key_material::{KeyMaterial, KeyType}; +/// use bouncycastle_core::traits::{StreamCipherDecryptor, StreamCipherEncryptor}; +/// use bouncycastle_modes::{Decrypting, Encrypting}; +/// +/// let key = KeyMaterial::<16>::from_bytes_as_type(&[0x42; 16], KeyType::SymmetricCipherKey) +/// .expect("a 16-byte symmetric cipher key"); +/// // 5 bytes: CFB8's segment is one byte, so any length at all is fine. +/// let message = *b"hello"; +/// let mut data = message; +/// let iv = AES_CFB8_128::::encrypt(&key, &mut data).unwrap(); +/// assert_ne!(data, message); +/// AES_CFB8_128::::decrypt(&key, &iv, &mut data).unwrap(); +/// assert_eq!(data, message); +/// +/// // Streaming, at any byte boundary: +/// let (mut enc, iv) = AES_CFB8_128::::do_encrypt_init(&key).unwrap(); +/// let mut first = [0u8; 3]; +/// let mut rest = [1u8; 20]; +/// enc.do_encrypt(&mut first).unwrap(); +/// enc.do_encrypt(&mut rest).unwrap(); +/// let mut dec = AES_CFB8_128::::do_decrypt_init(&key, &iv).unwrap(); +/// dec.do_decrypt(&mut first).unwrap(); +/// dec.do_decrypt(&mut rest).unwrap(); +/// assert_eq!(first, [0u8; 3]); +/// assert_eq!(rest, [1u8; 20]); +/// +/// // CFB8 and CFB128 are not interchangeable: same key, same IV, different ciphertext. +/// let mut as_cfb8 = message; +/// let iv = AES_CFB8_128::::encrypt(&key, &mut as_cfb8).unwrap(); +/// let mut as_cfb128 = as_cfb8; +/// AES_CFB_128::::decrypt(&key, &iv, &mut as_cfb128).unwrap(); +/// assert_ne!(as_cfb128, message); +/// ``` +#[allow(non_camel_case_types)] +pub type AES_CFB8_128 = Cfb8; + +/// AES-192 in CFB8 mode. See [`AES_CFB8_128`]. +/// +/// ``` +/// use bouncycastle_aes_lowmemory::AES_CFB8_192; +/// use bouncycastle_core::key_material::{KeyMaterial, KeyType}; +/// use bouncycastle_core::traits::{StreamCipherDecryptor, StreamCipherEncryptor}; +/// use bouncycastle_modes::{Decrypting, Encrypting}; +/// +/// let key = KeyMaterial::<24>::from_bytes_as_type(&[0x42; 24], KeyType::SymmetricCipherKey).unwrap(); +/// let mut data = [0u8; 30]; +/// let iv = AES_CFB8_192::::encrypt(&key, &mut data).unwrap(); +/// AES_CFB8_192::::decrypt(&key, &iv, &mut data).unwrap(); +/// assert_eq!(data, [0u8; 30]); +/// ``` +#[allow(non_camel_case_types)] +pub type AES_CFB8_192 = Cfb8; + +/// AES-256 in CFB8 mode. See [`AES_CFB8_128`]. +/// +/// ``` +/// use bouncycastle_aes_lowmemory::AES_CFB8_256; +/// use bouncycastle_core::key_material::{KeyMaterial, KeyType}; +/// use bouncycastle_core::traits::{StreamCipherDecryptor, StreamCipherEncryptor}; +/// use bouncycastle_modes::{Decrypting, Encrypting}; +/// +/// let key = KeyMaterial::<32>::from_bytes_as_type(&[0x42; 32], KeyType::SymmetricCipherKey).unwrap(); +/// let mut data = [0u8; 30]; +/// let iv = AES_CFB8_256::::encrypt(&key, &mut data).unwrap(); +/// AES_CFB8_256::::decrypt(&key, &iv, &mut data).unwrap(); +/// assert_eq!(data, [0u8; 30]); +/// ``` +#[allow(non_camel_case_types)] +pub type AES_CFB8_256 = Cfb8; diff --git a/crypto/aes-lowmemory/src/ctr.rs b/crypto/aes-lowmemory/src/ctr.rs new file mode 100644 index 00000000..5c6dc40a --- /dev/null +++ b/crypto/aes-lowmemory/src/ctr.rs @@ -0,0 +1,92 @@ +//! Type aliases for AES in CTR mode (NIST SP 800-38A Sec 6.5). +//! +//! `bouncycastle-modes` is deliberately cipher-agnostic, so `Ctr` takes the permutation, the +//! direction, and the `KEY_LEN` / `BLOCK_LEN` / `INIT_DATA_LEN` const parameters. These aliases pin +//! the AES values so callers never spell them out. They add nothing to the engine: the permutation +//! still implements none of the data-encryption traits itself (see the crate docs), the mode does. +//! +//! # The nonce length is 12, so the counter is 4 bytes +//! +//! `Ctr` splits the counter block into a nonce and a counter by the length of its init data, and +//! these aliases choose a **12-byte nonce**, leaving the 4-byte counter that is the mode's maximum. +//! That allows 2^32 blocks -- 64 GiB -- in one message, and past it the mode errors rather than +//! repeating keystream. A shorter message limit in exchange for more nonce bits is available by +//! naming `Ctr` directly with a 13, 14 or 15-byte nonce. + +use crate::{Aes128, Aes192, Aes256, BLOCK_LEN}; +use bouncycastle_modes::Ctr; + +/// The nonce length these aliases use, leaving a 4-byte counter. +pub const CTR_NONCE_LEN: usize = 12; + +/// AES-128 in CTR mode with a 12-byte nonce. `Dir` is [`bouncycastle_modes::Encrypting`] or +/// [`bouncycastle_modes::Decrypting`]; the wrong direction is a compile error, not a runtime check. +/// +/// CTR is a stream cipher, so the data is a `&mut [u8]` of any length and the ciphertext is exactly +/// as long as the plaintext. The nonce is generated by encryption and returned; it is never +/// supplied. Encryption and decryption work in place, and are the same operation. +/// +/// ``` +/// use bouncycastle_aes_lowmemory::AES_CTR_128; +/// use bouncycastle_core::key_material::{KeyMaterial, KeyType}; +/// use bouncycastle_core::traits::{StreamCipherDecryptor, StreamCipherEncryptor}; +/// use bouncycastle_modes::{Decrypting, Encrypting}; +/// +/// let key = KeyMaterial::<16>::from_bytes_as_type(&[0x42; 16], KeyType::SymmetricCipherKey) +/// .expect("a 16-byte symmetric cipher key"); +/// // 47 bytes: a stream cipher does not need a whole number of blocks. +/// let message = [0u8; 47]; +/// let mut data = message; +/// let nonce = AES_CTR_128::::encrypt(&key, &mut data).unwrap(); +/// assert_ne!(data, message); +/// AES_CTR_128::::decrypt(&key, &nonce, &mut data).unwrap(); +/// assert_eq!(data, message); +/// +/// // Streaming, at any byte boundary: +/// let (mut enc, nonce) = AES_CTR_128::::do_encrypt_init(&key).unwrap(); +/// let mut first = [0u8; 5]; +/// let mut rest = [1u8; 30]; +/// enc.do_encrypt(&mut first).unwrap(); +/// enc.do_encrypt(&mut rest).unwrap(); +/// let mut dec = AES_CTR_128::::do_decrypt_init(&key, &nonce).unwrap(); +/// dec.do_decrypt(&mut first).unwrap(); +/// dec.do_decrypt(&mut rest).unwrap(); +/// assert_eq!(first, [0u8; 5]); +/// assert_eq!(rest, [1u8; 30]); +/// ``` +#[allow(non_camel_case_types)] +pub type AES_CTR_128 = Ctr; + +/// AES-192 in CTR mode with a 12-byte nonce. See [`AES_CTR_128`]. +/// +/// ``` +/// use bouncycastle_aes_lowmemory::AES_CTR_192; +/// use bouncycastle_core::key_material::{KeyMaterial, KeyType}; +/// use bouncycastle_core::traits::{StreamCipherDecryptor, StreamCipherEncryptor}; +/// use bouncycastle_modes::{Decrypting, Encrypting}; +/// +/// let key = KeyMaterial::<24>::from_bytes_as_type(&[0x42; 24], KeyType::SymmetricCipherKey).unwrap(); +/// let mut data = [0u8; 30]; +/// let nonce = AES_CTR_192::::encrypt(&key, &mut data).unwrap(); +/// AES_CTR_192::::decrypt(&key, &nonce, &mut data).unwrap(); +/// assert_eq!(data, [0u8; 30]); +/// ``` +#[allow(non_camel_case_types)] +pub type AES_CTR_192 = Ctr; + +/// AES-256 in CTR mode with a 12-byte nonce. See [`AES_CTR_128`]. +/// +/// ``` +/// use bouncycastle_aes_lowmemory::AES_CTR_256; +/// use bouncycastle_core::key_material::{KeyMaterial, KeyType}; +/// use bouncycastle_core::traits::{StreamCipherDecryptor, StreamCipherEncryptor}; +/// use bouncycastle_modes::{Decrypting, Encrypting}; +/// +/// let key = KeyMaterial::<32>::from_bytes_as_type(&[0x42; 32], KeyType::SymmetricCipherKey).unwrap(); +/// let mut data = [0u8; 30]; +/// let nonce = AES_CTR_256::::encrypt(&key, &mut data).unwrap(); +/// AES_CTR_256::::decrypt(&key, &nonce, &mut data).unwrap(); +/// assert_eq!(data, [0u8; 30]); +/// ``` +#[allow(non_camel_case_types)] +pub type AES_CTR_256 = Ctr; diff --git a/crypto/aes-lowmemory/src/ecb.rs b/crypto/aes-lowmemory/src/ecb.rs new file mode 100644 index 00000000..d9902f8f --- /dev/null +++ b/crypto/aes-lowmemory/src/ecb.rs @@ -0,0 +1,101 @@ +//! Type aliases for AES in ECB mode (NIST SP 800-38A Sec 6.1). +//! +//! `bouncycastle-modes` is deliberately cipher-agnostic, so `Ecb` takes the permutation, the +//! direction, and the `KEY_LEN` / `BLOCK_LEN` const parameters. These aliases pin the AES values so +//! callers never spell them out. +//! +//! **ECB is not a confidentiality mode for data.** Under a given key every plaintext block maps to +//! the same ciphertext block (Sec 6.1), so the structure of the plaintext shows through, and blocks +//! can be reordered, repeated or removed undetectably. These aliases exist for interoperability with +//! systems that use ECB and for driving test vectors; for data, use CBC or CFB under authentication, +//! or better an AEAD. See the crate docs, "A block permutation is not a cipher". + +use crate::{Aes128, Aes192, Aes256, BLOCK_LEN}; +use bouncycastle_modes::Ecb; + +/// AES-128 in ECB mode. `Dir` is [`bouncycastle_modes::Encrypting`] or +/// [`bouncycastle_modes::Decrypting`]; the wrong direction is a compile error, not a runtime check. +/// +/// There is no IV: `encrypt` returns an empty array and `decrypt` takes one. Encryption and +/// decryption work in place. **Not confidential for data** -- see the module docs. +/// +/// ``` +/// use bouncycastle_aes_lowmemory::AES_ECB_128; +/// use bouncycastle_core::key_material::{KeyMaterial, KeyType}; +/// use bouncycastle_core::traits::{BlockCipherDecryptor, BlockCipherEncryptor}; +/// use bouncycastle_modes::{Decrypting, Encrypting}; +/// +/// let key = KeyMaterial::<16>::from_bytes_as_type(&[0x42; 16], KeyType::SymmetricCipherKey) +/// .expect("a 16-byte symmetric cipher key"); +/// // 48 bytes: three whole blocks. The length is checked at compile time. +/// let message = [0u8; 48]; +/// let mut data = message; +/// let no_iv: [u8; 0] = AES_ECB_128::::encrypt(&key, &mut data).unwrap(); +/// assert_ne!(data, message); +/// // The codebook property: three equal plaintext blocks give three equal ciphertext blocks. +/// assert_eq!(data[..16], data[16..32]); +/// assert_eq!(data[..16], data[32..]); +/// AES_ECB_128::::decrypt(&key, &no_iv, &mut data).unwrap(); +/// assert_eq!(data, message); +/// +/// // Streaming, a few blocks at a time: +/// let (mut enc, _) = AES_ECB_128::::do_encrypt_init(&key).unwrap(); +/// let mut first = [0u8; 16]; +/// let mut rest = [1u8; 32]; +/// enc.do_encrypt(&mut first).unwrap(); +/// enc.do_encrypt(&mut rest).unwrap(); +/// let mut dec = AES_ECB_128::::do_decrypt_init(&key, &[]).unwrap(); +/// dec.do_decrypt(&mut first).unwrap(); +/// dec.do_decrypt(&mut rest).unwrap(); +/// assert_eq!(first, [0u8; 16]); +/// assert_eq!(rest, [1u8; 32]); +/// ``` +/// +/// A length that is not a whole number of blocks is a **compile** error, not a runtime one: +/// +/// ```compile_fail +/// use bouncycastle_aes_lowmemory::AES_ECB_128; +/// use bouncycastle_core::key_material::{KeyMaterial, KeyType}; +/// use bouncycastle_core::traits::BlockCipherEncryptor; +/// use bouncycastle_modes::Encrypting; +/// +/// let key = KeyMaterial::<16>::from_bytes_as_type(&[0x42; 16], KeyType::SymmetricCipherKey).unwrap(); +/// // 47 bytes is not a multiple of 16: the inline const assertion in `encrypt` fails to compile. +/// let _ = AES_ECB_128::::encrypt(&key, &mut [0u8; 47]); +/// ``` +#[allow(non_camel_case_types)] +pub type AES_ECB_128 = Ecb; + +/// AES-192 in ECB mode. See [`AES_ECB_128`]. +/// +/// ``` +/// use bouncycastle_aes_lowmemory::AES_ECB_192; +/// use bouncycastle_core::key_material::{KeyMaterial, KeyType}; +/// use bouncycastle_core::traits::{BlockCipherDecryptor, BlockCipherEncryptor}; +/// use bouncycastle_modes::{Decrypting, Encrypting}; +/// +/// let key = KeyMaterial::<24>::from_bytes_as_type(&[0x42; 24], KeyType::SymmetricCipherKey).unwrap(); +/// let mut data = [0u8; 32]; +/// let no_iv = AES_ECB_192::::encrypt(&key, &mut data).unwrap(); +/// AES_ECB_192::::decrypt(&key, &no_iv, &mut data).unwrap(); +/// assert_eq!(data, [0u8; 32]); +/// ``` +#[allow(non_camel_case_types)] +pub type AES_ECB_192 = Ecb; + +/// AES-256 in ECB mode. See [`AES_ECB_128`]. +/// +/// ``` +/// use bouncycastle_aes_lowmemory::AES_ECB_256; +/// use bouncycastle_core::key_material::{KeyMaterial, KeyType}; +/// use bouncycastle_core::traits::{BlockCipherDecryptor, BlockCipherEncryptor}; +/// use bouncycastle_modes::{Decrypting, Encrypting}; +/// +/// let key = KeyMaterial::<32>::from_bytes_as_type(&[0x42; 32], KeyType::SymmetricCipherKey).unwrap(); +/// let mut data = [0u8; 32]; +/// let no_iv = AES_ECB_256::::encrypt(&key, &mut data).unwrap(); +/// AES_ECB_256::::decrypt(&key, &no_iv, &mut data).unwrap(); +/// assert_eq!(data, [0u8; 32]); +/// ``` +#[allow(non_camel_case_types)] +pub type AES_ECB_256 = Ecb; diff --git a/crypto/aes-lowmemory/src/lib.rs b/crypto/aes-lowmemory/src/lib.rs new file mode 100644 index 00000000..eed751d6 --- /dev/null +++ b/crypto/aes-lowmemory/src/lib.rs @@ -0,0 +1,227 @@ +//! A constant-time, table-free AES block cipher engine (NIST FIPS 197). +//! +//! This crate provides the raw AES keyed permutation -- [`Aes128`], [`Aes192`] and [`Aes256`] -- +//! implemented as a Boolean circuit over bit-planes rather than as byte substitutions through a +//! lookup table. That makes it both smaller and constant-time; see [Design](#design). +//! +//! It is a *permutation*, not a cipher you can encrypt data with. See +//! [Security Considerations](#security-considerations). +//! +//! # Usage Examples +//! +//! ## Encrypting and decrypting a single block +//! +//! ``` +//! use bouncycastle_aes_lowmemory::Aes128; +//! use bouncycastle_core::key_material::{KeyMaterial, KeyType}; +//! +//! let key = KeyMaterial::<16>::from_bytes_as_type( +//! &[0x2b, 0x7e, 0x15, 0x16, 0x28, 0xae, 0xd2, 0xa6, +//! 0xab, 0xf7, 0x15, 0x88, 0x09, 0xcf, 0x4f, 0x3c], +//! KeyType::SymmetricCipherKey, +//! ).expect("a 16-byte symmetric cipher key"); +//! +//! let aes = Aes128::new(&key).expect("a valid AES-128 key"); +//! +//! // FIPS 197 Appendix B. +//! let mut block = [0x32, 0x43, 0xf6, 0xa8, 0x88, 0x5a, 0x30, 0x8d, +//! 0x31, 0x31, 0x98, 0xa2, 0xe0, 0x37, 0x07, 0x34]; +//! aes.encrypt_block(&mut block); +//! assert_eq!(block, [0x39, 0x25, 0x84, 0x1d, 0x02, 0xdc, 0x09, 0xfb, +//! 0xdc, 0x11, 0x85, 0x97, 0x19, 0x6a, 0x0b, 0x32]); +//! +//! // The same value decrypts, from the same schedule -- there is no separate decryptor. +//! aes.decrypt_block(&mut block); +//! assert_eq!(block, [0x32, 0x43, 0xf6, 0xa8, 0x88, 0x5a, 0x30, 0x8d, +//! 0x31, 0x31, 0x98, 0xa2, 0xe0, 0x37, 0x07, 0x34]); +//! ``` +//! +//! ## Two blocks at a time +//! +//! The bit-sliced state holds two blocks, so two independent blocks cost barely more than one. +//! Where a caller has two, [`Aes::encrypt_blocks2`] is roughly twice the throughput of two +//! [`Aes::encrypt_block`] calls: +//! +//! ``` +//! use bouncycastle_aes_lowmemory::Aes256; +//! use bouncycastle_core::key_material::{KeyMaterial, KeyType}; +//! +//! let key = KeyMaterial::<32>::from_bytes_as_type(&[0x42; 32], KeyType::SymmetricCipherKey) +//! .expect("a 32-byte symmetric cipher key"); +//! let aes = Aes256::new(&key).expect("a valid AES-256 key"); +//! +//! let mut blocks = [[0u8; 16], [1u8; 16]]; +//! aes.encrypt_blocks2(&mut blocks); +//! aes.decrypt_blocks2(&mut blocks); +//! assert_eq!(blocks, [[0u8; 16], [1u8; 16]]); +//! ``` +//! +//! ## Modes of operation +//! +//! To encrypt more than one block, use a mode of operation from `bouncycastle-modes`. This crate +//! provides aliases that fill in the const parameters, with the direction left as the type +//! parameter: [`AES_CBC_128`], [`AES_CBC_192`] and [`AES_CBC_256`] for CBC (SP 800-38A Sec 6.2), +//! and [`AES_CFB_128`], [`AES_CFB_192`] and [`AES_CFB_256`] for CFB128 (Sec 6.3). +//! [`AES_CFB8_128`], [`AES_CFB8_192`] and [`AES_CFB8_256`] give CFB8, the `s = 8` segment size, +//! which is a different and non-interoperable mode costing one AES call per byte. +//! [`AES_CTR_128`], [`AES_CTR_192`] and [`AES_CTR_256`] give CTR (Sec 6.5) with a 12-byte nonce +//! and a 4-byte counter. +//! [`AES_ECB_128`], [`AES_ECB_192`] and [`AES_ECB_256`] give ECB (Sec 6.1) the same shape with no +//! IV, for interoperability and test vectors only -- see +//! [A block permutation is not a cipher](#a-block-permutation-is-not-a-cipher). +//! +//! CBC is a block cipher and needs whole blocks; the two CFB modes are stream ciphers and take any +//! length. See the `bouncycastle-modes` crate docs for the comparison. +//! +//! ``` +//! use bouncycastle_aes_lowmemory::AES_CBC_256; +//! use bouncycastle_core::key_material::{KeyMaterial, KeyType}; +//! use bouncycastle_core::traits::{BlockCipherDecryptor, BlockCipherEncryptor}; +//! use bouncycastle_modes::{Decrypting, Encrypting}; +//! +//! let key = KeyMaterial::<32>::from_bytes_as_type(&[0x42; 32], KeyType::SymmetricCipherKey) +//! .expect("a 32-byte symmetric cipher key"); +//! // 48 bytes: three whole blocks. A length that is not a multiple of 16 would not compile. +//! let plaintext = [0x5Au8; 48]; +//! +//! // Encryption is in place. The IV is generated for you and returned; there is no API for +//! // supplying one. +//! let mut data = plaintext; +//! let iv = AES_CBC_256::::encrypt(&key, &mut data).unwrap(); +//! assert_ne!(data, plaintext); +//! AES_CBC_256::::decrypt(&key, &iv, &mut data).unwrap(); +//! assert_eq!(data, plaintext); +//! ``` +//! +//! There is no one-shot static on the permutation, because `Aes128::new(&key)?.encrypt_block(..)` +//! already *is* the one shot. Data-level one-shots belong to the modes of operation, which take +//! arbitrary-length input and generate their own initialisation data. +//! +//! # Design +//! +//! ## Why not a lookup table +//! +//! FIPS 197 Sec 5.1.1 presents the S-box as a table (Table 4), and almost every AES +//! implementation stores it as one -- 256 bytes, or 2-8 KiB for the "T-table" variants that fold +//! MIXCOLUMNS() in. The trouble is that a table indexed by a byte of the state is indexed by +//! secret data, so on any CPU with a data cache the memory access pattern, and hence the timing, +//! depends on the key. That is a practical, repeatedly-demonstrated attack, and it is not fixable +//! while the lookup remains. +//! +//! Bouncy Castle's `AESLightEngine` in the Java and C# ports keeps two 256-byte S-box tables for +//! exactly this reason -- to be *small*, not to be constant-time -- and leaks through both the +//! cipher and the key schedule. +//! +//! ## Bit-slicing +//! +//! This crate has no tables at all. The state is transposed so that each of eight `u32` words +//! holds one *bit position* of every byte: word `q[k]` collects bit `k` of all the bytes. In that +//! form the S-box becomes a fixed Boolean circuit -- 32 AND, 77 XOR and 4 XNOR gates, the +//! 113-gate straight-line program of Boyar and Peralta -- and one `&` or `^` applies a gate to +//! every byte position at once. Nothing is ever indexed by a secret, and nothing branches on one. +//! +//! Eight 32-bit words hold 32 bytes, which is two AES blocks, so blocks are processed in pairs. +//! SHIFTROWS() and MIXCOLUMNS() become masks and rotations in the same representation, and the +//! key schedule is stored bit-sliced too, so no transposition happens inside the round loop. The +//! exact bit layout, and the derivation of every mask from it, is documented in the `bitslice` +//! and `round` modules -- those two module docs are the place to start when reading the source. +//! +//! Decryption follows FIPS 197 Algorithm 3, the straight inverse cipher, rather than the +//! equivalent inverse cipher of Sec 5.3.5. Algorithm 3 puts INVMIXCOLUMNS() after ADDROUNDKEY(), +//! so it uses the *unmodified* key schedule; the equivalent inverse cipher would need a second +//! schedule with each round key transformed. One [`Aes`] value therefore encrypts and decrypts +//! from one stored schedule. +//! +//! # Memory Usage +//! +//! There are no lookup tables and no heap allocation. The only persistent state is the key +//! schedule, which is `4 * (Nr + 1)` words -- exactly the size FIPS 197 Sec 5.2 defines, with the +//! bit-sliced form compressed so that bit-slicing costs nothing in space: +//! +//! | Type | Key | `Nr` | Schedule (persistent) | Tables | +//! |---|---|---|---|---| +//! | [`Aes128`] | 16 B | 10 | 176 B | 0 B | +//! | [`Aes192`] | 24 B | 12 | 208 B | 0 B | +//! | [`Aes256`] | 32 B | 14 | 240 B | 0 B | +//! +//! Per-call stack usage is independent of key length: 32 bytes of bit-sliced state for the two +//! blocks, 32 bytes for the round key expanded from its compressed form, plus the S-box circuit's +//! temporaries, most of which the compiler keeps in registers. +//! +//! For comparison, `AESLightEngine` carries 512 bytes of tables and a T-table implementation +//! carries 2-8 KiB, in both cases *on top of* a key schedule of this same size. +//! +//! Measure with `cargo run --release -p mem_usage_benches --bin bench_aes_mem_usage`. +//! +//! # Security Considerations +//! +//! ## A block permutation is not a cipher +//! +//! [`Aes128`] and friends transform exactly 16 bytes. Using them directly on data means ECB, +//! which is not confidential: identical plaintext blocks produce identical ciphertext blocks, so +//! structure in the plaintext survives encryption. **Do not do it.** Use a mode of operation, and +//! prefer an authenticated one so that ciphertext tampering is detected. +//! +//! The [`AES_ECB_128`] / [`AES_ECB_192`] / [`AES_ECB_256`] aliases give that same block-by-block +//! operation the mode API, so that systems and specifications which require ECB -- and test-vector +//! harnesses -- can use it through the same interface as the other modes. They do not make it +//! confidential; the warning above applies to them unchanged. +//! +//! ## Constant-time properties +//! +//! By construction there is no secret-dependent memory access and no secret-dependent branch, +//! in the cipher *or* in the key schedule -- SUBWORD() goes through the same circuit as +//! SUBBYTES(). The only branches are the round loops, which count over the public `Nr`. +//! +//! Caveats worth stating plainly: +//! +//! * The Rust compiler makes no guarantee it will preserve this. The code is written so that the +//! natural code generation is straight-line, and `#![forbid(unsafe_code)]` rules out the usual +//! ways of forcing the issue, but the property is not contractual. +//! * The 32-byte working state is not scrubbed after a block. Only the key schedule is wrapped in +//! `Secret`, and so only it is guaranteed to be zeroized on drop. +//! * Constant-time execution says nothing about power or electromagnetic side channels. +//! +//! # Provenance +//! +//! * Normative reference: **NIST FIPS 197** (Advanced Encryption Standard), including Update 1. +//! Every transformation cites its section, algorithm and equation numbers. +//! * The S-box circuit is the 113-gate straight-line program `SLP_AES_113.txt` from Peralta's +//! circuit collection, described in J. Boyar and R. Peralta, "A new combinational logic +//! minimization technique with applications to cryptology", +//! . +//! * The bit-sliced two-block structure, the transpose, and the SHIFTROWS()/MIXCOLUMNS() mask and +//! rotation constants are translated from BearSSL's `aes_ct` implementation by Thomas Pornin +//! (MIT licence). Each constant is re-derived from the documented bit layout in the comments, +//! and each is pinned by a test against a byte-wise reference written from the FIPS 197 +//! equations. +//! * Verified against FIPS 197 Appendix A (all three key expansions, every word), FIPS 197 +//! Appendix B, NIST SP 800-38A Appendix F.1 (ECB, all three key lengths, both directions), and +//! the NIST ACVP `ACVP-AES-ECB` vectors. + +#![no_std] +#![forbid(unsafe_code)] +#![forbid(missing_docs)] +// `AesParams` is deliberately sealed with a private supertrait so that no fourth parameter set can +// be added outside this crate; that is what triggers this lint. +#![allow(private_bounds)] + +mod aes; +mod bitslice; +mod cbc; +mod cfb; +mod cfb8; +mod ctr; +mod ecb; +mod round; +mod sbox; +mod schedule; + +pub use aes::{Aes, Aes128, Aes192, Aes256, BLOCK_LEN}; +pub use bitslice::Block; +pub use cbc::{AES_CBC_128, AES_CBC_192, AES_CBC_256}; +pub use cfb::{AES_CFB_128, AES_CFB_192, AES_CFB_256}; +pub use cfb8::{AES_CFB8_128, AES_CFB8_192, AES_CFB8_256}; +pub use ctr::{AES_CTR_128, AES_CTR_192, AES_CTR_256, CTR_NONCE_LEN}; +pub use ecb::{AES_ECB_128, AES_ECB_192, AES_ECB_256}; +pub use schedule::{Aes128Params, Aes192Params, Aes256Params, AesParams}; diff --git a/crypto/aes-lowmemory/src/round.rs b/crypto/aes-lowmemory/src/round.rs new file mode 100644 index 00000000..b42406cf --- /dev/null +++ b/crypto/aes-lowmemory/src/round.rs @@ -0,0 +1,507 @@ +//! The three linear round transformations, on bit-planes. +//! +//! | Function | FIPS 197 | Inverse | FIPS 197 | +//! |---|---|---|---| +//! | [`add_round_key`] | Sec 5.1.4, Eq 5.9 | itself (XOR) | Sec 5.3.4 | +//! | [`shift_rows`] | Sec 5.1.2, Eq 5.5 | [`inv_shift_rows`] | Sec 5.3.1, Eq 5.12 | +//! | [`mix_columns`] | Sec 5.1.3, Eq 5.8 | [`inv_mix_columns`] | Sec 5.3.3, Eq 5.15 | +//! +//! SUBBYTES() is in [`crate::sbox`], because it is the only non-linear step and the only one that +//! needs a circuit rather than masks and rotations. +//! +//! Everything here is XOR, AND with a constant mask, and rotation by a constant. No operation +//! depends on the data, so all of it is inherently constant-time. +//! +//! # How the layout turns row and column arithmetic into shifts +//! +//! From the layout derived in [`crate::bitslice`], within every plane the bit holding `s[r,c]` +//! of block A sits at bit position `8r + 2c` (and block B at `8r + 2c + 1`). Two consequences +//! drive every constant below: +//! +//! * **A row is a byte-lane.** All of row `r` lives in bits `8r..8r+8` of every plane, and +//! stepping one column along that row is a step of two bit positions. So SHIFTROWS(), which +//! only permutes within rows, is a rotation *inside* each byte-lane, by `2r` positions. +//! * **Rotating a whole plane by 8 changes the row.** `x.rotate_right(8)` brings the contents of +//! lane `r+1` into lane `r`, so `rotate_right(8)` reads "the next row down" and +//! `rotate_right(16)` reads "two rows down". MIXCOLUMNS(), which combines the four rows of a +//! column, is therefore expressible with those two rotations and no shuffling at all. +//! +//! Provenance: the mask and rotation constants are translated from BearSSL +//! `src/symcipher/aes_ct_enc.c` and `aes_ct_dec.c` (MIT, Thomas Pornin). Each is re-derived from +//! the layout in the comments below, and each is pinned by a test in this file against a +//! byte-wise reference written directly from the FIPS 197 equations. + +use crate::bitslice::Planes; + +/// ADDROUNDKEY(): XORs a round key into the state (FIPS 197 Sec 5.1.4, Eq 5.9). +/// +/// Eq 5.9 XORs word `w[4*round + c]` into column `c`. Here the round key has already been +/// bit-sliced into the same plane layout as the state by [`crate::schedule`], so the whole +/// transformation -- all four columns of both blocks -- is eight XORs. +/// +/// This is its own inverse, which is why FIPS 197 Sec 5.3.4 needs no separate INVADDROUNDKEY(). +#[inline(always)] +pub(crate) fn add_round_key(q: &mut Planes, round_key: &Planes) { + for (plane, key_plane) in q.iter_mut().zip(round_key.iter()) { + *plane ^= *key_plane; + } +} + +/// SHIFTROWS(): cyclically shifts row `r` left by `r` columns (FIPS 197 Sec 5.1.2, Eq 5.5). +/// +/// Eq 5.5 is `s'[r,c] = s[r,(c + r) mod 4]`. Row `r` occupies byte-lane `r` of every plane and +/// one column is two bit positions, so the new column `c` must take what is two-bits-times-`r` +/// further up the lane: a **rotate right by `2r` within lane `r`**. Rotating right, not left, +/// because taking from a higher column index means pulling data down towards bit 0. +/// +/// Written out per lane rather than as a loop, so the shift amounts stay compile-time constants: +/// +/// * lane 0 (`r = 0`): rotate by 0, so bits `0..8` pass through untouched. +/// * lane 1 (`r = 1`): rotate right by 2. Bits 10..16 drop to 8..14; bits 8..10 wrap to 14..16. +/// * lane 2 (`r = 2`): rotate right by 4. Bits 20..24 drop to 16..20; bits 16..20 wrap up. +/// * lane 3 (`r = 3`): rotate right by 6. Bits 30..32 drop to 24..26; bits 24..30 wrap up. +/// +/// Both interleaved blocks move together, since a column step of two positions carries the A and +/// B bits of that column as a pair. +/// +/// Translated from BearSSL `aes_ct_enc.c:shift_rows`. +#[inline(always)] +pub(crate) fn shift_rows(q: &mut Planes) { + for plane in q.iter_mut() { + let x = *plane; + *plane = (x & 0x0000_00FF) + | ((x & 0x0000_FC00) >> 2) + | ((x & 0x0000_0300) << 6) + | ((x & 0x00F0_0000) >> 4) + | ((x & 0x000F_0000) << 4) + | ((x & 0xC000_0000) >> 6) + | ((x & 0x3F00_0000) << 2); + } +} + +/// INVSHIFTROWS(): cyclically shifts row `r` right by `r` columns +/// (FIPS 197 Sec 5.3.1, Eq 5.12). +/// +/// Eq 5.12 is `s'[r,c] = s[r,(c - r) mod 4]`, so this is [`shift_rows`] with every lane rotation +/// reversed: **rotate left by `2r` within lane `r`**. The masks are the complementary halves of +/// the forward ones. +/// +/// Translated from BearSSL `aes_ct_dec.c:inv_shift_rows`. +#[inline(always)] +pub(crate) fn inv_shift_rows(q: &mut Planes) { + for plane in q.iter_mut() { + let x = *plane; + *plane = (x & 0x0000_00FF) + | ((x & 0x0000_3F00) << 2) + | ((x & 0x0000_C000) >> 6) + | ((x & 0x000F_0000) << 4) + | ((x & 0x00F0_0000) >> 4) + | ((x & 0x0300_0000) << 6) + | ((x & 0xFC00_0000) >> 2); + } +} + +/// MIXCOLUMNS(): multiplies every column by the fixed matrix of Eq 5.7 +/// (FIPS 197 Sec 5.1.3). +/// +/// # Derivation +/// +/// Eq 5.8 gives each output byte of a column. Collecting the four rows, and writing `s[r]` for +/// the byte in row `r` of the column being processed, every row obeys the same rule: +/// +/// ```text +/// s'[r] = {02}.s[r] ^ {03}.s[r+1] ^ s[r+2] ^ s[r+3] (rows mod 4) +/// = {02}.(s[r] ^ s[r+1]) ^ s[r+1] ^ s[r+2] ^ s[r+3] +/// ``` +/// +/// using `{03} = {02} ^ {01}`. Because "the next row" is `rotate_right(8)` and "two rows down" is +/// `rotate_right(16)` (see the module docs), with `p` the state planes and `r` = `p` rotated by 8: +/// +/// * `p[k]` is bit `k` of `s[r]`, `r[k]` is bit `k` of `s[r+1]`, +/// * `rotate_right(16)` of those two gives bit `k` of `s[r+2]` and of `s[r+3]`. +/// +/// So `s[r+2] ^ s[r+3]` is `(p[k] ^ r[k]).rotate_right(16)`, which is the `rotr16(..)` term in +/// every line below, and `s[r+1]` is the bare `r[k]`. +/// +/// The remaining `{02}.(s[r] ^ s[r+1])` is XTIMES() (Eq 4.5) in the plane basis. Multiplying by +/// `x` shifts every bit up one plane, and the degree-8 term that falls off the top is reduced by +/// XOR-ing `{1b} = 0b0001_1011` -- bits 0, 1, 3 and 4. So with `v[k] = p[k] ^ r[k]`, plane `k` of +/// `{02}.v` is: +/// +/// * `v[k-1]` from the shift, for `k >= 1` (plane 0 gets nothing from the shift), and +/// * `v[7]`, the reduction, for `k` in {0, 1, 3, 4} only. +/// +/// That is exactly where the extra `p[7] ^ r[7]` terms appear below: in the lines for planes 0, 1, +/// 3 and 4, and nowhere else. Plane 0 is the one line with no `p[k-1] ^ r[k-1]` term. +/// +/// Translated from BearSSL `aes_ct_enc.c:mix_columns`; the equivalence to Eq 5.8 is pinned by +/// `test_mix_columns_matches_equation_5_8`. +#[inline(always)] +pub(crate) fn mix_columns(q: &mut Planes) { + let p = *q; + // r[k] holds the same bit position of the next row down. + let r: Planes = core::array::from_fn(|k| p[k].rotate_right(8)); + + // The `p[7] ^ r[7]` term is the {1b} reduction, present only in planes 0, 1, 3 and 4. + q[0] = p[7] ^ r[7] ^ r[0] ^ (p[0] ^ r[0]).rotate_right(16); + q[1] = p[0] ^ r[0] ^ p[7] ^ r[7] ^ r[1] ^ (p[1] ^ r[1]).rotate_right(16); + q[2] = p[1] ^ r[1] ^ r[2] ^ (p[2] ^ r[2]).rotate_right(16); + q[3] = p[2] ^ r[2] ^ p[7] ^ r[7] ^ r[3] ^ (p[3] ^ r[3]).rotate_right(16); + q[4] = p[3] ^ r[3] ^ p[7] ^ r[7] ^ r[4] ^ (p[4] ^ r[4]).rotate_right(16); + q[5] = p[4] ^ r[4] ^ r[5] ^ (p[5] ^ r[5]).rotate_right(16); + q[6] = p[5] ^ r[5] ^ r[6] ^ (p[6] ^ r[6]).rotate_right(16); + q[7] = p[6] ^ r[6] ^ r[7] ^ (p[7] ^ r[7]).rotate_right(16); +} + +/// INVMIXCOLUMNS(): multiplies every column by the inverse matrix of Eq 5.14 +/// (FIPS 197 Sec 5.3.3). +/// +/// The same shape as [`mix_columns`] -- `r` is the next row down, `rotate_right(16)` reaches two +/// rows further -- but the defining word of Sec 4.3 is `[{0e},{09},{0d},{0b}]` (Eq 5.13) instead +/// of `[{02},{01},{01},{03}]` (Eq 5.6). Those have degree up to 3, so expanding each product +/// through XTIMES() +/// in the plane basis produces many more terms than the forward direction, and the per-plane term +/// lists below are that expansion of Eq 5.15 rather than something readable line by line. +/// +/// The reduction terms are not confined to planes 0, 1, 3 and 4 here, because the higher-degree +/// coefficients feed carries into every plane. +/// +/// Translated from BearSSL `aes_ct_dec.c:inv_mix_columns`. Rather than trust the expansion by +/// inspection, `test_inv_mix_columns_matches_equation_5_15` checks it against a byte-wise +/// reference written straight from Eq 5.15, and `test_inv_mix_columns_inverts_mix_columns` +/// checks the two are inverses. +#[inline(always)] +#[rustfmt::skip] +pub(crate) fn inv_mix_columns(q: &mut Planes) { + let p = *q; + let r: Planes = core::array::from_fn(|k| p[k].rotate_right(8)); + + q[0] = p[5] ^ p[6] ^ p[7] ^ r[0] ^ r[5] ^ r[7] + ^ (p[0] ^ p[5] ^ p[6] ^ r[0] ^ r[5]).rotate_right(16); + q[1] = p[0] ^ p[5] ^ r[0] ^ r[1] ^ r[5] ^ r[6] ^ r[7] + ^ (p[1] ^ p[5] ^ p[7] ^ r[1] ^ r[5] ^ r[6]).rotate_right(16); + q[2] = p[0] ^ p[1] ^ p[6] ^ r[1] ^ r[2] ^ r[6] ^ r[7] + ^ (p[0] ^ p[2] ^ p[6] ^ r[2] ^ r[6] ^ r[7]).rotate_right(16); + q[3] = p[0] ^ p[1] ^ p[2] ^ p[5] ^ p[6] ^ r[0] ^ r[2] ^ r[3] ^ r[5] + ^ (p[0] ^ p[1] ^ p[3] ^ p[5] ^ p[6] ^ p[7] ^ r[0] ^ r[3] ^ r[5] ^ r[7]).rotate_right(16); + q[4] = p[1] ^ p[2] ^ p[3] ^ p[5] ^ r[1] ^ r[3] ^ r[4] ^ r[5] ^ r[6] ^ r[7] + ^ (p[1] ^ p[2] ^ p[4] ^ p[5] ^ p[7] ^ r[1] ^ r[4] ^ r[5] ^ r[6]).rotate_right(16); + q[5] = p[2] ^ p[3] ^ p[4] ^ p[6] ^ r[2] ^ r[4] ^ r[5] ^ r[6] ^ r[7] + ^ (p[2] ^ p[3] ^ p[5] ^ p[6] ^ r[2] ^ r[5] ^ r[6] ^ r[7]).rotate_right(16); + q[6] = p[3] ^ p[4] ^ p[5] ^ p[7] ^ r[3] ^ r[5] ^ r[6] ^ r[7] + ^ (p[3] ^ p[4] ^ p[6] ^ p[7] ^ r[3] ^ r[6] ^ r[7]).rotate_right(16); + q[7] = p[4] ^ p[5] ^ p[6] ^ r[4] ^ r[6] ^ r[7] + ^ (p[4] ^ p[5] ^ p[7] ^ r[4] ^ r[7]).rotate_right(16); +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::bitslice::{pack, unpack}; + + /// Runs a plane transformation over one block placed in both halves, returning the A half. + fn apply(f: fn(&mut Planes), block: [u8; 16]) -> [u8; 16] { + let mut q = pack(&block, &block); + f(&mut q); + let mut a = [0u8; 16]; + let mut b = [0u8; 16]; + unpack(&q, &mut a, &mut b); + assert_eq!(a, b, "the two interleaved blocks must transform identically"); + a + } + + /// A block whose bytes are all distinct, so any mask error that moves a byte to the wrong + /// position is visible. + fn distinct_block() -> [u8; 16] { + core::array::from_fn(|i| (i as u8).wrapping_mul(17).wrapping_add(3)) + } + + // ---- byte-wise references, written from the FIPS 197 equations ---------------------- + // These use `state[r + 4c] == s[r,c]` (Eq 3.6). They exist only to check the plane + // implementations and are deliberately naive. + + /// Eq 5.5: `s'[r,c] = s[r,(c + r) mod 4]`. + fn ref_shift_rows(s: &[u8; 16]) -> [u8; 16] { + let mut o = [0u8; 16]; + for r in 0..4 { + for c in 0..4 { + o[r + 4 * c] = s[r + 4 * ((c + r) % 4)]; + } + } + o + } + + /// Eq 5.12: `s'[r,c] = s[r,(c - r) mod 4]`. + fn ref_inv_shift_rows(s: &[u8; 16]) -> [u8; 16] { + let mut o = [0u8; 16]; + for r in 0..4 { + for c in 0..4 { + o[r + 4 * c] = s[r + 4 * ((c + 4 - r) % 4)]; + } + } + o + } + + /// Eq 4.5 XTIMES(): multiply by `{02}` in GF(2^8). + fn xtimes(b: u8) -> u8 { + (b << 1) ^ if b & 0x80 != 0 { 0x1b } else { 0 } + } + + /// General GF(2^8) multiplication. Test-only; it branches on `b` and must never see secrets. + fn gf_mul(mut a: u8, mut b: u8) -> u8 { + let mut product = 0u8; + for _ in 0..8 { + if b & 1 != 0 { + product ^= a; + } + b >>= 1; + a = xtimes(a); + } + product + } + + /// Multiplication of a column by a fixed matrix, exactly as FIPS 197 Sec 4.3 defines it. + /// + /// Eq 4.8 gives the output word `[d0,d1,d2,d3]` from the input word `[b0,b1,b2,b3]` and the + /// matrix word `[a0,a1,a2,a3]`: + /// + /// ```text + /// d0 = (a0.b0) + (a3.b1) + (a2.b2) + (a1.b3) + /// d1 = (a1.b0) + (a0.b1) + (a3.b2) + (a2.b3) + /// d2 = (a2.b0) + (a1.b1) + (a0.b2) + (a3.b3) + /// d3 = (a3.b0) + (a2.b1) + (a1.b2) + (a0.b3) + /// ``` + /// + /// so entry `(r,k)` of the matrix is `a[(r - k) mod 4]`, which is what the indexing below is. + /// Both MIXCOLUMNS() and INVMIXCOLUMNS() use this same convention; only the word differs. + fn ref_mix_columns(s: &[u8; 16], coeffs: [u8; 4]) -> [u8; 16] { + let mut o = [0u8; 16]; + for c in 0..4 { + for r in 0..4 { + let mut v = 0u8; + for k in 0..4 { + v ^= gf_mul(s[k + 4 * c], coeffs[(r + 4 - k) % 4]); + } + o[r + 4 * c] = v; + } + } + o + } + + /// Eq 5.6: `[a0, a1, a2, a3] = [{02}, {01}, {01}, {03}]`. + /// + /// Note the order: it is *not* `[{02},{03},{01},{01}]`, which is the first row of the matrix + /// in Eq 5.7 rather than the defining word. Feeding the matrix row in here instead of the + /// word silently transposes the matrix, which happens to leave INVMIXCOLUMNS() passing, so + /// this is a comment worth keeping. + const MIX_COEFFS: [u8; 4] = [0x02, 0x01, 0x01, 0x03]; + /// Eq 5.13: `[a0, a1, a2, a3] = [{0e}, {09}, {0d}, {0b}]`. + const INV_MIX_COEFFS: [u8; 4] = [0x0e, 0x09, 0x0d, 0x0b]; + + /// Eq 5.8, transcribed literally, as a cross-check on [`ref_mix_columns`]. + /// + /// ```text + /// s'0,c = ({02}.s0,c) + ({03}.s1,c) + s2,c + s3,c + /// s'1,c = s0,c + ({02}.s1,c) + ({03}.s2,c) + s3,c + /// s'2,c = s0,c + s1,c + ({02}.s2,c) + ({03}.s3,c) + /// s'3,c = ({03}.s0,c) + s1,c + s2,c + ({02}.s3,c) + /// ``` + #[rustfmt::skip] + fn ref_mix_columns_literal(s: &[u8; 16]) -> [u8; 16] { + let mut o = [0u8; 16]; + for c in 0..4 { + let (s0, s1, s2, s3) = (s[4 * c], s[4 * c + 1], s[4 * c + 2], s[4 * c + 3]); + o[4 * c] = gf_mul(0x02, s0) ^ gf_mul(0x03, s1) ^ s2 ^ s3; + o[4 * c + 1] = s0 ^ gf_mul(0x02, s1) ^ gf_mul(0x03, s2) ^ s3; + o[4 * c + 2] = s0 ^ s1 ^ gf_mul(0x02, s2) ^ gf_mul(0x03, s3); + o[4 * c + 3] = gf_mul(0x03, s0) ^ s1 ^ s2 ^ gf_mul(0x02, s3); + } + o + } + + /// Eq 5.15, transcribed literally, as a cross-check on [`ref_mix_columns`]. + /// + /// ```text + /// s'0,c = ({0e}.s0,c) + ({0b}.s1,c) + ({0d}.s2,c) + ({09}.s3,c) + /// s'1,c = ({09}.s0,c) + ({0e}.s1,c) + ({0b}.s2,c) + ({0d}.s3,c) + /// s'2,c = ({0d}.s0,c) + ({09}.s1,c) + ({0e}.s2,c) + ({0b}.s3,c) + /// s'3,c = ({0b}.s0,c) + ({0d}.s1,c) + ({09}.s2,c) + ({0e}.s3,c) + /// ``` + #[rustfmt::skip] + fn ref_inv_mix_columns_literal(s: &[u8; 16]) -> [u8; 16] { + let mut o = [0u8; 16]; + for c in 0..4 { + let (s0, s1, s2, s3) = (s[4 * c], s[4 * c + 1], s[4 * c + 2], s[4 * c + 3]); + o[4 * c] = gf_mul(0x0e, s0) ^ gf_mul(0x0b, s1) ^ gf_mul(0x0d, s2) ^ gf_mul(0x09, s3); + o[4 * c + 1] = gf_mul(0x09, s0) ^ gf_mul(0x0e, s1) ^ gf_mul(0x0b, s2) ^ gf_mul(0x0d, s3); + o[4 * c + 2] = gf_mul(0x0d, s0) ^ gf_mul(0x09, s1) ^ gf_mul(0x0e, s2) ^ gf_mul(0x0b, s3); + o[4 * c + 3] = gf_mul(0x0b, s0) ^ gf_mul(0x0d, s1) ^ gf_mul(0x09, s2) ^ gf_mul(0x0e, s3); + } + o + } + + // ---- tests -------------------------------------------------------------------------- + + #[test] + fn test_the_two_reference_forms_agree() { + // Eq 5.7 (matrix, via the Sec 4.3 convention) against Eq 5.8 (explicit bytes), and the + // same for Eq 5.14 against Eq 5.15. This is what pins the coefficient word order: get + // MIX_COEFFS wrong and these disagree, independently of the plane implementation. + for seed in 0..32u8 { + let block: [u8; 16] = core::array::from_fn(|i| (i as u8).wrapping_mul(37) ^ seed); + assert_eq!(ref_mix_columns(&block, MIX_COEFFS), ref_mix_columns_literal(&block)); + assert_eq!( + ref_mix_columns(&block, INV_MIX_COEFFS), + ref_inv_mix_columns_literal(&block) + ); + } + } + + #[test] + fn test_xtimes_reference_matches_the_spec_example() { + // FIPS 197 Sec 4.2 works through {57} . {13}; the intermediate XTIMES() chain from + // Eq 4.5 is {57}, {ae}, {47}, {8e}, {07}. + assert_eq!(xtimes(0x57), 0xae); + assert_eq!(xtimes(0xae), 0x47); + assert_eq!(xtimes(0x47), 0x8e); + assert_eq!(xtimes(0x8e), 0x07); + // and the product itself, {57} . {13} = {fe}. + assert_eq!(gf_mul(0x57, 0x13), 0xfe); + } + + #[test] + fn test_shift_rows_matches_equation_5_5() { + for seed in 0..32u8 { + let block: [u8; 16] = core::array::from_fn(|i| (i as u8).wrapping_mul(31) ^ seed); + assert_eq!(apply(shift_rows, block), ref_shift_rows(&block)); + } + assert_eq!(apply(shift_rows, distinct_block()), ref_shift_rows(&distinct_block())); + } + + #[test] + fn test_inv_shift_rows_matches_equation_5_12() { + for seed in 0..32u8 { + let block: [u8; 16] = core::array::from_fn(|i| (i as u8).wrapping_mul(31) ^ seed); + assert_eq!(apply(inv_shift_rows, block), ref_inv_shift_rows(&block)); + } + } + + #[test] + fn test_inv_shift_rows_inverts_shift_rows() { + let block = distinct_block(); + let mut q = pack(&block, &block); + shift_rows(&mut q); + inv_shift_rows(&mut q); + let mut a = [0u8; 16]; + let mut b = [0u8; 16]; + unpack(&q, &mut a, &mut b); + assert_eq!(a, block); + } + + #[test] + fn test_shift_rows_is_a_bit_permutation() { + // Push a single set bit through and require exactly one bit out, with the induced map on + // bit positions a bijection. That is the real invariant behind the seven masked terms: + // their destination ranges are pairwise disjoint and together cover all 32 bits. + // + // It also explains a known `cargo mutants` result. The `| -> ^` mutants in [`shift_rows`] + // and [`inv_shift_rows`] survive, because on disjoint operands `|` and `^` compute the + // same function -- they are equivalent programs, not a gap in the tests, and no test can + // kill them. What *would* be a bug is masks that overlap or fail to cover, and this test + // is what rules that out. + for (name, f) in [ + ("shift_rows", shift_rows as fn(&mut Planes)), + ("inv_shift_rows", inv_shift_rows as fn(&mut Planes)), + ] { + let mut destinations = [false; 32]; + for bit in 0..32 { + let mut q: Planes = [1u32 << bit; 8]; + f(&mut q); + for plane in q { + assert_eq!( + plane.count_ones(), + 1, + "{name}: bit {bit} must map to exactly one bit, got {plane:#034b}" + ); + } + let dest = q[0].trailing_zeros() as usize; + assert!(!destinations[dest], "{name}: two source bits both map to bit {dest}"); + destinations[dest] = true; + } + assert!( + destinations.iter().all(|&hit| hit), + "{name}: the masks must cover all 32 bit positions" + ); + } + } + + #[test] + fn test_shift_rows_leaves_row_zero_alone() { + // Row 0 is bytes 0, 4, 8, 12 in the Eq 3.6 layout, and Eq 5.5 does not move it. + let block = distinct_block(); + let out = apply(shift_rows, block); + for c in 0..4 { + assert_eq!(out[4 * c], block[4 * c], "row 0, column {c}"); + } + } + + #[test] + fn test_mix_columns_matches_equation_5_8() { + for seed in 0..32u8 { + let block: [u8; 16] = core::array::from_fn(|i| (i as u8).wrapping_mul(37) ^ seed); + assert_eq!(apply(mix_columns, block), ref_mix_columns(&block, MIX_COEFFS)); + } + assert_eq!( + apply(mix_columns, distinct_block()), + ref_mix_columns(&distinct_block(), MIX_COEFFS) + ); + } + + #[test] + fn test_inv_mix_columns_matches_equation_5_15() { + for seed in 0..32u8 { + let block: [u8; 16] = core::array::from_fn(|i| (i as u8).wrapping_mul(37) ^ seed); + assert_eq!(apply(inv_mix_columns, block), ref_mix_columns(&block, INV_MIX_COEFFS)); + } + } + + #[test] + fn test_inv_mix_columns_inverts_mix_columns() { + let block = distinct_block(); + let mut q = pack(&block, &block); + mix_columns(&mut q); + inv_mix_columns(&mut q); + let mut a = [0u8; 16]; + let mut b = [0u8; 16]; + unpack(&q, &mut a, &mut b); + assert_eq!(a, block); + } + + #[test] + fn test_add_round_key_is_its_own_inverse() { + let block = distinct_block(); + let key = pack(&[0xA5u8; 16], &[0x5Au8; 16]); + let mut q = pack(&block, &block); + add_round_key(&mut q, &key); + add_round_key(&mut q, &key); + let mut a = [0u8; 16]; + let mut b = [0u8; 16]; + unpack(&q, &mut a, &mut b); + assert_eq!(a, block); + } + + #[test] + fn test_add_round_key_xors_the_expected_bytes() { + let block = distinct_block(); + let key_block = [0xA5u8; 16]; + let key = pack(&key_block, &key_block); + let mut q = pack(&block, &block); + add_round_key(&mut q, &key); + let mut a = [0u8; 16]; + let mut b = [0u8; 16]; + unpack(&q, &mut a, &mut b); + for i in 0..16 { + assert_eq!(a[i], block[i] ^ key_block[i]); + } + } +} diff --git a/crypto/aes-lowmemory/src/sbox.rs b/crypto/aes-lowmemory/src/sbox.rs new file mode 100644 index 00000000..8e68d2e3 --- /dev/null +++ b/crypto/aes-lowmemory/src/sbox.rs @@ -0,0 +1,381 @@ +//! SUBBYTES() and INVSUBBYTES() as a Boolean circuit (FIPS 197 Sec 5.1.1 and Sec 5.3.2). +//! +//! # Why a circuit and not a table +//! +//! FIPS 197 Sec 5.1.1 presents the S-box as a 256-entry lookup table (Table 4). A table lookup +//! indexed by a byte of the state is indexed by *secret data*, and on any CPU with a data cache +//! the access pattern -- hence the timing -- depends on that secret. That is the standard AES +//! cache-timing side channel, and it cannot be closed while keeping the lookup. +//! +//! So this module does not have a table. It computes the same function as Table 4 with AND, XOR +//! and XNOR gates applied to the bit-planes described in [`crate::bitslice`]. Every operation is +//! a straight-line word operation on public *positions*, so there is no secret-dependent memory +//! access and no secret-dependent branch. The two functions here are the only place in the crate +//! where secret data meets non-linear logic; everything else is XOR, rotate and mask. +//! +//! Because the planes hold sixteen byte positions of two blocks at once, one pass of the circuit +//! substitutes all 32 bytes -- the whole SUBBYTES() transformation of two blocks -- rather than +//! one byte. +//! +//! # What the circuit computes +//! +//! FIPS 197 Sec 5.1.1 defines the S-box as inversion in GF(2^8) followed by an affine map +//! (Eq. 5.2), tabulated in Table 4. The circuit below is the 113-gate straight-line program of +//! Boyar and Peralta -- 32 AND, 77 XOR and 4 XNOR gates -- which computes exactly that, +//! including the affine map and its `{63}` constant (the constant is folded into the four XNORs +//! at the end of the bottom linear transformation). +//! +//! Sources: +//! * The straight-line program `SLP_AES_113.txt`, from Peralta's circuit collection. +//! * J. Boyar and R. Peralta, "A new combinational logic minimization technique with +//! applications to cryptology", . +//! * The same circuit appears in BearSSL `aes_ct.c:br_aes_ct_bitslice_Sbox` (MIT, Thomas +//! Pornin), whose variable naming is kept here so the two can be diffed. BearSSL re-associates +//! two gates in the non-linear section (its `t17`/`t21` differ from the SLP file, computing the +//! same `t21`) and uses a different but equivalent bottom linear transformation; where they +//! disagree this file follows `SLP_AES_113.txt`. +//! +//! The gate list is a mechanical transcription of `SLP_AES_113.txt`: `+` became `^`, `x` became +//! `&`, `#` became `!(.. ^ ..)`, and the SLP variable names are unchanged apart from case. It is +//! not independently meaningful line by line and should not be "tidied"; it is verified as a +//! whole by `test_sbox_matches_fips197_table_4`, which checks all 256 inputs against Table 4. +//! +//! # Bit numbering +//! +//! The SLP numbers its inputs `U0..U7` and outputs `S0..S7` with **`U0` as the most significant +//! bit** of the byte, which is the reverse of the plane index. So `U0` is plane `q[7]` and `U7` +//! is plane `q[0]`, and likewise for the outputs. `test_sbox_matches_fips197_table_4` is what +//! pins this down -- reversing it produces a wrong S-box, not a subtly different one. + +use crate::bitslice::Planes; + +/// SUBBYTES(): applies the AES S-box to every byte position of both blocks in `q` +/// (FIPS 197 Sec 5.1.1, the transformation tabulated in Table 4). +/// +/// The 113-gate Boyar-Peralta circuit, transcribed from `SLP_AES_113.txt`. See the module docs. +pub(crate) fn sbox(q: &mut Planes) { + // SLP inputs U0..U7, most-significant bit first, so U0 is the highest plane. + let u0 = q[7]; + let u1 = q[6]; + let u2 = q[5]; + let u3 = q[4]; + let u4 = q[3]; + let u5 = q[2]; + let u6 = q[1]; + let u7 = q[0]; + + // Top linear transformation (23 gates): the input basis change. + let y14 = u3 ^ u5; + let y13 = u0 ^ u6; + let y9 = u0 ^ u3; + let y8 = u0 ^ u5; + let t0 = u1 ^ u2; + let y1 = t0 ^ u7; + let y4 = y1 ^ u3; + let y12 = y13 ^ y14; + let y2 = y1 ^ u0; + let y5 = y1 ^ u6; + let y3 = y5 ^ y8; + let t1 = u4 ^ y12; + let y15 = t1 ^ u5; + let y20 = t1 ^ u1; + let y6 = y15 ^ u7; + let y10 = y15 ^ t0; + let y11 = y20 ^ y9; + let y7 = u7 ^ y11; + let y17 = y10 ^ y11; + let y19 = y10 ^ y8; + let y16 = t0 ^ y11; + let y21 = y13 ^ y16; + let y18 = u0 ^ y16; + + // Non-linear section (62 gates): the GF(2^8) inversion, and the only ANDs in the circuit. + let t2 = y12 & y15; + let t3 = y3 & y6; + let t4 = t3 ^ t2; + let t5 = y4 & u7; + let t6 = t5 ^ t2; + let t7 = y13 & y16; + let t8 = y5 & y1; + let t9 = t8 ^ t7; + let t10 = y2 & y7; + let t11 = t10 ^ t7; + let t12 = y9 & y11; + let t13 = y14 & y17; + let t14 = t13 ^ t12; + let t15 = y8 & y10; + let t16 = t15 ^ t12; + let t17 = t4 ^ y20; + let t18 = t6 ^ t16; + let t19 = t9 ^ t14; + let t20 = t11 ^ t16; + let t21 = t17 ^ t14; + let t22 = t18 ^ y19; + let t23 = t19 ^ y21; + let t24 = t20 ^ y18; + let t25 = t21 ^ t22; + let t26 = t21 & t23; + let t27 = t24 ^ t26; + let t28 = t25 & t27; + let t29 = t28 ^ t22; + let t30 = t23 ^ t24; + let t31 = t22 ^ t26; + let t32 = t31 & t30; + let t33 = t32 ^ t24; + let t34 = t23 ^ t33; + let t35 = t27 ^ t33; + let t36 = t24 & t35; + // `cargo mutants` reports the `^ -> |` mutant on the next line as surviving. That is a true + // equivalence, not a gap: `t36` and `t34` are never both 1 for any of the 256 possible input + // bytes, so XOR and OR agree here. It is the only one of the circuit's 77 XOR gates with that + // property -- every other `^ -> |` mutant is killed by `test_sbox_matches_fips197_table_4`. + let t37 = t36 ^ t34; + let t38 = t27 ^ t36; + let t39 = t29 & t38; + let t40 = t25 ^ t39; + let t41 = t40 ^ t37; + let t42 = t29 ^ t33; + let t43 = t29 ^ t40; + let t44 = t33 ^ t37; + let t45 = t42 ^ t41; + let z0 = t44 & y15; + let z1 = t37 & y6; + let z2 = t33 & u7; + let z3 = t43 & y16; + let z4 = t40 & y1; + let z5 = t29 & y7; + let z6 = t42 & y11; + let z7 = t45 & y17; + let z8 = t41 & y10; + let z9 = t44 & y12; + let z10 = t37 & y3; + let z11 = t33 & y4; + let z12 = t43 & y13; + let z13 = t40 & y5; + let z14 = t29 & y2; + let z15 = t42 & y9; + let z16 = t45 & y14; + let z17 = t41 & y8; + + // Bottom linear transformation (28 gates): the output basis change and the affine map of + // Eq. 5.2, whose `{63}` constant is the four XNORs below. + let tc1 = z15 ^ z16; + let tc2 = z10 ^ tc1; + let tc3 = z9 ^ tc2; + let tc4 = z0 ^ z2; + let tc5 = z1 ^ z0; + let tc6 = z3 ^ z4; + let tc7 = z12 ^ tc4; + let tc8 = z7 ^ tc6; + let tc9 = z8 ^ tc7; + let tc10 = tc8 ^ tc9; + let tc11 = tc6 ^ tc5; + let tc12 = z3 ^ z5; + let tc13 = z13 ^ tc1; + let tc14 = tc4 ^ tc12; + let s3 = tc3 ^ tc11; + let tc16 = z6 ^ tc8; + let tc17 = z14 ^ tc10; + let tc18 = tc13 ^ tc14; + let s7 = !(z12 ^ tc18); + let tc20 = z15 ^ tc16; + let tc21 = tc2 ^ z11; + let s0 = tc3 ^ tc16; + let s6 = !(tc10 ^ tc18); + let s4 = tc14 ^ s3; + let s1 = !(s3 ^ tc16); + let tc26 = tc17 ^ tc20; + let s2 = !(tc26 ^ z17); + let s5 = tc21 ^ tc17; + + // SLP outputs S0..S7, most-significant bit first, mirroring the input mapping. + q[7] = s0; + q[6] = s1; + q[5] = s2; + q[4] = s3; + q[3] = s4; + q[2] = s5; + q[1] = s6; + q[0] = s7; +} + +/// INVSUBBYTES(): applies the inverse AES S-box to every byte position of both blocks in `q` +/// (FIPS 197 Sec 5.3.2, the transformation tabulated in Table 6). +/// +/// Rather than a second 113-gate circuit, this reuses [`sbox`] by conjugating it with the +/// inverse of its affine layer. Writing the S-box of Eq. 5.2 as `S(x) = A(I(x)) ^ {63}`, where +/// `I` is inversion in GF(2^8) and `A` the linear part, and letting `B` be the inverse of `A`: +/// +/// ```text +/// iS(x) = B(S(B(x ^ {63})) ^ {63}) +/// ``` +/// +/// which holds because `I` is an involution: +/// `iS(S(y)) = B(A(I(B(A(I(y)) ^ {63} ^ {63}))) ^ {63} ^ {63}) = y`. +/// +/// So applying [`inv_affine`], then the forward circuit, then [`inv_affine`] again yields the +/// inverse S-box, at the cost of 16 extra XORs and 8 complements instead of a whole second +/// circuit. Verified exhaustively against Table 6 by `test_inv_sbox_matches_fips197_table_6`. +/// +/// The derivation and the layer below are from BearSSL `aes_ct_dec.c` +/// (`br_aes_ct_bitslice_invSbox`). +pub(crate) fn inv_sbox(q: &mut Planes) { + inv_affine(q); + sbox(q); + inv_affine(q); +} + +/// `B(x ^ {63})`: the inverse of the affine layer of Eq. 5.2, composed with the constant. +/// +/// The complements on planes 0, 1, 5 and 6 are the `^ {63}`; the eight three-term XORs are `B`. +/// Translated from BearSSL `aes_ct_dec.c:br_aes_ct_bitslice_invSbox`. +fn inv_affine(q: &mut Planes) { + let q0 = !q[0]; + let q1 = !q[1]; + let q2 = q[2]; + let q3 = q[3]; + let q4 = q[4]; + let q5 = !q[5]; + let q6 = !q[6]; + let q7 = q[7]; + q[7] = q1 ^ q4 ^ q6; + q[6] = q0 ^ q3 ^ q5; + q[5] = q7 ^ q2 ^ q4; + q[4] = q6 ^ q1 ^ q3; + q[3] = q5 ^ q0 ^ q2; + q[2] = q4 ^ q7 ^ q1; + q[1] = q3 ^ q6 ^ q0; + q[0] = q2 ^ q5 ^ q7; +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::bitslice::{pack, unpack}; + + /// FIPS 197 Table 4 (SBOX), transcribed from the published PDF. Test-only: the + /// implementation evaluates the S-box as a Boolean circuit and never indexes a table. + #[rustfmt::skip] + const SBOX_TABLE_4: [u8; 256] = [ + 0x63, 0x7c, 0x77, 0x7b, 0xf2, 0x6b, 0x6f, 0xc5, 0x30, 0x01, 0x67, 0x2b, 0xfe, 0xd7, 0xab, 0x76, + 0xca, 0x82, 0xc9, 0x7d, 0xfa, 0x59, 0x47, 0xf0, 0xad, 0xd4, 0xa2, 0xaf, 0x9c, 0xa4, 0x72, 0xc0, + 0xb7, 0xfd, 0x93, 0x26, 0x36, 0x3f, 0xf7, 0xcc, 0x34, 0xa5, 0xe5, 0xf1, 0x71, 0xd8, 0x31, 0x15, + 0x04, 0xc7, 0x23, 0xc3, 0x18, 0x96, 0x05, 0x9a, 0x07, 0x12, 0x80, 0xe2, 0xeb, 0x27, 0xb2, 0x75, + 0x09, 0x83, 0x2c, 0x1a, 0x1b, 0x6e, 0x5a, 0xa0, 0x52, 0x3b, 0xd6, 0xb3, 0x29, 0xe3, 0x2f, 0x84, + 0x53, 0xd1, 0x00, 0xed, 0x20, 0xfc, 0xb1, 0x5b, 0x6a, 0xcb, 0xbe, 0x39, 0x4a, 0x4c, 0x58, 0xcf, + 0xd0, 0xef, 0xaa, 0xfb, 0x43, 0x4d, 0x33, 0x85, 0x45, 0xf9, 0x02, 0x7f, 0x50, 0x3c, 0x9f, 0xa8, + 0x51, 0xa3, 0x40, 0x8f, 0x92, 0x9d, 0x38, 0xf5, 0xbc, 0xb6, 0xda, 0x21, 0x10, 0xff, 0xf3, 0xd2, + 0xcd, 0x0c, 0x13, 0xec, 0x5f, 0x97, 0x44, 0x17, 0xc4, 0xa7, 0x7e, 0x3d, 0x64, 0x5d, 0x19, 0x73, + 0x60, 0x81, 0x4f, 0xdc, 0x22, 0x2a, 0x90, 0x88, 0x46, 0xee, 0xb8, 0x14, 0xde, 0x5e, 0x0b, 0xdb, + 0xe0, 0x32, 0x3a, 0x0a, 0x49, 0x06, 0x24, 0x5c, 0xc2, 0xd3, 0xac, 0x62, 0x91, 0x95, 0xe4, 0x79, + 0xe7, 0xc8, 0x37, 0x6d, 0x8d, 0xd5, 0x4e, 0xa9, 0x6c, 0x56, 0xf4, 0xea, 0x65, 0x7a, 0xae, 0x08, + 0xba, 0x78, 0x25, 0x2e, 0x1c, 0xa6, 0xb4, 0xc6, 0xe8, 0xdd, 0x74, 0x1f, 0x4b, 0xbd, 0x8b, 0x8a, + 0x70, 0x3e, 0xb5, 0x66, 0x48, 0x03, 0xf6, 0x0e, 0x61, 0x35, 0x57, 0xb9, 0x86, 0xc1, 0x1d, 0x9e, + 0xe1, 0xf8, 0x98, 0x11, 0x69, 0xd9, 0x8e, 0x94, 0x9b, 0x1e, 0x87, 0xe9, 0xce, 0x55, 0x28, 0xdf, + 0x8c, 0xa1, 0x89, 0x0d, 0xbf, 0xe6, 0x42, 0x68, 0x41, 0x99, 0x2d, 0x0f, 0xb0, 0x54, 0xbb, 0x16, + ]; + + /// FIPS 197 Table 6 (INVSBOX), transcribed from the published PDF. Test-only. + #[rustfmt::skip] + const INVSBOX_TABLE_6: [u8; 256] = [ + 0x52, 0x09, 0x6a, 0xd5, 0x30, 0x36, 0xa5, 0x38, 0xbf, 0x40, 0xa3, 0x9e, 0x81, 0xf3, 0xd7, 0xfb, + 0x7c, 0xe3, 0x39, 0x82, 0x9b, 0x2f, 0xff, 0x87, 0x34, 0x8e, 0x43, 0x44, 0xc4, 0xde, 0xe9, 0xcb, + 0x54, 0x7b, 0x94, 0x32, 0xa6, 0xc2, 0x23, 0x3d, 0xee, 0x4c, 0x95, 0x0b, 0x42, 0xfa, 0xc3, 0x4e, + 0x08, 0x2e, 0xa1, 0x66, 0x28, 0xd9, 0x24, 0xb2, 0x76, 0x5b, 0xa2, 0x49, 0x6d, 0x8b, 0xd1, 0x25, + 0x72, 0xf8, 0xf6, 0x64, 0x86, 0x68, 0x98, 0x16, 0xd4, 0xa4, 0x5c, 0xcc, 0x5d, 0x65, 0xb6, 0x92, + 0x6c, 0x70, 0x48, 0x50, 0xfd, 0xed, 0xb9, 0xda, 0x5e, 0x15, 0x46, 0x57, 0xa7, 0x8d, 0x9d, 0x84, + 0x90, 0xd8, 0xab, 0x00, 0x8c, 0xbc, 0xd3, 0x0a, 0xf7, 0xe4, 0x58, 0x05, 0xb8, 0xb3, 0x45, 0x06, + 0xd0, 0x2c, 0x1e, 0x8f, 0xca, 0x3f, 0x0f, 0x02, 0xc1, 0xaf, 0xbd, 0x03, 0x01, 0x13, 0x8a, 0x6b, + 0x3a, 0x91, 0x11, 0x41, 0x4f, 0x67, 0xdc, 0xea, 0x97, 0xf2, 0xcf, 0xce, 0xf0, 0xb4, 0xe6, 0x73, + 0x96, 0xac, 0x74, 0x22, 0xe7, 0xad, 0x35, 0x85, 0xe2, 0xf9, 0x37, 0xe8, 0x1c, 0x75, 0xdf, 0x6e, + 0x47, 0xf1, 0x1a, 0x71, 0x1d, 0x29, 0xc5, 0x89, 0x6f, 0xb7, 0x62, 0x0e, 0xaa, 0x18, 0xbe, 0x1b, + 0xfc, 0x56, 0x3e, 0x4b, 0xc6, 0xd2, 0x79, 0x20, 0x9a, 0xdb, 0xc0, 0xfe, 0x78, 0xcd, 0x5a, 0xf4, + 0x1f, 0xdd, 0xa8, 0x33, 0x88, 0x07, 0xc7, 0x31, 0xb1, 0x12, 0x10, 0x59, 0x27, 0x80, 0xec, 0x5f, + 0x60, 0x51, 0x7f, 0xa9, 0x19, 0xb5, 0x4a, 0x0d, 0x2d, 0xe5, 0x7a, 0x9f, 0x93, 0xc9, 0x9c, 0xef, + 0xa0, 0xe0, 0x3b, 0x4d, 0xae, 0x2a, 0xf5, 0xb0, 0xc8, 0xeb, 0xbb, 0x3c, 0x83, 0x53, 0x99, 0x61, + 0x17, 0x2b, 0x04, 0x7e, 0xba, 0x77, 0xd6, 0x26, 0xe1, 0x69, 0x14, 0x63, 0x55, 0x21, 0x0c, 0x7d, + ]; + + /// Runs a plane transformation over a block placed in both halves, returning the A half. + /// + /// Filling both halves means a wrong interleave shows up as a difference between the two + /// blocks rather than silently passing. + fn apply(f: fn(&mut Planes), block: [u8; 16]) -> [u8; 16] { + let mut q = pack(&block, &block); + f(&mut q); + let mut a = [0u8; 16]; + let mut b = [0u8; 16]; + unpack(&q, &mut a, &mut b); + assert_eq!(a, b, "the two interleaved blocks must transform identically"); + a + } + + #[test] + fn test_sbox_matches_fips197_table_4() { + // Exhaustive over the whole domain: this is the test that makes the 113 gates + // trustworthy, so it must stay exhaustive. + for x in 0..=255u8 { + let out = apply(sbox, [x; 16]); + assert!( + out.iter().all(|&b| b == out[0]), + "all 16 byte positions must substitute alike, x={x:#04x}" + ); + assert_eq!( + out[0], SBOX_TABLE_4[x as usize], + "SBOX({x:#04x}) should be {:#04x}", + SBOX_TABLE_4[x as usize] + ); + } + } + + #[test] + fn test_inv_sbox_matches_fips197_table_6() { + for x in 0..=255u8 { + let out = apply(inv_sbox, [x; 16]); + assert_eq!( + out[0], INVSBOX_TABLE_6[x as usize], + "INVSBOX({x:#04x}) should be {:#04x}", + INVSBOX_TABLE_6[x as usize] + ); + } + } + + #[test] + fn test_inv_sbox_inverts_sbox() { + for x in 0..=255u8 { + let mut q = pack(&[x; 16], &[x.wrapping_add(1); 16]); + sbox(&mut q); + inv_sbox(&mut q); + let mut a = [0u8; 16]; + let mut b = [0u8; 16]; + unpack(&q, &mut a, &mut b); + assert_eq!(a, [x; 16]); + assert_eq!(b, [x.wrapping_add(1); 16]); + } + } + + #[test] + fn test_sbox_worked_example_from_section_5_1_1() { + // FIPS 197 Sec 5.1.1: "if s(r,c) = {53} ... s'(r,c) = {ed}". + assert_eq!(apply(sbox, [0x53; 16])[0], 0xed); + assert_eq!(SBOX_TABLE_4[0x53], 0xed); + } + + #[test] + fn test_the_two_spec_tables_are_inverses() { + // Guards the transcription of both tables against a typo in either one. + for x in 0..=255u8 { + assert_eq!(INVSBOX_TABLE_6[SBOX_TABLE_4[x as usize] as usize], x); + } + } + + #[test] + fn test_sbox_operates_on_each_byte_position_independently() { + // A block of distinct values, so a mask error that mixes byte positions is caught. + let block: [u8; 16] = core::array::from_fn(|i| (i as u8) * 17); + let out = apply(sbox, block); + for i in 0..16 { + assert_eq!(out[i], SBOX_TABLE_4[block[i] as usize], "byte position {i}"); + } + } +} diff --git a/crypto/aes-lowmemory/src/schedule.rs b/crypto/aes-lowmemory/src/schedule.rs new file mode 100644 index 00000000..9ae50e38 --- /dev/null +++ b/crypto/aes-lowmemory/src/schedule.rs @@ -0,0 +1,461 @@ +//! KEYEXPANSION() (FIPS 197 Sec 5.2, Algorithm 2) and the per-key-length parameters. +//! +//! # Storage +//! +//! The schedule is `4 * (Nr + 1)` words -- 44, 52 or 60 -- exactly as FIPS 197 Sec 5.2 defines +//! it, so 176, 208 or 240 bytes. It is stored in a **compressed** bit-sliced form: because +//! bit-slicing is a permutation of bits it does not change the size, and because both interleaved +//! blocks are encrypted under the same key the two halves of a bit-sliced round key are +//! identical, so only one of every pair of words needs keeping. [`round_key`] re-doubles a single +//! round key onto the stack when the round loop needs it. +//! +//! The alternative -- storing the doubled 8-plane form -- would need 352, 416 or 480 bytes, and +//! holding the classical schedule *and* a bit-sliced copy would be worse still. Since low memory +//! is the point of this crate, neither is done: [`expand`] writes the classical schedule into the +//! final array and then rewrites it in place, one round key at a time, using eight words of +//! stack. In particular it does not mirror BearSSL's `uint32_t skey[120]` (480-byte) scratch +//! buffer. +//! +//! # Constant-time +//! +//! The key is secret, so SUBWORD() in the expansion has the same table-lookup problem as +//! SUBBYTES() in the cipher, and gets the same treatment: [`sub_word`] routes the word through +//! the bit-sliced circuit in [`crate::sbox`]. A table-driven "light" AES that only removes the +//! tables from the cipher, and not from the key schedule, still leaks through the schedule. + +use crate::bitslice::{Planes, ortho}; +use crate::sbox::sbox; +use bouncycastle_utils::secret::{Secret, ZeroizablePrimitive}; + +/// FIPS 197 Sec 5.2, Table 5: the round constants, `Rcon[j]` for `1 <= j <= 10`. +/// +/// Table 5 gives each as the word `[x, 00, 00, 00]`; only the leftmost byte is ever non-zero, and +/// words are held little-endian here, so the word `Rcon[j]` is just this byte. Indexing is shifted +/// by one against the spec: `RCON[j - 1]` is the spec's `Rcon[j]`, since the spec counts from 1. +const RCON: [u32; 10] = [0x01, 0x02, 0x04, 0x08, 0x10, 0x20, 0x40, 0x80, 0x1b, 0x36]; + +/// Prevents a fourth parameter set from being added outside this crate. +/// +/// FIPS 197 Sec 6.1 defines exactly three: AES-128, AES-192 and AES-256. Because [`AesParams`] +/// has this private supertrait, only the three types in this module can implement it, so no +/// downstream crate can instantiate the cipher with an unapproved key length or round count. +trait AesParamsSealed {} + +/// The per-key-length constants of FIPS 197 Sec 6.1. +/// +/// This is a trait rather than const generic parameters because the schedule length +/// `4 * (Nr + 1)` cannot be written as an expression over another const parameter on stable +/// const-generics; each implementation spells its own array type out instead. The same pattern is +/// used by the `HashDRBG80090AParams_*` types in `bouncycastle-rng`. +/// +/// Sealed via a private supertrait, so the three types below are the only implementations. +pub trait AesParams: AesParamsSealed { + /// Key length in bytes: 16, 24 or 32 (FIPS 197 Sec 6.1). + const KEY_LEN: usize; + /// `Nk`, the key length in 32-bit words: 4, 6 or 8 (FIPS 197 Sec 6.1). + const NK: usize; + /// `Nr`, the number of rounds: 10, 12 or 14 (FIPS 197 Sec 6.1). + const NR: usize; + /// The algorithm name, as reported by `Algorithm::ALG_NAME`. + const ALG_NAME: &'static str; + /// `[u32; 4 * (NR + 1)]` -- the compressed schedule. See the module docs. + type Schedule: ZeroizablePrimitive + AsRef<[u32]> + AsMut<[u32]>; +} + +/// AES-128 parameters: 16-byte key, `Nk` = 4, `Nr` = 10 (FIPS 197 Sec 6.1). +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub struct Aes128Params; +/// AES-192 parameters: 24-byte key, `Nk` = 6, `Nr` = 12 (FIPS 197 Sec 6.1). +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub struct Aes192Params; +/// AES-256 parameters: 32-byte key, `Nk` = 8, `Nr` = 14 (FIPS 197 Sec 6.1). +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub struct Aes256Params; + +impl AesParamsSealed for Aes128Params {} +impl AesParamsSealed for Aes192Params {} +impl AesParamsSealed for Aes256Params {} + +impl AesParams for Aes128Params { + const KEY_LEN: usize = 16; + const NK: usize = 4; + const NR: usize = 10; + const ALG_NAME: &'static str = "AES-128"; + type Schedule = [u32; 44]; // 4 * (10 + 1) +} + +impl AesParams for Aes192Params { + const KEY_LEN: usize = 24; + const NK: usize = 6; + const NR: usize = 12; + const ALG_NAME: &'static str = "AES-192"; + type Schedule = [u32; 52]; // 4 * (12 + 1) +} + +impl AesParams for Aes256Params { + const KEY_LEN: usize = 32; + const NK: usize = 8; + const NR: usize = 14; + const ALG_NAME: &'static str = "AES-256"; + type Schedule = [u32; 60]; // 4 * (14 + 1) +} + +/// ROTWORD(): `[a0,a1,a2,a3] -> [a1,a2,a3,a0]` (FIPS 197 Sec 5.2, Eq 5.10). +/// +/// Words are held little-endian, so `a0` is the low byte. Moving `a1` down into the low byte and +/// wrapping `a0` to the top is a rotate right by 8 of the whole word. +#[inline(always)] +fn rot_word(word: u32) -> u32 { + word.rotate_right(8) +} + +/// SUBWORD(): applies the S-box to each of the four bytes of a word +/// (FIPS 197 Sec 5.2, Eq 5.11). +/// +/// The key is secret, so this must not be a table lookup. It reuses the bit-sliced circuit +/// instead, by replicating `word` into all eight planes before transposing: +/// +/// after [`ortho`], plane `q[k]` bit `8L + i` equals bit `8L + k` of the *input* word `q[i]` -- +/// and every input word is the same `word`, so that bit is bit `k` of byte `L` of `word` +/// regardless of `i`. In the layout of [`crate::bitslice`], the bit positions `8L + i` for +/// `i = 0..8` are all four columns of row `L`, in both blocks. So the transposed state holds byte +/// `L` of `word` in every position of row `L`, one S-box pass substitutes all four bytes (sixteen +/// times over, redundantly), and transposing back reassembles the word. All eight planes then +/// hold the same result, so `q[0]` is SUBWORD(`word`); `test_sub_word_fills_every_plane` checks +/// that. +/// +/// It costs a full 113-gate S-box evaluation to substitute four bytes, which is wasteful, but it +/// happens `Nr` or so times per key rather than per block. Translated from BearSSL +/// `aes_ct.c:sub_word`. +fn sub_word(word: u32) -> u32 { + let mut q: Planes = [word; 8]; + ortho(&mut q); + sbox(&mut q); + ortho(&mut q); + q[0] +} + +/// KEYEXPANSION() (FIPS 197 Sec 5.2, Algorithm 2), returning the compressed bit-sliced schedule. +/// +/// `key` must be exactly `P::KEY_LEN` bytes; [`crate::aes`] checks that before calling, so this +/// cannot fail and takes no `Result`. +/// +/// Algorithm 2 is followed literally -- lines 2-6 copy the key into `w[0..Nk]`, lines 7-16 derive +/// the rest -- and then the finished schedule is rewritten in place into the storage form +/// described in the module docs. Verified against the worked expansions in FIPS 197 +/// Appendix A.1, A.2 and A.3 by the tests at the bottom of this file, which decompress the +/// stored schedule and compare every w[i]. +pub(crate) fn expand(key: &[u8]) -> Secret { + debug_assert_eq!(key.len(), P::KEY_LEN); + + let mut schedule = Secret::::new(); + let w = (*schedule).as_mut(); + + // Algorithm 2 lines 2-6: w[i] = key[4i .. 4i+3] for i < Nk. + for i in 0..P::NK { + // Cannot fail: `key` is P::KEY_LEN == 4 * P::NK bytes, so this window is in bounds. + w[i] = u32::from_le_bytes(key[4 * i..4 * i + 4].try_into().unwrap()); + } + + // Algorithm 2 lines 7-16. + let mut temp = w[P::NK - 1]; // line 8, hoisted: w[i-1] is the temp from the previous pass + for i in P::NK..w.len() { + if i % P::NK == 0 { + // line 10: temp = SUBWORD(ROTWORD(temp)) XOR Rcon[i / Nk] + temp = sub_word(rot_word(temp)) ^ RCON[i / P::NK - 1]; + } else if P::NK > 6 && i % P::NK == 4 { + // lines 11-12: the extra substitution that only AES-256 reaches + temp = sub_word(temp); + } + // line 14: w[i] = w[i - Nk] XOR temp + temp ^= w[i - P::NK]; + w[i] = temp; + } + + // Rewrite in place into the compressed bit-sliced form, one 4-word round key at a time. + // Both interleaved blocks use the same key, so each round key is bit-sliced with the word + // duplicated into both halves; the two halves are then identical and one bit of each pair is + // redundant, so the even-position bits of the first word and the odd-position bits of the + // second are packed into a single stored word. + for base in (0..w.len()).step_by(4) { + let mut q: Planes = [0u32; 8]; + for j in 0..4 { + q[2 * j] = w[base + j]; + q[2 * j + 1] = w[base + j]; + } + ortho(&mut q); + for j in 0..4 { + // The two masks are complementary, so the operands are disjoint and `|` and `^` agree. + // That is why `cargo mutants` reports the `| -> ^` mutant here as surviving. + w[base + j] = (q[2 * j] & 0x5555_5555) | (q[2 * j + 1] & 0xAAAA_AAAA); + } + } + + schedule +} + +/// Re-doubles round key `round` of a compressed schedule into its eight-plane form. +/// +/// The inverse of the packing at the end of [`expand`]: the even-position bits are spread back +/// over both positions of each pair, and likewise the odd-position bits, giving the two identical +/// halves that [`crate::round::add_round_key`] expects. Eight words of stack, built fresh each +/// round rather than stored. +/// +/// Translated from BearSSL `aes_ct.c:br_aes_ct_skey_expand`. +#[inline(always)] +pub(crate) fn round_key(schedule: &P::Schedule, round: usize) -> Planes { + debug_assert!(round <= P::NR); + let w = schedule.as_ref(); + let mut sk: Planes = [0u32; 8]; + for j in 0..4 { + let packed = w[4 * round + j]; + let even = packed & 0x5555_5555; + let odd = packed & 0xAAAA_AAAA; + // `even` occupies only even bit positions and `even << 1` only odd ones (and vice versa + // for `odd`), so both spreads combine disjoint operands and `|` and `^` agree. Hence the + // two `| -> ^` mutants `cargo mutants` reports here as surviving. + sk[2 * j] = even | (even << 1); + sk[2 * j + 1] = odd | (odd >> 1); + } + sk +} + +#[cfg(test)] +mod tests { + use super::*; + + /// FIPS 197 Appendix A.1: every w[i] of the AES-128 key expansion, as printed + /// (i.e. the byte sequence [a0,a1,a2,a3] read left to right). + #[rustfmt::skip] + const APPENDIX_A1_WORDS: [u32; 44] = [ + 0x2b7e1516, 0x28aed2a6, 0xabf71588, 0x09cf4f3c, + 0xa0fafe17, 0x88542cb1, 0x23a33939, 0x2a6c7605, + 0xf2c295f2, 0x7a96b943, 0x5935807a, 0x7359f67f, + 0x3d80477d, 0x4716fe3e, 0x1e237e44, 0x6d7a883b, + 0xef44a541, 0xa8525b7f, 0xb671253b, 0xdb0bad00, + 0xd4d1c6f8, 0x7c839d87, 0xcaf2b8bc, 0x11f915bc, + 0x6d88a37a, 0x110b3efd, 0xdbf98641, 0xca0093fd, + 0x4e54f70e, 0x5f5fc9f3, 0x84a64fb2, 0x4ea6dc4f, + 0xead27321, 0xb58dbad2, 0x312bf560, 0x7f8d292f, + 0xac7766f3, 0x19fadc21, 0x28d12941, 0x575c006e, + 0xd014f9a8, 0xc9ee2589, 0xe13f0cc8, 0xb6630ca6, + ]; + + /// FIPS 197 Appendix A.2: every w[i] of the AES-192 key expansion, as printed. + #[rustfmt::skip] + const APPENDIX_A2_WORDS: [u32; 52] = [ + 0x8e73b0f7, 0xda0e6452, 0xc810f32b, 0x809079e5, + 0x62f8ead2, 0x522c6b7b, 0xfe0c91f7, 0x2402f5a5, + 0xec12068e, 0x6c827f6b, 0x0e7a95b9, 0x5c56fec2, + 0x4db7b4bd, 0x69b54118, 0x85a74796, 0xe92538fd, + 0xe75fad44, 0xbb095386, 0x485af057, 0x21efb14f, + 0xa448f6d9, 0x4d6dce24, 0xaa326360, 0x113b30e6, + 0xa25e7ed5, 0x83b1cf9a, 0x27f93943, 0x6a94f767, + 0xc0a69407, 0xd19da4e1, 0xec1786eb, 0x6fa64971, + 0x485f7032, 0x22cb8755, 0xe26d1352, 0x33f0b7b3, + 0x40beeb28, 0x2f18a259, 0x6747d26b, 0x458c553e, + 0xa7e1466c, 0x9411f1df, 0x821f750a, 0xad07d753, + 0xca400538, 0x8fcc5006, 0x282d166a, 0xbc3ce7b5, + 0xe98ba06f, 0x448c773c, 0x8ecc7204, 0x01002202, + ]; + + /// FIPS 197 Appendix A.3: every w[i] of the AES-256 key expansion, as printed. + #[rustfmt::skip] + const APPENDIX_A3_WORDS: [u32; 60] = [ + 0x603deb10, 0x15ca71be, 0x2b73aef0, 0x857d7781, + 0x1f352c07, 0x3b6108d7, 0x2d9810a3, 0x0914dff4, + 0x9ba35411, 0x8e6925af, 0xa51a8b5f, 0x2067fcde, + 0xa8b09c1a, 0x93d194cd, 0xbe49846e, 0xb75d5b9a, + 0xd59aecb8, 0x5bf3c917, 0xfee94248, 0xde8ebe96, + 0xb5a9328a, 0x2678a647, 0x98312229, 0x2f6c79b3, + 0x812c81ad, 0xdadf48ba, 0x24360af2, 0xfab8b464, + 0x98c5bfc9, 0xbebd198e, 0x268c3ba7, 0x09e04214, + 0x68007bac, 0xb2df3316, 0x96e939e4, 0x6c518d80, + 0xc814e204, 0x76a9fb8a, 0x5025c02d, 0x59c58239, + 0xde136967, 0x6ccc5a71, 0xfa256395, 0x9674ee15, + 0x5886ca5d, 0x2e2f31d7, 0x7e0af1fa, 0x27cf73c3, + 0x749c47ab, 0x18501dda, 0xe2757e4f, 0x7401905a, + 0xcafaaae3, 0xe4d59b34, 0x9adf6ace, 0xbd10190d, + 0xfe4890d1, 0xe6188d0b, 0x046df344, 0x706c631e, + ]; + + /// Recovers the classical `w[i]` from a stored schedule. + /// + /// [`round_key`] undoes the pair-compression, and [`ortho`] then undoes the bit-slicing, + /// leaving the duplicated pre-slicing words with `w[4*round + j]` in position `2j`. This is + /// what lets the Appendix A vectors test the real [`expand`] output rather than a + /// reimplementation of it. + fn classical_word(schedule: &P::Schedule, i: usize) -> u32 { + let mut q = round_key::

(schedule, i / 4); + ortho(&mut q); + let j = i % 4; + assert_eq!(q[2 * j], q[2 * j + 1], "both interleaved halves hold the same round key"); + q[2 * j] + } + + /// Compares a whole expansion against an Appendix A table. + /// + /// Appendix A prints a word as the byte sequence `[a0,a1,a2,a3]` left to right, so the + /// tabulated `u32` has `a0` in its *most* significant byte; words are held little-endian + /// here, so `swap_bytes` is the conversion. + fn assert_expansion_matches(key: &[u8], expected: &[u32], label: &str) { + let schedule = expand::

(key); + assert_eq!(expected.len(), 4 * (P::NR + 1), "{label}: table length"); + for (i, &want) in expected.iter().enumerate() { + let got = classical_word::

(&schedule, i).swap_bytes(); + assert_eq!(got, want, "{label}: w[{i}] should be {want:#010x}, got {got:#010x}"); + } + } + + #[test] + fn test_key_expansion_matches_fips197_appendix_a1() { + let key = [ + 0x2b, 0x7e, 0x15, 0x16, 0x28, 0xae, 0xd2, 0xa6, 0xab, 0xf7, 0x15, 0x88, 0x09, 0xcf, + 0x4f, 0x3c, + ]; + assert_expansion_matches::(&key, &APPENDIX_A1_WORDS, "Appendix A.1"); + } + + #[test] + fn test_key_expansion_matches_fips197_appendix_a2() { + let key = [ + 0x8e, 0x73, 0xb0, 0xf7, 0xda, 0x0e, 0x64, 0x52, 0xc8, 0x10, 0xf3, 0x2b, 0x80, 0x90, + 0x79, 0xe5, 0x62, 0xf8, 0xea, 0xd2, 0x52, 0x2c, 0x6b, 0x7b, + ]; + assert_expansion_matches::(&key, &APPENDIX_A2_WORDS, "Appendix A.2"); + } + + #[test] + fn test_key_expansion_matches_fips197_appendix_a3() { + let key = [ + 0x60, 0x3d, 0xeb, 0x10, 0x15, 0xca, 0x71, 0xbe, 0x2b, 0x73, 0xae, 0xf0, 0x85, 0x7d, + 0x77, 0x81, 0x1f, 0x35, 0x2c, 0x07, 0x3b, 0x61, 0x08, 0xd7, 0x2d, 0x98, 0x10, 0xa3, + 0x09, 0x14, 0xdf, 0xf4, + ]; + assert_expansion_matches::(&key, &APPENDIX_A3_WORDS, "Appendix A.3"); + } + + #[test] + fn test_the_first_nk_schedule_words_are_the_key_itself() { + // Algorithm 2 lines 2-6, and a check that the expansion is reading the key + // little-endian consistently with how Appendix A prints it. + let key = [ + 0x2b, 0x7e, 0x15, 0x16, 0x28, 0xae, 0xd2, 0xa6, 0xab, 0xf7, 0x15, 0x88, 0x09, 0xcf, + 0x4f, 0x3c, + ]; + let schedule = expand::(&key); + for i in 0..Aes128Params::NK { + let got = classical_word::(&schedule, i); + assert_eq!(got.to_le_bytes(), key[4 * i..4 * i + 4]); + } + } + + #[test] + fn test_rot_word_matches_equation_5_10() { + // FIPS 197 Eq 5.10 on the byte sequence [a0,a1,a2,a3] = [0x09,0xcf,0x4f,0x3c], which is + // the temp at i = 4 of Appendix A.1, whose ROTWORD() the appendix gives as cf4f3c09. + let word = u32::from_le_bytes([0x09, 0xcf, 0x4f, 0x3c]); + assert_eq!(rot_word(word).to_le_bytes(), [0xcf, 0x4f, 0x3c, 0x09]); + } + + #[test] + fn test_sub_word_matches_the_appendix_a1_example() { + // Appendix A.1, i = 4: "After ROTWORD()" is cf4f3c09 and "After SUBWORD()" is 8a84eb01. + // The appendix prints a word as the byte sequence [a0,a1,a2,a3]; words are held + // little-endian here, so `a0` is the low byte. + let after_rot = u32::from_le_bytes([0xcf, 0x4f, 0x3c, 0x09]); + assert_eq!(sub_word(after_rot).to_le_bytes(), [0x8a, 0x84, 0xeb, 0x01]); + } + + #[test] + fn test_sub_word_fills_every_plane() { + // The doc comment claims all eight planes end up holding SUBWORD(word); if that ever + // stopped being true, picking q[0] would be an arbitrary choice rather than a correct one. + let word = 0x1234_5678u32; + let mut q: Planes = [word; 8]; + ortho(&mut q); + sbox(&mut q); + ortho(&mut q); + assert!(q.iter().all(|&plane| plane == q[0])); + assert_eq!(q[0], sub_word(word)); + } + + #[test] + fn test_round_key_inverts_the_compression() { + // Round-tripping a known schedule: expand(), then round_key() for every round, and check + // the recovered planes match bit-slicing the classical words directly. + let key = [ + 0x2b, 0x7e, 0x15, 0x16, 0x28, 0xae, 0xd2, 0xa6, 0xab, 0xf7, 0x15, 0x88, 0x09, 0xcf, + 0x4f, 0x3c, + ]; + let schedule = expand::(&key); + + // Recompute the classical schedule without the compression step. + let mut w = [0u32; 44]; + for i in 0..4 { + w[i] = u32::from_le_bytes(key[4 * i..4 * i + 4].try_into().unwrap()); + } + let mut temp = w[3]; + for i in 4..44 { + if i % 4 == 0 { + temp = sub_word(rot_word(temp)) ^ RCON[i / 4 - 1]; + } + temp ^= w[i - 4]; + w[i] = temp; + } + + for round in 0..=Aes128Params::NR { + let got = round_key::(&schedule, round); + let mut expected: Planes = [0u32; 8]; + for j in 0..4 { + expected[2 * j] = w[4 * round + j]; + expected[2 * j + 1] = w[4 * round + j]; + } + ortho(&mut expected); + assert_eq!(got, expected, "round {round}"); + } + } + + #[test] + fn test_schedule_lengths_match_four_times_nr_plus_one() { + // FIPS 197 Sec 5.2: the schedule is 4 * (Nr + 1) words. The array types are written out + // by hand per parameter set, so this guards against a typo in one of them. + assert_eq!( + size_of::<::Schedule>() / 4, + 4 * (Aes128Params::NR + 1) + ); + assert_eq!( + size_of::<::Schedule>() / 4, + 4 * (Aes192Params::NR + 1) + ); + assert_eq!( + size_of::<::Schedule>() / 4, + 4 * (Aes256Params::NR + 1) + ); + } + + #[test] + fn test_key_len_is_four_times_nk() { + // FIPS 197 Sec 6.1 ties the two together; both are declared independently above. + assert_eq!(Aes128Params::KEY_LEN, 4 * Aes128Params::NK); + assert_eq!(Aes192Params::KEY_LEN, 4 * Aes192Params::NK); + assert_eq!(Aes256Params::KEY_LEN, 4 * Aes256Params::NK); + } + + #[test] + fn test_rcon_table_5_values() { + // FIPS 197 Sec 5.2: "for j > 0, these bytes may be generated by successively applying + // XTIMES() to the byte represented by x^(j-1)". Derive the table and compare, so a typo + // in the transcription of Table 5 shows up here. + let mut expected = [0u32; 10]; + let mut v: u8 = 0x01; + for slot in expected.iter_mut() { + *slot = u32::from(v); + v = (v << 1) ^ if v & 0x80 != 0 { 0x1b } else { 0 }; + } + assert_eq!(RCON, expected); + // Spot-check the two values from Table 5 that are not plain powers of two. + assert_eq!(RCON[8], 0x1b); + assert_eq!(RCON[9], 0x36); + } +} diff --git a/crypto/aes-lowmemory/tests/acvp_tests.rs b/crypto/aes-lowmemory/tests/acvp_tests.rs new file mode 100644 index 00000000..aa7018f8 --- /dev/null +++ b/crypto/aes-lowmemory/tests/acvp_tests.rs @@ -0,0 +1,285 @@ +//! Known-answer tests against the NIST ACVP `ACVP-AES-ECB` vectors from the `bc-test-data` repo. +//! +//! Requires `bc-test-data` to be cloned alongside this repository, i.e. at `../bc-test-data` +//! relative to the root of this git project. If it is absent the tests print a warning and pass, +//! matching the convention used by the ML-KEM and ML-DSA test suites -- `cargo test` must stay +//! green for someone who has only cloned this repository. +//! +//! # Why ECB, and where the other ACVP AES files are used +//! +//! ECB applies the raw permutation to each block independently, so an ECB test vector *is* a +//! block-permutation test vector -- which is the only reason ECB is mentioned in this crate. See +//! the crate docs on why you must never use ECB to encrypt data. +//! +//! `bc-test-data` ships thirteen ACVP AES vector sets, one per mode. This file deliberately +//! consumes only `ACVP-AES-ECB`, because that is the one that tests the permutation rather than a +//! mode. The others belong with whatever implements the mode: +//! +//! | Vector set | Consumed by | +//! |---|---| +//! | `ACVP-AES-ECB` | this file (the permutation) and `crypto/modes/tests/acvp_ecb_tests.rs` (the `Ecb` mode) | +//! | `ACVP-AES-CBC` | `crypto/modes/tests/acvp_tests.rs` | +//! | `ACVP-AES-CBC-CS1` / `-CS2` / `-CS3` | nothing yet (ciphertext stealing is unimplemented) | +//! | `ACVP-AES-CFB128` | `crypto/modes/tests/acvp_cfb_tests.rs` | +//! | `ACVP-AES-CFB8` | `crypto/modes/tests/acvp_cfb8_tests.rs` | +//! | `ACVP-AES-OFB` | nothing yet (OFB is unimplemented) | +//! | `ACVP-AES-CTR` | nothing yet (CTR is unimplemented) | +//! | `ACVP-AES-KW` / `-KWP` | nothing yet (key wrap is unimplemented) | +//! | `ACVP-AES-FF1` / `-FF3-1` | nothing yet (format-preserving encryption is unimplemented) | +//! +//! So an unused vector set here means an unimplemented mode, not an untested one. Adding a mode +//! should include wiring up its file. +//! +//! The response file records `key`, `pt` and `ct` for every test case regardless of the group's +//! declared direction, so each case is checked in **both** directions: encrypting `pt` must give +//! `ct` and decrypting `ct` must give `pt`. That is strictly stronger than honouring the declared +//! direction, and it means the group metadata in the request file is not needed. +//! +//! # Coverage and one gap +//! +//! The AFT (Algorithm Functional Test) groups cover all three key lengths in both directions, +//! including cases whose plaintext spans several blocks. The six MCT (Monte Carlo Test) groups +//! are **not** implemented: their expected output is a `resultsArray` produced by a chained +//! key/plaintext update rule defined in the ACVP AES specification rather than in FIPS 197, and +//! implementing it from anything other than that specification would be guesswork. The test +//! reports how many it skipped so the gap is visible rather than silent. + +use bouncycastle_aes_lowmemory::{Aes128, Aes192, Aes256, BLOCK_LEN}; +use bouncycastle_core::key_material::{ + KeyMaterial, KeyMaterialTrait, KeyType, do_hazardous_operations, +}; +use bouncycastle_core::traits::SecurityStrength; +use bouncycastle_hex as hex; +use serde_json::Value; +use std::fs; +use std::path::{Path, PathBuf}; + +/// Candidate locations, covering `cargo test` run from the crate root or from the repo root. +const TEST_DATA_PATHS: [&str; 2] = [ + "../../../bc-test-data/crypto/aes_tdes_vectors/AES", + "../bc-test-data/crypto/aes_tdes_vectors/AES", +]; + +const RESPONSE_FILE: &str = "ACVP-AES-ECB.4014527.rsp.json"; + +/// Locates the ACVP AES directory, or `None` if `bc-test-data` is not checked out. +fn test_data_dir() -> Option { + for candidate in TEST_DATA_PATHS { + let path = Path::new(candidate); + if path.join(RESPONSE_FILE).exists() { + return Some(path.to_path_buf()); + } + } + println!( + "WARNING: bc-test-data not found (looked in {TEST_DATA_PATHS:?}); \ + ACVP AES-ECB tests will be skipped" + ); + None +} + +/// Builds a `KeyMaterial` from raw ACVP key bytes, including the all-zero keys. +/// +/// The ACVP set deliberately includes an all-zero key (the GFSbox-style groups vary only the +/// plaintext under a zero key). `KeyMaterial` tags an all-zero buffer as [`KeyType::Zeroized`] +/// and will not promote it outside a [`do_hazardous_operations`] closure, which is the right +/// default -- an all-zero key normally means a broken RNG, and `Aes128::new` rejecting it is +/// tested in `fips197_tests.rs`. Here the zero key is deliberate and comes from NIST, so this +/// opts in explicitly rather than the library weakening its guard. +fn cipher_key(bytes: &[u8]) -> KeyMaterial { + assert_eq!(bytes.len(), N, "key length should match the parameter set"); + let mut key = KeyMaterial::::from_bytes_as_type(bytes, KeyType::SymmetricCipherKey) + .expect("ACVP key bytes fit the buffer"); + + if key.key_type() != KeyType::SymmetricCipherKey { + do_hazardous_operations(&mut key, |k| { + k.set_key_type(KeyType::SymmetricCipherKey)?; + k.set_security_strength(SecurityStrength::from_bytes(N)) + }) + .expect("promoting a NIST all-zero test key"); + } + + key +} + +/// A single-block transformation, resolved once per test case rather than per block. +type BlockTransform = Box; + +/// Encrypts or decrypts `data` block by block, i.e. ECB, dispatching on the key length. +fn ecb(key: &[u8], data: &[u8], encrypt: bool) -> Vec { + assert_eq!(data.len() % BLOCK_LEN, 0, "ACVP ECB data must be block-aligned"); + + let transform: BlockTransform = match key.len() { + 16 => { + let km = cipher_key::<16>(key); + let aes = Aes128::new(&km).expect("valid AES-128 key"); + if encrypt { + Box::new(move |b| aes.encrypt_block(b)) + } else { + Box::new(move |b| aes.decrypt_block(b)) + } + } + 24 => { + let km = cipher_key::<24>(key); + let aes = Aes192::new(&km).expect("valid AES-192 key"); + if encrypt { + Box::new(move |b| aes.encrypt_block(b)) + } else { + Box::new(move |b| aes.decrypt_block(b)) + } + } + 32 => { + let km = cipher_key::<32>(key); + let aes = Aes256::new(&km).expect("valid AES-256 key"); + if encrypt { + Box::new(move |b| aes.encrypt_block(b)) + } else { + Box::new(move |b| aes.decrypt_block(b)) + } + } + other => panic!("ACVP AES vectors should only use 16, 24 or 32 byte keys, got {other}"), + }; + + let mut out = Vec::with_capacity(data.len()); + for chunk in data.chunks(BLOCK_LEN) { + // Cannot fail: the length is asserted block-aligned above. + let mut block: [u8; BLOCK_LEN] = chunk.try_into().unwrap(); + transform(&mut block); + out.extend_from_slice(&block); + } + out +} + +/// The same, using the two-block entry points where a pair is available. +fn ecb_pairwise(key: &[u8], data: &[u8], encrypt: bool) -> Vec { + assert_eq!(data.len() % BLOCK_LEN, 0, "ACVP ECB data must be block-aligned"); + let mut blocks: Vec<[u8; BLOCK_LEN]> = + data.chunks(BLOCK_LEN).map(|c| c.try_into().unwrap()).collect(); + + match key.len() { + 16 => { + let km = cipher_key::<16>(key); + let aes = Aes128::new(&km).unwrap(); + run_pairwise(&mut blocks, encrypt, |p, e| { + if e { aes.encrypt_blocks2(p) } else { aes.decrypt_blocks2(p) } + }); + } + 24 => { + let km = cipher_key::<24>(key); + let aes = Aes192::new(&km).unwrap(); + run_pairwise(&mut blocks, encrypt, |p, e| { + if e { aes.encrypt_blocks2(p) } else { aes.decrypt_blocks2(p) } + }); + } + 32 => { + let km = cipher_key::<32>(key); + let aes = Aes256::new(&km).unwrap(); + run_pairwise(&mut blocks, encrypt, |p, e| { + if e { aes.encrypt_blocks2(p) } else { aes.decrypt_blocks2(p) } + }); + } + other => panic!("ACVP AES vectors should only use 16, 24 or 32 byte keys, got {other}"), + } + + blocks.concat() +} + +/// Walks `blocks` two at a time, leaving a trailing odd block to a duplicated pair. +fn run_pairwise( + blocks: &mut [[u8; BLOCK_LEN]], + encrypt: bool, + transform: impl Fn(&mut [[u8; BLOCK_LEN]; 2], bool), +) { + let mut chunks = blocks.chunks_exact_mut(2); + for pair in &mut chunks { + // Cannot fail: `chunks_exact_mut(2)` yields slices of length 2. + let pair: &mut [[u8; BLOCK_LEN]; 2] = pair.try_into().unwrap(); + transform(pair, encrypt); + } + // An odd trailing block still has to go through the two-block path. + if let [last] = chunks.into_remainder() { + let mut pair = [*last, *last]; + transform(&mut pair, encrypt); + *last = pair[0]; + } +} + +#[test] +fn acvp_aes_ecb_known_answer_tests() { + let Some(dir) = test_data_dir() else { return }; + + let contents = fs::read_to_string(dir.join(RESPONSE_FILE)).expect("readable response file"); + let parsed: Value = serde_json::from_str(&contents).expect("valid ACVP JSON"); + + // The ACVP file is an array: element 0 is the version header, element 1 the vector set. + let groups = parsed + .get(1) + .and_then(|set| set.get("testGroups")) + .and_then(Value::as_array) + .expect("testGroups array"); + + let mut checked = 0usize; + let mut skipped_mct = 0usize; + let mut by_key_len = [0usize; 3]; // 128, 192, 256 + + for group in groups { + let tests = group.get("tests").and_then(Value::as_array).expect("tests array"); + for test in tests { + let tc_id = test.get("tcId").and_then(Value::as_u64).expect("tcId"); + + // Monte Carlo groups carry a chained resultsArray instead of a single pt/ct pair. + if test.get("resultsArray").is_some() { + skipped_mct += 1; + continue; + } + + let get = |name: &str| -> Vec { + let s = test + .get(name) + .and_then(Value::as_str) + .unwrap_or_else(|| panic!("tcId {tc_id}: missing field {name}")); + hex::decode(s).unwrap_or_else(|_| panic!("tcId {tc_id}: bad hex in {name}")) + }; + + let key = get("key"); + let pt = get("pt"); + let ct = get("ct"); + + assert_eq!(pt.len(), ct.len(), "tcId {tc_id}: pt and ct differ in length"); + + assert_eq!(ecb(&key, &pt, true), ct, "tcId {tc_id}: AES-{} encrypt", key.len() * 8); + assert_eq!(ecb(&key, &ct, false), pt, "tcId {tc_id}: AES-{} decrypt", key.len() * 8); + + // The two-block path must agree with the single-block path on real vectors too. + assert_eq!( + ecb_pairwise(&key, &pt, true), + ct, + "tcId {tc_id}: AES-{} encrypt via encrypt_blocks2", + key.len() * 8 + ); + assert_eq!( + ecb_pairwise(&key, &ct, false), + pt, + "tcId {tc_id}: AES-{} decrypt via decrypt_blocks2", + key.len() * 8 + ); + + by_key_len[match key.len() { + 16 => 0, + 24 => 1, + _ => 2, + }] += 1; + checked += 1; + } + } + + println!( + "ACVP AES-ECB: {checked} test cases checked in both directions \ + (AES-128: {}, AES-192: {}, AES-256: {}); {skipped_mct} MCT cases skipped", + by_key_len[0], by_key_len[1], by_key_len[2] + ); + + // Guard against a silently-empty run: the published vector set has thousands of AFT cases + // across all three key lengths. + assert!(checked > 1000, "expected the full ACVP AFT set, only checked {checked}"); + assert!(by_key_len.iter().all(|&n| n > 0), "every key length should be covered"); +} diff --git a/crypto/aes-lowmemory/tests/electronic_code_book_tests.rs b/crypto/aes-lowmemory/tests/electronic_code_book_tests.rs new file mode 100644 index 00000000..2098315e --- /dev/null +++ b/crypto/aes-lowmemory/tests/electronic_code_book_tests.rs @@ -0,0 +1,25 @@ +//! `ElectronicCodeBook` trait conformance, via the shared test framework. +//! +//! The framework checks the properties every implementor must have -- both directions are +//! inverses, the permutation is injective, the pair methods are indistinguishable from two +//! single-block calls *including their order*, and the key checks behave. That last pair of +//! properties matters here specifically: this crate overrides `encrypt_blocks2` and +//! `decrypt_blocks2`, so the default implementation is not what runs. + +use bouncycastle_aes_lowmemory::{Aes128, Aes192, Aes256, BLOCK_LEN}; +use bouncycastle_core_test_framework::electronic_code_book::TestFrameworkElectronicCodeBook; + +#[test] +fn aes128_conforms_to_electronic_code_book() { + TestFrameworkElectronicCodeBook::new().test::<16, BLOCK_LEN, Aes128>(); +} + +#[test] +fn aes192_conforms_to_electronic_code_book() { + TestFrameworkElectronicCodeBook::new().test::<24, BLOCK_LEN, Aes192>(); +} + +#[test] +fn aes256_conforms_to_electronic_code_book() { + TestFrameworkElectronicCodeBook::new().test::<32, BLOCK_LEN, Aes256>(); +} diff --git a/crypto/aes-lowmemory/tests/fips197_tests.rs b/crypto/aes-lowmemory/tests/fips197_tests.rs new file mode 100644 index 00000000..d1261b8d --- /dev/null +++ b/crypto/aes-lowmemory/tests/fips197_tests.rs @@ -0,0 +1,230 @@ +//! Known-answer tests from NIST FIPS 197 itself. +//! +//! Appendix B -- the worked single-block AES-128 encryption -- plus its inverse, the two-block +//! path, and key-handling behaviour. +//! +//! The Appendix A key expansions are **not** tested here. The key schedule is deliberately not +//! public API (it is a `Secret` field), and a round-trip through the cipher cannot check it: a +//! wrong `w[i]` is used by encryption and decryption alike, so the round trip still succeeds. +//! Every word of all three expansions is instead checked against Appendix A inside +//! `src/schedule.rs`, where the stored schedule can be decompressed and compared directly. +//! +//! Known-answer coverage for AES-192 and AES-256, which Appendix B does not reach, is in +//! `sp800_38a_tests.rs` and `acvp_tests.rs`. +//! +//! All values here are transcribed from the published FIPS 197 (Update 1) PDF. + +use bouncycastle_aes_lowmemory::{Aes128, Aes192, Aes256}; +use bouncycastle_core::key_material::{KeyMaterial, KeyMaterialTrait, KeyType}; +use bouncycastle_core::traits::SecurityStrength; + +/// Appendix A.1 / Appendix B key: `2b7e151628aed2a6abf7158809cf4f3c`. +const KEY_128: [u8; 16] = [ + 0x2b, 0x7e, 0x15, 0x16, 0x28, 0xae, 0xd2, 0xa6, 0xab, 0xf7, 0x15, 0x88, 0x09, 0xcf, 0x4f, 0x3c, +]; + +/// Appendix A.2 key: `8e73b0f7da0e6452c810f32b809079e562f8ead2522c6b7b`. +const KEY_192: [u8; 24] = [ + 0x8e, 0x73, 0xb0, 0xf7, 0xda, 0x0e, 0x64, 0x52, 0xc8, 0x10, 0xf3, 0x2b, 0x80, 0x90, 0x79, 0xe5, + 0x62, 0xf8, 0xea, 0xd2, 0x52, 0x2c, 0x6b, 0x7b, +]; + +/// Appendix A.3 key: +/// `603deb1015ca71be2b73aef0857d77811f352c073b6108d72d9810a30914dff4`. +const KEY_256: [u8; 32] = [ + 0x60, 0x3d, 0xeb, 0x10, 0x15, 0xca, 0x71, 0xbe, 0x2b, 0x73, 0xae, 0xf0, 0x85, 0x7d, 0x77, 0x81, + 0x1f, 0x35, 0x2c, 0x07, 0x3b, 0x61, 0x08, 0xd7, 0x2d, 0x98, 0x10, 0xa3, 0x09, 0x14, 0xdf, 0xf4, +]; + +fn key_material(bytes: &[u8; N]) -> KeyMaterial { + KeyMaterial::::from_bytes_as_type(bytes, KeyType::SymmetricCipherKey) + .expect("a valid symmetric cipher key") +} + +#[test] +fn appendix_b_encrypts_the_documented_block() { + // Appendix B: Input = 32 43 f6 a8 88 5a 30 8d 31 31 98 a2 e0 37 07 34 + // Key = 2b 7e 15 16 28 ae d2 a6 ab f7 15 88 09 cf 4f 3c + // The final state printed as "output" reads, column by column (Eq 3.7): + // 39 25 84 1d 02 dc 09 fb dc 11 85 97 19 6a 0b 32 + let aes = Aes128::new(&key_material(&KEY_128)).unwrap(); + + let mut block = [ + 0x32, 0x43, 0xf6, 0xa8, 0x88, 0x5a, 0x30, 0x8d, 0x31, 0x31, 0x98, 0xa2, 0xe0, 0x37, 0x07, + 0x34, + ]; + aes.encrypt_block(&mut block); + assert_eq!( + block, + [ + 0x39, 0x25, 0x84, 0x1d, 0x02, 0xdc, 0x09, 0xfb, 0xdc, 0x11, 0x85, 0x97, 0x19, 0x6a, + 0x0b, 0x32 + ] + ); +} + +#[test] +fn appendix_b_decrypts_back_to_the_documented_input() { + let aes = Aes128::new(&key_material(&KEY_128)).unwrap(); + + let mut block = [ + 0x39, 0x25, 0x84, 0x1d, 0x02, 0xdc, 0x09, 0xfb, 0xdc, 0x11, 0x85, 0x97, 0x19, 0x6a, 0x0b, + 0x32, + ]; + aes.decrypt_block(&mut block); + assert_eq!( + block, + [ + 0x32, 0x43, 0xf6, 0xa8, 0x88, 0x5a, 0x30, 0x8d, 0x31, 0x31, 0x98, 0xa2, 0xe0, 0x37, + 0x07, 0x34 + ] + ); +} + +#[test] +fn appendix_b_two_block_path_agrees_with_the_single_block_path() { + let aes = Aes128::new(&key_material(&KEY_128)).unwrap(); + let input = [ + 0x32, 0x43, 0xf6, 0xa8, 0x88, 0x5a, 0x30, 0x8d, 0x31, 0x31, 0x98, 0xa2, 0xe0, 0x37, 0x07, + 0x34, + ]; + let expected = [ + 0x39, 0x25, 0x84, 0x1d, 0x02, 0xdc, 0x09, 0xfb, 0xdc, 0x11, 0x85, 0x97, 0x19, 0x6a, 0x0b, + 0x32, + ]; + + // Pairing the Appendix B block with an unrelated one must not disturb either half. + let other = [0xAAu8; 16]; + let mut other_alone = other; + aes.encrypt_block(&mut other_alone); + + let mut pair = [input, other]; + aes.encrypt_blocks2(&mut pair); + assert_eq!(pair[0], expected); + assert_eq!(pair[1], other_alone); + + // ...and in the other slot, which is a different bit position in the interleave. + let mut pair = [other, input]; + aes.encrypt_blocks2(&mut pair); + assert_eq!(pair[0], other_alone); + assert_eq!(pair[1], expected); +} + +/// Encryption and decryption are inverses, under each Appendix A key. +/// +/// This checks `decrypt_block` really inverts `encrypt_block` from the same stored schedule, +/// which is the load-bearing claim of following FIPS 197 Algorithm 3 rather than Sec 5.3.5. It +/// deliberately makes no claim about the schedule being *correct* -- see the module docs. +#[test] +fn encryption_and_decryption_are_inverses_for_all_three_key_lengths() { + let aes128 = Aes128::new(&key_material(&KEY_128)).unwrap(); + let aes192 = Aes192::new(&key_material(&KEY_192)).unwrap(); + let aes256 = Aes256::new(&key_material(&KEY_256)).unwrap(); + + for block in [[0u8; 16], [0xFFu8; 16], core::array::from_fn(|i| i as u8)] { + let mut b = block; + aes128.encrypt_block(&mut b); + assert_ne!(b, block, "AES-128 must actually transform the block"); + aes128.decrypt_block(&mut b); + assert_eq!(b, block, "AES-128 round trip with the Appendix A.1 key"); + + let mut b = block; + aes192.encrypt_block(&mut b); + assert_ne!(b, block, "AES-192 must actually transform the block"); + aes192.decrypt_block(&mut b); + assert_eq!(b, block, "AES-192 round trip with the Appendix A.2 key"); + + let mut b = block; + aes256.encrypt_block(&mut b); + assert_ne!(b, block, "AES-256 must actually transform the block"); + aes256.decrypt_block(&mut b); + assert_eq!(b, block, "AES-256 round trip with the Appendix A.3 key"); + } +} + +/// The three key lengths must give different results for the same input. +/// +/// Guards against a parameter set silently using another set's `Nr` or `Nk`. +#[test] +fn the_three_key_lengths_are_distinct_permutations() { + // A key whose first 16 bytes are shared, so only Nk/Nr and the extra key bytes differ. + let shared = [0x11u8; 32]; + let aes128 = Aes128::new(&key_material::<16>(&shared[..16].try_into().unwrap())).unwrap(); + let aes192 = Aes192::new(&key_material::<24>(&shared[..24].try_into().unwrap())).unwrap(); + let aes256 = Aes256::new(&key_material(&shared)).unwrap(); + + let block = [0x42u8; 16]; + let mut b128 = block; + let mut b192 = block; + let mut b256 = block; + aes128.encrypt_block(&mut b128); + aes192.encrypt_block(&mut b192); + aes256.encrypt_block(&mut b256); + + assert_ne!(b128, b192); + assert_ne!(b192, b256); + assert_ne!(b128, b256); +} + +// ---- key handling ----------------------------------------------------------------------- + +#[test] +fn a_key_of_the_wrong_type_is_rejected() { + // KeyType::Seed is not a cipher key: a seed reused directly as an AES key is a real mistake + // and the type system tracks enough to catch it. + let key = KeyMaterial::<16>::from_bytes_as_type(&[0x01; 16], KeyType::Seed).unwrap(); + assert!(Aes128::new(&key).is_err()); + + let key = KeyMaterial::<16>::from_bytes_as_type(&[0x01; 16], KeyType::MACKey).unwrap(); + assert!(Aes128::new(&key).is_err()); +} + +#[test] +fn a_key_of_the_wrong_length_is_rejected() { + // The capacity is right but only part of it is populated, so `key_len()` disagrees with the + // parameter set. This is the one length error the const generic cannot catch by itself. + let key = + KeyMaterial::<32>::from_bytes_as_type(&[0x01; 16], KeyType::SymmetricCipherKey).unwrap(); + assert!(Aes256::new(&key).is_err()); +} + +#[test] +fn a_key_carrying_too_low_a_security_strength_is_rejected() { + // A full-length key whose material was only ever derived at a lower security strength must + // not be usable at the strength its length implies. `from_bytes_as_type` tags a 32-byte key + // as 256-bit, so lower it deliberately -- lowering does not need a hazardous closure, only + // raising does. + let mut key = + KeyMaterial::<32>::from_bytes_as_type(&[0x01; 32], KeyType::SymmetricCipherKey).unwrap(); + assert_eq!(key.security_strength(), SecurityStrength::_256bit); + + key.set_security_strength(SecurityStrength::_128bit).unwrap(); + assert!( + Aes256::new(&key).is_err(), + "AES-256 must reject a 32-byte key only derived at the 128-bit strength" + ); + + // The same key at its full strength is fine, so the rejection is about the strength tag and + // not about anything else having gone wrong with the key. + let good = + KeyMaterial::<32>::from_bytes_as_type(&[0x01; 32], KeyType::SymmetricCipherKey).unwrap(); + assert!(Aes256::new(&good).is_ok()); +} + +#[test] +fn a_correctly_typed_key_of_each_length_is_accepted() { + assert!(Aes128::new(&key_material(&KEY_128)).is_ok()); + assert!(Aes192::new(&key_material(&KEY_192)).is_ok()); + assert!(Aes256::new(&key_material(&KEY_256)).is_ok()); +} + +#[test] +fn debug_does_not_print_the_key_schedule() { + // The schedule is secret; `Debug` must not be a way to leak it. + let aes = Aes128::new(&key_material(&KEY_128)).unwrap(); + let rendered = format!("{aes:?}"); + assert_eq!(rendered, "AES-128"); + // No byte of the key should appear as hex in the output. + assert!(!rendered.contains("2b")); + assert!(!rendered.contains("7e")); +} diff --git a/crypto/aes-lowmemory/tests/sp800_38a_tests.rs b/crypto/aes-lowmemory/tests/sp800_38a_tests.rs new file mode 100644 index 00000000..8e975eca --- /dev/null +++ b/crypto/aes-lowmemory/tests/sp800_38a_tests.rs @@ -0,0 +1,176 @@ +//! Known-answer tests from NIST SP 800-38A Appendix F.1, "ECB Example Vectors". +//! +//! These are the only NIST-published known-answer vectors for AES-192 and AES-256 that live in a +//! specification document rather than a separate vector file -- FIPS 197 Appendix B only covers +//! AES-128, and FIPS 197 (Update 1) removed the Appendix C example vectors in favour of a pointer +//! to the CSRC website. `acvp_tests.rs` covers far more cases, but only when the `bc-test-data` +//! repository is present, so these vectors are the always-available known-answer floor. +//! +//! ECB applies the raw permutation to each block independently, so an ECB example vector *is* a +//! block-permutation test vector. (That is the only reason ECB appears in this crate; see the +//! crate docs on why you must not use it to encrypt anything.) +//! +//! The keys are the same three keys as FIPS 197 Appendix A.1, A.2 and A.3, so these vectors also +//! pin each key expansion against a NIST-published answer, in both directions. +//! +//! Transcribed from the published SP 800-38A PDF, sections F.1.1 through F.1.6. + +use bouncycastle_aes_lowmemory::{Aes128, Aes192, Aes256, BLOCK_LEN}; +use bouncycastle_core::key_material::{KeyMaterial, KeyType}; +use bouncycastle_hex as hex; + +/// The four plaintext blocks shared by every F.1 subsection. +const PLAINTEXTS: [&str; 4] = [ + "6bc1bee22e409f96e93d7e117393172a", + "ae2d8a571e03ac9c9eb76fac45af8e51", + "30c81c46a35ce411e5fbc1191a0a52ef", + "f69f2445df4f9b17ad2b417be66c3710", +]; + +/// F.1.1 / F.1.2 key. +const KEY_128: &str = "2b7e151628aed2a6abf7158809cf4f3c"; +/// F.1.1 ECB-AES128.Encrypt output blocks. +const CIPHERTEXTS_128: [&str; 4] = [ + "3ad77bb40d7a3660a89ecaf32466ef97", + "f5d3d58503b9699de785895a96fdbaaf", + "43b1cd7f598ece23881b00e3ed030688", + "7b0c785e27e8ad3f8223207104725dd4", +]; + +/// F.1.3 / F.1.4 key. +const KEY_192: &str = "8e73b0f7da0e6452c810f32b809079e562f8ead2522c6b7b"; +/// F.1.3 ECB-AES192.Encrypt output blocks. +const CIPHERTEXTS_192: [&str; 4] = [ + "bd334f1d6e45f25ff712a214571fa5cc", + "974104846d0ad3ad7734ecb3ecee4eef", + "ef7afd2270e2e60adce0ba2face6444e", + "9a4b41ba738d6c72fb16691603c18e0e", +]; + +/// F.1.5 / F.1.6 key. +const KEY_256: &str = "603deb1015ca71be2b73aef0857d77811f352c073b6108d72d9810a30914dff4"; +/// F.1.5 ECB-AES256.Encrypt output blocks. +const CIPHERTEXTS_256: [&str; 4] = [ + "f3eed1bdb5d2a03c064b5a7e3db181f8", + "591ccb10d410ed26dc5ba74a31362870", + "b6ed21b99ca6f4f9f153e7b1beafed1d", + "23304b7a39f9f3ff067d8d8f9e24ecc7", +]; + +fn block(hex_str: &str) -> [u8; BLOCK_LEN] { + hex::decode(hex_str).expect("valid hex").try_into().expect("16 bytes") +} + +fn key_material(hex_str: &str) -> KeyMaterial { + let bytes = hex::decode(hex_str).expect("valid hex"); + assert_eq!(bytes.len(), N, "key length"); + KeyMaterial::::from_bytes_as_type(&bytes, KeyType::SymmetricCipherKey) + .expect("a valid symmetric cipher key") +} + +// ---- F.1.1 / F.1.2 ECB-AES128 ------------------------------------------------------------- + +#[test] +fn f_1_1_ecb_aes128_encrypt() { + let aes = Aes128::new(&key_material::<16>(KEY_128)).unwrap(); + for (i, (pt, ct)) in PLAINTEXTS.iter().zip(CIPHERTEXTS_128.iter()).enumerate() { + let mut b = block(pt); + aes.encrypt_block(&mut b); + assert_eq!(b, block(ct), "F.1.1 block #{}", i + 1); + } +} + +#[test] +fn f_1_2_ecb_aes128_decrypt() { + let aes = Aes128::new(&key_material::<16>(KEY_128)).unwrap(); + for (i, (pt, ct)) in PLAINTEXTS.iter().zip(CIPHERTEXTS_128.iter()).enumerate() { + let mut b = block(ct); + aes.decrypt_block(&mut b); + assert_eq!(b, block(pt), "F.1.2 block #{}", i + 1); + } +} + +// ---- F.1.3 / F.1.4 ECB-AES192 ------------------------------------------------------------- + +#[test] +fn f_1_3_ecb_aes192_encrypt() { + let aes = Aes192::new(&key_material::<24>(KEY_192)).unwrap(); + for (i, (pt, ct)) in PLAINTEXTS.iter().zip(CIPHERTEXTS_192.iter()).enumerate() { + let mut b = block(pt); + aes.encrypt_block(&mut b); + assert_eq!(b, block(ct), "F.1.3 block #{}", i + 1); + } +} + +#[test] +fn f_1_4_ecb_aes192_decrypt() { + let aes = Aes192::new(&key_material::<24>(KEY_192)).unwrap(); + for (i, (pt, ct)) in PLAINTEXTS.iter().zip(CIPHERTEXTS_192.iter()).enumerate() { + let mut b = block(ct); + aes.decrypt_block(&mut b); + assert_eq!(b, block(pt), "F.1.4 block #{}", i + 1); + } +} + +// ---- F.1.5 / F.1.6 ECB-AES256 ------------------------------------------------------------- + +#[test] +fn f_1_5_ecb_aes256_encrypt() { + let aes = Aes256::new(&key_material::<32>(KEY_256)).unwrap(); + for (i, (pt, ct)) in PLAINTEXTS.iter().zip(CIPHERTEXTS_256.iter()).enumerate() { + let mut b = block(pt); + aes.encrypt_block(&mut b); + assert_eq!(b, block(ct), "F.1.5 block #{}", i + 1); + } +} + +#[test] +fn f_1_6_ecb_aes256_decrypt() { + let aes = Aes256::new(&key_material::<32>(KEY_256)).unwrap(); + for (i, (pt, ct)) in PLAINTEXTS.iter().zip(CIPHERTEXTS_256.iter()).enumerate() { + let mut b = block(ct); + aes.decrypt_block(&mut b); + assert_eq!(b, block(pt), "F.1.6 block #{}", i + 1); + } +} + +// ---- the two-block path against the same vectors ------------------------------------------- + +/// The two-block entry points must produce exactly the single-block answers. +/// +/// This is the test that pins the interleave: a mistake in which bit of each pair belongs to +/// which block shows up here and nowhere in the single-block tests, because a single-block call +/// puts the same data in both halves. +#[test] +fn two_block_path_matches_the_f_1_vectors() { + let aes = Aes128::new(&key_material::<16>(KEY_128)).unwrap(); + + // Blocks 1 and 2 as a pair, then 3 and 4. + for chunk in 0..2 { + let (i, j) = (chunk * 2, chunk * 2 + 1); + let mut pair = [block(PLAINTEXTS[i]), block(PLAINTEXTS[j])]; + aes.encrypt_blocks2(&mut pair); + assert_eq!(pair[0], block(CIPHERTEXTS_128[i]), "pair {chunk} slot 0"); + assert_eq!(pair[1], block(CIPHERTEXTS_128[j]), "pair {chunk} slot 1"); + + aes.decrypt_blocks2(&mut pair); + assert_eq!(pair[0], block(PLAINTEXTS[i])); + assert_eq!(pair[1], block(PLAINTEXTS[j])); + } +} + +/// Swapping the two slots must swap the two results, and nothing else. +#[test] +fn two_block_path_is_slot_symmetric() { + let aes = Aes256::new(&key_material::<32>(KEY_256)).unwrap(); + + let mut forward = [block(PLAINTEXTS[0]), block(PLAINTEXTS[1])]; + let mut reversed = [block(PLAINTEXTS[1]), block(PLAINTEXTS[0])]; + aes.encrypt_blocks2(&mut forward); + aes.encrypt_blocks2(&mut reversed); + + assert_eq!(forward[0], reversed[1]); + assert_eq!(forward[1], reversed[0]); + assert_eq!(forward[0], block(CIPHERTEXTS_256[0])); + assert_eq!(forward[1], block(CIPHERTEXTS_256[1])); +} diff --git a/crypto/core-test-framework/src/electronic_code_book.rs b/crypto/core-test-framework/src/electronic_code_book.rs new file mode 100644 index 00000000..4691e3f9 --- /dev/null +++ b/crypto/core-test-framework/src/electronic_code_book.rs @@ -0,0 +1,200 @@ +//! Shared conformance tests for [`ElectronicCodeBook`] implementors. + +use crate::DUMMY_SEED; +use bouncycastle_core::errors::SymmetricCipherError; +use bouncycastle_core::key_material::{ + KeyMaterial, KeyMaterialTrait, KeyType, do_hazardous_operations, +}; +use bouncycastle_core::traits::{ElectronicCodeBook, SecurityStrength}; + +/// Instance of the test framework. +pub struct TestFrameworkElectronicCodeBook { + // Put any config options here +} + +impl Default for TestFrameworkElectronicCodeBook { + fn default() -> Self { + Self::new() + } +} + +impl TestFrameworkElectronicCodeBook { + /// + pub fn new() -> Self { + Self {} + } + + /// Exercises the trait contract for one implementor. + /// + /// Checks, in order: + /// * `decrypt_block` inverts `encrypt_block` on every block of [`DUMMY_SEED`]; + /// * the permutation actually permutes (a block is not left unchanged); + /// * distinct inputs give distinct outputs, i.e. it is injective on the blocks tested; + /// * `encrypt_blocks2` agrees with two `encrypt_block` calls **including their order**, and + /// likewise for `decrypt_blocks2` -- this is what pins an override to the default's + /// semantics, and it is the reason the pair methods are worth having in the trait at all; + /// * the pair methods round-trip each other; + /// * `encrypt_blocks8` / `decrypt_blocks8` likewise agree with eight single-block calls in + /// order, and round-trip each other; + /// * a key of the wrong [`KeyType`] is rejected; + /// * the security-strength policy matches [`Algorithm::MAX_SECURITY_STRENGTH`]. + /// + /// [`Algorithm::MAX_SECURITY_STRENGTH`]: bouncycastle_core::traits::Algorithm::MAX_SECURITY_STRENGTH + pub fn test< + const KEY_LEN: usize, + const BLOCK_LEN: usize, + P: ElectronicCodeBook, + >( + &self, + ) { + let key = KeyMaterial::::from_bytes_as_type( + &DUMMY_SEED[..KEY_LEN], + KeyType::SymmetricCipherKey, + ) + .unwrap(); + let perm = P::new(&key).unwrap(); + + let blocks = DUMMY_SEED.as_chunks::().0; + + // encrypt / decrypt are inverses, and the permutation is not the identity. + for block in blocks.iter() { + let mut buf = *block; + perm.encrypt_block(&mut buf); + assert_ne!(&buf, block, "encrypt_block must not be the identity"); + perm.decrypt_block(&mut buf); + assert_eq!(&buf, block, "decrypt_block must invert encrypt_block"); + + // ...and the other way round, since a mode may call either direction first. + let mut buf = *block; + perm.decrypt_block(&mut buf); + assert_ne!(&buf, block, "decrypt_block must not be the identity"); + perm.encrypt_block(&mut buf); + assert_eq!(&buf, block, "encrypt_block must invert decrypt_block"); + } + + // Distinct inputs must give distinct outputs. A permutation is injective, so this catches + // an implementation that collapses inputs (e.g. one that masks part of the block away). + for pair in blocks.as_chunks::<2>().0.iter() { + let [a, b] = pair; + assert_ne!(a, b, "DUMMY_SEED blocks should differ; test setup problem"); + let mut ea = *a; + let mut eb = *b; + perm.encrypt_block(&mut ea); + perm.encrypt_block(&mut eb); + assert_ne!(ea, eb, "distinct blocks must encrypt to distinct blocks"); + } + + // The pair methods must be indistinguishable from the single-block ones, in both slots. + // An override that swapped the two results, or that processed only one of them, fails here. + for pair in blocks.as_chunks::<2>().0.iter() { + let [a, b] = pair; + + let mut singly = [*a, *b]; + perm.encrypt_block(&mut singly[0]); + perm.encrypt_block(&mut singly[1]); + let mut paired = [*a, *b]; + perm.encrypt_blocks2(&mut paired); + assert_eq!(paired, singly, "encrypt_blocks2 must match two encrypt_block calls"); + + let mut singly = [*a, *b]; + perm.decrypt_block(&mut singly[0]); + perm.decrypt_block(&mut singly[1]); + let mut paired = [*a, *b]; + perm.decrypt_blocks2(&mut paired); + assert_eq!(paired, singly, "decrypt_blocks2 must match two decrypt_block calls"); + + // Round-trip through the pair methods alone. + let mut buf = [*a, *b]; + perm.encrypt_blocks2(&mut buf); + perm.decrypt_blocks2(&mut buf); + assert_eq!(buf, [*a, *b], "decrypt_blocks2 must invert encrypt_blocks2"); + } + + // The eight-block methods must be indistinguishable from eight single-block calls, in every + // slot, whether they are the trait default (four pair calls) or an override. + let eights = blocks.as_chunks::<8>().0; + assert!( + !eights.is_empty(), + "DUMMY_SEED should hold at least eight blocks; test setup problem" + ); + for eight in eights.iter() { + let mut singly = *eight; + for block in singly.iter_mut() { + perm.encrypt_block(block); + } + let mut batched = *eight; + perm.encrypt_blocks8(&mut batched); + assert_eq!(batched, singly, "encrypt_blocks8 must match eight encrypt_block calls"); + + let mut singly = *eight; + for block in singly.iter_mut() { + perm.decrypt_block(block); + } + let mut batched = *eight; + perm.decrypt_blocks8(&mut batched); + assert_eq!(batched, singly, "decrypt_blocks8 must match eight decrypt_block calls"); + + let mut buf = *eight; + perm.encrypt_blocks8(&mut buf); + perm.decrypt_blocks8(&mut buf); + assert_eq!(buf, *eight, "decrypt_blocks8 must invert encrypt_blocks8"); + } + + // A pair of *identical* blocks must give a pair of identical outputs. This catches an + // implementation whose two lanes are not actually independent. + let block = blocks[0]; + let mut buf = [block, block]; + perm.encrypt_blocks2(&mut buf); + assert_eq!(buf[0], buf[1], "identical inputs must give identical outputs"); + let mut single = block; + perm.encrypt_block(&mut single); + assert_eq!(buf[0], single); + + // error case: KeyMaterial of the wrong type + let mac_key = + KeyMaterial::::from_bytes_as_type(&DUMMY_SEED[..KEY_LEN], KeyType::MACKey) + .unwrap(); + match P::new(&mac_key) { + Err(SymmetricCipherError::KeyMaterialError(_)) => { /* good */ } + _ => panic!("A key that is not a SymmetricCipherKey should have been rejected"), + }; + + // error case: security strengths too weak, and strong enough + let mut key = KeyMaterial::::from_bytes_as_type( + &DUMMY_SEED[..KEY_LEN], + KeyType::SymmetricCipherKey, + ) + .unwrap(); + let security_strengths = [ + SecurityStrength::None, + SecurityStrength::_112bit, + SecurityStrength::_128bit, + SecurityStrength::_192bit, + SecurityStrength::_256bit, + ]; + for ss in security_strengths.iter() { + // `set_security_strength` enforces its key-length guard even inside a + // do_hazardous_operations() closure, so skip the strengths a KEY_LEN-byte key cannot + // carry. Do NOT relax that guard in `KeyMaterial`: core's + // `test_hazardous_ops_error_handling` requires it to stay enforced. + if ss > &SecurityStrength::from_bytes(KEY_LEN) { + continue; + } + + // Tag the key at an arbitrary strength for the purpose of this test. + do_hazardous_operations(&mut key, |key| key.set_security_strength(ss.clone())).unwrap(); + + match P::new(&key) { + Ok(_) => assert!( + ss >= &P::MAX_SECURITY_STRENGTH, + "should have required a key at least as strong as the algorithm" + ), + Err(SymmetricCipherError::KeyMaterialError(_)) => assert!( + ss < &P::MAX_SECURITY_STRENGTH, + "should not have rejected a key strong enough for the algorithm" + ), + _ => panic!("Unexpected error"), + }; + } + } +} diff --git a/crypto/core-test-framework/src/hash.rs b/crypto/core-test-framework/src/hash.rs index 6c880ba9..44037462 100644 --- a/crypto/core-test-framework/src/hash.rs +++ b/crypto/core-test-framework/src/hash.rs @@ -99,7 +99,7 @@ impl TestFrameworkHash { /*** fn do_final_partial_bits_out(self, partial_byte: u8, num_bits: usize, output: &mut [u8]) -> Result; ***/ // A known-answer test for these needs a different expected output from the rest of this - // Helper: the digest of `input` finished with the low `num_bits` bits of `partial_byte`. + // Helper: the digest of `input` finished with the top `num_bits` bits of `partial_byte`. let partial_digest = |partial_byte: u8, num_bits: usize| -> Vec { let mut message_digest = H::default(); message_digest.do_update(input); @@ -119,17 +119,18 @@ impl TestFrameworkHash { ); } - // "The num_bits message bits are taken from the least significant bits of - // partial_byte": the unused high bits are not part of the message, and so must not - // change the output. + // "the num_bits message bits are the most significant bits of partial_byte ... and the + // low 8 - num_bits bits (the BIT STRING's "unused bits") are ignored": so the unused + // low bits are not part of the message, and must not change the output. for num_bits in 0..=7 { - // no overflow: 1u8 << 7 == 0x80 - let mask = (1u8 << num_bits) - 1; + // the used bits are the top num_bits; built in u16 so that num_bits == 0 cannot overflow + let mask = (0xFF00u16 >> num_bits) as u8; for partial_byte in [0x00u8, 0x5A, 0xA5, 0xFF] { assert_eq!( partial_digest(partial_byte, num_bits), partial_digest(partial_byte & mask, num_bits), - "bits above num_bits = {num_bits} must be ignored / partial_byte: {partial_byte:#04X}" + "the low 8 - num_bits = {} bits must be ignored / partial_byte: {partial_byte:#04X}", + 8 - num_bits ); } } @@ -184,11 +185,14 @@ impl TestFrameworkHash { // Each (num_bits, partial_byte) pair is a distinct message, and so must produce a // distinct digest. This is what catches an implementation that silently drops the - // partial bits, or absorbs the wrong number of them. + // partial bits, or absorbs the wrong number of them. The num_bits message bits are + // enumerated in the top bits of the byte (the shift is done in u16 so that + // num_bits == 0, an 8-bit shift, cannot overflow). let mut partial_outputs: Vec> = Vec::new(); for num_bits in 0..=7 { - for partial_byte in 0..(1u16 << num_bits) { - partial_outputs.push(partial_digest(partial_byte as u8, num_bits)); + for message_bits in 0..(1u16 << num_bits) { + let partial_byte = (message_bits << (8 - num_bits)) as u8; + partial_outputs.push(partial_digest(partial_byte, num_bits)); } } let num_partial_outputs = partial_outputs.len(); diff --git a/crypto/core-test-framework/src/lib.rs b/crypto/core-test-framework/src/lib.rs index 2dced83d..45d922e4 100644 --- a/crypto/core-test-framework/src/lib.rs +++ b/crypto/core-test-framework/src/lib.rs @@ -14,6 +14,7 @@ // properly document everything. #![forbid(missing_docs)] +pub mod electronic_code_book; pub mod hash; pub mod kdf; pub mod kem; diff --git a/crypto/core-test-framework/src/symmetric_ciphers.rs b/crypto/core-test-framework/src/symmetric_ciphers.rs index 57fc0ee1..2aa5f8d4 100644 --- a/crypto/core-test-framework/src/symmetric_ciphers.rs +++ b/crypto/core-test-framework/src/symmetric_ciphers.rs @@ -1,23 +1,30 @@ //! Generic behaviour tests for the symmetric cipher traits. -use crate::DUMMY_SEED; +use crate::{DUMMY_SEED, FixedSeedRNG}; use bouncycastle_core::errors::SymmetricCipherError; use bouncycastle_core::key_material::{ KeyMaterial, KeyMaterialTrait, KeyType, do_hazardous_operations, }; use bouncycastle_core::traits::{ - AEADCipher, BlockCipher, SecurityStrength, StreamCipher, SymmetricCipher, + AEADCipher, BlockCipherDecryptor, BlockCipherEncryptor, SecurityStrength, + StreamCipherDecryptor, StreamCipherEncryptor, SymmetricCipher, SymmetricCipherDecryptor, + SymmetricCipherEncryptor, }; /// Instance of the test framework. pub struct TestFrameworkSymmetricCipher { - // Put any config options here + /// For [`test_encryptor_decryptor`](Self::test_encryptor_decryptor): the plaintext length + /// granularity the pair accepts. 1 (the default) means every length round-trips. A larger value + /// -- the block length, for a `PaddedEncryptor` over `NoPadding` -- means only multiples of it + /// round-trip, and every other length must be *rejected* by `do_final` / `encrypt_out` with a + /// `PaddingError`, which the test then asserts instead. + pub required_alignment: usize, } impl TestFrameworkSymmetricCipher { /// pub fn new() -> Self { - Self {} + Self { required_alignment: 1 } } /// Test all the members of trait SymmetricCipher against the given input-output pair. @@ -108,6 +115,262 @@ impl TestFrameworkSymmetricCipher { } } +impl TestFrameworkSymmetricCipher { + /// Exercises the [`SymmetricCipherEncryptor`] / [`SymmetricCipherDecryptor`] contract for a + /// paired implementor. + /// + /// Checks, in order: + /// * the one-shot `encrypt_out` / `decrypt_out` round-trip for every plaintext length from + /// 0 to a few times `FINAL_LEN`, writing exactly `encrypt_out_len` bytes and at most + /// `decrypt_out_max_len`; + /// * the `std` one-shots agree with the `_out` ones; + /// * streaming in every chunking agrees with the one-shot, `update_out_len` is exact on every + /// call, and `do_final_out` agrees with `do_final`; + /// * a driven RNG reproduces its init data, and the same key and init data give the same + /// ciphertext through `do_encrypt_init_rng` and `encrypt_out_rng`; + /// * a corrupted ciphertext either fails to decrypt or decrypts to something else; + /// * an output buffer that is too short is refused, naming the required length, before any + /// work is done; + /// * a key of the wrong [`KeyType`] is rejected, and the security-strength policy matches + /// [`Algorithm::MAX_SECURITY_STRENGTH`]. + /// + /// [`Algorithm::MAX_SECURITY_STRENGTH`]: bouncycastle_core::traits::Algorithm::MAX_SECURITY_STRENGTH + pub fn test_encryptor_decryptor< + const KEY_LEN: usize, + const INIT_DATA_LEN: usize, + const FINAL_LEN: usize, + E: SymmetricCipherEncryptor, + D: SymmetricCipherDecryptor, + >( + &self, + ) { + let key = KeyMaterial::::from_bytes_as_type( + &DUMMY_SEED[..KEY_LEN], + KeyType::SymmetricCipherKey, + ) + .unwrap(); + // Enough plaintext lengths to cross several final-chunk boundaries (a block, for padding). + let align = self.required_alignment.max(1); + let max_len = (3 * FINAL_LEN.max(1) + 5).next_multiple_of(align); + + // one-shot round trip, every (accepted) length; every other length must be refused + for len in 0..=max_len { + let msg = &DUMMY_SEED[..len]; + if !len.is_multiple_of(align) { + let mut ct = vec![0u8; E::encrypt_out_len(len) + FINAL_LEN]; + match E::encrypt_out(&key, msg, &mut ct) { + Err(SymmetricCipherError::PaddingError(_)) => {} + other => panic!("len {len} is not aligned and must be refused, got {other:?}"), + } + let (mut enc, _) = E::do_encrypt_init(&key).unwrap(); + let mut buf = vec![0u8; enc.update_out_len(len)]; + enc.do_update_out(msg, &mut buf).unwrap(); + assert!( + matches!(enc.do_final(), Err(SymmetricCipherError::PaddingError(_))), + "len {len}: streaming do_final must refuse an unaligned message" + ); + continue; + } + let mut ct = vec![0u8; E::encrypt_out_len(len)]; + let (init_data, ct_len) = E::encrypt_out(&key, msg, &mut ct).unwrap(); + assert_eq!(ct_len, ct.len(), "encrypt_out must write exactly encrypt_out_len bytes"); + + let mut pt = vec![0u8; D::decrypt_out_max_len(ct_len)]; + let pt_len = D::decrypt_out(&key, &init_data, &ct[..ct_len], &mut pt).unwrap(); + assert!(pt_len <= pt.len(), "decrypt_out_max_len must bound the plaintext"); + assert_eq!(&pt[..pt_len], msg, "one-shot round trip, len {len}"); + + // the std one-shots agree with the _out ones for the same init data + let (init_data2, ct2) = E::encrypt(&key, msg).unwrap(); + assert_eq!(ct2.len(), ct_len, "encrypt must return exactly the bytes written"); + let pt2 = D::decrypt(&key, &init_data2, &ct2).unwrap(); + assert_eq!(pt2, msg, "std round trip, len {len}"); + let pt3 = D::decrypt(&key, &init_data, &ct[..ct_len]).unwrap(); + assert_eq!(pt3, msg, "decrypt must agree with decrypt_out"); + } + + // streaming in every chunking agrees with the one-shot + let len = max_len; + let msg = &DUMMY_SEED[..len]; + let chunkings: [usize; 8] = + [1, 2, 3, 7, FINAL_LEN.max(1), FINAL_LEN + 1, 2 * FINAL_LEN + 3, len]; + for chunk in chunkings { + // encrypt in chunks, checking update_out_len is exact each time + let (mut enc, init_data) = E::do_encrypt_init(&key).unwrap(); + let mut ct = Vec::new(); + for piece in msg.chunks(chunk) { + let expect = enc.update_out_len(piece.len()); + let mut buf = vec![0u8; expect]; + let n = enc.do_update_out(piece, &mut buf).unwrap(); + assert_eq!(n, expect, "update_out_len must be exact (encrypt, chunk {chunk})"); + ct.extend_from_slice(&buf[..n]); + } + let mut last = [0u8; FINAL_LEN]; + let last_len = enc.do_final_out(&mut last).unwrap(); + assert!(last_len <= FINAL_LEN, "do_final_out must not claim more than FINAL_LEN bytes"); + ct.extend_from_slice(&last[..last_len]); + assert_eq!( + ct.len(), + E::encrypt_out_len(len), + "streaming total must match encrypt_out_len" + ); + + // one-shot decrypt of the streamed ciphertext + let mut pt = vec![0u8; D::decrypt_out_max_len(ct.len())]; + let m = D::decrypt_out(&key, &init_data, &ct, &mut pt).unwrap(); + assert_eq!( + &pt[..m], + msg, + "streamed ciphertext must decrypt in one shot (chunk {chunk})" + ); + + // decrypt in the same chunks, via do_final and via do_final_out + for use_out in [false, true] { + let mut dec = D::do_decrypt_init(&key, &init_data).unwrap(); + let mut rec = Vec::new(); + for piece in ct.chunks(chunk) { + let expect = dec.update_out_len(piece.len()); + let mut buf = vec![0u8; expect]; + let n = dec.do_update_out(piece, &mut buf).unwrap(); + assert_eq!(n, expect, "update_out_len must be exact (decrypt, chunk {chunk})"); + rec.extend_from_slice(&buf[..n]); + } + let (block, data_len) = if use_out { + let mut block = [0u8; FINAL_LEN]; + let data_len = dec.do_final_out(&mut block).unwrap(); + (block, data_len) + } else { + dec.do_final().unwrap() + }; + rec.extend_from_slice(&block[..data_len]); + assert_eq!(rec, msg, "streamed round trip (chunk {chunk}, do_final_out {use_out})"); + } + } + + // a driven RNG reproduces its init data, and determines the ciphertext + let seed: [u8; INIT_DATA_LEN] = core::array::from_fn(|i| DUMMY_SEED[100 + i]); + let (mut enc, init_data) = + E::do_encrypt_init_rng(&key, &mut FixedSeedRNG::::new(seed)).unwrap(); + assert_eq!(init_data, seed, "a fixed RNG must yield its stream as the init data"); + let mut streamed = vec![0u8; enc.update_out_len(len)]; + let n = enc.do_update_out(msg, &mut streamed).unwrap(); + streamed.truncate(n); + let (last, last_len) = enc.do_final().unwrap(); + streamed.extend_from_slice(&last[..last_len]); + let mut one_shot = vec![0u8; E::encrypt_out_len(len)]; + let (init_data2, n2) = E::encrypt_out_rng( + &key, + &mut FixedSeedRNG::::new(seed), + msg, + &mut one_shot, + ) + .unwrap(); + assert_eq!(init_data2, seed); + assert_eq!( + &one_shot[..n2], + &streamed[..], + "same key and init data must give the same ciphertext" + ); + + // corrupting the ciphertext does not give back the plaintext (or fails to decrypt) + let mut ct = vec![0u8; E::encrypt_out_len(len)]; + let (init_data, ct_len) = E::encrypt_out(&key, msg, &mut ct).unwrap(); + assert!(ct_len > 0, "the test message is non-empty, so its ciphertext must be"); + for flip in [0usize, ct_len / 2, ct_len - 1] { + let mut bad = ct[..ct_len].to_vec(); + bad[flip] ^= 0x80; + let mut pt = vec![0u8; D::decrypt_out_max_len(ct_len)]; + match D::decrypt_out(&key, &init_data, &bad, &mut pt) { + Ok(m) => { + assert_ne!(&pt[..m], msg, "corrupted byte {flip} decrypted to the plaintext") + } + Err(SymmetricCipherError::DecryptionFailed) + | Err(SymmetricCipherError::PaddingError(_)) + | Err(SymmetricCipherError::AEADTagCheckFailed) => { /* also fine */ } + Err(e) => panic!("unexpected error for corrupted byte {flip}: {e:?}"), + } + } + + // too-short output buffers are refused with the required length, before any work is done + let need = E::encrypt_out_len(len); + let mut short = vec![0u8; need - 1]; + match E::encrypt_out(&key, msg, &mut short) { + Err(SymmetricCipherError::IncorrectOutputBufferLength(_, n)) => assert_eq!(n, need), + other => panic!("encrypt_out into a short buffer: {other:?}"), + } + let need = D::decrypt_out_max_len(ct_len); + if need > 0 { + let mut short = vec![0u8; need - 1]; + match D::decrypt_out(&key, &init_data, &ct[..ct_len], &mut short) { + Err(SymmetricCipherError::IncorrectOutputBufferLength(_, n)) => assert_eq!(n, need), + other => panic!("decrypt_out into a short buffer: {other:?}"), + } + } + let (mut enc, _) = E::do_encrypt_init(&key).unwrap(); + let need = enc.update_out_len(len); + if need > 0 { + let mut short = vec![0u8; need - 1]; + match enc.do_update_out(msg, &mut short) { + Err(SymmetricCipherError::IncorrectOutputBufferLength(_, n)) => assert_eq!(n, need), + other => panic!("do_update_out into a short buffer: {other:?}"), + } + } + + // error case: KeyMaterial of the wrong type + let mac_key = + KeyMaterial::::from_bytes_as_type(&DUMMY_SEED[..KEY_LEN], KeyType::MACKey) + .unwrap(); + match E::do_encrypt_init(&mac_key) { + Err(SymmetricCipherError::KeyMaterialError(_)) => { /* good */ } + _ => panic!("A key that is not a SymmetricCipherKey should have been rejected"), + }; + match D::do_decrypt_init(&mac_key, &init_data) { + Err(SymmetricCipherError::KeyMaterialError(_)) => { /* good */ } + _ => panic!("A key that is not a SymmetricCipherKey should have been rejected"), + }; + + // error case: security strengths too weak, and strong enough + let mut key = KeyMaterial::::from_bytes_as_type( + &DUMMY_SEED[..KEY_LEN], + KeyType::SymmetricCipherKey, + ) + .unwrap(); + let security_strengths = [ + SecurityStrength::None, + SecurityStrength::_112bit, + SecurityStrength::_128bit, + SecurityStrength::_192bit, + SecurityStrength::_256bit, + ]; + for ss in security_strengths.iter() { + // Skip the strengths a KEY_LEN-byte key cannot carry; see `TestFrameworkElectronicCodeBook`. + if ss > &SecurityStrength::from_bytes(KEY_LEN) { + continue; + } + do_hazardous_operations(&mut key, |key| key.set_security_strength(*ss)).unwrap(); + + match E::do_encrypt_init(&key) { + Ok(_) => assert!( + ss >= &E::MAX_SECURITY_STRENGTH, + "should have required a key at least as strong as the algorithm" + ), + Err(SymmetricCipherError::KeyMaterialError(_)) => assert!( + ss < &E::MAX_SECURITY_STRENGTH, + "should not have rejected a key strong enough for the algorithm" + ), + _ => panic!("Unexpected error"), + }; + match D::do_decrypt_init(&key, &init_data) { + Ok(_) => assert!(ss >= &D::MAX_SECURITY_STRENGTH), + Err(SymmetricCipherError::KeyMaterialError(_)) => { + assert!(ss < &D::MAX_SECURITY_STRENGTH) + } + _ => panic!("Unexpected error"), + }; + } + } +} + /// Instance of the test framework. pub struct TestFrameworkBlockCipher { // Put any config options here @@ -124,7 +387,8 @@ impl TestFrameworkBlockCipher { const KEY_LEN: usize, const INIT_DATA_LEN: usize, const BLOCK_LEN: usize, - C: BlockCipher, + E: BlockCipherEncryptor, + D: BlockCipherDecryptor, >( &self, ) { @@ -135,42 +399,88 @@ impl TestFrameworkBlockCipher { .unwrap(); // to test blocks, we'll chunk our dummy seed - let (mut encryptor, iv) = C::do_encrypt_init(&key).unwrap(); - let mut decryptor = C::do_decrypt_init(&key, &iv).unwrap(); + let (mut encryptor, iv) = E::do_encrypt_init(&key).unwrap(); + let mut decryptor = D::do_decrypt_init(&key, &iv).unwrap(); + // one block at a time, through the flat streaming methods (LEN = BLOCK_LEN), in place for msg_chunk in DUMMY_SEED.as_chunks::().0.iter() { - let ct = encryptor.do_encrypt_block(msg_chunk).unwrap(); - let pt = decryptor.do_decrypt_block(&ct).unwrap(); - assert_eq!(msg_chunk, &pt); + let mut buf = *msg_chunk; + encryptor.do_encrypt(&mut buf).unwrap(); + decryptor.do_decrypt(&mut buf).unwrap(); + assert_eq!(msg_chunk, &buf); } - // do it again using the _out versions - - let (mut encryptor, iv) = C::do_encrypt_init(&key).unwrap(); - let mut decryptor = C::do_decrypt_init(&key, &iv).unwrap(); - - let mut ct = [0u8; BLOCK_LEN]; - let mut pt = [0u8; BLOCK_LEN]; - for msg_chunk in DUMMY_SEED.as_chunks::().0.iter() { - let ct_bytes_written = encryptor.do_encrypt_block_out(msg_chunk, &mut ct).unwrap(); - assert_eq!(ct_bytes_written, BLOCK_LEN); - - let pt_bytes_written = decryptor.do_decrypt_block_out(&ct, &mut pt).unwrap(); - assert_eq!(pt_bytes_written, BLOCK_LEN); + // multi-block (two at a time) through the implementor hook `do_*_blocks`: blocks encrypted together + // must decrypt both together and one at a time, and blocks encrypted one at a time must + // decrypt together. + let (mut encryptor, iv) = E::do_encrypt_init(&key).unwrap(); + let mut decryptor = D::do_decrypt_init(&key, &iv).unwrap(); + + for msg_pair in DUMMY_SEED.as_chunks::().0.as_chunks::<2>().0.iter() { + // encrypt together, decrypt together + let mut buf = *msg_pair; + encryptor.do_encrypt_blocks(&mut buf).unwrap(); + decryptor.do_decrypt_blocks(&mut buf).unwrap(); + assert_eq!(msg_pair, &buf); + + // encrypt together, decrypt one at a time + let mut buf = *msg_pair; + encryptor.do_encrypt_blocks(&mut buf).unwrap(); + for (msg_chunk, block) in msg_pair.iter().zip(buf.iter_mut()) { + decryptor.do_decrypt(block).unwrap(); + assert_eq!(msg_chunk, block); + } - assert_eq!(msg_chunk, &pt); + // encrypt one at a time, decrypt together + let mut buf = *msg_pair; + for block in buf.iter_mut() { + encryptor.do_encrypt(block).unwrap(); + } + decryptor.do_decrypt_blocks(&mut buf).unwrap(); + assert_eq!(msg_pair, &buf); } - // test that the iv is random (ie not the same on two runs) - let (_encryptor, iv1) = C::do_encrypt_init(&key).unwrap(); - let (_encryptor, iv2) = C::do_encrypt_init(&key).unwrap(); - assert_ne!(iv1, iv2); + // one-shot API: a block-aligned byte array, in place. It must round-trip and agree with the + // streaming API for the same key and init data. Only LEN = BLOCK_LEN can be formed + // generically here (`2 * BLOCK_LEN` needs generic_const_exprs); multi-block one-shots are + // covered by the modes crate's tests with a concrete BLOCK_LEN. + let one_block: &[u8; BLOCK_LEN] = &DUMMY_SEED.as_chunks::().0[0]; + let mut buf = *one_block; + let iv = E::encrypt(&key, &mut buf).unwrap(); + let ct = buf; + D::decrypt(&key, &iv, &mut buf).unwrap(); + assert_eq!(buf, *one_block); + // ...and it must agree with the streaming API under the same init data. + let mut streamed = D::do_decrypt_init(&key, &iv).unwrap(); + let mut buf = ct; + streamed.do_decrypt(&mut buf).unwrap(); + assert_eq!(buf, *one_block); + + // the RNG-taking one-shot must give the streaming API's answer for the same RNG stream + let pinned = [0xA5u8; INIT_DATA_LEN]; + let mut expected = *one_block; + let (mut streamed, iv_streamed) = + E::do_encrypt_init_rng(&key, &mut FixedSeedRNG::::new(pinned)).unwrap(); + streamed.do_encrypt(&mut expected).unwrap(); + let mut buf = *one_block; + let iv = E::encrypt_rng(&key, &mut FixedSeedRNG::::new(pinned), &mut buf) + .unwrap(); + assert_eq!(iv, iv_streamed); + assert_eq!(buf, expected); + + // test that the iv is random (ie not the same on two runs). A mode with no init data at all + // (ECB, INIT_DATA_LEN == 0) has nothing to compare: two empty arrays are always equal. + if INIT_DATA_LEN > 0 { + let (_encryptor, iv1) = E::do_encrypt_init(&key).unwrap(); + let (_encryptor, iv2) = E::do_encrypt_init(&key).unwrap(); + assert_ne!(iv1, iv2); + } // error case: KeyMaterial of wrong type let mac_key = KeyMaterial::::from_bytes_as_type(&DUMMY_SEED[..KEY_LEN], KeyType::MACKey) .unwrap(); - match C::do_encrypt_init(&mac_key) { + match E::do_encrypt_init(&mac_key) { Err(SymmetricCipherError::KeyMaterialError(_)) => { /* good */ } _ => panic!("Unexpected error"), }; @@ -189,20 +499,28 @@ impl TestFrameworkBlockCipher { SecurityStrength::_256bit, ]; for ss in security_strengths.iter() { - // Tag the key at an arbitrary strength for the purpose of this test. Inside a - // do_hazardous_operations() closure, set_security_strength() raises the strength - // (and bypasses the key-length guard) without complaining. + // `set_security_strength` enforces its key-length guard even inside a + // do_hazardous_operations() closure -- a KEY_LEN-byte key cannot be tagged at a + // strength above `from_bytes(KEY_LEN)` -- so skip the strengths this key cannot carry + // rather than unwrapping an error. (A 16-byte key can reach 128-bit and no higher.) + // Do NOT "fix" this by relaxing that guard in `KeyMaterial`: core's + // `test_hazardous_ops_error_handling` requires it to stay enforced. + if ss > &SecurityStrength::from_bytes(KEY_LEN) { + continue; + } + + // Tag the key at an arbitrary strength for the purpose of this test. do_hazardous_operations(&mut key, |key| key.set_security_strength(ss.clone())).unwrap(); - match C::do_encrypt_init(&key) { + match E::do_encrypt_init(&key) { Ok(_) => { - if ss >= &C::MAX_SECURITY_STRENGTH { /* good */ + if ss >= &E::MAX_SECURITY_STRENGTH { /* good */ } else { panic!("Should have been a strong enough key"); } } Err(SymmetricCipherError::KeyMaterialError(_)) => { - if ss < &C::MAX_SECURITY_STRENGTH { /* good */ + if ss < &E::MAX_SECURITY_STRENGTH { /* good */ } else { panic!("Should not have accepted a key weaker than algorithm"); } @@ -366,15 +684,173 @@ impl TestFrameworkStreamCipher { Self {} } - /// Test all the members of trait StreamCipher against the given input-output pair. - /// This gives good baseline test coverage, but is not exhaustive. + /// Test the contract of a [`StreamCipherEncryptor`] / [`StreamCipherDecryptor`] pair: every + /// chunking of the streaming API agrees with the one-shot and round-trips through the other + /// direction, the RNG-taking constructors reproduce their init data, and the key-type and + /// security-strength policy is enforced. This gives good baseline test coverage, but is not + /// exhaustive; algorithm-specific test vectors belong in the implementing crate. pub fn test< const KEY_LEN: usize, const INIT_DATA_LEN: usize, - C: StreamCipher, + E: StreamCipherEncryptor, + D: StreamCipherDecryptor, >( &self, ) { - todo!() + let key = KeyMaterial::::from_bytes_as_type( + &DUMMY_SEED[..KEY_LEN], + KeyType::SymmetricCipherKey, + ) + .unwrap(); + + // one-shot, in place: must round-trip. + let mut buf = *DUMMY_SEED; + let iv = E::encrypt(&key, &mut buf).unwrap(); + let reference_ct = buf; + assert_ne!(&reference_ct[..], &DUMMY_SEED[..], "encryption must change the data"); + D::decrypt(&key, &iv, &mut buf).unwrap(); + assert_eq!(&buf[..], &DUMMY_SEED[..]); + + // the streaming API under the same init data must give the one-shot's answer whatever + // the chunking, including chunks that are not a multiple of any internal keystream block + // and empty chunks; and encrypting in one chunking must decrypt in any other. + let chunkings: &[usize] = &[1, 3, 7, 16, 63, 64, 65, 250, DUMMY_SEED.len()]; + for &enc_chunk in chunkings { + let mut buf = *DUMMY_SEED; + let (mut encryptor, iv2) = E::do_encrypt_init(&key).unwrap(); + // stream through the encryptor, with an empty chunk thrown in at the start and end + encryptor.do_encrypt(&mut []).unwrap(); + for chunk in buf.chunks_mut(enc_chunk) { + encryptor.do_encrypt(chunk).unwrap(); + } + encryptor.do_encrypt(&mut []).unwrap(); + let ct = buf; + + for &dec_chunk in chunkings { + let mut buf = ct; + let mut decryptor = D::do_decrypt_init(&key, &iv2).unwrap(); + decryptor.do_decrypt(&mut []).unwrap(); + for chunk in buf.chunks_mut(dec_chunk) { + decryptor.do_decrypt(chunk).unwrap(); + } + decryptor.do_decrypt(&mut []).unwrap(); + assert_eq!( + &buf[..], + &DUMMY_SEED[..], + "enc chunk {enc_chunk}, dec chunk {dec_chunk}" + ); + } + + // and the one-shot decrypt agrees with every streaming encryption + let mut buf = ct; + D::decrypt(&key, &iv2, &mut buf).unwrap(); + assert_eq!(&buf[..], &DUMMY_SEED[..]); + } + + // the streaming decryptor must agree with the one-shot encryptor under its init data + let mut buf = reference_ct; + let mut streamed = D::do_decrypt_init(&key, &iv).unwrap(); + for chunk in buf.chunks_mut(5) { + streamed.do_decrypt(chunk).unwrap(); + } + assert_eq!(&buf[..], &DUMMY_SEED[..]); + + // the RNG-taking one-shot must give the streaming API's answer for the same RNG stream, + // and the same init data. + let pinned = [0xA5u8; INIT_DATA_LEN]; + let mut expected = *DUMMY_SEED; + let (mut streamed, iv_streamed) = + E::do_encrypt_init_rng(&key, &mut FixedSeedRNG::::new(pinned)).unwrap(); + streamed.do_encrypt(&mut expected).unwrap(); + let mut buf = *DUMMY_SEED; + let iv = E::encrypt_rng(&key, &mut FixedSeedRNG::::new(pinned), &mut buf) + .unwrap(); + assert_eq!(iv, iv_streamed); + assert_eq!(&buf[..], &expected[..]); + // ...and a driven RNG determines the ciphertext: the same RNG stream again gives the same + // init data and ciphertext, so the ciphertext is a function of (key, init data) alone. + let mut buf2 = *DUMMY_SEED; + let iv_again = + E::encrypt_rng(&key, &mut FixedSeedRNG::::new(pinned), &mut buf2) + .unwrap(); + assert_eq!(iv, iv_again); + assert_eq!(&buf[..], &buf2[..]); + + // test that the init data is random (ie not the same on two runs). A cipher with no init + // data at all (INIT_DATA_LEN == 0) has nothing to compare: two empty arrays are always equal. + if INIT_DATA_LEN > 0 { + let (_encryptor, iv1) = E::do_encrypt_init(&key).unwrap(); + let (_encryptor, iv2) = E::do_encrypt_init(&key).unwrap(); + assert_ne!(iv1, iv2); + // and different init data under the same key gives different ciphertext + let mut a = *DUMMY_SEED; + let mut b = *DUMMY_SEED; + let iv_a = E::encrypt(&key, &mut a).unwrap(); + let iv_b = E::encrypt(&key, &mut b).unwrap(); + assert_ne!(iv_a, iv_b); + assert_ne!(&a[..], &b[..]); + } + + // error case: KeyMaterial of wrong type, for both directions + let mac_key = + KeyMaterial::::from_bytes_as_type(&DUMMY_SEED[..KEY_LEN], KeyType::MACKey) + .unwrap(); + match E::do_encrypt_init(&mac_key) { + Err(SymmetricCipherError::KeyMaterialError(_)) => { /* good */ } + _ => panic!("Unexpected error"), + }; + match D::do_decrypt_init(&mac_key, &[0u8; INIT_DATA_LEN]) { + Err(SymmetricCipherError::KeyMaterialError(_)) => { /* good */ } + _ => panic!("Unexpected error"), + }; + + // error case: security strengths too weak and too strong + let mut key = KeyMaterial::::from_bytes_as_type( + &DUMMY_SEED[..KEY_LEN], + KeyType::SymmetricCipherKey, + ) + .unwrap(); + let security_strengths = [ + SecurityStrength::None, + SecurityStrength::_112bit, + SecurityStrength::_128bit, + SecurityStrength::_192bit, + SecurityStrength::_256bit, + ]; + for ss in security_strengths.iter() { + // `set_security_strength` enforces its key-length guard even inside a + // do_hazardous_operations() closure -- a KEY_LEN-byte key cannot be tagged at a + // strength above `from_bytes(KEY_LEN)` -- so skip the strengths this key cannot carry + // rather than unwrapping an error. (A 16-byte key can reach 128-bit and no higher.) + // Do NOT "fix" this by relaxing that guard in `KeyMaterial`: core's + // `test_hazardous_ops_error_handling` requires it to stay enforced. + if ss > &SecurityStrength::from_bytes(KEY_LEN) { + continue; + } + + // Tag the key at an arbitrary strength for the purpose of this test. + do_hazardous_operations(&mut key, |key| key.set_security_strength(ss.clone())).unwrap(); + + let check = |r: Result<(), SymmetricCipherError>, max: &SecurityStrength| match r { + Ok(_) => { + if ss >= max { /* good */ + } else { + panic!("Should have been a strong enough key"); + } + } + Err(SymmetricCipherError::KeyMaterialError(_)) => { + if ss < max { /* good */ + } else { + panic!("Should not have accepted a key weaker than algorithm"); + } + } + _ => panic!("Unexpected error"), + }; + check(E::do_encrypt_init(&key).map(|_| ()), &E::MAX_SECURITY_STRENGTH); + check( + D::do_decrypt_init(&key, &[0u8; INIT_DATA_LEN]).map(|_| ()), + &D::MAX_SECURITY_STRENGTH, + ); + } } } diff --git a/crypto/core-test-framework/src/xof.rs b/crypto/core-test-framework/src/xof.rs index 9ec5040b..fbbe7006 100644 --- a/crypto/core-test-framework/src/xof.rs +++ b/crypto/core-test-framework/src/xof.rs @@ -126,7 +126,7 @@ impl TestFrameworkXOF { ); } - // Helper: the output stream of `input` finished with the low `num_bits` bits of + // Helper: the output stream of `input` finished with the top `num_bits` bits of // `partial_byte`. let partial_absorb_output = |partial_byte: u8, num_bits: usize| -> Vec { let mut xof = X::default(); @@ -147,17 +147,18 @@ impl TestFrameworkXOF { ); } - // "The num_bits message bits are taken from the least significant bits of - // partial_byte". - // So the unused high bits are not part of the message and must not change the output. + // "the num_bits message bits are the most significant bits of partial_byte ... and the + // low 8 - num_bits bits (the BIT STRING's "unused bits") are ignored". + // So the unused low bits are not part of the message and must not change the output. for num_bits in 0..=7 { - // no overflow: 1u8 << 7 == 0x80 - let mask = (1u8 << num_bits) - 1; + // the used bits are the top num_bits; built in u16 so that num_bits == 0 cannot overflow + let mask = (0xFF00u16 >> num_bits) as u8; for partial_byte in [0x00u8, 0x5A, 0xA5, 0xFF] { assert_eq!( partial_absorb_output(partial_byte, num_bits), partial_absorb_output(partial_byte & mask, num_bits), - "bits above num_bits = {num_bits} must be ignored / partial_byte: {partial_byte:#04X}" + "the low 8 - num_bits = {} bits must be ignored / partial_byte: {partial_byte:#04X}", + 8 - num_bits ); } } @@ -179,14 +180,16 @@ impl TestFrameworkXOF { /*** fn squeeze_partial_byte_final(self, num_bits: usize) -> Result ***/ /*** fn squeeze_partial_byte_final_out(self, num_bits: usize, output: &mut u8) -> Result<(), HashError> ***/ - // "The bits are returned in the least significant num_bits bits of the returned u8, with - // the remaining high bits zero." - // They are the bits of the next byte of the output stream, which `expected_output` gives - // us: after squeezing `split` bytes, the next byte is expected_output[split]. + // "in the most significant num_bits bits of the returned u8, first output bit first, with + // the low 8 - num_bits "unused" bits zero." + // They are the first bits of the next byte of the output stream, which `expected_output` + // gives us: after squeezing `split` bytes, the next byte is expected_output[split]. In + // that byte the first output bit is the LSB (FIPS 202 B.1 / the byte-oriented stream), so + // the expected partial byte is the bit-reversal of it, masked to the top num_bits bits. let split = expected_output.len() / 2; for num_bits in 0..=7 { - // no overflow: 1u8 << 7 == 0x80 - let mask = (1u8 << num_bits) - 1; + // the used bits are the top num_bits; built in u16 so that num_bits == 0 cannot overflow + let mask = (0xFF00u16 >> num_bits) as u8; let mut xof = X::default(); xof.absorb(input).expect("absorb() before any squeeze must succeed"); @@ -197,13 +200,13 @@ impl TestFrameworkXOF { assert_eq!( partial_byte, - expected_output[split] & mask, - "the squeezed bits must be the low bits of the next output byte / num_bits: {num_bits}" + expected_output[split].reverse_bits() & mask, + "the squeezed bits must be the first bits of the next output byte, MSB-first / num_bits: {num_bits}" ); assert_eq!( partial_byte & !mask, 0x00, - "the unused high bits of the result must be zero / num_bits: {num_bits}" + "the unused low bits of the result must be zero / num_bits: {num_bits}" ); // "The same as XOF::squeeze_partial_byte_final, but writes into the provided output diff --git a/crypto/core/src/errors.rs b/crypto/core/src/errors.rs index 7be5197e..53a987af 100644 --- a/crypto/core/src/errors.rs +++ b/crypto/core/src/errors.rs @@ -176,12 +176,35 @@ pub enum SymmetricCipherError { /// KeyMaterialError(KeyMaterialError), /// + PaddingError(PaddingError), + /// RNGError(RNGError), /// StateError(&'static str), } +/// Errors from a [`crate::traits::Padding`] scheme. +#[derive(Debug, PartialEq, Eq)] +#[non_exhaustive] +pub enum PaddingError { + /// `pad()` was asked to pad more data than fits in a block alongside at least one byte of padding. + /// The usize is the maximum permitted data length (`BLOCK_LEN - 1`). + DataLengthTooLong(usize), + /// `unpad()` found the block does not carry well-formed padding. Deliberately carries no detail + /// about *how* the padding was malformed. + InvalidPadding, + /// `pad()` was asked to add padding by a scheme that adds none (`NoPadding`): the data was not + /// a whole number of blocks, and the caller must align it. + PaddingNotPermitted, +} + /*** Promotion functions ***/ +impl From for SymmetricCipherError { + fn from(e: PaddingError) -> SymmetricCipherError { + Self::PaddingError(e) + } +} + impl From for SymmetricCipherError { fn from(e: KeyMaterialError) -> SymmetricCipherError { Self::KeyMaterialError(e) diff --git a/crypto/core/src/traits.rs b/crypto/core/src/traits.rs index 22652570..cfc77a29 100644 --- a/crypto/core/src/traits.rs +++ b/crypto/core/src/traits.rs @@ -33,15 +33,15 @@ pub trait AEADCipher, aad: &[u8], plaintext: &[u8], ciphertext: &mut [u8], ) -> Result<([u8; NONCE_LEN], usize, [u8; TAG_LEN]), SymmetricCipherError>; - /// All AEAD ciphers will also be either a [`BlockCipher`] or a [`StreamCipher`], and so will already + /// All AEAD ciphers will also be either a block cipher ([`BlockCipherEncryptor`] / [`BlockCipherDecryptor`]) or a stream cipher ([`StreamCipherEncryptor`] / [`StreamCipherDecryptor`]), and so will already /// have a streaming API. /// This allows you to finish either style of streaming API flow with AEAD specific do_final() /// that computes and returns the authentication tag. @@ -70,7 +70,7 @@ pub trait AEADCipher Result; - /// All AEAD ciphers will also be either a [`BlockCipher`] or a [`StreamCipher`], and so will already + /// All AEAD ciphers will also be either a block cipher ([`BlockCipherEncryptor`] / [`BlockCipherDecryptor`]) or a stream cipher ([`StreamCipherEncryptor`] / [`StreamCipherDecryptor`]), and so will already /// have a streaming API. /// This allows you to finish either style of streaming API flow with AEAD specific do_final() /// that computes and returns the authentication tag. @@ -95,73 +95,252 @@ pub trait AlgorithmOID { const OID_DER: &'static [u8]; } -/// The basic functions of a block cipher. +/// The decryption half of a block cipher's streaming API; see [`BlockCipherEncryptor`], whose +/// notes on in-place operation, compile-time lengths and the `Result` all apply here too. +pub trait BlockCipherDecryptor< + const KEY_LEN: usize, + const INIT_DATA_LEN: usize, + const BLOCK_LEN: usize, +>: Algorithm + Sized +{ + /// Begins a streaming decryption flow from the init data returned by [`BlockCipherEncryptor::do_encrypt_init`]. + fn do_decrypt_init( + key: &KeyMaterial, + init_data: &[u8; INIT_DATA_LEN], + ) -> Result; + /// The implementor hook: decrypts consecutive whole blocks in place. See + /// [`BlockCipherEncryptor::do_encrypt_blocks`]; callers should normally use the flat + /// [`BlockCipherDecryptor::do_decrypt`] instead. + fn do_decrypt_blocks( + &mut self, + blocks: &mut [[u8; BLOCK_LEN]], + ) -> Result<(), SymmetricCipherError>; + + /// Streaming: decrypts `LEN` bytes, a whole number of blocks, in place. `LEN % BLOCK_LEN == 0` + /// is checked at compile time, exactly as for [`BlockCipherEncryptor::do_encrypt`]. + fn do_decrypt( + &mut self, + data: &mut [u8; LEN], + ) -> Result<(), SymmetricCipherError> { + const { + assert!( + LEN.is_multiple_of(BLOCK_LEN), + "length must be a whole number of BLOCK_LEN-byte blocks" + ) + }; + // The remainder is provably empty (asserted above) and ignored. + let (blocks, _) = data.as_chunks_mut::(); + self.do_decrypt_blocks(blocks) + } + + /// One-shot: decrypts `LEN` bytes in place from the given init data. `LEN % BLOCK_LEN == 0` is + /// checked at compile time exactly as for [`BlockCipherEncryptor::encrypt`]. + fn decrypt( + key: &KeyMaterial, + init_data: &[u8; INIT_DATA_LEN], + data: &mut [u8; LEN], + ) -> Result<(), SymmetricCipherError> { + Self::do_decrypt_init(key, init_data)?.do_decrypt(data) + } +} + +/// The encryption half of a block cipher's streaming API. Strictly block-aligned: whole blocks in, whole +/// blocks out, no finalization step. Padding of non-block-aligned data is handled by a separate layer +/// (`PaddedEncryptor` / `PaddedDecryptor`) built on top of this trait. +/// +/// Encryption and decryption are separate traits (as with [`KEMEncapsulator`] / [`KEMDecapsulator`]) so +/// that the direction can be encoded in the type, and so that a policy can permit decryption of an +/// algorithm while forbidding new encryptions. +/// /// This trait allows for a block cipher to generate initialization data, such as an Initialization Vector (IV) or Counter (CTR) /// which is not technically part of the ciphertext, but must be transmitted along with the ciphertext in order for the /// recipient to perform successful decryption. The length of the initialization data is specified by the implementing struct /// via the `INIT_DATA_LEN` constant. -/// In order for these one-shot APIs to be usable securely in all contexts, the init data will be generated +/// In order for these APIs to be usable securely in all contexts, the init data will be generated /// securely by the block cipher implementation and returned along with the ciphertext, and there is no API for the /// user to provide the init data. If you require this functionality, see the documentation for the underlying implementation. -pub trait BlockCipher: - SymmetricCipher + Sized +/// +/// # Everything is in place +/// +/// Every data method here transforms its buffer in place: the plaintext goes in, the ciphertext +/// comes out in the same bytes. A block cipher mode never changes the length of its data, so a +/// separate output buffer would only ever be a copy, and a copy of plaintext is one more thing to +/// scrub. Callers that need to keep the plaintext copy it first. +/// +/// # Lengths are checked at compile time +/// +/// Every buffer is a `[u8; LEN]`, and `LEN % BLOCK_LEN == 0` is checked by an inline `const` +/// assertion when the method is instantiated: a misaligned length is a compile error at the call +/// site, not a runtime `Err`, which is why there is no length variant of [`SymmetricCipherError`] +/// here. Data whose length is only known at run time is fed in block by block, or through the +/// padding layer. +/// +/// # Why the data methods still return `Result` +/// +/// Nothing about the buffer can go wrong, and a constructed value is always ready to use, so a +/// mode like CBC never returns `Err` from them. The `Result` is for modes with a per-initialization +/// data limit -- a counter-based mode must refuse to encrypt past the point where its counter would +/// repeat -- which a streaming API cannot check any earlier than the call that would cross it. +pub trait BlockCipherEncryptor< + const KEY_LEN: usize, + const INIT_DATA_LEN: usize, + const BLOCK_LEN: usize, +>: Algorithm + Sized { - /// Constructor that begins a flow of the streaming API for encrypting one block at a time. - /// Allows for the implementation to return init data such as an IV which is generated prior to encrypting the first block. + /// Begins a streaming encryption flow, returning the generated init data (e.g. IV). + /// Sources randomness from the library's default OS-backed RNG. fn do_encrypt_init( key: &KeyMaterial, ) -> Result<(Self, [u8; INIT_DATA_LEN]), SymmetricCipherError>; - /// Encrypts a single block of plaintext. - fn do_encrypt_block( - &mut self, - plaintext: &[u8; BLOCK_LEN], - ) -> Result<[u8; BLOCK_LEN], SymmetricCipherError>; - /// Encrypts a single block of plaintext and writes the ciphertext to the provided buffer. - fn do_encrypt_block_out( - &mut self, - plaintext: &[u8; BLOCK_LEN], - ciphertext: &mut [u8; BLOCK_LEN], - ) -> Result; - /// Encrypts the final block of plaintext. - fn do_encrypt_final( - &mut self, - plaintext: &[u8; BLOCK_LEN], - ) -> Result<[u8; BLOCK_LEN], SymmetricCipherError>; - /// Encrypts the final block of plaintext and writes the ciphertext to the provided buffer. - fn do_encrypt_final_out( - &mut self, - plaintext: &[u8; BLOCK_LEN], - ciphertext: &mut [u8; BLOCK_LEN], - ) -> Result; - /// Constructor that begins a flow of the streaming API for decryption one block at a time. - fn do_decrypt_init( + /// As [`BlockCipherEncryptor::do_encrypt_init`], but sources randomness from the provided RNG. + fn do_encrypt_init_rng( key: &KeyMaterial, - init_data: &[u8; INIT_DATA_LEN], - ) -> Result; - /// Decrypts a single block of ciphertext. - fn do_decrypt_block( - &mut self, - ciphertext: &[u8; BLOCK_LEN], - ) -> Result<[u8; BLOCK_LEN], SymmetricCipherError>; - /// Decrypts a single block of ciphertext and writes the plaintext to the provided buffer. - fn do_decrypt_block_out( - &mut self, - ciphertext: &[u8; BLOCK_LEN], - plaintext: &mut [u8; BLOCK_LEN], - ) -> Result; - /// Decrypts the final block of ciphertext. - /// This is the decryption counterpart to [`BlockCipher::do_encrypt_final`] and is where an - /// implementation validates and strips any padding (or otherwise finalizes the flow). - fn do_decrypt_final( + rng: &mut dyn RNG, + ) -> Result<(Self, [u8; INIT_DATA_LEN]), SymmetricCipherError>; + /// The implementor hook: encrypts consecutive whole blocks in place. A sequence of calls is + /// equivalent to one call over the concatenation. + /// + /// This is the only method an implementor writes besides the two `_init` constructors; the + /// block shape is what guarantees it never sees a partial block. It takes a slice rather than + /// a `[[u8; BLOCK_LEN]; N]` array because every whole number of blocks is valid, so there is + /// no length invariant for a const parameter to carry, and because how to batch the blocks -- + /// singly, in pairs, in eights -- is the mode's decision, not the caller's: a mode whose + /// permutation processes several blocks at once (CBC decryption, CTR) chunks the slice itself. + /// Callers should normally use the flat [`BlockCipherEncryptor::do_encrypt`] instead. + fn do_encrypt_blocks( &mut self, - ciphertext: &[u8; BLOCK_LEN], - ) -> Result<[u8; BLOCK_LEN], SymmetricCipherError>; - /// Decrypts the final block of ciphertext and writes the plaintext to the provided buffer. - fn do_decrypt_final_out( + blocks: &mut [[u8; BLOCK_LEN]], + ) -> Result<(), SymmetricCipherError>; + + /// Streaming: encrypts `LEN` bytes, a whole number of blocks, in place. A sequence of calls + /// is equivalent to one call over the concatenation. + /// + /// `LEN % BLOCK_LEN == 0` is checked **at compile time**; see the trait docs. The whole buffer + /// then goes to [`BlockCipherEncryptor::do_encrypt_blocks`] in one call. + fn do_encrypt( &mut self, - ciphertext: &[u8; BLOCK_LEN], - plaintext: &mut [u8; BLOCK_LEN], - ) -> Result; + data: &mut [u8; LEN], + ) -> Result<(), SymmetricCipherError> { + const { + assert!( + LEN.is_multiple_of(BLOCK_LEN), + "length must be a whole number of BLOCK_LEN-byte blocks" + ) + }; + // The remainder is provably empty (asserted above) and ignored. + let (blocks, _) = data.as_chunks_mut::(); + self.do_encrypt_blocks(blocks) + } + + /// One-shot: encrypts `LEN` bytes in place under a fresh init, and returns the generated init + /// data. `LEN % BLOCK_LEN == 0` is checked **at compile time**; see the trait docs. + fn encrypt( + key: &KeyMaterial, + data: &mut [u8; LEN], + ) -> Result<[u8; INIT_DATA_LEN], SymmetricCipherError> { + let (mut enc, init_data) = Self::do_encrypt_init(key)?; + enc.do_encrypt(data)?; + Ok(init_data) + } + /// As [`BlockCipherEncryptor::encrypt`], but sources randomness from the provided RNG. + fn encrypt_rng( + key: &KeyMaterial, + rng: &mut dyn RNG, + data: &mut [u8; LEN], + ) -> Result<[u8; INIT_DATA_LEN], SymmetricCipherError> { + let (mut enc, init_data) = Self::do_encrypt_init_rng(key, rng)?; + enc.do_encrypt(data)?; + Ok(init_data) + } +} + +/// A keyed block permutation: the `CIPH_K` / `CIPH^-1_K` of NIST SP 800-38A Sec 5.1. +/// +/// This is the raw primitive a mode of operation is built on, not something to encrypt data with. +/// It transforms exactly one block, so applying it directly to data is ECB (Sec 6.1), which is not +/// confidential -- the trait is named for the mode it *is* when used that way, as a reminder. [`BlockCipherEncryptor`] and [`BlockCipherDecryptor`] are the *mode* traits -- +/// they carry initialization data and chaining state; this one carries only a key schedule. +/// +/// Implementors are expected to hold that key schedule in a zeroize-on-drop wrapper +/// (`bouncycastle_utils::secret::Secret`), so it is scrubbed when the value is dropped. +/// +/// # Why the block methods are infallible +/// +/// Every length here is fixed by a type, and a constructed value is always ready to use, so there +/// is nothing a caller can get wrong once [`ElectronicCodeBook::new`] has returned. Only `new` can +/// fail, and only because of the key. +pub trait ElectronicCodeBook: + Algorithm + Sized +{ + /// Expands the key. + /// + /// # Errors + /// Rejects a key whose [`KeyType`] is not [`KeyType::SymmetricCipherKey`], and one whose + /// security strength is below [`Algorithm::MAX_SECURITY_STRENGTH`], both as a + /// [`SymmetricCipherError::KeyMaterialError`]. + fn new(key: &KeyMaterial) -> Result; + + /// The forward cipher function, in place. + fn encrypt_block(&self, block: &mut [u8; BLOCK_LEN]); + + /// The inverse cipher function, in place. + fn decrypt_block(&self, block: &mut [u8; BLOCK_LEN]); + + /// The forward cipher function on two *independent* blocks, in place. + /// + /// Provided as two [`ElectronicCodeBook::encrypt_block`] calls. Bit-sliced implementations + /// override it, because a pair of blocks is their natural unit of work and costs barely more + /// than one; see `bouncycastle-aes-lowmemory`. + /// + /// Overrides must be indistinguishable from the default, including the order of the two + /// results. `TestFrameworkElectronicCodeBook` pins that. + /// + /// Modes whose structure is parallel -- CBC decryption, CFB decryption, CTR -- should prefer + /// this. CBC and CFB *encryption* cannot use it: each input block depends on the previous + /// output. + fn encrypt_blocks2(&self, blocks: &mut [[u8; BLOCK_LEN]; 2]) { + let [a, b] = blocks; + self.encrypt_block(a); + self.encrypt_block(b); + } + + /// The inverse cipher function on two *independent* blocks, in place. + /// See [`ElectronicCodeBook::encrypt_blocks2`]. + fn decrypt_blocks2(&self, blocks: &mut [[u8; BLOCK_LEN]; 2]) { + let [a, b] = blocks; + self.decrypt_block(a); + self.decrypt_block(b); + } + + /// The forward cipher function on eight *independent* blocks, in place. + /// + /// Provided as four [`ElectronicCodeBook::encrypt_blocks2`] calls, so an implementation that + /// overrides only the pair form gets its benefit here too. An engine whose natural unit is + /// larger than a pair overrides this directly: a bit-sliced engine whose S-box circuit + /// substitutes four blocks per pass runs eight blocks as two full passes rather than four + /// half-empty pair calls. + /// + /// Overrides must be indistinguishable from the default, including the order of the eight + /// results. `TestFrameworkElectronicCodeBook` pins that. + /// + /// Modes with parallel structure chunk their data into eights first, then pairs, then single + /// blocks; see CBC decryption in `bouncycastle-modes`. + fn encrypt_blocks8(&self, blocks: &mut [[u8; BLOCK_LEN]; 8]) { + // Eight is a multiple of two, so the remainder is empty. + let (pairs, _) = blocks.as_mut_slice().as_chunks_mut::<2>(); + for pair in pairs { + self.encrypt_blocks2(pair); + } + } + + /// The inverse cipher function on eight *independent* blocks, in place. + /// See [`ElectronicCodeBook::encrypt_blocks8`]. + fn decrypt_blocks8(&self, blocks: &mut [[u8; BLOCK_LEN]; 8]) { + let (pairs, _) = blocks.as_mut_slice().as_chunks_mut::<2>(); + for pair in pairs { + self.decrypt_blocks2(pair); + } + } } /// A hash function is a cryptographic primitive that takes an input of any length and produces a fixed-size output. @@ -210,9 +389,20 @@ pub trait Hash: Algorithm + Default { fn do_final_out(self, output: &mut [u8]) -> usize; /// The same as [`Hash::do_final`], but allows for supplying a partial byte as the last input. - /// The `num_bits` message bits are taken from the least significant bits of - /// `partial_byte`, in order (bit 0 of `partial_byte` is the first message bit). This is the - /// FIPS 202 Appendix B.1 convention and is used uniformly for every hash family in this library. + /// + /// The partial byte is taken as it arrives in the final octet of an ASN.1 BIT STRING + /// (X.690 s. 8.6.2.1: the bits are placed "commencing with the leading bit ... in bits 8 to 1"): + /// the `num_bits` message bits are the most significant bits of `partial_byte`, leading bit first, + /// and the low `8 - num_bits` bits (the BIT STRING's "unused bits", X.690 s. 8.6.2.2) are ignored. + /// So for a BIT STRING whose initial octet is `unused` (1..=7), pass its final content octet with + /// `num_bits = 8 - unused`. The convention is the same for every hash family in this library; + /// implementations whose native bit order differs (SHA-3, which absorbs a byte LSB-first per + /// FIPS 202 Appendix B.1) convert internally. + /// + /// Note on test vectors: the NIST CAVP SHAVS (SHA-2) bit-oriented files pack trailing bits + /// left-justified and can be passed here directly; the SHA3VS files use the FIPS 202 B.1 packing + /// (first bit in the LSB) and must be bit-reversed (`u8::reverse_bits`) first. + /// /// 0 is a valid value and means the message ends on a byte boundary (equivalent to [`Hash::do_final`]). /// `num_bits` must be in `0..=7`; larger values return [`HashError::InvalidLength`]. fn do_final_partial_bits(self, partial_byte: u8, num_bits: usize) @@ -544,6 +734,34 @@ pub trait MAC: Sized { fn max_security_strength(&self) -> SecurityStrength; } +/// A block padding scheme, used to extend arbitrary-length data to a whole number of blocks so that it +/// can be processed by a [`BlockCipherEncryptor`]. Implementations are pure functions of the block +/// contents: no key, no state. +/// +/// Only the final, partial block of a message is ever padded; the padding layer sitting between the +/// caller and the block cipher is responsible for routing whole blocks straight through. +pub trait Padding { + /// Whether the scheme appends a whole block of padding to data that is already a whole number + /// of blocks. `true` for a scheme like PKCS7, which must always add at least one byte so that + /// unpadding is unambiguous; a caller then finishes an aligned message with `pad(block, 0)`. + /// `false` for a scheme that never adds bytes (`NoPadding`): an aligned message is finished with + /// no final block, and `pad` is called only for a partial one -- where such a scheme errors. + const ALWAYS_PADS: bool; + /// Pads `block` in place: bytes `0..data_len` are data and are left untouched, bytes + /// `data_len..BLOCK_LEN` are overwritten with padding. `data_len` must be less than `BLOCK_LEN` + /// (a full block of data requires a whole additional block of padding, which the caller supplies + /// as `data_len = 0` -- only when [`ALWAYS_PADS`](Self::ALWAYS_PADS) is `true`). + /// + /// # Errors + /// [`PaddingError::DataLengthTooLong`] if `data_len >= BLOCK_LEN`; + /// [`PaddingError::PaddingNotPermitted`] from a scheme that adds no bytes and was asked to. + fn pad(block: &mut [u8; BLOCK_LEN], data_len: usize) -> Result<(), PaddingError>; + /// Returns the number of data bytes in a padded `block`, or [`PaddingError::InvalidPadding`]. + /// Implementations must run in constant time with respect to the block contents, so that a + /// decryptor built on them does not leak a padding oracle. + fn unpad(block: &[u8; BLOCK_LEN]) -> Result; +} + /// Pre-Hashed Signature Verifier is an extension to [`SignatureVerifier`] that adds functionality specific to signature /// primatives that can operate on a pre-hashed message instead of the full message. pub trait PHSignatureVerifier< @@ -875,55 +1093,109 @@ pub trait Signer, const SK_LEN: usize, const SIG fn sign_final_out(self, output: &mut [u8; SIG_LEN]) -> Result; } -/// The basic functions of a stream cipher, which differ from those of a block cipher only in that -/// a stream cipher is assumed to have no underlying block size tied to the implementation, and so the caller gets to specify -/// the block size for the streaming APIs. -pub trait StreamCipher: - SymmetricCipher + Sized +/// The decryption half of a stream cipher's streaming API; see [`StreamCipherEncryptor`], whose +/// notes on in-place operation, arbitrary lengths and the `Result` all apply here too. +pub trait StreamCipherDecryptor: + Algorithm + Sized { - /// Constructor that begins a flow of the streaming API for encrypting one block at a time. - /// Allows for the implementation to return init data such as an IV which is generated prior to encrypting the first block. - fn do_stream_encrypt_init( - key: &KeyMaterial, - ) -> Result<(Self, [u8; INIT_DATA_LEN]), SymmetricCipherError>; - /// Encrypts a single block of plaintext. - fn do_stream_encrypt_block( - &mut self, - plaintext: &[u8; BLOCK_LEN], - ) -> Result<[u8; BLOCK_LEN], SymmetricCipherError>; - /// Encrypts a single block of plaintext and writes the ciphertext to the provided buffer. - fn do_stream_encrypt_block_out( - &mut self, - plaintext: &[u8; BLOCK_LEN], - ciphertext: &mut [u8; BLOCK_LEN], - ) -> Result; - /// Encrypts the final block of plaintext. - fn do_stream_encrypt_final( - &mut self, - plaintext: &[u8; BLOCK_LEN], - ) -> Result<[u8; BLOCK_LEN], SymmetricCipherError>; - /// Encrypts the final block of plaintext and writes the ciphertext to the provided buffer. - fn do_stream_encrypt_final_out( - &mut self, - plaintext: &[u8; BLOCK_LEN], - ciphertext: &mut [u8; BLOCK_LEN], - ) -> Result; - /// Constructor that begins a flow of the streaming API for decryption one block at a time. - fn do_stream_decrypt_init( + /// Begins a streaming decryption flow from the init data returned by + /// [`StreamCipherEncryptor::do_encrypt_init`]. + fn do_decrypt_init( key: &KeyMaterial, init_data: &[u8; INIT_DATA_LEN], ) -> Result; - /// Decrypts a single block of ciphertext. - fn do_stream_decrypt_block( - &mut self, - ciphertext: &[u8; BLOCK_LEN], - ) -> Result<[u8; BLOCK_LEN], SymmetricCipherError>; - /// Decrypts a single block of ciphertext and writes the plaintext to the provided buffer. - fn do_stream_decrypt_block_out( - &mut self, - ciphertext: &[u8; BLOCK_LEN], - plaintext: &mut [u8; BLOCK_LEN], - ) -> Result; + + /// Streaming: decrypts `data`, of any length, in place. A sequence of calls is equivalent to + /// one call over the concatenation, whatever the chunking, exactly as for + /// [`StreamCipherEncryptor::do_encrypt`]. + fn do_decrypt(&mut self, data: &mut [u8]) -> Result<(), SymmetricCipherError>; + + /// One-shot: decrypts `data` in place from the given init data. + fn decrypt( + key: &KeyMaterial, + init_data: &[u8; INIT_DATA_LEN], + data: &mut [u8], + ) -> Result<(), SymmetricCipherError> { + Self::do_decrypt_init(key, init_data)?.do_decrypt(data) + } +} + +/// The encryption half of a stream cipher's streaming API. This is the stream-cipher counterpart +/// of [`BlockCipherEncryptor`]: the same in-place, init-data-generating shape, but with no block +/// length. A stream cipher applies its keystream byte by byte, so the data methods take a +/// `&mut [u8]` of any length, and there is no alignment to check, no padding layer to reach for, +/// and no finalization step. +/// +/// Encryption and decryption are separate traits for the same reasons as +/// [`BlockCipherEncryptor`] / [`BlockCipherDecryptor`]: the direction is encoded in the type, and a +/// policy can permit decryption of an algorithm while forbidding new encryptions. +/// +/// Init data (a nonce or IV) is generated securely by the implementation in the constructor and +/// returned for transmission alongside the ciphertext; there is no API for the user to supply it, +/// for the same reason as in [`BlockCipherEncryptor`]. A stream cipher is only as safe as its +/// nonce is unique, so if you require a caller-chosen nonce, see the documentation for the +/// underlying implementation. +/// +/// # Everything is in place +/// +/// Every data method here transforms its buffer in place: the plaintext goes in, the ciphertext +/// comes out in the same bytes. A stream cipher never changes the length of its data, so a +/// separate output buffer would only ever be a copy, and a copy of plaintext is one more thing to +/// scrub. Callers that need to keep the plaintext copy it first. +/// +/// # Any length, as a slice +/// +/// The data is a `&mut [u8]` rather than a `&[u8; LEN]` because every length is valid, including +/// zero, so there is no invariant for a const parameter to carry and nothing for a compile-time +/// check to check. How the keystream is produced internally -- in 64-byte blocks, in words, a bit +/// at a time -- is the cipher's business; it buffers any unused keystream between calls so that +/// the caller's chunking is never visible in the output. +/// +/// # Why the data methods still return `Result` +/// +/// Nothing about the buffer can go wrong, and a constructed value is always ready to use. The +/// `Result` is for the per-initialization data limit most stream ciphers have: a counter-driven +/// keystream must refuse to run past the point where its counter would wrap and the keystream +/// repeat, and a streaming API cannot check that any earlier than the call that would cross it. +pub trait StreamCipherEncryptor: + Algorithm + Sized +{ + /// Begins a streaming encryption flow, returning the generated init data (e.g. nonce). + /// Sources randomness from the library's default OS-backed RNG. + fn do_encrypt_init( + key: &KeyMaterial, + ) -> Result<(Self, [u8; INIT_DATA_LEN]), SymmetricCipherError>; + /// As [`StreamCipherEncryptor::do_encrypt_init`], but sources randomness from the provided RNG. + fn do_encrypt_init_rng( + key: &KeyMaterial, + rng: &mut dyn RNG, + ) -> Result<(Self, [u8; INIT_DATA_LEN]), SymmetricCipherError>; + + /// Streaming: encrypts `data`, of any length, in place. A sequence of calls is equivalent to + /// one call over the concatenation, whatever the chunking. + /// + /// This is the only method an implementor writes besides the two `_init` constructors. + fn do_encrypt(&mut self, data: &mut [u8]) -> Result<(), SymmetricCipherError>; + + /// One-shot: encrypts `data` in place under a fresh init, and returns the generated init data. + fn encrypt( + key: &KeyMaterial, + data: &mut [u8], + ) -> Result<[u8; INIT_DATA_LEN], SymmetricCipherError> { + let (mut enc, init_data) = Self::do_encrypt_init(key)?; + enc.do_encrypt(data)?; + Ok(init_data) + } + /// As [`StreamCipherEncryptor::encrypt`], but sources randomness from the provided RNG. + fn encrypt_rng( + key: &KeyMaterial, + rng: &mut dyn RNG, + data: &mut [u8], + ) -> Result<[u8; INIT_DATA_LEN], SymmetricCipherError> { + let (mut enc, init_data) = Self::do_encrypt_init_rng(key, rng)?; + enc.do_encrypt(data)?; + Ok(init_data) + } } /// Allows a stateful object to suspend its operation by serializing its state into a byte array @@ -989,6 +1261,9 @@ pub trait SuspendableKeyed: Sized { ) -> Result; } +// todo -- migrate AEADCipher onto SymmetricCipherEncryptor / SymmetricCipherDecryptor (below), +// which are the split form of this trait, and retire this one. (StreamCipher has already gone: +// its split form is StreamCipherEncryptor / StreamCipherDecryptor.) /// The basic one-shot encrypt and decrypt that all types of symmetric ciphers must implement. /// These are meant to be simple, easy to use, secure, and fool-proof APIs, but they may result in /// ciphertexts that are incompatible with other implementations as ciphers in more complex modes, such @@ -1038,6 +1313,278 @@ pub trait SymmetricCipher: Alg ) -> Result; } +/// The decryption half of a symmetric cipher's arbitrary-length API. See +/// [`SymmetricCipherEncryptor`] for the shape of the API and the meaning of `FINAL_LEN`; this is +/// its mirror image, and the two are implemented by paired types. +/// +/// Decryption is not the exact mirror of encryption in one respect: the last `FINAL_LEN` bytes a +/// decryptor releases may be only partly data. A padding scheme's final block carries +/// `data_len < BLOCK_LEN` bytes of plaintext and the rest padding, and an authenticated cipher may +/// release nothing at all once it has checked the tag. So [`do_final`](Self::do_final) returns the +/// buffer *and* how much of it is data, and the one-shot length helper is an upper bound rather +/// than an exact count. +/// +/// The one-shot [`decrypt_out`](Self::decrypt_out) is provided over the streaming methods, as is +/// the allocating [`decrypt`](Self::decrypt) behind the `std` feature. An implementor writes only +/// [`do_decrypt_init`](Self::do_decrypt_init), [`update_out_len`](Self::update_out_len), +/// [`do_update_out`](Self::do_update_out), [`do_final`](Self::do_final) and +/// [`decrypt_out_max_len`](Self::decrypt_out_max_len). +pub trait SymmetricCipherDecryptor< + const KEY_LEN: usize, + const INIT_DATA_LEN: usize, + const FINAL_LEN: usize, +>: Algorithm + Sized +{ + /// Begins a streaming decryption from the init data returned by + /// [`SymmetricCipherEncryptor::do_encrypt_init`]. + /// + /// # Errors + /// Rejects a key whose [`KeyType`] is not [`KeyType::SymmetricCipherKey`], and one whose + /// security strength is below [`Algorithm::MAX_SECURITY_STRENGTH`], both as a + /// [`SymmetricCipherError::KeyMaterialError`]. + fn do_decrypt_init( + key: &KeyMaterial, + init_data: &[u8; INIT_DATA_LEN], + ) -> Result; + + /// The exact number of bytes the next [`do_update_out`](Self::do_update_out) will write if + /// given `input_len` more bytes of ciphertext. Depends on what is already buffered. + fn update_out_len(&self, input_len: usize) -> usize; + + /// Streaming: consumes `ciphertext`, writing every plaintext byte that can be released so far + /// into `plaintext` and buffering the rest. Returns the number of bytes written, which is + /// exactly [`update_out_len`](Self::update_out_len) of `ciphertext.len()`. + /// + /// A decryptor may have to hold back the tail of what it has seen -- the last block, which + /// might carry the padding, or the bytes that might be the tag -- so a sequence of calls + /// releases data later than the corresponding encryptor produced it, but the concatenation of + /// everything released plus the data part of [`do_final`](Self::do_final) is the plaintext. + /// + /// # Errors + /// [`SymmetricCipherError::IncorrectOutputBufferLength`] if `plaintext` is shorter than + /// [`update_out_len`](Self::update_out_len), carrying the required length. Nothing is + /// consumed in that case. + fn do_update_out( + &mut self, + ciphertext: &[u8], + plaintext: &mut [u8], + ) -> Result; + + /// Finishes the decryption, consuming the decryptor: processes whatever was held back, checks + /// it -- padding, tag -- and returns the final buffer together with the number of leading + /// bytes of it that are plaintext. The remainder of the buffer is not data and must not be + /// used. + /// + /// # Errors + /// [`SymmetricCipherError::DecryptionFailed`] if the ciphertext was malformed (empty, or not a + /// whole number of blocks); [`SymmetricCipherError::PaddingError`] or + /// [`SymmetricCipherError::AEADTagCheckFailed`] if the check fails. In every error case the + /// caller learns only that decryption failed, not where. + fn do_final(self) -> Result<([u8; FINAL_LEN], usize), SymmetricCipherError>; + + /// As [`do_final`](Self::do_final), writing the final buffer into `plaintext`. Returns the + /// number of leading bytes of it that are data. + fn do_final_out(self, plaintext: &mut [u8; FINAL_LEN]) -> Result { + let (buffer, data_len) = self.do_final()?; + *plaintext = buffer; + Ok(data_len) + } + + /// An upper bound on the plaintext recovered from `ciphertext_len` bytes of ciphertext, i.e. + /// the buffer [`decrypt_out`](Self::decrypt_out) requires. Exact for ciphers with no padding; + /// for a padding scheme the exact length is only known after decryption. + fn decrypt_out_max_len(ciphertext_len: usize) -> usize; + + /// One-shot: decrypts `ciphertext` into `plaintext`, which needs + /// [`decrypt_out_max_len`](Self::decrypt_out_max_len) bytes. Returns the number of plaintext + /// bytes written. + /// + /// Provided as `do_decrypt_init`, one `do_update_out` and `do_final`. + /// + /// # Errors + /// [`SymmetricCipherError::IncorrectOutputBufferLength`] if `plaintext` is too short, checked + /// before any work is done; otherwise whatever the streaming methods return. + fn decrypt_out( + key: &KeyMaterial, + init_data: &[u8; INIT_DATA_LEN], + ciphertext: &[u8], + plaintext: &mut [u8], + ) -> Result { + let needed = Self::decrypt_out_max_len(ciphertext.len()); + if plaintext.len() < needed { + return Err(SymmetricCipherError::IncorrectOutputBufferLength("plaintext", needed)); + } + let mut dec = Self::do_decrypt_init(key, init_data)?; + let written = dec.do_update_out(ciphertext, plaintext)?; + let (last, data_len) = dec.do_final()?; + // `decrypt_out_max_len` bounds `written + data_len`, so this fits in `plaintext[..needed]`. + plaintext[written..written + data_len].copy_from_slice(&last[..data_len]); + Ok(written + data_len) + } + + #[cfg(feature = "std")] + /// One-shot, allocating: as [`decrypt_out`](Self::decrypt_out), returning the plaintext as a + /// `Vec` of exactly the recovered length. Only available with the `std` feature. + fn decrypt( + key: &KeyMaterial, + init_data: &[u8; INIT_DATA_LEN], + ciphertext: &[u8], + ) -> Result, SymmetricCipherError> { + let mut plaintext = vec![0u8; Self::decrypt_out_max_len(ciphertext.len())]; + let written = Self::decrypt_out(key, init_data, ciphertext, &mut plaintext)?; + plaintext.truncate(written); + Ok(plaintext) + } +} + +/// The encryption half of a symmetric cipher's arbitrary-length API: streaming `do_update_out` / +/// `do_final`, plus one-shots provided over them. +/// +/// This is the layer a caller with *data* uses, as opposed to the block-aligned +/// [`BlockCipherEncryptor`] a mode implements. Its shape is that of the padding adapters in +/// `bouncycastle-padding`, which are its first implementors: an authenticated cipher or a stream +/// cipher fits the same shape, with the tag or nothing in place of the final padded block. +/// +/// `FINAL_LEN` is the fixed length of what [`do_final`](Self::do_final) produces after the last +/// byte of plaintext has been consumed: one block for a padding scheme, the tag length for an +/// authenticated cipher, zero for a stream cipher. Everything else about the output length is +/// answered exactly, before the fact, by [`update_out_len`](Self::update_out_len) and +/// [`encrypt_out_len`](Self::encrypt_out_len), so a caller can size buffers without guessing. +/// +/// Init data (an IV or nonce) is generated by the constructor and returned, never supplied, for +/// the same reason as in [`BlockCipherEncryptor`]. Everything is `no_std`-friendly except the +/// allocating [`encrypt`](Self::encrypt), which sits behind the `std` feature. +/// +/// The one-shots [`encrypt_out`](Self::encrypt_out) and [`encrypt_out_rng`](Self::encrypt_out_rng) +/// are provided over the streaming methods. An implementor writes only the two `_init` +/// constructors, [`update_out_len`](Self::update_out_len), [`do_update_out`](Self::do_update_out), +/// [`do_final`](Self::do_final) and [`encrypt_out_len`](Self::encrypt_out_len). +pub trait SymmetricCipherEncryptor< + const KEY_LEN: usize, + const INIT_DATA_LEN: usize, + const FINAL_LEN: usize, +>: Algorithm + Sized +{ + /// Begins a streaming encryption, returning the encryptor and the generated init data (IV or + /// nonce), which the recipient needs for [`SymmetricCipherDecryptor::do_decrypt_init`]. Sources + /// randomness from the library's default OS-backed RNG. + /// + /// # Errors + /// Rejects a key whose [`KeyType`] is not [`KeyType::SymmetricCipherKey`], and one whose + /// security strength is below [`Algorithm::MAX_SECURITY_STRENGTH`], both as a + /// [`SymmetricCipherError::KeyMaterialError`]. + fn do_encrypt_init( + key: &KeyMaterial, + ) -> Result<(Self, [u8; INIT_DATA_LEN]), SymmetricCipherError>; + + /// As [`do_encrypt_init`](Self::do_encrypt_init), but sources randomness from the provided RNG. + fn do_encrypt_init_rng( + key: &KeyMaterial, + rng: &mut dyn RNG, + ) -> Result<(Self, [u8; INIT_DATA_LEN]), SymmetricCipherError>; + + /// The exact number of bytes the next [`do_update_out`](Self::do_update_out) will write if + /// given `input_len` more bytes of plaintext. Depends on what is already buffered. + fn update_out_len(&self, input_len: usize) -> usize; + + /// Streaming: consumes `plaintext`, writing every ciphertext byte that can be produced so far + /// into `ciphertext` and buffering the rest. Returns the number of bytes written, which is + /// exactly [`update_out_len`](Self::update_out_len) of `plaintext.len()`. A sequence of calls + /// is equivalent to one call over the concatenation. + /// + /// # Errors + /// [`SymmetricCipherError::IncorrectOutputBufferLength`] if `ciphertext` is shorter than + /// [`update_out_len`](Self::update_out_len), carrying the required length. Nothing is + /// consumed in that case. + fn do_update_out( + &mut self, + plaintext: &[u8], + ciphertext: &mut [u8], + ) -> Result; + + /// Finishes the encryption, consuming the encryptor: pads and encrypts whatever was buffered, + /// or computes the tag, and returns the final buffer together with the number of leading bytes + /// of it that are ciphertext -- the last bytes of the message. For most ciphers that is always + /// `FINAL_LEN` (the padded block, the tag); a padding scheme that adds nothing to aligned data + /// returns 0 for an aligned message. The remainder of the buffer is not output. + /// + /// # Errors + /// [`SymmetricCipherError::PaddingError`] if the buffered data cannot be finished -- with a + /// scheme that adds no padding, a message that is not a whole number of blocks. + fn do_final(self) -> Result<([u8; FINAL_LEN], usize), SymmetricCipherError>; + + /// As [`do_final`](Self::do_final), writing the final buffer into `ciphertext`. Returns the + /// number of leading bytes of it that are output. + fn do_final_out(self, ciphertext: &mut [u8; FINAL_LEN]) -> Result { + let (buffer, out_len) = self.do_final()?; + *ciphertext = buffer; + Ok(out_len) + } + + /// The exact ciphertext length for a `plaintext_len`-byte plaintext that the cipher accepts, + /// i.e. the buffer [`encrypt_out`](Self::encrypt_out) requires and the number of bytes it + /// writes. (A length the cipher rejects -- unaligned data under a scheme that adds no padding -- + /// fails in [`do_final`](Self::do_final) instead.) + fn encrypt_out_len(plaintext_len: usize) -> usize; + + /// One-shot: encrypts `plaintext` into `ciphertext`, which needs + /// [`encrypt_out_len`](Self::encrypt_out_len) bytes. Returns the generated init data and the + /// number of bytes written. + /// + /// Provided as `do_encrypt_init`, one `do_update_out` and `do_final`. + /// + /// # Errors + /// [`SymmetricCipherError::IncorrectOutputBufferLength`] if `ciphertext` is too short, checked + /// before any work is done; otherwise whatever the streaming methods return. + fn encrypt_out( + key: &KeyMaterial, + plaintext: &[u8], + ciphertext: &mut [u8], + ) -> Result<([u8; INIT_DATA_LEN], usize), SymmetricCipherError> { + let needed = Self::encrypt_out_len(plaintext.len()); + if ciphertext.len() < needed { + return Err(SymmetricCipherError::IncorrectOutputBufferLength("ciphertext", needed)); + } + let (mut enc, init_data) = Self::do_encrypt_init(key)?; + let written = enc.do_update_out(plaintext, ciphertext)?; + let (last, last_len) = enc.do_final()?; + // `encrypt_out_len` is exactly `written + last_len`, so this fits in `ciphertext[..needed]`. + ciphertext[written..written + last_len].copy_from_slice(&last[..last_len]); + Ok((init_data, written + last_len)) + } + + /// As [`encrypt_out`](Self::encrypt_out), but sources randomness from the provided RNG. + fn encrypt_out_rng( + key: &KeyMaterial, + rng: &mut dyn RNG, + plaintext: &[u8], + ciphertext: &mut [u8], + ) -> Result<([u8; INIT_DATA_LEN], usize), SymmetricCipherError> { + let needed = Self::encrypt_out_len(plaintext.len()); + if ciphertext.len() < needed { + return Err(SymmetricCipherError::IncorrectOutputBufferLength("ciphertext", needed)); + } + let (mut enc, init_data) = Self::do_encrypt_init_rng(key, rng)?; + let written = enc.do_update_out(plaintext, ciphertext)?; + let (last, last_len) = enc.do_final()?; + ciphertext[written..written + last_len].copy_from_slice(&last[..last_len]); + Ok((init_data, written + last_len)) + } + + #[cfg(feature = "std")] + /// One-shot, allocating: as [`encrypt_out`](Self::encrypt_out), returning the ciphertext as a + /// `Vec`. Only available with the `std` feature. + fn encrypt( + key: &KeyMaterial, + plaintext: &[u8], + ) -> Result<([u8; INIT_DATA_LEN], Vec), SymmetricCipherError> { + let mut ciphertext = vec![0u8; Self::encrypt_out_len(plaintext.len())]; + let (init_data, written) = Self::encrypt_out(key, plaintext, &mut ciphertext)?; + ciphertext.truncate(written); + Ok((init_data, ciphertext)) + } +} + /// Extensible Output Functions (XOFs) are similar to hash functions, except that they can produce output of arbitrary length. /// The naming used for the functions of this trait are borrowed from the SHA3-style sponge constructions that split XOF operation /// into two phases: an absorb phase in which an arbitrary amount of input is provided to the XOF, @@ -1078,9 +1625,11 @@ pub trait XOF: Default { fn absorb(&mut self, data: &[u8]) -> Result<(), HashError>; /// The same as [`XOF::absorb`], but allows for supplying a partial byte as the last input. - /// The `num_bits` message bits are taken from the least significant bits of - /// `partial_byte`, in order (bit 0 of `partial_byte` is the first message bit). This is the - /// FIPS 202 Appendix B.1 convention and is used uniformly for every hash family in this library. + /// The partial byte is taken as it arrives in the final octet of an ASN.1 BIT STRING + /// (X.690 s. 8.6.2.1): the `num_bits` message bits are the most significant bits of + /// `partial_byte`, leading bit first, and the low `8 - num_bits` bits (the BIT STRING's "unused + /// bits") are ignored. This is the same convention as [`Hash::do_final_partial_bits`]; see there + /// for the relationship to the FIPS 202 Appendix B.1 bit order and to the NIST test vector files. /// 0 is a valid value and means the message ends on a byte boundary (equivalent to [`XOF::absorb`]). /// `num_bits` must be in `0..=7`; larger values return [`HashError::InvalidLength`]. /// @@ -1101,10 +1650,11 @@ pub trait XOF: Default { fn squeeze_out(&mut self, output: &mut [u8]) -> usize; /// Squeezes a partial byte (`num_bits` in `0..=7`) from the XOF. - /// The bits are returned in the least significant `num_bits` bits of the returned u8, with the - /// remaining high bits zero. This follows the FIPS 202 Appendix B.1 bit-string convention - /// (the first bit of a byte is its least significant bit) and matches the input convention of - /// [`XOF::absorb_last_partial_byte`]. + /// The bits are returned as they would be placed in the final octet of an ASN.1 BIT STRING + /// (X.690 s. 8.6.2.1): in the most significant `num_bits` bits of the returned u8, first output + /// bit first, with the low `8 - num_bits` "unused" bits zero. This matches the input convention of + /// [`XOF::absorb_last_partial_byte`]. (FIPS 202 Appendix B.1 orders the bits of an output byte + /// LSB-first; the implementation converts.) /// 0 is a valid value and requests no bits, so the result is `0x00`. /// `num_bits` must be in `0..=7`; larger values return [`HashError::InvalidLength`]. /// This is a final call and consumes self. diff --git a/crypto/factory/Cargo.toml b/crypto/factory/Cargo.toml index e35e31f4..22836c5f 100644 --- a/crypto/factory/Cargo.toml +++ b/crypto/factory/Cargo.toml @@ -7,6 +7,7 @@ edition.workspace = true bouncycastle-core.workspace = true bouncycastle-sha2.workspace = true bouncycastle-sha3.workspace = true +bouncycastle-sm3.workspace = true bouncycastle-rng.workspace = true [dev-dependencies] diff --git a/crypto/factory/src/hash_factory.rs b/crypto/factory/src/hash_factory.rs index edbfd17a..9c89fa40 100644 --- a/crypto/factory/src/hash_factory.rs +++ b/crypto/factory/src/hash_factory.rs @@ -31,9 +31,13 @@ use crate::{DEFAULT, DEFAULT_128_BIT, DEFAULT_256_BIT}; use bouncycastle_core::errors::HashError; use bouncycastle_core::traits::{Algorithm, Hash, SecurityStrength}; use bouncycastle_sha2 as sha2; -use bouncycastle_sha2::{SHA224_NAME, SHA256_NAME, SHA384_NAME, SHA512_NAME}; +use bouncycastle_sha2::{ + SHA224_NAME, SHA256_NAME, SHA384_NAME, SHA512_224_NAME, SHA512_256_NAME, SHA512_NAME, +}; use bouncycastle_sha3 as sha3; use bouncycastle_sha3::{SHA3_224_NAME, SHA3_256_NAME, SHA3_384_NAME, SHA3_512_NAME}; +use bouncycastle_sm3 as sm3; +use bouncycastle_sm3::SM3_NAME; /// Wrapper object for all algorithms that impl [`Hash`]. /// Note: no SHAKE because SHAKE is not NIST approved as a hash function. See FIPS 202 section A.2. @@ -48,6 +52,10 @@ pub enum HashFactory { /// SHA512(sha2::SHA512), /// + SHA512_224(sha2::SHA512_224), + /// + SHA512_256(sha2::SHA512_256), + /// SHA3_224(sha3::SHA3_224), /// SHA3_256(sha3::SHA3_256), @@ -55,6 +63,8 @@ pub enum HashFactory { SHA3_384(sha3::SHA3_384), /// SHA3_512(sha3::SHA3_512), + /// + SM3(sm3::SM3), } impl Default for HashFactory { @@ -80,10 +90,13 @@ impl AlgorithmFactory for HashFactory { SHA256_NAME => Ok(Self::SHA256(sha2::SHA256::new())), SHA384_NAME => Ok(Self::SHA384(sha2::SHA384::new())), SHA512_NAME => Ok(Self::SHA512(sha2::SHA512::new())), + SHA512_224_NAME => Ok(Self::SHA512_224(sha2::SHA512_224::new())), + SHA512_256_NAME => Ok(Self::SHA512_256(sha2::SHA512_256::new())), SHA3_224_NAME => Ok(Self::SHA3_224(sha3::SHA3_224::new())), SHA3_256_NAME => Ok(Self::SHA3_256(sha3::SHA3_256::new())), SHA3_384_NAME => Ok(Self::SHA3_384(sha3::SHA3_384::new())), SHA3_512_NAME => Ok(Self::SHA3_512(sha3::SHA3_512::new())), + SM3_NAME => Ok(Self::SM3(sm3::SM3::new())), _ => Err(FactoryError::UnsupportedAlgorithm(format!( "The algorithm: \"{}\" is not a known Hash", alg_name @@ -108,10 +121,13 @@ impl Hash for HashFactory { Self::SHA256(h) => h.block_bitlen(), Self::SHA384(h) => h.block_bitlen(), Self::SHA512(h) => h.block_bitlen(), + Self::SHA512_224(h) => h.block_bitlen(), + Self::SHA512_256(h) => h.block_bitlen(), Self::SHA3_224(h) => h.block_bitlen(), Self::SHA3_256(h) => h.block_bitlen(), Self::SHA3_384(h) => h.block_bitlen(), Self::SHA3_512(h) => h.block_bitlen(), + Self::SM3(h) => h.block_bitlen(), } } @@ -121,10 +137,13 @@ impl Hash for HashFactory { Self::SHA256(h) => h.output_len(), Self::SHA384(h) => h.output_len(), Self::SHA512(h) => h.output_len(), + Self::SHA512_224(h) => h.output_len(), + Self::SHA512_256(h) => h.output_len(), Self::SHA3_224(h) => h.output_len(), Self::SHA3_256(h) => h.output_len(), Self::SHA3_384(h) => h.output_len(), Self::SHA3_512(h) => h.output_len(), + Self::SM3(h) => h.output_len(), } } @@ -134,10 +153,13 @@ impl Hash for HashFactory { Self::SHA256(h) => h.hash(data), Self::SHA384(h) => h.hash(data), Self::SHA512(h) => h.hash(data), + Self::SHA512_224(h) => h.hash(data), + Self::SHA512_256(h) => h.hash(data), Self::SHA3_224(h) => h.hash(data), Self::SHA3_256(h) => h.hash(data), Self::SHA3_384(h) => h.hash(data), Self::SHA3_512(h) => h.hash(data), + Self::SM3(h) => h.hash(data), } } @@ -149,10 +171,13 @@ impl Hash for HashFactory { Self::SHA256(h) => h.hash_out(data, output), Self::SHA384(h) => h.hash_out(data, output), Self::SHA512(h) => h.hash_out(data, output), + Self::SHA512_224(h) => h.hash_out(data, output), + Self::SHA512_256(h) => h.hash_out(data, output), Self::SHA3_224(h) => h.hash_out(data, output), Self::SHA3_256(h) => h.hash_out(data, output), Self::SHA3_384(h) => h.hash_out(data, output), Self::SHA3_512(h) => h.hash_out(data, output), + Self::SM3(h) => h.hash_out(data, output), } } @@ -162,10 +187,13 @@ impl Hash for HashFactory { Self::SHA256(h) => h.do_update(data), Self::SHA384(h) => h.do_update(data), Self::SHA512(h) => h.do_update(data), + Self::SHA512_224(h) => h.do_update(data), + Self::SHA512_256(h) => h.do_update(data), Self::SHA3_224(h) => h.do_update(data), Self::SHA3_256(h) => h.do_update(data), Self::SHA3_384(h) => h.do_update(data), Self::SHA3_512(h) => h.do_update(data), + Self::SM3(h) => h.do_update(data), } } @@ -175,10 +203,13 @@ impl Hash for HashFactory { Self::SHA256(h) => h.do_final(), Self::SHA384(h) => h.do_final(), Self::SHA512(h) => h.do_final(), + Self::SHA512_224(h) => h.do_final(), + Self::SHA512_256(h) => h.do_final(), Self::SHA3_224(h) => h.do_final(), Self::SHA3_256(h) => h.do_final(), Self::SHA3_384(h) => h.do_final(), Self::SHA3_512(h) => h.do_final(), + Self::SM3(h) => h.do_final(), } } @@ -190,10 +221,13 @@ impl Hash for HashFactory { Self::SHA256(h) => h.do_final_out(output), Self::SHA384(h) => h.do_final_out(output), Self::SHA512(h) => h.do_final_out(output), + Self::SHA512_224(h) => h.do_final_out(output), + Self::SHA512_256(h) => h.do_final_out(output), Self::SHA3_224(h) => h.do_final_out(output), Self::SHA3_256(h) => h.do_final_out(output), Self::SHA3_384(h) => h.do_final_out(output), Self::SHA3_512(h) => h.do_final_out(output), + Self::SM3(h) => h.do_final_out(output), } } @@ -207,10 +241,13 @@ impl Hash for HashFactory { Self::SHA256(h) => h.do_final_partial_bits(partial_byte, num_partial_bits), Self::SHA384(h) => h.do_final_partial_bits(partial_byte, num_partial_bits), Self::SHA512(h) => h.do_final_partial_bits(partial_byte, num_partial_bits), + Self::SHA512_224(h) => h.do_final_partial_bits(partial_byte, num_partial_bits), + Self::SHA512_256(h) => h.do_final_partial_bits(partial_byte, num_partial_bits), Self::SHA3_224(h) => h.do_final_partial_bits(partial_byte, num_partial_bits), Self::SHA3_256(h) => h.do_final_partial_bits(partial_byte, num_partial_bits), Self::SHA3_384(h) => h.do_final_partial_bits(partial_byte, num_partial_bits), Self::SHA3_512(h) => h.do_final_partial_bits(partial_byte, num_partial_bits), + Self::SM3(h) => h.do_final_partial_bits(partial_byte, num_partial_bits), } } @@ -225,6 +262,12 @@ impl Hash for HashFactory { Self::SHA256(h) => h.do_final_partial_bits_out(partial_byte, num_partial_bits, output), Self::SHA384(h) => h.do_final_partial_bits_out(partial_byte, num_partial_bits, output), Self::SHA512(h) => h.do_final_partial_bits_out(partial_byte, num_partial_bits, output), + Self::SHA512_224(h) => { + h.do_final_partial_bits_out(partial_byte, num_partial_bits, output) + } + Self::SHA512_256(h) => { + h.do_final_partial_bits_out(partial_byte, num_partial_bits, output) + } Self::SHA3_224(h) => { h.do_final_partial_bits_out(partial_byte, num_partial_bits, output) } @@ -237,6 +280,7 @@ impl Hash for HashFactory { Self::SHA3_512(h) => { h.do_final_partial_bits_out(partial_byte, num_partial_bits, output) } + Self::SM3(h) => h.do_final_partial_bits_out(partial_byte, num_partial_bits, output), } } @@ -246,10 +290,13 @@ impl Hash for HashFactory { Self::SHA256(h) => h.max_security_strength(), Self::SHA384(h) => h.max_security_strength(), Self::SHA512(h) => h.max_security_strength(), + Self::SHA512_224(h) => h.max_security_strength(), + Self::SHA512_256(h) => h.max_security_strength(), Self::SHA3_224(h) => h.max_security_strength(), Self::SHA3_256(h) => h.max_security_strength(), Self::SHA3_384(h) => h.max_security_strength(), Self::SHA3_512(h) => h.max_security_strength(), + Self::SM3(h) => h.max_security_strength(), } } } diff --git a/crypto/factory/src/mac_factory.rs b/crypto/factory/src/mac_factory.rs index 14e4d0b4..bdda273d 100644 --- a/crypto/factory/src/mac_factory.rs +++ b/crypto/factory/src/mac_factory.rs @@ -76,12 +76,15 @@ use bouncycastle_core::key_material::KeyMaterialTrait; use bouncycastle_core::traits::{MAC, SecurityStrength}; use bouncycastle_sha2 as sha2; use bouncycastle_sha2::hmac::{ - HMAC_SHA224_NAME, HMAC_SHA256_NAME, HMAC_SHA384_NAME, HMAC_SHA512_NAME, + HMAC_SHA224_NAME, HMAC_SHA256_NAME, HMAC_SHA384_NAME, HMAC_SHA512_224_NAME, + HMAC_SHA512_256_NAME, HMAC_SHA512_NAME, }; use bouncycastle_sha3 as sha3; use bouncycastle_sha3::hmac::{ HMAC_SHA3_224_NAME, HMAC_SHA3_256_NAME, HMAC_SHA3_384_NAME, HMAC_SHA3_512_NAME, }; +use bouncycastle_sm3 as sm3; +use bouncycastle_sm3::hmac::HMAC_SM3_NAME; /*** Defaults ***/ /// @@ -107,6 +110,10 @@ pub enum MACFactory { /// HMAC_SHA512(sha2::hmac::HMAC_SHA512), /// + HMAC_SHA512_224(sha2::hmac::HMAC_SHA512_224), + /// + HMAC_SHA512_256(sha2::hmac::HMAC_SHA512_256), + /// HMAC_SHA3_224(sha3::hmac::HMAC_SHA3_224), /// HMAC_SHA3_256(sha3::hmac::HMAC_SHA3_256), @@ -114,6 +121,8 @@ pub enum MACFactory { HMAC_SHA3_384(sha3::hmac::HMAC_SHA3_384), /// HMAC_SHA3_512(sha3::hmac::HMAC_SHA3_512), + /// + HMAC_SM3(sm3::hmac::HMAC_SM3), } impl MACFactory { @@ -139,10 +148,17 @@ impl MACFactory { HMAC_SHA256_NAME => Ok(Self::HMAC_SHA256(sha2::hmac::HMAC_SHA256::new(key)?)), HMAC_SHA384_NAME => Ok(Self::HMAC_SHA384(sha2::hmac::HMAC_SHA384::new(key)?)), HMAC_SHA512_NAME => Ok(Self::HMAC_SHA512(sha2::hmac::HMAC_SHA512::new(key)?)), + HMAC_SHA512_224_NAME => { + Ok(Self::HMAC_SHA512_224(sha2::hmac::HMAC_SHA512_224::new(key)?)) + } + HMAC_SHA512_256_NAME => { + Ok(Self::HMAC_SHA512_256(sha2::hmac::HMAC_SHA512_256::new(key)?)) + } HMAC_SHA3_224_NAME => Ok(Self::HMAC_SHA3_224(sha3::hmac::HMAC_SHA3_224::new(key)?)), HMAC_SHA3_256_NAME => Ok(Self::HMAC_SHA3_256(sha3::hmac::HMAC_SHA3_256::new(key)?)), HMAC_SHA3_384_NAME => Ok(Self::HMAC_SHA3_384(sha3::hmac::HMAC_SHA3_384::new(key)?)), HMAC_SHA3_512_NAME => Ok(Self::HMAC_SHA3_512(sha3::hmac::HMAC_SHA3_512::new(key)?)), + HMAC_SM3_NAME => Ok(Self::HMAC_SM3(sm3::hmac::HMAC_SM3::new(key)?)), _ => Err(FactoryError::UnsupportedAlgorithm(format!( "The algorithm: \"{}\" is not a known MAC", alg_name @@ -168,10 +184,13 @@ impl MAC for MACFactory { Self::HMAC_SHA256(h) => h.output_len(), Self::HMAC_SHA384(h) => h.output_len(), Self::HMAC_SHA512(h) => h.output_len(), + Self::HMAC_SHA512_224(h) => h.output_len(), + Self::HMAC_SHA512_256(h) => h.output_len(), Self::HMAC_SHA3_224(h) => h.output_len(), Self::HMAC_SHA3_256(h) => h.output_len(), Self::HMAC_SHA3_384(h) => h.output_len(), Self::HMAC_SHA3_512(h) => h.output_len(), + Self::HMAC_SM3(h) => h.output_len(), } } @@ -181,10 +200,13 @@ impl MAC for MACFactory { Self::HMAC_SHA256(h) => h.mac(data), Self::HMAC_SHA384(h) => h.mac(data), Self::HMAC_SHA512(h) => h.mac(data), + Self::HMAC_SHA512_224(h) => h.mac(data), + Self::HMAC_SHA512_256(h) => h.mac(data), Self::HMAC_SHA3_224(h) => h.mac(data), Self::HMAC_SHA3_256(h) => h.mac(data), Self::HMAC_SHA3_384(h) => h.mac(data), Self::HMAC_SHA3_512(h) => h.mac(data), + Self::HMAC_SM3(h) => h.mac(data), } } @@ -196,10 +218,13 @@ impl MAC for MACFactory { Self::HMAC_SHA256(h) => h.mac_out(data, out), Self::HMAC_SHA384(h) => h.mac_out(data, out), Self::HMAC_SHA512(h) => h.mac_out(data, out), + Self::HMAC_SHA512_224(h) => h.mac_out(data, out), + Self::HMAC_SHA512_256(h) => h.mac_out(data, out), Self::HMAC_SHA3_224(h) => h.mac_out(data, out), Self::HMAC_SHA3_256(h) => h.mac_out(data, out), Self::HMAC_SHA3_384(h) => h.mac_out(data, out), Self::HMAC_SHA3_512(h) => h.mac_out(data, out), + Self::HMAC_SM3(h) => h.mac_out(data, out), } } @@ -209,10 +234,13 @@ impl MAC for MACFactory { Self::HMAC_SHA256(h) => h.verify(data, mac), Self::HMAC_SHA384(h) => h.verify(data, mac), Self::HMAC_SHA512(h) => h.verify(data, mac), + Self::HMAC_SHA512_224(h) => h.verify(data, mac), + Self::HMAC_SHA512_256(h) => h.verify(data, mac), Self::HMAC_SHA3_224(h) => h.verify(data, mac), Self::HMAC_SHA3_256(h) => h.verify(data, mac), Self::HMAC_SHA3_384(h) => h.verify(data, mac), Self::HMAC_SHA3_512(h) => h.verify(data, mac), + Self::HMAC_SM3(h) => h.verify(data, mac), } } @@ -222,10 +250,13 @@ impl MAC for MACFactory { Self::HMAC_SHA256(h) => h.do_update(data), Self::HMAC_SHA384(h) => h.do_update(data), Self::HMAC_SHA512(h) => h.do_update(data), + Self::HMAC_SHA512_224(h) => h.do_update(data), + Self::HMAC_SHA512_256(h) => h.do_update(data), Self::HMAC_SHA3_224(h) => h.do_update(data), Self::HMAC_SHA3_256(h) => h.do_update(data), Self::HMAC_SHA3_384(h) => h.do_update(data), Self::HMAC_SHA3_512(h) => h.do_update(data), + Self::HMAC_SM3(h) => h.do_update(data), } } @@ -235,10 +266,13 @@ impl MAC for MACFactory { Self::HMAC_SHA256(h) => h.do_final(), Self::HMAC_SHA384(h) => h.do_final(), Self::HMAC_SHA512(h) => h.do_final(), + Self::HMAC_SHA512_224(h) => h.do_final(), + Self::HMAC_SHA512_256(h) => h.do_final(), Self::HMAC_SHA3_224(h) => h.do_final(), Self::HMAC_SHA3_256(h) => h.do_final(), Self::HMAC_SHA3_384(h) => h.do_final(), Self::HMAC_SHA3_512(h) => h.do_final(), + Self::HMAC_SM3(h) => h.do_final(), } } @@ -250,10 +284,13 @@ impl MAC for MACFactory { Self::HMAC_SHA256(h) => h.do_final_out(&mut out), Self::HMAC_SHA384(h) => h.do_final_out(&mut out), Self::HMAC_SHA512(h) => h.do_final_out(&mut out), + Self::HMAC_SHA512_224(h) => h.do_final_out(&mut out), + Self::HMAC_SHA512_256(h) => h.do_final_out(&mut out), Self::HMAC_SHA3_224(h) => h.do_final_out(&mut out), Self::HMAC_SHA3_256(h) => h.do_final_out(&mut out), Self::HMAC_SHA3_384(h) => h.do_final_out(&mut out), Self::HMAC_SHA3_512(h) => h.do_final_out(&mut out), + Self::HMAC_SM3(h) => h.do_final_out(&mut out), } } @@ -263,10 +300,13 @@ impl MAC for MACFactory { Self::HMAC_SHA256(h) => h.do_verify_final(mac), Self::HMAC_SHA384(h) => h.do_verify_final(mac), Self::HMAC_SHA512(h) => h.do_verify_final(mac), + Self::HMAC_SHA512_224(h) => h.do_verify_final(mac), + Self::HMAC_SHA512_256(h) => h.do_verify_final(mac), Self::HMAC_SHA3_224(h) => h.do_verify_final(mac), Self::HMAC_SHA3_256(h) => h.do_verify_final(mac), Self::HMAC_SHA3_384(h) => h.do_verify_final(mac), Self::HMAC_SHA3_512(h) => h.do_verify_final(mac), + Self::HMAC_SM3(h) => h.do_verify_final(mac), } } @@ -276,10 +316,13 @@ impl MAC for MACFactory { Self::HMAC_SHA256(h) => h.max_security_strength(), Self::HMAC_SHA384(h) => h.max_security_strength(), Self::HMAC_SHA512(h) => h.max_security_strength(), + Self::HMAC_SHA512_224(h) => h.max_security_strength(), + Self::HMAC_SHA512_256(h) => h.max_security_strength(), Self::HMAC_SHA3_224(h) => h.max_security_strength(), Self::HMAC_SHA3_256(h) => h.max_security_strength(), Self::HMAC_SHA3_384(h) => h.max_security_strength(), Self::HMAC_SHA3_512(h) => h.max_security_strength(), + Self::HMAC_SM3(h) => h.max_security_strength(), } } } diff --git a/crypto/factory/tests/hash_factory_tests.rs b/crypto/factory/tests/hash_factory_tests.rs index 31d216bc..8d90be83 100644 --- a/crypto/factory/tests/hash_factory_tests.rs +++ b/crypto/factory/tests/hash_factory_tests.rs @@ -54,6 +54,69 @@ mod hash_factory_tests { let sha2 = HashFactory::new(sha2::SHA512_NAME).unwrap(); assert_eq!(sha2.output_len(), 64); assert_eq!(sha2.hash(&DUMMY_SEED[..512]), b"\xed\xb9\xbe\xd7\x21\xaa\x6a\x5f\x6f\xbc\x66\x19\xd3\xa3\xc2\xbe\x3d\x04\x30\x43\xf0\x5a\x9a\xeb\xc7\xb1\x19\x7a\x2a\xa9\xc4\x9a\x57\xd5\xdd\xd4\x67\x4c\x17\x85\x78\x50\x88\xd9\xf1\xff\x42\xc7\x97\xa0\x2a\xdc\x9b\x81\x7a\x13\x9a\x50\x97\x0d\xa6\xc9\x95\x24"); + + // SHA512/224 -- "abc" vector from the NIST example file SHA512_224.pdf + let sha2 = HashFactory::new("SHA512/224").unwrap(); + assert_eq!(sha2.output_len(), 28); + assert_eq!(sha2.hash(b"abc"), b"\x46\x34\x27\x0f\x70\x7b\x6a\x54\xda\xae\x75\x30\x46\x08\x42\xe2\x0e\x37\xed\x26\x5c\xee\xe9\xa4\x3e\x89\x24\xaa"); + + let sha2 = HashFactory::new(sha2::SHA512_224_NAME).unwrap(); + assert_eq!(sha2.output_len(), 28); + assert_eq!(sha2.hash(b"abc"), b"\x46\x34\x27\x0f\x70\x7b\x6a\x54\xda\xae\x75\x30\x46\x08\x42\xe2\x0e\x37\xed\x26\x5c\xee\xe9\xa4\x3e\x89\x24\xaa"); + + // SHA512/256 -- "abc" vector from the NIST example file SHA512_256.pdf + let sha2 = HashFactory::new("SHA512/256").unwrap(); + assert_eq!(sha2.output_len(), 32); + assert_eq!(sha2.hash(b"abc"), b"\x53\x04\x8e\x26\x81\x94\x1e\xf9\x9b\x2e\x29\xb7\x6b\x4c\x7d\xab\xe4\xc2\xd0\xc6\x34\xfc\x6d\x46\xe0\xe2\xf1\x31\x07\xe7\xaf\x23"); + + let sha2 = HashFactory::new(sha2::SHA512_256_NAME).unwrap(); + assert_eq!(sha2.output_len(), 32); + assert_eq!(sha2.hash(b"abc"), b"\x53\x04\x8e\x26\x81\x94\x1e\xf9\x9b\x2e\x29\xb7\x6b\x4c\x7d\xab\xe4\xc2\xd0\xc6\x34\xfc\x6d\x46\xe0\xe2\xf1\x31\x07\xe7\xaf\x23"); + + // The remaining pass-throughs, on the same "abc" vectors: streaming, the _out variants + // and block_bitlen. + let expected_224 = HashFactory::new("SHA512/224").unwrap().hash(b"abc"); + let expected_256 = HashFactory::new("SHA512/256").unwrap().hash(b"abc"); + for (name, expected) in [("SHA512/224", &expected_224), ("SHA512/256", &expected_256)] { + let mut sha2 = HashFactory::new(name).unwrap(); + assert_eq!(sha2.block_bitlen(), 1024); + sha2.do_update(b"a"); + sha2.do_update(b"bc"); + assert_eq!(&sha2.do_final(), expected); + + let mut sha2 = HashFactory::new(name).unwrap(); + sha2.do_update(b"abc"); + let mut out = vec![0xffu8; expected.len()]; + assert_eq!(sha2.do_final_out(&mut out), expected.len()); + assert_eq!(&out, expected); + + let mut out = vec![0xffu8; expected.len()]; + assert_eq!( + HashFactory::new(name).unwrap().hash_out(b"abc", &mut out), + expected.len() + ); + assert_eq!(&out, expected); + } + } + + #[test] + fn sm3_hash_tests() { + use bouncycastle_sm3 as sm3; + // Expected values: GB/T 32905-2016 Appendix A ("abc") and openssl dgst -sm3 (DUMMY_SEED[..512]). + for name in ["SM3", sm3::SM3_NAME] { + let h = HashFactory::new(name).unwrap(); + assert_eq!(h.output_len(), 32); + assert_eq!(h.block_bitlen(), 512); + assert_eq!( + h.hash(&DUMMY_SEED[..512]), + b"\xb2\x1f\x83\x0d\xca\x06\xbe\x8b\x67\x8c\xf9\x87\xf2\x6b\x9a\x43\x6e\x1b\x42\x79\x63\xb4\x45\x03\x32\xf0\x12\x70\xbd\x2d\xf7\x5c" + ); + let h = HashFactory::new(name).unwrap(); + assert_eq!( + h.hash(b"abc"), + b"\x66\xc7\xf0\xf4\x62\xee\xed\xd9\xd1\xf2\xd4\x6b\xdc\x10\xe4\xe2\x41\x67\xc4\x87\x5c\xf2\xf7\xa2\x29\x7d\xa0\x2b\x8f\x4b\xa8\xe0" + ); + } } #[test] diff --git a/crypto/factory/tests/mac_factory_tests.rs b/crypto/factory/tests/mac_factory_tests.rs index 912a7587..a7121465 100644 --- a/crypto/factory/tests/mac_factory_tests.rs +++ b/crypto/factory/tests/mac_factory_tests.rs @@ -22,7 +22,149 @@ mod hash_factory_tests { &hex::decode("896fb1128abbdf196832107cd49df33f47b4b1169912ba4f53684b22").unwrap(), )); + // HMAC-SHA512/224 -- NIST ACVP HMAC-SHA2-512/224 2.0, tgId 1, tcId 106 (MAC truncated to 160 bits) + let key = KeyMaterial::<45>::from_bytes_as_type( + &hex::decode("a0b7276557f6880d151ea5e147fa2c29daf3104fda96ff8ee440f69e2c07a74b6eb38751fe54b08f9f4a84d1d7").unwrap(), + KeyType::MACKey, + ) + .unwrap(); + let msg = hex::decode("2579f5df03e0fccde2b515944d88dc81ca3b4a20517cdc54170559f0d2f889e2f543eacf8a84b34563d0139351ea9a77399d274c5c6c1b0f488063b7255f9df648667fe800151ef288a68d6c8c24d57abd7e4f70eed149752beae4a9763cebf03c").unwrap(); + let expected = hex::decode("6e927067f724d4fedc96b310c5115979e8dde8a4").unwrap(); + let hmac = MACFactory::new("HMAC-SHA512/224", &key).unwrap(); + assert_eq!(hmac.output_len(), 28); + assert_eq!(&hmac.mac(&msg)[..20], &expected[..]); + let hmac = + MACFactory::new(bouncycastle_sha2::hmac::HMAC_SHA512_224_NAME, &key).unwrap(); + assert_eq!(&hmac.mac(&msg)[..20], &expected[..]); + + // HMAC-SHA512/256 -- NIST ACVP HMAC-SHA2-512/256 2.0, tgId 1, tcId 147 (MAC truncated to 160 bits) + let key = KeyMaterial::<55>::from_bytes_as_type( + &hex::decode("4915691891f05dec5569ca75819daac897aaeeebb2fb04e7fc696d076feccef399f0eea660a7de4b7bb6ef7829a5f82feed70b35b40458").unwrap(), + KeyType::MACKey, + ) + .unwrap(); + let msg = hex::decode("").unwrap(); + let expected = hex::decode("7857d4737760e127f1533185c6ad183ac4e10bd9").unwrap(); + let hmac = MACFactory::new("HMAC-SHA512/256", &key).unwrap(); + assert_eq!(hmac.output_len(), 32); + assert_eq!(&hmac.mac(&msg)[..20], &expected[..]); + let hmac = + MACFactory::new(bouncycastle_sha2::hmac::HMAC_SHA512_256_NAME, &key).unwrap(); + assert_eq!(&hmac.mac(&msg)[..20], &expected[..]); + + // HMAC-SHA512/224 pass-throughs: streaming, mac_out, verify and do_verify_final. + let key = KeyMaterial::<45>::from_bytes_as_type( + &hex::decode("a0b7276557f6880d151ea5e147fa2c29daf3104fda96ff8ee440f69e2c07a74b6eb38751fe54b08f9f4a84d1d7").unwrap(), + KeyType::MACKey, + ) + .unwrap(); + let msg = hex::decode("2579f5df03e0fccde2b515944d88dc81ca3b4a20517cdc54170559f0d2f889e2f543eacf8a84b34563d0139351ea9a77399d274c5c6c1b0f488063b7255f9df648667fe800151ef288a68d6c8c24d57abd7e4f70eed149752beae4a9763cebf03c").unwrap(); + let full = MACFactory::new("HMAC-SHA512/224", &key).unwrap().mac(&msg); + assert_eq!(full.len(), 28); + assert_eq!( + &full[..20], + &hex::decode("6e927067f724d4fedc96b310c5115979e8dde8a4").unwrap()[..] + ); + + let mut hmac = MACFactory::new("HMAC-SHA512/224", &key).unwrap(); + for chunk in msg.chunks(7) { + hmac.do_update(chunk); + } + assert_eq!(hmac.do_final(), full); + + let mut out = vec![0xffu8; 28]; + assert_eq!( + MACFactory::new("HMAC-SHA512/224", &key).unwrap().mac_out(&msg, &mut out).unwrap(), + 28 + ); + assert_eq!(out, full); + + let mut out = vec![0xffu8; 28]; + let mut hmac = MACFactory::new("HMAC-SHA512/224", &key).unwrap(); + hmac.do_update(&msg); + assert_eq!(hmac.do_final_out(&mut out).unwrap(), 28); + assert_eq!(out, full); + + let mut wrong = full.clone(); + wrong[0] ^= 1; + assert!(MACFactory::new("HMAC-SHA512/224", &key).unwrap().verify(&msg, &full)); + assert!(!MACFactory::new("HMAC-SHA512/224", &key).unwrap().verify(&msg, &wrong)); + let mut hmac = MACFactory::new("HMAC-SHA512/224", &key).unwrap(); + hmac.do_update(&msg); + assert!(hmac.do_verify_final(&full)); + let mut hmac = MACFactory::new("HMAC-SHA512/224", &key).unwrap(); + hmac.do_update(&msg); + assert!(!hmac.do_verify_final(&wrong)); + + // HMAC-SHA512/256 pass-throughs: streaming, mac_out, verify and do_verify_final. + let key = KeyMaterial::<55>::from_bytes_as_type( + &hex::decode("4915691891f05dec5569ca75819daac897aaeeebb2fb04e7fc696d076feccef399f0eea660a7de4b7bb6ef7829a5f82feed70b35b40458").unwrap(), + KeyType::MACKey, + ) + .unwrap(); + let msg = hex::decode("").unwrap(); + let full = MACFactory::new("HMAC-SHA512/256", &key).unwrap().mac(&msg); + assert_eq!(full.len(), 32); + assert_eq!( + &full[..20], + &hex::decode("7857d4737760e127f1533185c6ad183ac4e10bd9").unwrap()[..] + ); + + let mut hmac = MACFactory::new("HMAC-SHA512/256", &key).unwrap(); + for chunk in msg.chunks(7) { + hmac.do_update(chunk); + } + assert_eq!(hmac.do_final(), full); + + let mut out = vec![0xffu8; 32]; + assert_eq!( + MACFactory::new("HMAC-SHA512/256", &key).unwrap().mac_out(&msg, &mut out).unwrap(), + 32 + ); + assert_eq!(out, full); + + let mut out = vec![0xffu8; 32]; + let mut hmac = MACFactory::new("HMAC-SHA512/256", &key).unwrap(); + hmac.do_update(&msg); + assert_eq!(hmac.do_final_out(&mut out).unwrap(), 32); + assert_eq!(out, full); + + let mut wrong = full.clone(); + wrong[0] ^= 1; + assert!(MACFactory::new("HMAC-SHA512/256", &key).unwrap().verify(&msg, &full)); + assert!(!MACFactory::new("HMAC-SHA512/256", &key).unwrap().verify(&msg, &wrong)); + let mut hmac = MACFactory::new("HMAC-SHA512/256", &key).unwrap(); + hmac.do_update(&msg); + assert!(hmac.do_verify_final(&full)); + let mut hmac = MACFactory::new("HMAC-SHA512/256", &key).unwrap(); + hmac.do_update(&msg); + assert!(!hmac.do_verify_final(&wrong)); + // TODO: at least one test for each type } + + #[test] + fn hmac_sm3_tests() { + // RFC4231 Test Case 1 key/message; expected value from `openssl dgst -sm3 -mac HMAC`, + // confirmed with bc-java's HMac(new SM3Digest()). + let key = KeyMaterial::<32>::from_bytes_as_type( + &hex::decode("0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b").unwrap(), + KeyType::MACKey, + ) + .unwrap(); + for name in ["HMAC-SM3", bouncycastle_sm3::hmac::HMAC_SM3_NAME] { + let hmac = MACFactory::new(name, &key).unwrap(); + assert_eq!(hmac.output_len(), 32); + assert!( + hmac.verify( + b"Hi There", + &hex::decode( + "51b00d1fb49832bfb01c3ce27848e59f871d9ba938dc563b338ca964755cce70" + ) + .unwrap(), + ) + ); + } + } } } diff --git a/crypto/hmac/Cargo.toml b/crypto/hmac/Cargo.toml index 44d1eed1..383f1f65 100644 --- a/crypto/hmac/Cargo.toml +++ b/crypto/hmac/Cargo.toml @@ -7,7 +7,7 @@ edition.workspace = true bouncycastle-core.workspace = true bouncycastle-utils.workspace = true -# bouncycastle-sha2, -sha3 and -rng are dev-dependencies so that the tests, benches and doc examples +# bouncycastle-sha2, -sha3, -sm3 and -rng are dev-dependencies so that the tests, benches and doc examples # here can still exercise HMAC over the library's own hashes; Cargo permits cycles through # dev-dependencies. # todo -- we're about to change that and move them to their respective crates in the next phase. @@ -18,3 +18,4 @@ bouncycastle-hex.workspace = true bouncycastle-rng.workspace = true bouncycastle-sha2.workspace = true bouncycastle-sha3.workspace = true +bouncycastle-sm3.workspace = true diff --git a/crypto/hmac/tests/hmac_tests.rs b/crypto/hmac/tests/hmac_tests.rs index 0cfbe415..6e9a3eb7 100644 --- a/crypto/hmac/tests/hmac_tests.rs +++ b/crypto/hmac/tests/hmac_tests.rs @@ -15,6 +15,8 @@ mod hmac_tests { use bouncycastle_sha2::*; use bouncycastle_sha3::hmac::*; use bouncycastle_sha3::{SHA3_224, SHA3_256, SHA3_384, SHA3_512}; + use bouncycastle_sm3::SM3; + use bouncycastle_sm3::hmac::*; #[test] fn simple_tests() { @@ -77,6 +79,12 @@ mod hmac_tests { _ = HMAC::::new(&key).unwrap(); _ = HMAC_SHA512::new(&key).unwrap(); + _ = HMAC::::new(&key).unwrap(); + _ = HMAC_SHA512_224::new(&key).unwrap(); + + _ = HMAC::::new(&key).unwrap(); + _ = HMAC_SHA512_256::new(&key).unwrap(); + _ = HMAC::::new(&key).unwrap(); _ = HMAC_SHA3_224::new(&key).unwrap(); @@ -88,6 +96,9 @@ mod hmac_tests { _ = HMAC::::new(&key).unwrap(); _ = HMAC_SHA3_512::new(&key).unwrap(); + + _ = HMAC::::new(&key).unwrap(); + _ = HMAC_SM3::new(&key).unwrap(); } #[test] @@ -282,10 +293,111 @@ mod hmac_tests { assert_eq!(HMAC_SHA256::ALG_NAME, HMAC_SHA256_NAME); assert_eq!(HMAC_SHA384::ALG_NAME, HMAC_SHA384_NAME); assert_eq!(HMAC_SHA512::ALG_NAME, HMAC_SHA512_NAME); + assert_eq!(HMAC_SHA512_224::ALG_NAME, HMAC_SHA512_224_NAME); + assert_eq!(HMAC_SHA512_256::ALG_NAME, HMAC_SHA512_256_NAME); + assert_eq!(HMAC_SHA512_224_NAME, "HMAC-SHA512/224"); + assert_eq!(HMAC_SHA512_256_NAME, "HMAC-SHA512/256"); + assert_eq!(HMAC_SHA512_224::MAX_SECURITY_STRENGTH, SecurityStrength::_112bit); + assert_eq!(HMAC_SHA512_256::MAX_SECURITY_STRENGTH, SecurityStrength::_128bit); assert_eq!(HMAC_SHA3_224::ALG_NAME, HMAC_SHA3_224_NAME); assert_eq!(HMAC_SHA3_256::ALG_NAME, HMAC_SHA3_256_NAME); assert_eq!(HMAC_SHA3_384::ALG_NAME, HMAC_SHA3_384_NAME); assert_eq!(HMAC_SHA3_512::ALG_NAME, HMAC_SHA3_512_NAME); + assert_eq!(HMAC_SM3::ALG_NAME, HMAC_SM3_NAME); + } + + #[cfg(test)] + mod acvp_sha512t { + use super::*; + + /// NIST ACVP known-answer tests for HMAC-SHA2-512/224, from the ACVP-Server repository + /// (gen-val/json-files/HMAC-SHA2-512-224-2.0/internalProjection.json, vsId 0). + /// The published vectors only carry MACs truncated to at most 160 bits (ACVP "macLen"), so the + /// leading bytes of the full 224-bit MAC are compared. The second case uses a key longer than the + /// 1024-bit block, which exercises the RFC 2104 pre-hashing of the key. + #[test] + fn hmac_sha512_224() { + // tgId 1, tcId 106: 45-byte key, MAC truncated to 160 bits + let key = KeyMaterial::<45>::from_bytes_as_type( + &hex::decode("a0b7276557f6880d151ea5e147fa2c29daf3104fda96ff8ee440f69e2c07a74b6eb38751fe54b08f9f4a84d1d7").unwrap(), + KeyType::MACKey, + ) + .unwrap(); + let msg = hex::decode("2579f5df03e0fccde2b515944d88dc81ca3b4a20517cdc54170559f0d2f889e2f543eacf8a84b34563d0139351ea9a77399d274c5c6c1b0f488063b7255f9df648667fe800151ef288a68d6c8c24d57abd7e4f70eed149752beae4a9763cebf03c").unwrap(); + let expected = hex::decode("6e927067f724d4fedc96b310c5115979e8dde8a4").unwrap(); + let full = HMAC_SHA512_224::new(&key).unwrap().mac(&msg); + assert_eq!(full.len(), 28); + assert_eq!(&full[..20], &expected[..]); + // the same vector through the streaming API in uneven chunks + let mut mac = HMAC_SHA512_224::new(&key).unwrap(); + for chunk in msg.chunks(13) { + mac.do_update(chunk); + } + assert_eq!(mac.do_final(), full); + + // tgId 1, tcId 110: 247-byte key (longer than the block, so pre-hashed), MAC truncated to 160 bits + let key = KeyMaterial::<247>::from_bytes_as_type( + &hex::decode("0791758d5d91b0108e885039e997dc32c41a0f986b1820d1f8c4c3da0ae6d88da58d91e1732942bb401eddc59ba1a39ee6cca8824705619873e9b6a04cf02e6b4debdb8c35c3fe6d9c569ecdb193baaf6510ca39522679811ac7a57297df11deeb8e58555108aeb106faa8c0867c5f185b4e7f5ece1afaa5412d95e47505684517254911ac15fde56e99534ccbbaaeb0ab1a77ff252903359f046b4eed1d4b5a47747b352c0b33d24da587d24f9aaaac7b8301c05fb0ba925a761cdfe74b8af66ca3e776662a33addad6b0dfbc5dabbce3529a7813b7fd2feae25f5fb80da8fd844430fb578eff15fb15775cdfa575b9d6d5ed90490f3a").unwrap(), + KeyType::MACKey, + ) + .unwrap(); + let msg = hex::decode("dedb0cc1c2a9b960d3").unwrap(); + let expected = hex::decode("9cf6def15b5ead939e1fda675b52147a01a6ccb6").unwrap(); + let full = HMAC_SHA512_224::new(&key).unwrap().mac(&msg); + assert_eq!(full.len(), 28); + assert_eq!(&full[..20], &expected[..]); + // the same vector through the streaming API in uneven chunks + let mut mac = HMAC_SHA512_224::new(&key).unwrap(); + for chunk in msg.chunks(13) { + mac.do_update(chunk); + } + assert_eq!(mac.do_final(), full); + } + + /// NIST ACVP known-answer tests for HMAC-SHA2-512/256, from the ACVP-Server repository + /// (gen-val/json-files/HMAC-SHA2-512-256-2.0/internalProjection.json, vsId 0). + /// The published vectors only carry MACs truncated to at most 160 bits (ACVP "macLen"), so the + /// leading bytes of the full 256-bit MAC are compared. The second case uses a key longer than the + /// 1024-bit block, which exercises the RFC 2104 pre-hashing of the key. + #[test] + fn hmac_sha512_256() { + // tgId 1, tcId 147: 55-byte key, MAC truncated to 160 bits + let key = KeyMaterial::<55>::from_bytes_as_type( + &hex::decode("4915691891f05dec5569ca75819daac897aaeeebb2fb04e7fc696d076feccef399f0eea660a7de4b7bb6ef7829a5f82feed70b35b40458").unwrap(), + KeyType::MACKey, + ) + .unwrap(); + let msg = hex::decode("").unwrap(); + let expected = hex::decode("7857d4737760e127f1533185c6ad183ac4e10bd9").unwrap(); + let full = HMAC_SHA512_256::new(&key).unwrap().mac(&msg); + assert_eq!(full.len(), 32); + assert_eq!(&full[..20], &expected[..]); + // the same vector through the streaming API in uneven chunks + let mut mac = HMAC_SHA512_256::new(&key).unwrap(); + for chunk in msg.chunks(13) { + mac.do_update(chunk); + } + assert_eq!(mac.do_final(), full); + + // tgId 1, tcId 106: 245-byte key (longer than the block, so pre-hashed), MAC truncated to 160 bits + let key = KeyMaterial::<245>::from_bytes_as_type( + &hex::decode("98d135e3cc6dffc2524a8a6c186cd0584eede3a734148b453199f71154bb3b96a315a037597c72f5081a17b2ef9990c065c2aaa65226c939098f603e6307dd69fc7906a82c361af89336cefe4d95d491d85b193125380fa9becd6e7475052cd7196447c32b681b7ef3cfde62d087067703d5438fdff6ce443c321048b50ec771999f85540cd8671cebf828f37d4cdbce1523823d77c5769fb8549b938406771cc35caeac561b9b8613ba5556958799d8c5954e2c2a8ace484bdc6fa75e7ad7404ebe7b1724a164634fadc8450dc27b28fcfa0e5c46c5da3e73d34dba7fea33db00631811b096d2d4f194f204c9421b9996ef929156").unwrap(), + KeyType::MACKey, + ) + .unwrap(); + let msg = + hex::decode("9268f10c36fd3366012e841260e60227a968f6c8546dee6abc83b3").unwrap(); + let expected = hex::decode("3288232187dcf1ea421f5c12bdeb4fd9d0a0a25b").unwrap(); + let full = HMAC_SHA512_256::new(&key).unwrap().mac(&msg); + assert_eq!(full.len(), 32); + assert_eq!(&full[..20], &expected[..]); + // the same vector through the streaming API in uneven chunks + let mut mac = HMAC_SHA512_256::new(&key).unwrap(); + for chunk in msg.chunks(13) { + mac.do_update(chunk); + } + assert_eq!(mac.do_final(), full); + } } #[cfg(test)] @@ -605,6 +717,65 @@ mod hmac_tests { } } + /// HMAC-SM3 known answers. There is no RFC 4231 equivalent for SM3, so these reuse the RFC 4231 + /// keys/messages (cases 1, 2 and 6) with expected values generated by + /// `openssl dgst -sm3 -mac HMAC` and independently confirmed with bc-java's + /// `HMac(new SM3Digest())`, plus a zero-length key. + #[test] + fn hmac_sm3_known_answers() { + use bouncycastle_core::key_material::KeyMaterial; + let test_framework = TestFrameworkMAC::new(); + + // RFC4231 Test Case 1 key/message + test_framework.test_mac::( + &KeyMaterial::<20>::from_bytes_as_type( + &hex::decode("0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b").unwrap(), + KeyType::MACKey, + ) + .unwrap(), + b"Hi There", + &hex::decode("51b00d1fb49832bfb01c3ce27848e59f871d9ba938dc563b338ca964755cce70") + .unwrap(), + ); + // RFC4231 Test Case 2 key/message + test_framework.test_mac::( + &KeyMaterial::<4>::from_bytes_as_type(b"Jefe", KeyType::MACKey).unwrap(), + b"what do ya want for nothing?", + &hex::decode("2e87f1d16862e6d964b50a5200bf2b10b764faa9680a296a2405f24bec39f882") + .unwrap(), + ); + // RFC4231 Test Case 6 key/message: key larger than the 64-byte block, so it is hashed first + test_framework.test_mac::( + &KeyMaterial::<131>::from_bytes_as_type(&[0xaa; 131], KeyType::MACKey).unwrap(), + b"Test Using Larger Than Block-Size Key - Hash Key First", + &hex::decode("b4fd844e13342002f0b2e0690ea7741f1497d993a70494cea601e657bedf67a0") + .unwrap(), + ); + + // zero-length key (weak; needs new_allow_weak_key) + let mut zero_length_key = KeyMaterial256::default(); + key_material::do_hazardous_operations(&mut zero_length_key, |k| { + k.set_key_type(KeyType::MACKey) + }) + .unwrap(); + let mut mac = HMAC_SM3::new_allow_weak_key(&zero_length_key).unwrap(); + mac.do_update(b"abc"); + assert_eq!( + mac.do_final(), + hex::decode("36525058ca466791502435c910517f1a7e86613d5f35ac1f18a94def0eaac81f") + .unwrap() + ); + + assert_eq!( + HMAC_SM3::new( + &KeyMaterial256::from_bytes_as_type(&DUMMY_SEED[..32], KeyType::MACKey).unwrap() + ) + .unwrap() + .output_len(), + 32 + ); + } + #[test] fn suspendable_keyed_state() { use bouncycastle_core::errors::SuspendableError; @@ -660,7 +831,10 @@ mod hmac_tests { round_trip(HMAC_SHA256::new(&key).unwrap(), &key, msg); round_trip(HMAC_SHA512::new(&key).unwrap(), &key, msg); + round_trip(HMAC_SHA512_224::new(&key).unwrap(), &key, msg); + round_trip(HMAC_SHA512_256::new(&key).unwrap(), &key, msg); round_trip(HMAC_SHA3_256::new(&key).unwrap(), &key, msg); + round_trip(HMAC_SM3::new(&key).unwrap(), &key, msg); // test suspend / resume with a key larger than block size let long_key = @@ -716,10 +890,13 @@ mod hmac_tests { keygen_test!(keygen_hmac_sha256, HMAC_SHA256, 32); keygen_test!(keygen_hmac_sha384, HMAC_SHA384, 48); keygen_test!(keygen_hmac_sha512, HMAC_SHA512, 64); + keygen_test!(keygen_hmac_sha512_224, HMAC_SHA512_224, 28); + keygen_test!(keygen_hmac_sha512_256, HMAC_SHA512_256, 32); keygen_test!(keygen_hmac_sha3_224, HMAC_SHA3_224, 28); keygen_test!(keygen_hmac_sha3_256, HMAC_SHA3_256, 32); keygen_test!(keygen_hmac_sha3_384, HMAC_SHA3_384, 48); keygen_test!(keygen_hmac_sha3_512, HMAC_SHA3_512, 64); + keygen_test!(keygen_hmac_sm3, HMAC_SM3, 32); /// `keygen_from_rng` must refuse an RNG whose security strength is below the strength the HMAC /// claims, otherwise the returned key would be tagged stronger than the entropy behind it. diff --git a/crypto/mldsa-lowmemory/benches/note_on_mem_usage_benches.md b/crypto/mldsa-lowmemory/benches/note_on_mem_usage_benches.md deleted file mode 100644 index d029e88e..00000000 --- a/crypto/mldsa-lowmemory/benches/note_on_mem_usage_benches.md +++ /dev/null @@ -1 +0,0 @@ -Note that a test framework is located in the `\/src/bench_mldsa_mem_usage.rs` so that it can be built as a standalone binary and have its memory usage measured with /usr/bin/time without also measuring any of the cargo bench framework. \ No newline at end of file diff --git a/crypto/modes/Cargo.toml b/crypto/modes/Cargo.toml new file mode 100644 index 00000000..81a97597 --- /dev/null +++ b/crypto/modes/Cargo.toml @@ -0,0 +1,24 @@ +[package] +name = "bouncycastle-modes" +version.workspace = true +edition.workspace = true + +[dependencies] +bouncycastle-core.workspace = true +# Only for the default OS-backed DRBG that generates the IV in `do_encrypt_init`. +bouncycastle-rng.workspace = true +# Only for `Secret`, which holds CTR's unused keystream so it is zeroized on drop. +bouncycastle-utils.workspace = true + +[dev-dependencies] +bouncycastle-aes-lowmemory.workspace = true +bouncycastle-core-test-framework.workspace = true +bouncycastle-hex.workspace = true +# Only to prove the modes compose with the padding layer for arbitrary-length data; no runtime dep. +bouncycastle-padding.workspace = true +criterion.workspace = true +serde_json = "1.0" + +[[bench]] +name = "modes_benches" +harness = false diff --git a/crypto/modes/benches/modes_benches.rs b/crypto/modes/benches/modes_benches.rs new file mode 100644 index 00000000..c867e92a --- /dev/null +++ b/crypto/modes/benches/modes_benches.rs @@ -0,0 +1,747 @@ +//! Criterion benchmarks for the modes. +//! +//! The number to watch is the **decrypt/encrypt throughput ratio at N >= 2**. Encryption in both +//! CBC and CFB is serial by construction (SP 800-38A Sec 6.2 and Sec 6.3: each forward cipher input +//! depends on the previous output), so it can only ever use the single-block path. *Decryption* in +//! both is parallel, and this implementation hands blocks to the permutation's batch methods -- +//! eights first, then pairs, then the remainder singly: for CBC that is `decrypt_blocks8` / +//! `decrypt_blocks2`, for CFB it is `encrypt_blocks8` / `encrypt_blocks2`, since CFB uses the +//! forward function in both directions. AES overrides only the pair form, so its eights are four +//! pairs. With the bit-sliced AES, whose two-block path costs barely more than one block, +//! decryption should therefore run at roughly twice the throughput of encryption. That gap is the +//! entire justification for the batch methods on `ElectronicCodeBook`, so if it disappears, +//! something has stopped taking the pair path. +//! +//! `N = 1` is included to show the effect vanishing: with one block there is no pair to form, so +//! decryption falls back to the single-block path and the ratio should be about 1. +//! +//! CFB is a stream cipher (`StreamCipherEncryptor` / `StreamCipherDecryptor`), so `N` there is +//! simply the call length in blocks; the same 16 KiB goes through `do_encrypt` / `do_decrypt` as +//! `16 * N`-byte slices. Two extra CFB measurements use calls that are *not* a whole number of +//! blocks: every such call ends mid-segment and the next one starts by finishing it byte by byte, +//! so they show what the byte path costs relative to the block path at a comparable call length. +//! +//! The `modes::cfb8::Aes128` group measures the other thing worth knowing about CFB8: it spends one +//! full forward cipher per *byte*, so on a 16-byte block it should come out at roughly **1/16** the +//! throughput of CFB over the same 16 KiB. That ratio, against `modes::cfb::Aes128`, is the number +//! to watch; it is inherent to `s = 8` (Sec 6.3 discards `b - s` bits of every output block), not a +//! property of this implementation. Decryption should still beat encryption, because CFB8 +//! decryption builds its input blocks in series and then batches the ciphers eight at a time while +//! encryption cannot. +//! +//! The cipher works in place, so each measurement runs on a fresh copy of the data made in +//! criterion's untimed setup (`iter_batched`); the copy is not part of the timing. +//! +//! The `modes::cbc::Aes128` and `modes::cfb::Aes128` groups are directly comparable -- same cipher, +//! same data, same call granularity -- so the difference between them is the cost of the mode. CFB +//! never calls the inverse cipher, so on an engine whose inverse is slower than its forward +//! direction, CFB decryption is expected to come out ahead of CBC decryption. + +use bouncycastle_aes_lowmemory::{Aes128, Aes256}; +use bouncycastle_core::errors::SymmetricCipherError; +use bouncycastle_core::key_material::{KeyMaterial, KeyType}; +use bouncycastle_core::traits::{ + Algorithm, BlockCipherDecryptor, BlockCipherEncryptor, ElectronicCodeBook, SecurityStrength, + StreamCipherDecryptor, StreamCipherEncryptor, +}; +use bouncycastle_modes::{Cbc, Cfb, Cfb8, Ctr, Decrypting, Ecb, Encrypting}; +use criterion::{BatchSize, Criterion, Throughput, criterion_group, criterion_main}; +use std::hint::black_box; + +const BLOCK_LEN: usize = 16; +/// 16 KiB, i.e. 1024 AES blocks. +const NUM_BLOCKS: usize = 1024; +const DATA_LEN: usize = NUM_BLOCKS * BLOCK_LEN; + +type Aes128Cbc

= Cbc; +type Aes256Cbc = Cbc; +type Aes128Cfb = Cfb; +type Aes256Cfb = Cfb; +type Aes128Cfb8 = Cfb8; +type Aes128Ctr = Ctr; +type Aes256Ctr = Ctr; +type Aes128Ecb = Ecb; + +/// AES-128 with the pair methods **not** overridden, so they fall back to the trait defaults of +/// two single-block calls. +/// +/// This exists purely to isolate the value of the pair path. Comparing `Cbc` against +/// `Cbc` at the *same* `N` holds everything else fixed -- same cipher, same +/// call granularity, same amount of data movement -- so the difference is attributable to +/// `decrypt_blocks2` and nothing else. +/// +/// Comparing `N = 1` against `N = 8` does *not* isolate it: encryption, which can never pair, also +/// speeds up substantially between those two, so call granularity dominates that comparison. +struct UnpairedAes128(Aes128); + +impl Algorithm for UnpairedAes128 { + const ALG_NAME: &'static str = "AES-128 (unpaired)"; + const MAX_SECURITY_STRENGTH: SecurityStrength = SecurityStrength::_128bit; +} + +impl ElectronicCodeBook<16, BLOCK_LEN> for UnpairedAes128 { + fn new(key: &KeyMaterial<16>) -> Result { + Ok(Self(>::new(key)?)) + } + fn encrypt_block(&self, block: &mut [u8; BLOCK_LEN]) { + >::encrypt_block(&self.0, block) + } + fn decrypt_block(&self, block: &mut [u8; BLOCK_LEN]) { + >::decrypt_block(&self.0, block) + } + // encrypt_blocks2 / decrypt_blocks2 deliberately left as the trait defaults. +} + +type UnpairedAes128Cbc = Cbc; +type UnpairedAes128Cfb = Cfb; +type UnpairedAes128Ecb = Ecb; + +fn key() -> KeyMaterial { + let bytes: [u8; N] = core::array::from_fn(|i| (i as u8).wrapping_mul(7).wrapping_add(1)); + KeyMaterial::::from_bytes_as_type(&bytes, KeyType::SymmetricCipherKey).unwrap() +} + +fn data() -> Vec<[u8; BLOCK_LEN]> { + (0..NUM_BLOCKS) + .map(|i| core::array::from_fn(|j| (i.wrapping_mul(31).wrapping_add(j)) as u8)) + .collect() +} + +fn bench_aes128(c: &mut Criterion) { + let k = key::<16>(); + let blocks = data(); + + let mut group = c.benchmark_group("modes::cbc::Aes128"); + group.throughput(Throughput::Bytes(DATA_LEN as u64)); + + // ---- encryption: serial, one block at a time is all it can do ---- + group.bench_function("16KiB encrypt -- N=1", |b| { + b.iter_batched( + || blocks.clone(), + |mut scratch| { + let (mut enc, _) = Aes128Cbc::::do_encrypt_init(&k).unwrap(); + for block in scratch.iter_mut() { + enc.do_encrypt(block).unwrap(); + } + black_box(&scratch); + }, + BatchSize::LargeInput, + ) + }); + + group.bench_function("16KiB encrypt -- N=8", |b| { + b.iter_batched( + || blocks.clone(), + |mut scratch| { + let (mut enc, _) = Aes128Cbc::::do_encrypt_init(&k).unwrap(); + for chunk in scratch.chunks_exact_mut(8) { + let arr: &mut [u8; 8 * BLOCK_LEN] = + chunk.as_flattened_mut().try_into().unwrap(); + enc.do_encrypt(arr).unwrap(); + } + black_box(&scratch); + }, + BatchSize::LargeInput, + ) + }); + + // ---- decryption: parallel, uses decrypt_blocks2 for every pair ---- + let (mut enc, iv) = Aes128Cbc::::do_encrypt_init(&k).unwrap(); + let mut ciphertext = blocks.clone(); + for chunk in ciphertext.chunks_exact_mut(8) { + enc.do_encrypt_blocks(chunk).unwrap(); + } + + // N=1 never forms a pair, so this is the single-block path: the ratio against encrypt should + // be about 1. + group.bench_function("16KiB decrypt -- N=1 (no pairing)", |b| { + b.iter_batched( + || ciphertext.clone(), + |mut scratch| { + let mut dec = Aes128Cbc::::do_decrypt_init(&k, &iv).unwrap(); + for block in scratch.iter_mut() { + dec.do_decrypt(block).unwrap(); + } + black_box(&scratch); + }, + BatchSize::LargeInput, + ) + }); + + // N=2 is one pair and N=8 one eight (four pairs, for AES), so every block goes through + // decrypt_blocks2. + group.bench_function("16KiB decrypt -- N=2 (all pairs)", |b| { + b.iter_batched( + || ciphertext.clone(), + |mut scratch| { + let mut dec = Aes128Cbc::::do_decrypt_init(&k, &iv).unwrap(); + for chunk in scratch.chunks_exact_mut(2) { + let arr: &mut [u8; 2 * BLOCK_LEN] = + chunk.as_flattened_mut().try_into().unwrap(); + dec.do_decrypt(arr).unwrap(); + } + black_box(&scratch); + }, + BatchSize::LargeInput, + ) + }); + + group.bench_function("16KiB decrypt -- N=8 (all pairs)", |b| { + b.iter_batched( + || ciphertext.clone(), + |mut scratch| { + let mut dec = Aes128Cbc::::do_decrypt_init(&k, &iv).unwrap(); + for chunk in scratch.chunks_exact_mut(8) { + let arr: &mut [u8; 8 * BLOCK_LEN] = + chunk.as_flattened_mut().try_into().unwrap(); + dec.do_decrypt(arr).unwrap(); + } + black_box(&scratch); + }, + BatchSize::LargeInput, + ) + }); + + // N=9 is four pairs plus a one-block remainder, so it exercises the tail path too. + group.bench_function("16KiB decrypt -- N=9 (pairs + remainder)", |b| { + b.iter_batched( + || ciphertext.clone(), + |mut scratch| { + let mut dec = Aes128Cbc::::do_decrypt_init(&k, &iv).unwrap(); + for chunk in scratch.chunks_exact_mut(9) { + let arr: &mut [u8; 9 * BLOCK_LEN] = + chunk.as_flattened_mut().try_into().unwrap(); + dec.do_decrypt(arr).unwrap(); + } + black_box(&scratch); + }, + BatchSize::LargeInput, + ) + }); + + // The controlled comparison: identical N, identical cipher, pair methods overridden vs not. + // This pair of numbers -- and only this pair -- measures what `decrypt_blocks2` buys. + group.bench_function("16KiB decrypt -- N=8, pair path (blocks2 overridden)", |b| { + b.iter_batched( + || ciphertext.clone(), + |mut scratch| { + let mut dec = Aes128Cbc::::do_decrypt_init(&k, &iv).unwrap(); + for chunk in scratch.chunks_exact_mut(8) { + let arr: &mut [u8; 8 * BLOCK_LEN] = + chunk.as_flattened_mut().try_into().unwrap(); + dec.do_decrypt(arr).unwrap(); + } + black_box(&scratch); + }, + BatchSize::LargeInput, + ) + }); + + group.bench_function("16KiB decrypt -- N=8, no pair path (trait default)", |b| { + b.iter_batched( + || ciphertext.clone(), + |mut scratch| { + let mut dec = UnpairedAes128Cbc::::do_decrypt_init(&k, &iv).unwrap(); + for chunk in scratch.chunks_exact_mut(8) { + let arr: &mut [u8; 8 * BLOCK_LEN] = + chunk.as_flattened_mut().try_into().unwrap(); + dec.do_decrypt(arr).unwrap(); + } + black_box(&scratch); + }, + BatchSize::LargeInput, + ) + }); + + group.finish(); +} + +fn bench_aes256(c: &mut Criterion) { + let k = key::<32>(); + let blocks = data(); + + let mut group = c.benchmark_group("modes::cbc::Aes256"); + group.throughput(Throughput::Bytes(DATA_LEN as u64)); + + group.bench_function("16KiB encrypt -- N=8", |b| { + b.iter_batched( + || blocks.clone(), + |mut scratch| { + let (mut enc, _) = Aes256Cbc::::do_encrypt_init(&k).unwrap(); + for chunk in scratch.chunks_exact_mut(8) { + let arr: &mut [u8; 8 * BLOCK_LEN] = + chunk.as_flattened_mut().try_into().unwrap(); + enc.do_encrypt(arr).unwrap(); + } + black_box(&scratch); + }, + BatchSize::LargeInput, + ) + }); + + let (mut enc, iv) = Aes256Cbc::::do_encrypt_init(&k).unwrap(); + let mut ciphertext = blocks.clone(); + for chunk in ciphertext.chunks_exact_mut(8) { + enc.do_encrypt_blocks(chunk).unwrap(); + } + + group.bench_function("16KiB decrypt -- N=8 (all pairs)", |b| { + b.iter_batched( + || ciphertext.clone(), + |mut scratch| { + let mut dec = Aes256Cbc::::do_decrypt_init(&k, &iv).unwrap(); + for chunk in scratch.chunks_exact_mut(8) { + let arr: &mut [u8; 8 * BLOCK_LEN] = + chunk.as_flattened_mut().try_into().unwrap(); + dec.do_decrypt(arr).unwrap(); + } + black_box(&scratch); + }, + BatchSize::LargeInput, + ) + }); + + group.finish(); +} + +/// Runs the 16 KiB through a stream-cipher encryptor in `call_len`-byte calls. Used by the CFB, +/// CFB8 and CTR groups: it is generic over the trait, not over the mode. +fn cfb_encrypt_in_calls< + E: StreamCipherEncryptor, + const KEY_LEN: usize, + const INIT_DATA_LEN: usize, +>( + k: &KeyMaterial, + scratch: &mut [u8], + call_len: usize, +) { + let (mut enc, _) = E::do_encrypt_init(k).unwrap(); + for piece in scratch.chunks_mut(call_len) { + enc.do_encrypt(piece).unwrap(); + } +} + +/// Runs the 16 KiB through a stream-cipher decryptor in `call_len`-byte calls. Shared as above. +fn cfb_decrypt_in_calls< + D: StreamCipherDecryptor, + const KEY_LEN: usize, + const INIT_DATA_LEN: usize, +>( + k: &KeyMaterial, + iv: &[u8; INIT_DATA_LEN], + scratch: &mut [u8], + call_len: usize, +) { + let mut dec = D::do_decrypt_init(k, iv).unwrap(); + for piece in scratch.chunks_mut(call_len) { + dec.do_decrypt(piece).unwrap(); + } +} + +fn bench_cfb_aes128(c: &mut Criterion) { + let k = key::<16>(); + let blocks = data(); + let flat: Vec = blocks.as_flattened().to_vec(); + + let mut group = c.benchmark_group("modes::cfb::Aes128"); + group.throughput(Throughput::Bytes(DATA_LEN as u64)); + + // ---- encryption: serial. Oj+1 = CIPH_K(Cj), and Cj is the previous call's output ---- + for (name, call_len) in [ + ("16KiB encrypt -- N=1", BLOCK_LEN), + ("16KiB encrypt -- N=8", 8 * BLOCK_LEN), + // 125 bytes: 7 blocks and 13 bytes, so every call finishes the segment the previous one + // left open, then does whole blocks, then opens a new segment. Compare with N=8. + ("16KiB encrypt -- 125-byte calls (byte path at both ends)", 125), + ] { + group.bench_function(name, |b| { + b.iter_batched( + || flat.clone(), + |mut scratch| { + cfb_encrypt_in_calls::, 16, BLOCK_LEN>( + &k, &mut scratch, call_len, + ); + black_box(&scratch); + }, + BatchSize::LargeInput, + ) + }); + } + + // ---- decryption: parallel, and uses `encrypt_blocks8` / `encrypt_blocks2` -- the FORWARD + // batch methods ---- + let (mut enc, iv) = Aes128Cfb::::do_encrypt_init(&k).unwrap(); + let mut ciphertext = flat.clone(); + enc.do_encrypt(&mut ciphertext).unwrap(); + + for (name, call_len) in [ + // N=1 never forms a pair, so this is the single-block path: the ratio against encrypt + // should be about 1. + ("16KiB decrypt -- N=1 (no pairing)", BLOCK_LEN), + // N=2 and N=8 are all pairs (N=8 one eight), so every block goes through a batch method. + ("16KiB decrypt -- N=2 (all pairs)", 2 * BLOCK_LEN), + ("16KiB decrypt -- N=8 (all pairs)", 8 * BLOCK_LEN), + // N=9 is one eight plus a one-block remainder, so it exercises the tail path too. + ("16KiB decrypt -- N=9 (pairs + remainder)", 9 * BLOCK_LEN), + // As for encryption: 7 blocks plus 13 bytes per call. Compare with N=8. + ("16KiB decrypt -- 125-byte calls (byte path at both ends)", 125), + ] { + group.bench_function(name, |b| { + b.iter_batched( + || ciphertext.clone(), + |mut scratch| { + cfb_decrypt_in_calls::, 16, BLOCK_LEN>( + &k, &iv, &mut scratch, call_len, + ); + black_box(&scratch); + }, + BatchSize::LargeInput, + ) + }); + } + + // The controlled comparison: identical N, identical cipher, pair methods overridden vs not. + // This pair of numbers -- and only this pair -- measures what `encrypt_blocks2` buys CFB. + group.bench_function("16KiB decrypt -- N=8, pair path (blocks2 overridden)", |b| { + b.iter_batched( + || ciphertext.clone(), + |mut scratch| { + cfb_decrypt_in_calls::, 16, BLOCK_LEN>( + &k, + &iv, + &mut scratch, + 8 * BLOCK_LEN, + ); + black_box(&scratch); + }, + BatchSize::LargeInput, + ) + }); + + group.bench_function("16KiB decrypt -- N=8, no pair path (trait default)", |b| { + b.iter_batched( + || ciphertext.clone(), + |mut scratch| { + cfb_decrypt_in_calls::, 16, BLOCK_LEN>( + &k, + &iv, + &mut scratch, + 8 * BLOCK_LEN, + ); + black_box(&scratch); + }, + BatchSize::LargeInput, + ) + }); + + group.finish(); +} + +fn bench_cfb_aes256(c: &mut Criterion) { + let k = key::<32>(); + let flat: Vec = data().as_flattened().to_vec(); + + let mut group = c.benchmark_group("modes::cfb::Aes256"); + group.throughput(Throughput::Bytes(DATA_LEN as u64)); + + group.bench_function("16KiB encrypt -- N=8", |b| { + b.iter_batched( + || flat.clone(), + |mut scratch| { + cfb_encrypt_in_calls::, 32, BLOCK_LEN>( + &k, + &mut scratch, + 8 * BLOCK_LEN, + ); + black_box(&scratch); + }, + BatchSize::LargeInput, + ) + }); + + let (mut enc, iv) = Aes256Cfb::::do_encrypt_init(&k).unwrap(); + let mut ciphertext = flat.clone(); + enc.do_encrypt(&mut ciphertext).unwrap(); + + group.bench_function("16KiB decrypt -- N=8 (all pairs)", |b| { + b.iter_batched( + || ciphertext.clone(), + |mut scratch| { + cfb_decrypt_in_calls::, 32, BLOCK_LEN>( + &k, + &iv, + &mut scratch, + 8 * BLOCK_LEN, + ); + black_box(&scratch); + }, + BatchSize::LargeInput, + ) + }); + + group.finish(); +} + +/// CFB8: one forward cipher per byte, so ~1/16 of CFB's throughput on a 16-byte block. +/// +/// Encryption is strictly serial. Decryption builds its input blocks in series and then runs them +/// through `encrypt_blocks8` / `encrypt_blocks2` (SP 800-38A Sec 6.3's parallel decryption), so it +/// should be substantially faster than encryption -- the same batch effect CBC and CFB show, at +/// byte granularity. +fn bench_cfb8_aes128(c: &mut Criterion) { + let k = key::<16>(); + let flat: Vec = data().as_flattened().to_vec(); + + let mut group = c.benchmark_group("modes::cfb8::Aes128"); + group.throughput(Throughput::Bytes(DATA_LEN as u64)); + + // Serial by construction: I_{j+1} needs Cj, which this call just produced. + group.bench_function("16KiB encrypt -- whole message in one call", |b| { + b.iter_batched( + || flat.clone(), + |mut scratch| { + cfb_encrypt_in_calls::, 16, BLOCK_LEN>( + &k, &mut scratch, DATA_LEN, + ); + black_box(&scratch); + }, + BatchSize::LargeInput, + ) + }); + + let (mut enc, iv) = Aes128Cfb8::::do_encrypt_init(&k).unwrap(); + let mut ciphertext = flat.clone(); + enc.do_encrypt(&mut ciphertext).unwrap(); + + for (name, call_len) in [ + // One call: eights, then pairs, then the tail. This is the batched path. + ("16KiB decrypt -- whole message in one call (batched)", DATA_LEN), + // 8-byte calls: still exactly one eight-block batch per call. + ("16KiB decrypt -- 8-byte calls (one batch each)", 8), + // 1-byte calls: never batches, so this is the cost of the serial path on the decrypt side + // and the controlled comparison for what batching buys. + ("16KiB decrypt -- 1-byte calls (no batching)", 1), + ] { + group.bench_function(name, |b| { + b.iter_batched( + || ciphertext.clone(), + |mut scratch| { + cfb_decrypt_in_calls::, 16, BLOCK_LEN>( + &k, &iv, &mut scratch, call_len, + ); + black_box(&scratch); + }, + BatchSize::LargeInput, + ) + }); + } + + group.finish(); +} + +/// CTR: the only mode here whose **encryption** is parallel too. +/// +/// Counter blocks depend on nothing but the nonce and the index (SP 800-38A Sec 6.5), so unlike CBC +/// and CFB there is no serial direction: encryption should show the same `N >= 2` speed-up that only +/// decryption shows for the feedback modes, and the two directions should measure the same, since +/// they are the same operation. That symmetry is the number to watch here. +fn bench_ctr_aes128(c: &mut Criterion) { + let k = key::<16>(); + let flat: Vec = data().as_flattened().to_vec(); + + let mut group = c.benchmark_group("modes::ctr::Aes128"); + group.throughput(Throughput::Bytes(DATA_LEN as u64)); + + for (name, call_len) in [ + // N=1 never forms a pair: the single-block path, and the baseline for the batch effect. + ("16KiB encrypt -- N=1 (no batching)", BLOCK_LEN), + ("16KiB encrypt -- N=2 (all pairs)", 2 * BLOCK_LEN), + ("16KiB encrypt -- N=8 (one eight per call)", 8 * BLOCK_LEN), + // Calls that are not a whole number of blocks, so each end goes byte by byte. + ("16KiB encrypt -- 125-byte calls (byte path at both ends)", 125), + ] { + group.bench_function(name, |b| { + b.iter_batched( + || flat.clone(), + |mut scratch| { + cfb_encrypt_in_calls::, 16, 12>( + &k, &mut scratch, call_len, + ); + black_box(&scratch); + }, + BatchSize::LargeInput, + ) + }); + } + + let (mut enc, nonce) = Aes128Ctr::::do_encrypt_init(&k).unwrap(); + let mut ciphertext = flat.clone(); + enc.do_encrypt(&mut ciphertext).unwrap(); + + for (name, call_len) in [ + ("16KiB decrypt -- N=1 (no batching)", BLOCK_LEN), + ("16KiB decrypt -- N=8 (one eight per call)", 8 * BLOCK_LEN), + ] { + group.bench_function(name, |b| { + b.iter_batched( + || ciphertext.clone(), + |mut scratch| { + cfb_decrypt_in_calls::, 16, 12>( + &k, &nonce, &mut scratch, call_len, + ); + black_box(&scratch); + }, + BatchSize::LargeInput, + ) + }); + } + + group.finish(); +} + +/// AES-256 CTR, for the same key-length comparison the other modes carry. +fn bench_ctr_aes256(c: &mut Criterion) { + let k = key::<32>(); + let flat: Vec = data().as_flattened().to_vec(); + + let mut group = c.benchmark_group("modes::ctr::Aes256"); + group.throughput(Throughput::Bytes(DATA_LEN as u64)); + + group.bench_function("16KiB encrypt -- N=8", |b| { + b.iter_batched( + || flat.clone(), + |mut scratch| { + cfb_encrypt_in_calls::, 32, 12>( + &k, + &mut scratch, + 8 * BLOCK_LEN, + ); + black_box(&scratch); + }, + BatchSize::LargeInput, + ) + }); + + group.finish(); +} + +/// ECB has no chaining, so *both* directions batch (SP 800-38A Sec 6.1: forward and inverse +/// cipher functions "can be computed in parallel"). Encryption should therefore show the same +/// N >= 2 speed-up that only decryption shows for CBC and CFB, and the encrypt/decrypt gap should be +/// just the permutation's own forward/inverse cost difference. +fn bench_ecb_aes128(c: &mut Criterion) { + let k = key::<16>(); + let blocks = data(); + + let mut group = c.benchmark_group("modes::ecb::Aes128"); + group.throughput(Throughput::Bytes(DATA_LEN as u64)); + + group.bench_function("16KiB encrypt -- N=1 (no batching)", |b| { + b.iter_batched( + || blocks.clone(), + |mut scratch| { + let (mut enc, _) = Aes128Ecb::::do_encrypt_init(&k).unwrap(); + for block in scratch.iter_mut() { + enc.do_encrypt(block).unwrap(); + } + black_box(&scratch); + }, + BatchSize::LargeInput, + ) + }); + + group.bench_function("16KiB encrypt -- N=8 (eights)", |b| { + b.iter_batched( + || blocks.clone(), + |mut scratch| { + let (mut enc, _) = Aes128Ecb::::do_encrypt_init(&k).unwrap(); + for chunk in scratch.chunks_exact_mut(8) { + let arr: &mut [u8; 8 * BLOCK_LEN] = + chunk.as_flattened_mut().try_into().unwrap(); + enc.do_encrypt(arr).unwrap(); + } + black_box(&scratch); + }, + BatchSize::LargeInput, + ) + }); + + group.bench_function("16KiB decrypt -- N=8 (eights)", |b| { + b.iter_batched( + || blocks.clone(), + |mut scratch| { + let mut dec = Aes128Ecb::::do_decrypt_init(&k, &[]).unwrap(); + for chunk in scratch.chunks_exact_mut(8) { + let arr: &mut [u8; 8 * BLOCK_LEN] = + chunk.as_flattened_mut().try_into().unwrap(); + dec.do_decrypt(arr).unwrap(); + } + black_box(&scratch); + }, + BatchSize::LargeInput, + ) + }); + + // The controlled comparison: identical N, identical cipher, batch methods overridden vs not. + group.bench_function("16KiB encrypt -- N=8, no pair path (trait default)", |b| { + b.iter_batched( + || blocks.clone(), + |mut scratch| { + let (mut enc, _) = UnpairedAes128Ecb::::do_encrypt_init(&k).unwrap(); + for chunk in scratch.chunks_exact_mut(8) { + let arr: &mut [u8; 8 * BLOCK_LEN] = + chunk.as_flattened_mut().try_into().unwrap(); + enc.do_encrypt(arr).unwrap(); + } + black_box(&scratch); + }, + BatchSize::LargeInput, + ) + }); + + group.finish(); +} + +/// `do_*_init` includes a key expansion, and for encryption also an IV draw from the OS-backed +/// DRBG. Worth its own measurement, because for short messages it dominates. +fn bench_init(c: &mut Criterion) { + let k128 = key::<16>(); + let k256 = key::<32>(); + let iv = [0u8; BLOCK_LEN]; + + let mut group = c.benchmark_group("modes::init"); + + group.bench_function("Aes128 do_encrypt_init (key schedule + IV)", |b| { + b.iter(|| black_box(Aes128Cbc::::do_encrypt_init(black_box(&k128)).unwrap().1)) + }); + group.bench_function("Aes128 do_decrypt_init (key schedule only)", |b| { + b.iter(|| { + black_box(Aes128Cbc::::do_decrypt_init(black_box(&k128), &iv).unwrap()) + }) + }); + group.bench_function("Aes256 do_decrypt_init (key schedule only)", |b| { + b.iter(|| { + black_box(Aes256Cbc::::do_decrypt_init(black_box(&k256), &iv).unwrap()) + }) + }); + + // CFB does exactly the same work here -- one key expansion, plus an IV draw when encrypting -- + // so these should match the CBC numbers. A divergence would mean one mode is doing something + // extra at construction time. + group.bench_function("Aes128 do_encrypt_init, CFB (key schedule + IV)", |b| { + b.iter(|| black_box(Aes128Cfb::::do_encrypt_init(black_box(&k128)).unwrap().1)) + }); + group.bench_function("Aes128 do_decrypt_init, CFB (key schedule only)", |b| { + b.iter(|| { + black_box(Aes128Cfb::::do_decrypt_init(black_box(&k128), &iv).unwrap()) + }) + }); + + group.finish(); +} + +criterion_group!( + benches, bench_aes128, bench_aes256, bench_cfb_aes128, bench_cfb_aes256, bench_cfb8_aes128, + bench_ctr_aes128, bench_ctr_aes256, bench_ecb_aes128, bench_init +); +criterion_main!(benches); diff --git a/crypto/modes/src/cbc.rs b/crypto/modes/src/cbc.rs new file mode 100644 index 00000000..a5ea5ce1 --- /dev/null +++ b/crypto/modes/src/cbc.rs @@ -0,0 +1,237 @@ +//! The Cipher Block Chaining mode of operation (NIST SP 800-38A Sec 6.2). +//! +//! # The specification +//! +//! SP 800-38A Sec 6.2 defines the mode as, quoting verbatim: +//! +//! ```text +//! CBC Encryption: C1 = CIPH_K(P1 XOR IV); +//! Cj = CIPH_K(Pj XOR Cj-1) for j = 2 ... n. +//! +//! CBC Decryption: P1 = CIPH^-1_K(C1) XOR IV; +//! Pj = CIPH^-1_K(Cj) XOR Cj-1 for j = 2 ... n. +//! ``` +//! +//! The `j = 1` and `j >= 2` cases differ only in that the first one uses the IV where the others +//! use the previous ciphertext block. So this implementation keeps a single `chain` field holding +//! "whatever gets XORed next", initialised to the IV and replaced by each ciphertext block as it +//! is produced or consumed. That is the equivalence being used, and it is why there is no special +//! case for the first block anywhere below. +//! +//! # Parallel decryption +//! +//! Sec 6.2 notes that in CBC decryption "the input blocks for the inverse cipher function, i.e., +//! the ciphertext blocks, are immediately available, so that multiple inverse cipher operations can +//! be performed in parallel", whereas in encryption "the input block to each forward cipher +//! operation (except the first) depends on the result of the previous forward cipher operation, so +//! the forward cipher operations cannot be performed in parallel". +//! +//! This implementation uses that: decryption walks the ciphertext eight blocks at a time through +//! [`ElectronicCodeBook::decrypt_blocks8`], then any remaining pair through +//! [`ElectronicCodeBook::decrypt_blocks2`], then the last block singly. A bit-sliced engine +//! computes a pair (AES) or eight blocks (SM4) for barely more than the cost of one. Encryption +//! cannot, and does not. + +use crate::iv::random_iv; +use crate::{Decrypting, Encrypting}; +use bouncycastle_core::errors::SymmetricCipherError; +use bouncycastle_core::key_material::KeyMaterial; +use bouncycastle_core::traits::{ + Algorithm, BlockCipherDecryptor, BlockCipherEncryptor, ElectronicCodeBook, RNG, + SecurityStrength, +}; +use bouncycastle_rng::HashDRBG_SHA512; +use core::marker::PhantomData; + +/// CBC mode over any [`ElectronicCodeBook`], with the direction encoded in the type. +/// +/// `Dir` is [`Encrypting`] or [`Decrypting`]. [`BlockCipherEncryptor`] is implemented only for the +/// former and [`BlockCipherDecryptor`] only for the latter, so a `Cbc<_, Encrypting, _, _>` has no +/// decryption methods at all -- using one in the wrong direction is a compile error rather than a +/// runtime check. +/// +/// The initialization data is one block, so `INIT_DATA_LEN == BLOCK_LEN`. +/// +/// # State +/// +/// Two fields: the permutation (which owns the key schedule, and is responsible for keeping it in +/// a zeroize-on-drop wrapper) and one block of chaining value. The chaining value is an IV or a +/// ciphertext block, both of which are public, so it is deliberately not wrapped in a `Secret`. +pub struct Cbc +where + P: ElectronicCodeBook, +{ + perm: P, + /// `Cj-1`, initialised to the IV. See the module docs on why there is only one field for both. + chain: [u8; BLOCK_LEN], + _dir: PhantomData, +} + +impl Cbc +where + P: ElectronicCodeBook, +{ + /// `Cj = CIPH_K(Pj XOR Cj-1)` in place, then `Cj` becomes the next chaining value. + #[inline] + fn encrypt_one(&mut self, block: &mut [u8; BLOCK_LEN]) { + for (b, chain) in block.iter_mut().zip(self.chain.iter()) { + *b ^= *chain; // Pj XOR Cj-1 + } + self.perm.encrypt_block(block); // Cj = CIPH_K(..) + self.chain = *block; + } + + /// `Pj = CIPH^-1_K(Cj) XOR Cj-1` in place, then `Cj` becomes the next chaining value. + /// + /// `Cj` is overwritten by `Pj`, so it is copied first: it is the next chaining value. + #[inline] + fn decrypt_one(&mut self, block: &mut [u8; BLOCK_LEN]) { + let cj = *block; + self.perm.decrypt_block(block); // CIPH^-1_K(Cj) + for (b, chain) in block.iter_mut().zip(self.chain.iter()) { + *b ^= *chain; // XOR Cj-1 + } + self.chain = cj; + } + + /// Decrypts two consecutive blocks with one [`ElectronicCodeBook::decrypt_blocks2`] call. + /// + /// Writing the pair as `Cj, Cj+1` with `Cj-1` the incoming chaining value, Sec 6.2 gives + /// + /// ```text + /// Pj = CIPH^-1_K(Cj) XOR Cj-1 + /// Pj+1 = CIPH^-1_K(Cj+1) XOR Cj + /// ``` + /// + /// Neither inverse cipher depends on the other's *output* -- only on ciphertext, which is + /// already in hand -- so computing them together changes nothing. The two XOR operands do + /// differ, and the second one is `Cj`, so both ciphertext blocks are copied out before the + /// permutation overwrites them, and the chaining value is then advanced to `Cj+1`. + #[inline] + fn decrypt_pair(&mut self, blocks: &mut [[u8; BLOCK_LEN]; 2]) { + let [cj, cj1] = *blocks; + self.perm.decrypt_blocks2(blocks); + + let [pj, pj1] = blocks; + for (b, chain) in pj.iter_mut().zip(self.chain.iter()) { + *b ^= *chain; // XOR Cj-1 + } + for (b, prev) in pj1.iter_mut().zip(cj.iter()) { + *b ^= *prev; // XOR Cj + } + + self.chain = cj1; + } + + /// Decrypts eight consecutive blocks with one [`ElectronicCodeBook::decrypt_blocks8`] call. + /// + /// The same argument as [`Self::decrypt_pair`], eight wide: `Pj+k = CIPH^-1_K(Cj+k) XOR Cj+k-1` + /// for `k = 0..8`, with `Cj-1` the incoming chaining value. No inverse cipher depends on + /// another's output, so all eight run together; the ciphertexts are copied out first because + /// the permutation overwrites them and each is the next block's XOR operand, and the chaining + /// value advances to `Cj+7`. + #[inline] + fn decrypt_eight(&mut self, blocks: &mut [[u8; BLOCK_LEN]; 8]) { + let cts = *blocks; + self.perm.decrypt_blocks8(blocks); + + let mut prev = self.chain; + for (pj, cj) in blocks.iter_mut().zip(cts.iter()) { + for (b, chain) in pj.iter_mut().zip(prev.iter()) { + *b ^= *chain; // XOR Cj+k-1 + } + prev = *cj; + } + self.chain = prev; + } +} + +impl Algorithm + for Cbc +where + P: ElectronicCodeBook, +{ + /// The underlying permutation's name. The mode is not appended: `&'static str`s cannot be + /// concatenated in a `const`, and the mode is already in the type. + const ALG_NAME: &'static str = P::ALG_NAME; + /// A mode does not change the strength of the underlying cipher. + const MAX_SECURITY_STRENGTH: SecurityStrength = P::MAX_SECURITY_STRENGTH; +} + +impl + BlockCipherEncryptor for Cbc +where + P: ElectronicCodeBook, +{ + /// Begins an encryption flow, generating the IV from the library's default OS-backed DRBG. + fn do_encrypt_init( + key: &KeyMaterial, + ) -> Result<(Self, [u8; BLOCK_LEN]), SymmetricCipherError> { + let mut rng = HashDRBG_SHA512::new_from_os(); + Self::do_encrypt_init_rng(key, &mut rng) + } + + /// As [`BlockCipherEncryptor::do_encrypt_init`], but takes the IV from the provided RNG. + fn do_encrypt_init_rng( + key: &KeyMaterial, + rng: &mut dyn RNG, + ) -> Result<(Self, [u8; BLOCK_LEN]), SymmetricCipherError> { + let perm = P::new(key)?; + let iv = random_iv::(rng)?; + Ok((Self { perm, chain: iv, _dir: PhantomData }, iv)) + } + + /// The implementor hook (the flat `do_encrypt` is provided over it). + /// + /// Strictly serial: `Cj` is the input to block `j + 1`, so there is no pair path here. See the + /// module docs. Never fails: CBC has no per-IV data limit. + fn do_encrypt_blocks( + &mut self, + blocks: &mut [[u8; BLOCK_LEN]], + ) -> Result<(), SymmetricCipherError> { + for block in blocks.iter_mut() { + self.encrypt_one(block); + } + Ok(()) + } +} + +impl + BlockCipherDecryptor for Cbc +where + P: ElectronicCodeBook, +{ + /// Begins a decryption flow from the IV returned by + /// [`BlockCipherEncryptor::do_encrypt_init`]. + fn do_decrypt_init( + key: &KeyMaterial, + init_data: &[u8; BLOCK_LEN], + ) -> Result { + let perm = P::new(key)?; + Ok(Self { perm, chain: *init_data, _dir: PhantomData }) + } + + /// The implementor hook (the flat `do_decrypt` is provided over it). + /// + /// Walks the input in eights through `decrypt_blocks8`, then pairs through `decrypt_blocks2`, + /// then the at-most-one block left over: Sec 6.2's parallelism, in the units the permutation + /// offers. `as_chunks_mut` splits into exactly those shapes with no runtime length check and no + /// indexing arithmetic. Never fails: CBC has no per-IV data limit. + fn do_decrypt_blocks( + &mut self, + blocks: &mut [[u8; BLOCK_LEN]], + ) -> Result<(), SymmetricCipherError> { + let (eights, rest) = blocks.as_chunks_mut::<8>(); + for eight in eights.iter_mut() { + self.decrypt_eight(eight); + } + let (pairs, tail) = rest.as_chunks_mut::<2>(); + for pair in pairs.iter_mut() { + self.decrypt_pair(pair); + } + for block in tail.iter_mut() { + self.decrypt_one(block); + } + Ok(()) + } +} diff --git a/crypto/modes/src/cfb.rs b/crypto/modes/src/cfb.rs new file mode 100644 index 00000000..76178b1d --- /dev/null +++ b/crypto/modes/src/cfb.rs @@ -0,0 +1,417 @@ +//! The Cipher Feedback mode of operation (NIST SP 800-38A Sec 6.3), full-block segment, as a stream +//! cipher. +//! +//! # The specification +//! +//! Sec 6.3 defines CFB against a segment size `s` with `1 <= s <= b`, where `b` is the block size. +//! Quoting the equations verbatim: +//! +//! ```text +//! CFB Encryption: I1 = IV; +//! Ij = LSB_{b-s}(I_{j-1}) | C#_{j-1} for j = 2 ... n; +//! Oj = CIPH_K(Ij) for j = 1, 2 ... n; +//! C#_j = P#_j XOR MSB_s(Oj) for j = 1, 2 ... n. +//! +//! CFB Decryption: I1 = IV; +//! Ij = LSB_{b-s}(I_{j-1}) | C#_{j-1} for j = 2 ... n; +//! Oj = CIPH_K(Ij) for j = 1, 2 ... n; +//! P#_j = C#_j XOR MSB_s(Oj) for j = 1, 2 ... n. +//! ``` +//! +//! # This type is the `s = b` specialisation +//! +//! [`Cfb`] implements **only** `s = b`, the variant Sec 6.3 says is "sometimes incorporated into +//! the name of the mode", i.e. CFB128 for a 128-bit block. Substituting `s = b` collapses the +//! equations exactly: +//! +//! * `LSB_{b-s}(I_{j-1})` becomes `LSB_0(I_{j-1})`, the empty bit string, so the concatenation +//! leaves `Ij = C_{j-1}`. Sec 6.3's alternative description agrees: the previous input block +//! "circularly shift[s] s positions to the left, and then the ciphertext segment replaces the s +//! least significant bits of the result" -- shifting a whole block by its own width and replacing +//! every bit of it is just assignment. +//! * `MSB_s(Oj)` becomes `MSB_b(Oj)`, which is `Oj`. No part of the output block is discarded, so +//! there are no wasted cipher calls: one forward cipher per block, the same as CBC. +//! +//! leaving +//! +//! ```text +//! I1 = IV; Ij = C_{j-1} (j >= 2); Oj = CIPH_K(Ij); Cj = Pj XOR Oj / Pj = Cj XOR Oj +//! ``` +//! +//! The other segment sizes are **different, non-interoperable modes**, not variants of this one: +//! with `s < b` the shift register keeps `b - s` bits of the previous input block, which `s = b` +//! never does, so the ciphertexts diverge immediately. `s = 8` is [`Cfb8`](crate::Cfb8), in its own +//! type for exactly that reason; `s = 1` is not provided. SP 800-38A Appendix F.3 gives vectors for +//! all three. +//! +//! # A stream cipher, not a block cipher +//! +//! CFB is a keystream mode: the cipher never touches the data, only `Ij`, and the data is XORed +//! with the output block byte for byte. So the data need not arrive in whole blocks, and [`Cfb`] +//! implements [`StreamCipherEncryptor`] / [`StreamCipherDecryptor`] -- any length, in place, +//! chunked however the caller likes -- rather than the block-aligned `BlockCipherEncryptor` / +//! `BlockCipherDecryptor` that `Cbc` implements. The chunking is invisible in the output because +//! the state carries the unused part of `Oj` from one call to the next; see +//! [One buffer, three roles](#one-buffer-three-roles). +//! +//! ## The final partial segment +//! +//! Sec 5.2 requires "the total number of bits in the plaintext" to be "a multiple of a parameter, +//! denoted s", so a message whose length is not a multiple of the block does not have an +//! `s = b` segmentation at all, and Appendix A puts padding it "outside the scope of this +//! recommendation". This implementation instead accepts any length and treats the last `r < b` +//! bytes as a short final segment: +//! +//! ```text +//! C#_n = P#_n XOR MSB_{8r}(On) +//! ``` +//! +//! That is, it takes the `s = 8r` step of the Sec 6.3 equations for the last segment only and +//! discards the rest of `On`, exactly as Sec 6.3 discards `b - s` bits of every output block when +//! `s < b`. Since no input block is formed after the last segment, the `LSB_{b-s} | C#` feedback +//! rule, which is where `s < b` and `s = b` differ, is never exercised by the short segment, so +//! the result is well defined and unambiguous. It is also the behaviour of the streaming CFB128 +//! implementations in common use (OpenSSL's `EVP_aes_*_cfb128`, for one), so ciphertexts +//! interoperate at every length. A whole number of blocks is still the only length Sec 5.2 +//! defines, and the only one the Appendix F.3 and ACVP vectors cover. +//! +//! # One buffer, three roles +//! +//! The whole state beyond the permutation is one block, `buf`, and a byte count, `used`. Within +//! segment `j`, `buf[..used]` holds the ciphertext bytes produced (or consumed) so far and +//! `buf[used..]` holds the bytes of `Oj` not yet used. Both are needed and they fit in one block +//! because each ciphertext byte is written over the keystream byte that produced it: `Cj[i] = +//! Pj[i] XOR Oj[i]`, and `Oj[i]` is never needed again, while `Cj[i]` is exactly what the next +//! input block wants in position `i` (`I_{j+1} = Cj`). When `used == BLOCK_LEN` the buffer *is* +//! `I_{j+1}`, and the next byte encrypts it in place into `O_{j+1}`. So the same 16 bytes are the +//! input block, then the output block, then the next input block, and no copy is ever made. +//! +//! Between calls the buffer therefore holds `Ij` or `Cj` -- both public -- and, mid-segment, the +//! unused tail of `Oj`. Those keystream bytes have not been XORed with anything, so they reveal +//! nothing about the message, and they are `CIPH_K` of a public block, which a secure permutation +//! makes worthless without the key. They are not key material and the buffer is not wrapped in a +//! `Secret`; the key schedule itself lives in the permutation, which is responsible for zeroizing +//! it. +//! +//! # Decryption uses the *forward* cipher function +//! +//! This is the thing about CFB that surprises a reader used to CBC: both directions apply +//! `CIPH_K`. Sec 6.3 is explicit -- "In CFB decryption, the IV is the first input block, and each +//! successive input block is formed as in CFB encryption [...] The *forward cipher* function is +//! applied to each input block to produce the output blocks." +//! +//! So [`Cfb`](Cfb) never calls [`ElectronicCodeBook::decrypt_block`], +//! [`ElectronicCodeBook::decrypt_blocks2`] or [`ElectronicCodeBook::decrypt_blocks8`]. A +//! permutation could implement only the forward direction and still work here; `cfb_tests.rs` pins +//! that with a toy whose inverse panics. The mode XORs a keystream in both directions, and the two +//! directions differ only in which of the two values -- the byte that came in, or the byte that +//! went out -- is the ciphertext to be fed back. +//! +//! # Parallel decryption +//! +//! Sec 6.3: "In CFB encryption, like CBC encryption, the input block to each forward cipher +//! function (except the first) depends on the result of the previous forward cipher function; +//! therefore, multiple forward cipher operations cannot be performed in parallel. In CFB +//! decryption, the required forward cipher operations can be performed in parallel if the input +//! blocks are first constructed (in series) from the IV and the ciphertext." +//! +//! Constructing them "in series" is trivial here: with `s = b` the input blocks *are* the IV +//! followed by the ciphertext blocks, already in hand. Decryption therefore walks the +//! block-aligned part of the data in eights through [`ElectronicCodeBook::encrypt_blocks8`] and +//! pairs through [`ElectronicCodeBook::encrypt_blocks2`], which a bit-sliced engine computes for +//! barely more than the cost of one block. Encryption cannot, and does not. Only the bytes that +//! complete an open segment, and the bytes that open the final short one, go singly. + +use crate::iv::random_iv; +use crate::{Decrypting, Encrypting}; +use bouncycastle_core::errors::SymmetricCipherError; +use bouncycastle_core::key_material::KeyMaterial; +use bouncycastle_core::traits::{ + Algorithm, ElectronicCodeBook, RNG, SecurityStrength, StreamCipherDecryptor, + StreamCipherEncryptor, +}; +use bouncycastle_rng::HashDRBG_SHA512; +use core::marker::PhantomData; + +/// CFB mode over any [`ElectronicCodeBook`], as a stream cipher, with the direction encoded in the +/// type. +/// +/// The segment size is the full block (`s = b`, i.e. CFB128 for AES); see the module docs for why +/// the other segment sizes are out of scope, and for how a message that is not a whole number of +/// blocks is handled. +/// +/// `Dir` is [`Encrypting`] or [`Decrypting`]. [`StreamCipherEncryptor`] is implemented only for the +/// former and [`StreamCipherDecryptor`] only for the latter, so a `Cfb<_, Encrypting, _, _>` has no +/// decryption methods at all -- using one in the wrong direction is a compile error rather than a +/// runtime check. +/// +/// The initialization data is one block, so `INIT_DATA_LEN == BLOCK_LEN`. +/// +/// # State +/// +/// The permutation (which owns the key schedule, and is responsible for keeping it in a +/// zeroize-on-drop wrapper), one block, and a byte count. The block is `Ij`, `Oj` and `I_{j+1}` in +/// turn -- see the module docs, "One buffer, three roles" -- which is what lets a call end at any +/// byte and the next one pick up where it left off. That is one `usize` more than `Cbc` carries; +/// the module docs explain why the unused keystream it may hold between calls is not wrapped in a +/// `Secret`. +pub struct Cfb +where + P: ElectronicCodeBook, +{ + perm: P, + /// `buf[..used]` is the ciphertext of the current segment so far, i.e. the head of `I_{j+1}`; + /// `buf[used..]` is the unused tail of `Oj`. When `used == BLOCK_LEN` the whole buffer is the + /// next input block (initially `I1 = IV`) and no keystream is pending. + buf: [u8; BLOCK_LEN], + /// Bytes of the current segment already processed, `0..=BLOCK_LEN`. + used: usize, + _dir: PhantomData, +} + +impl Cfb +where + P: ElectronicCodeBook, +{ + /// `I1 = IV`, with no segment open: the first byte in either direction will compute `O1`. + #[inline] + fn start(perm: P, iv: [u8; BLOCK_LEN]) -> Self { + Self { perm, buf: iv, used: BLOCK_LEN, _dir: PhantomData } + } + + /// Makes the next keystream byte available: if the current segment is complete, `buf` is the + /// next input block, so `Oj = CIPH_K(Ij)` is computed in place and a new segment opened. + /// + /// The forward cipher function, in both directions -- see the module docs. + #[inline] + fn refill_if_used_up(&mut self) { + if self.used == BLOCK_LEN { + self.perm.encrypt_block(&mut self.buf); + self.used = 0; + } + } + + /// Encrypts fewer than a block's worth of bytes, byte by byte, within the open segment or + /// opening a new one: `Cj[i] = Pj[i] XOR Oj[i]`, then `Cj[i]` takes the place of `Oj[i]` in the + /// buffer as the `i`th byte of `I_{j+1}`. + /// + /// Correct for any length, but only called with what the block path cannot take: the bytes that + /// complete a segment left open by an earlier call, and the final short segment. + #[inline] + fn encrypt_bytes(&mut self, data: &mut [u8]) { + for byte in data.iter_mut() { + self.refill_if_used_up(); + *byte ^= self.buf[self.used]; + self.buf[self.used] = *byte; + self.used += 1; + } + } + + /// The decrypting counterpart of [`Self::encrypt_bytes`]: `Pj[i] = Cj[i] XOR Oj[i]`, and it is + /// the *ciphertext* byte `Cj[i]` -- the one that came in, not the one going out -- that is fed + /// back into the buffer. + #[inline] + fn decrypt_bytes(&mut self, data: &mut [u8]) { + for byte in data.iter_mut() { + self.refill_if_used_up(); + // `I_{j+1} = C#_j` of the spec equations: the ciphertext segment is what is fed back. + // Feeding back the plaintext instead would still decrypt the first block correctly and + // nothing after it, which is why `cfb_tests.rs` checks exactly that. + let c = *byte; + *byte ^= self.buf[self.used]; + self.buf[self.used] = c; + self.used += 1; + } + } + + /// Encrypts one whole block at a segment boundary (`used == BLOCK_LEN`, so `buf` is `Ij`): + /// `Oj = CIPH_K(Ij)` in place, `Cj = Pj XOR Oj`, then `Cj` becomes `I_{j+1}` -- which leaves + /// `used == BLOCK_LEN` again, so consecutive calls need no bookkeeping. + #[inline] + fn encrypt_one(&mut self, block: &mut [u8; BLOCK_LEN]) { + debug_assert_eq!(self.used, BLOCK_LEN, "the block path needs a segment boundary"); + self.perm.encrypt_block(&mut self.buf); + for (b, o) in block.iter_mut().zip(self.buf.iter()) { + *b ^= *o; + } + // I_{j+1} = Cj. Serial: this is the input to the next cipher call. + self.buf = *block; + } + + /// Decrypts one whole block at a segment boundary. `Cj` is overwritten by `Pj`, so it is copied + /// first to become `I_{j+1}`. + #[inline] + fn decrypt_one(&mut self, block: &mut [u8; BLOCK_LEN]) { + debug_assert_eq!(self.used, BLOCK_LEN, "the block path needs a segment boundary"); + let cj = *block; + self.perm.encrypt_block(&mut self.buf); + for (b, o) in block.iter_mut().zip(self.buf.iter()) { + *b ^= *o; + } + self.buf = cj; + } + + /// Decrypts two consecutive blocks with one [`ElectronicCodeBook::encrypt_blocks2`] call. + /// + /// Writing the pair as `Cj, Cj+1` with `Ij` the incoming input block, the `s = b` equations + /// give + /// + /// ```text + /// Ij = buf Oj = CIPH_K(Ij) Pj = Cj XOR Oj + /// Ij+1 = Cj Oj+1 = CIPH_K(Ij+1) Pj+1 = Cj+1 XOR Oj+1 + /// ``` + /// + /// Both input blocks are known before either cipher call -- `Ij` is already held and `Ij+1` is + /// just `Cj`, which the caller supplied -- so the two forward ciphers are independent and + /// computing them together changes nothing. This is precisely the parallelism Sec 6.3 describes, + /// with the input blocks "first constructed (in series) from the IV and the ciphertext". + /// + /// In place: the two input blocks are the keystream buffer, so the ciphertext is never + /// overwritten before it has been read, and only `Cj+1` needs copying for the next input block. + #[inline] + fn decrypt_pair(&mut self, blocks: &mut [[u8; BLOCK_LEN]; 2]) { + debug_assert_eq!(self.used, BLOCK_LEN, "the block path needs a segment boundary"); + // The two input blocks, constructed in series: Ij (already held) and Ij+1 (= Cj). + let mut o = [self.buf, blocks[0]]; + self.perm.encrypt_blocks2(&mut o); + + // I_{j+2} = Cj+1, read before the XOR below turns it into Pj+1. + self.buf = blocks[1]; + + for (block, o) in blocks.iter_mut().zip(o.iter()) { + for (b, o) in block.iter_mut().zip(o.iter()) { + *b ^= *o; + } + } + } + + /// Decrypts eight consecutive blocks with one [`ElectronicCodeBook::encrypt_blocks8`] call. + /// + /// The same construction as [`Self::decrypt_pair`] widened to eight: the input blocks are the + /// incoming input block followed by the first seven ciphertext blocks, all known before any + /// cipher call, so the eight forward ciphers are independent (Sec 6.3's parallel decryption). + /// `I_{j+8} = Cj+7` is read before the XOR turns it into `Pj+7`. + #[inline] + fn decrypt_eight(&mut self, blocks: &mut [[u8; BLOCK_LEN]; 8]) { + debug_assert_eq!(self.used, BLOCK_LEN, "the block path needs a segment boundary"); + let mut o = + [self.buf, blocks[0], blocks[1], blocks[2], blocks[3], blocks[4], blocks[5], blocks[6]]; + self.perm.encrypt_blocks8(&mut o); + self.buf = blocks[7]; + for (block, o) in blocks.iter_mut().zip(o.iter()) { + for (b, o) in block.iter_mut().zip(o.iter()) { + *b ^= *o; + } + } + } + + /// Splits `data` into the bytes that complete the currently open segment (none, if a segment + /// boundary has been reached), the whole blocks that follow, and the short tail that opens the + /// final segment. After the head has been processed `used == BLOCK_LEN`, which is what the + /// block path requires; the tail is shorter than a block, so it opens at most one segment. + #[inline] + fn split<'a>( + &self, + data: &'a mut [u8], + ) -> (&'a mut [u8], &'a mut [[u8; BLOCK_LEN]], &'a mut [u8]) { + let head_len = core::cmp::min(BLOCK_LEN - self.used, data.len()); + let (head, rest) = data.split_at_mut(head_len); + let (blocks, tail) = rest.as_chunks_mut::(); + (head, blocks, tail) + } +} + +impl Algorithm + for Cfb +where + P: ElectronicCodeBook, +{ + /// The underlying permutation's name. The mode is not appended: `&'static str`s cannot be + /// concatenated in a `const`, and the mode is already in the type. + const ALG_NAME: &'static str = P::ALG_NAME; + /// A mode does not change the strength of the underlying cipher. + const MAX_SECURITY_STRENGTH: SecurityStrength = P::MAX_SECURITY_STRENGTH; +} + +impl StreamCipherEncryptor + for Cfb +where + P: ElectronicCodeBook, +{ + /// Begins an encryption flow, generating the IV from the library's default OS-backed DRBG. + fn do_encrypt_init( + key: &KeyMaterial, + ) -> Result<(Self, [u8; BLOCK_LEN]), SymmetricCipherError> { + let mut rng = HashDRBG_SHA512::new_from_os(); + Self::do_encrypt_init_rng(key, &mut rng) + } + + /// As [`StreamCipherEncryptor::do_encrypt_init`], but takes the IV from the provided RNG. + fn do_encrypt_init_rng( + key: &KeyMaterial, + rng: &mut dyn RNG, + ) -> Result<(Self, [u8; BLOCK_LEN]), SymmetricCipherError> { + let perm = P::new(key)?; + // `I1 = IV`. + let iv = random_iv::(rng)?; + Ok((Self::start(perm, iv), iv)) + } + + /// Encrypts `data`, of any length, in place. + /// + /// Strictly serial: `Oj+1 = CIPH_K(Cj)` and `Cj` is the *output* of the previous cipher call, so + /// there is no pair path here; the block-aligned middle goes one cipher call per block, and + /// only the bytes that complete an open segment or open the final short one go singly. See the + /// module docs. Never fails: CFB has no per-IV data limit. + fn do_encrypt(&mut self, data: &mut [u8]) -> Result<(), SymmetricCipherError> { + let (head, blocks, tail) = self.split(data); + self.encrypt_bytes(head); + for block in blocks.iter_mut() { + self.encrypt_one(block); + } + self.encrypt_bytes(tail); + Ok(()) + } +} + +impl StreamCipherDecryptor + for Cfb +where + P: ElectronicCodeBook, +{ + /// Begins a decryption flow from the IV returned by + /// [`StreamCipherEncryptor::do_encrypt_init`]. + fn do_decrypt_init( + key: &KeyMaterial, + init_data: &[u8; BLOCK_LEN], + ) -> Result { + let perm = P::new(key)?; + // `I1 = IV`, exactly as on the encrypt side. + Ok(Self::start(perm, *init_data)) + } + + /// Decrypts `data`, of any length, in place. + /// + /// Walks the block-aligned middle in eights through the permutation's *forward* eight-block + /// path, then in pairs through its forward pair path, then the remaining block singly. + /// `as_chunks_mut` splits into exactly those shapes with no runtime length check and no + /// indexing arithmetic. The bytes that complete an open segment, and the final short segment, + /// go singly. Never fails: CFB has no per-IV data limit. + fn do_decrypt(&mut self, data: &mut [u8]) -> Result<(), SymmetricCipherError> { + let (head, blocks, tail) = self.split(data); + self.decrypt_bytes(head); + let (eights, rest) = blocks.as_chunks_mut::<8>(); + for eight in eights.iter_mut() { + self.decrypt_eight(eight); + } + let (pairs, single) = rest.as_chunks_mut::<2>(); + for pair in pairs.iter_mut() { + self.decrypt_pair(pair); + } + for block in single.iter_mut() { + self.decrypt_one(block); + } + self.decrypt_bytes(tail); + Ok(()) + } +} diff --git a/crypto/modes/src/cfb8.rs b/crypto/modes/src/cfb8.rs new file mode 100644 index 00000000..717e6bf9 --- /dev/null +++ b/crypto/modes/src/cfb8.rs @@ -0,0 +1,275 @@ +//! The Cipher Feedback mode of operation (NIST SP 800-38A Sec 6.3), 8-bit segment. +//! +//! # The specification +//! +//! Sec 6.3 defines CFB against a segment size `s` with `1 <= s <= b`, where `b` is the block size. +//! Quoting the equations verbatim: +//! +//! ```text +//! CFB Encryption: I1 = IV; +//! Ij = LSB_{b-s}(I_{j-1}) | C#_{j-1} for j = 2 ... n; +//! Oj = CIPH_K(Ij) for j = 1, 2 ... n; +//! C#_j = P#_j XOR MSB_s(Oj) for j = 1, 2 ... n. +//! +//! CFB Decryption: I1 = IV; +//! Ij = LSB_{b-s}(I_{j-1}) | C#_{j-1} for j = 2 ... n; +//! Oj = CIPH_K(Ij) for j = 1, 2 ... n; +//! P#_j = C#_j XOR MSB_s(Oj) for j = 1, 2 ... n. +//! ``` +//! +//! # This type is the `s = 8` specialisation +//! +//! [`Cfb8`] implements **only** `s = 8`, "the 8-bit CFB mode" of Sec 6.3, universally called CFB8. +//! A segment is one byte, so with `s = 8` the equations become, for each byte of the message: +//! +//! ```text +//! I1 = IV; Ij = LSB_{b-8}(I_{j-1}) | C_{j-1}; Oj = CIPH_K(Ij); Cj = Pj XOR MSB_8(Oj) +//! ``` +//! +//! * `LSB_{b-8}(I_{j-1}) | C_{j-1}` keeps all but the leading byte of the previous input block and +//! appends the ciphertext byte. Sec 6.3's alternative description is the shift register this +//! implements literally: "the bits of the first input block circularly shift s positions to the +//! left, and then the ciphertext segment replaces the s least significant bits of the result". +//! [`Cfb8::shift_in`] is `rotate_left(1)` followed by writing the ciphertext byte into the last +//! position -- those two sentences, in that order. +//! * `MSB_8(Oj)` is the **first byte** of the output block. The other `b - 8` bytes are discarded, +//! as Sec 6.3 says of the general case: "The remaining b-s bits of the first output block are +//! discarded." +//! +//! # One cipher call per byte +//! +//! Discarding `b - 8` of every `b` output bytes is what CFB8 costs: a full forward cipher for each +//! byte of the message, so on a 16-byte block it does **16 times** the cipher work of +//! [`Cfb`](crate::Cfb) for the same data. That is inherent to the mode, not to this implementation. +//! Use it when a byte-granular, self-synchronising stream is genuinely required or an existing +//! format demands it; otherwise prefer `Cfb`, which discards nothing. +//! +//! CFB8 is a **different, non-interoperable mode** from CFB128, not a variant of it: the two differ +//! from the very first byte of ciphertext, because CFB8 forms its second input block by shifting +//! whereas `s = b` replaces the block outright. `cfb8_tests.rs` pins that they disagree. +//! +//! # A stream cipher +//! +//! Every byte is a whole segment, so a CFB8 message has no alignment requirement at all: Sec 5.2 +//! asks only that "the total number of bits in the plaintext" be "a multiple of a parameter, +//! denoted s", and with `s = 8` every byte string qualifies. [`Cfb8`] therefore implements +//! [`StreamCipherEncryptor`] / [`StreamCipherDecryptor`] and needs no padding layer, no +//! finalization step and -- unlike [`Cfb`](crate::Cfb), whose segment is a whole block -- no +//! partial-segment state: a call can end after any byte because every byte ends a segment. +//! +//! # Decryption uses the *forward* cipher function +//! +//! As in CFB128, both directions apply `CIPH_K`. Sec 6.3: "In CFB decryption, the IV is the first +//! input block, and each successive input block is formed as in CFB encryption [...] The *forward +//! cipher* function is applied to each input block to produce the output blocks." So +//! [`Cfb8`](Cfb8) never calls [`ElectronicCodeBook::decrypt_block`] or its batch +//! forms; `cfb8_tests.rs` pins that with a toy whose inverse panics. +//! +//! # Parallel decryption +//! +//! Sec 6.3: "In CFB encryption, like CBC encryption, the input block to each forward cipher +//! function (except the first) depends on the result of the previous forward cipher function; +//! therefore, multiple forward cipher operations cannot be performed in parallel. In CFB +//! decryption, the required forward cipher operations can be performed in parallel if the input +//! blocks are first constructed (in series) from the IV and the ciphertext." +//! +//! Decryption knows every ciphertext byte before it starts, so it can build the shift register's +//! successive states in series -- byte shuffling, no cipher calls -- and then run the forward +//! ciphers together. This implementation does exactly that, in eights through +//! [`ElectronicCodeBook::encrypt_blocks8`] and then pairs through +//! [`ElectronicCodeBook::encrypt_blocks2`], which is where a bit-sliced engine earns back a large +//! part of what the mode costs. Encryption cannot: `Ij` needs `C_{j-1}`, which is the output of the +//! previous cipher call. + +use crate::iv::random_iv; +use crate::{Decrypting, Encrypting}; +use bouncycastle_core::errors::SymmetricCipherError; +use bouncycastle_core::key_material::KeyMaterial; +use bouncycastle_core::traits::{ + Algorithm, ElectronicCodeBook, RNG, SecurityStrength, StreamCipherDecryptor, + StreamCipherEncryptor, +}; +use bouncycastle_rng::HashDRBG_SHA512; +use core::marker::PhantomData; + +/// CFB8 mode over any [`ElectronicCodeBook`], with the direction encoded in the type. +/// +/// The segment size is one byte (`s = 8`); see the module docs, and note that this is **not** +/// interoperable with [`Cfb`](crate::Cfb), which is `s = b`. +/// +/// `Dir` is [`Encrypting`] or [`Decrypting`]. [`StreamCipherEncryptor`] is implemented only for the +/// former and [`StreamCipherDecryptor`] only for the latter, so a `Cfb8<_, Encrypting, _, _>` has +/// no decryption methods at all -- using one in the wrong direction is a compile error rather than +/// a runtime check. +/// +/// The initialization data is one block, so `INIT_DATA_LEN == BLOCK_LEN`. +/// +/// # State +/// +/// Two fields, the same size as `Cbc`: the permutation (which owns the key schedule, and is +/// responsible for keeping it in a zeroize-on-drop wrapper) and one block holding the shift +/// register `Ij`. `Ij` is built from the IV and ciphertext bytes, both of which are public, so it +/// is deliberately not wrapped in a `Secret`. +/// +/// Note what is *not* stored: the output block `Oj`. It is recomputed from the register on each +/// byte and lives only in a local, so no keystream outlives the call that used it. No partial +/// segment is stored either, because a segment is one byte. +pub struct Cfb8 +where + P: ElectronicCodeBook, +{ + perm: P, + /// `Ij`: the IV, then the shift register. See the module docs. + chain: [u8; BLOCK_LEN], + _dir: PhantomData, +} + +impl Cfb8 +where + P: ElectronicCodeBook, +{ + /// `I_{j+1} = LSB_{b-8}(Ij) | Cj`: shift the register one byte left and put the ciphertext byte + /// in the least significant position. + /// + /// This is Sec 6.3's alternative description verbatim -- "the bits of the first input block + /// circularly shift s positions to the left, and then the ciphertext segment replaces the s + /// least significant bits of the result" -- so the rotate is the spec's rotate, and overwriting + /// the last byte is what discards the byte the rotate carried round. + #[inline] + fn shift_in(&mut self, ciphertext_byte: u8) { + self.chain.rotate_left(1); + // BLOCK_LEN is non-zero for any permutation: a zero-length block has no cipher. + self.chain[BLOCK_LEN - 1] = ciphertext_byte; + } + + /// `MSB_8(Oj)`, the one keystream byte this segment uses: `Oj = CIPH_K(Ij)`, first byte kept, + /// the other `b - 8` discarded as Sec 6.3 requires. + /// + /// The forward cipher function, in both directions -- see the module docs. + #[inline] + fn keystream_byte(&self) -> u8 { + let mut o = self.chain; + self.perm.encrypt_block(&mut o); + o[0] + } + + /// Decrypts `N` consecutive bytes with one batched forward-cipher call. + /// + /// The input blocks are built in series first -- each is the previous one shifted with the + /// previous *ciphertext* byte appended, which decryption already has -- so the `N` forward + /// ciphers are independent. This is precisely the parallelism Sec 6.3 describes, with the input + /// blocks "first constructed (in series) from the IV and the ciphertext". + /// + /// `batch` is the permutation's `N`-block method; the scratch array holds the input blocks on + /// the way in and the output blocks on the way out. + #[inline] + fn decrypt_batch( + &mut self, + bytes: &mut [u8; N], + batch: impl Fn(&P, &mut [[u8; BLOCK_LEN]; N]), + ) { + let mut blocks = [[0u8; BLOCK_LEN]; N]; + for (block, c) in blocks.iter_mut().zip(bytes.iter()) { + *block = self.chain; + // I_{j+1} = LSB(Ij) | C#_j: the ciphertext byte is what is fed back, and on this side + // it is the byte that came in, before the XOR below turns it into plaintext. + self.shift_in(*c); + } + batch(&self.perm, &mut blocks); + for (byte, o) in bytes.iter_mut().zip(blocks.iter()) { + *byte ^= o[0]; + } + } +} + +impl Algorithm + for Cfb8 +where + P: ElectronicCodeBook, +{ + /// The underlying permutation's name. The mode is not appended: `&'static str`s cannot be + /// concatenated in a `const`, and the mode is already in the type. + const ALG_NAME: &'static str = P::ALG_NAME; + /// A mode does not change the strength of the underlying cipher. + const MAX_SECURITY_STRENGTH: SecurityStrength = P::MAX_SECURITY_STRENGTH; +} + +impl StreamCipherEncryptor + for Cfb8 +where + P: ElectronicCodeBook, +{ + /// Begins an encryption flow, generating the IV from the library's default OS-backed DRBG. + fn do_encrypt_init( + key: &KeyMaterial, + ) -> Result<(Self, [u8; BLOCK_LEN]), SymmetricCipherError> { + let mut rng = HashDRBG_SHA512::new_from_os(); + Self::do_encrypt_init_rng(key, &mut rng) + } + + /// As [`StreamCipherEncryptor::do_encrypt_init`], but takes the IV from the provided RNG. + fn do_encrypt_init_rng( + key: &KeyMaterial, + rng: &mut dyn RNG, + ) -> Result<(Self, [u8; BLOCK_LEN]), SymmetricCipherError> { + let perm = P::new(key)?; + // `I1 = IV`. + let iv = random_iv::(rng)?; + Ok((Self { perm, chain: iv, _dir: PhantomData }, iv)) + } + + /// Encrypts `data`, of any length, in place: `Cj = Pj XOR MSB_8(CIPH_K(Ij))` for each byte, + /// then `Cj` shifts into the register. + /// + /// Strictly serial, one forward cipher per byte: `I_{j+1}` needs `Cj`, which is the result of + /// the XOR that the cipher call produced. See the module docs. Never fails: CFB has no per-IV + /// data limit. + fn do_encrypt(&mut self, data: &mut [u8]) -> Result<(), SymmetricCipherError> { + for byte in data.iter_mut() { + *byte ^= self.keystream_byte(); + self.shift_in(*byte); + } + Ok(()) + } +} + +impl StreamCipherDecryptor + for Cfb8 +where + P: ElectronicCodeBook, +{ + /// Begins a decryption flow from the IV returned by + /// [`StreamCipherEncryptor::do_encrypt_init`]. + fn do_decrypt_init( + key: &KeyMaterial, + init_data: &[u8; BLOCK_LEN], + ) -> Result { + let perm = P::new(key)?; + // `I1 = IV`, exactly as on the encrypt side. + Ok(Self { perm, chain: *init_data, _dir: PhantomData }) + } + + /// Decrypts `data`, of any length, in place: `Pj = Cj XOR MSB_8(CIPH_K(Ij))` for each byte, + /// with the *ciphertext* byte -- the one that came in, not the plaintext going out -- shifted + /// into the register. + /// + /// Walks the data in eights through the permutation's *forward* eight-block path, then in pairs + /// through its forward pair path, then the remaining bytes singly (Sec 6.3's parallel + /// decryption; see the module docs). Never fails: CFB has no per-IV data limit. + fn do_decrypt(&mut self, data: &mut [u8]) -> Result<(), SymmetricCipherError> { + let (eights, rest) = data.as_chunks_mut::<8>(); + for eight in eights.iter_mut() { + self.decrypt_batch(eight, P::encrypt_blocks8); + } + let (pairs, tail) = rest.as_chunks_mut::<2>(); + for pair in pairs.iter_mut() { + self.decrypt_batch(pair, P::encrypt_blocks2); + } + for byte in tail.iter_mut() { + let c = *byte; + *byte ^= self.keystream_byte(); + self.shift_in(c); + } + Ok(()) + } +} diff --git a/crypto/modes/src/ctr.rs b/crypto/modes/src/ctr.rs new file mode 100644 index 00000000..cb3564d8 --- /dev/null +++ b/crypto/modes/src/ctr.rs @@ -0,0 +1,459 @@ +//! The Counter mode of operation (NIST SP 800-38A Sec 6.5). +//! +//! # The specification +//! +//! Sec 6.5 defines CTR against a sequence of counter blocks `T1, T2, ... Tn`. Quoting the +//! equations verbatim: +//! +//! ```text +//! CTR Encryption: Oj = CIPH_K(Tj) for j = 1, 2 ... n; +//! Cj = Pj XOR Oj for j = 1, 2 ... n-1; +//! C*_n = P*_n XOR MSB_u(On). +//! +//! CTR Decryption: Oj = CIPH_K(Tj) for j = 1, 2 ... n; +//! Pj = Cj XOR Oj for j = 1, 2 ... n-1; +//! P*_n = C*_n XOR MSB_u(On). +//! ``` +//! +//! The cipher never touches the data: it is applied to the counter blocks alone, and the output +//! blocks are XORed with the plaintext. The last block may be partial, and Sec 6.5 says what to do +//! with it -- "the most significant u bits of the last output block are used for the exclusive-OR +//! operation; the remaining b-u bits of the last output block are discarded" -- so unlike CBC there +//! is no alignment requirement anywhere in the mode. [`Ctr`] therefore implements +//! [`StreamCipherEncryptor`] / [`StreamCipherDecryptor`]. +//! +//! **Encryption and decryption are the same operation.** Both compute `Oj = CIPH_K(Tj)` and XOR; +//! only the name of the input changes. The two directions are still separate types here, for the +//! same policy reason as in the other modes, and they share one implementation. +//! +//! # Where the counter comes from: the nonce is the init data +//! +//! Sec 6.5 requires that "each block in the sequence is different from every other block", and +//! that this holds "across all of the messages that are encrypted under the given key". Appendix +//! B.2 gives the construction this type uses, its second approach: +//! +//! > The leading b/2 bits (rounding up, if b is odd) of each counter block would be the message +//! > nonce, and the standard incrementing function would be applied to the remaining m bits to +//! > provide an index to the counter blocks for the message. Thus, if N is the message nonce for a +//! > given message, then the jth counter block is given by `Tj = N | [j]m`. +//! +//! So a counter block is a **nonce followed by a counter**, and this type splits the block by the +//! length of its init data: the init data is the nonce, and whatever is left of the block is the +//! counter. +//! +//! ```text +//! INIT_DATA_LEN bytes of nonce | CTR_LEN bytes of counter (CTR_LEN = BLOCK_LEN - INIT_DATA_LEN) +//! ``` +//! +//! For AES that means a 12-byte nonce gives a 4-byte counter, a 13-byte nonce a 3-byte counter, and +//! so on. `CTR_LEN` is capped at **4 bytes** and must be at least 1, both checked at compile time, +//! so for a 16-byte block `INIT_DATA_LEN` is 12, 13, 14 or 15. A longer counter is not useful here: +//! it would raise a per-message limit that is already far beyond any single message, at the cost of +//! nonce bits, which are the scarcer resource. +//! +//! ## The counter starts at zero, not at one +//! +//! B.2's formula is `Tj = N | [j]m` **for j = 1...n**, so read literally its first counter block is +//! `N | 1`. This type instead starts at 0, i.e. `Tj = N | [j - 1]m`, and the choice is deliberate. +//! +//! It is permitted. The normative requirement is Sec 6.5's -- "each block in the sequence is +//! different from every other block" -- which both indexings satisfy; B.2 is presented as one of +//! "Two examples of approaches", and Appendix B closes by saying "This recommendation allows other +//! methods and approaches for achieving the uniqueness property". +//! +//! It is also what the test vectors assume. NIST's ACVP `ACVP-AES-CTR` set gives each case a full +//! initial counter block, and of its 2138 functional cases **1853 end in four zero bytes** and +//! **none end in `00000001`**. Those 1853 are exactly a 12-byte nonce with the counter at zero, so +//! starting at zero makes them directly usable as known-answer tests -- see `acvp_ctr_tests.rs` -- +//! and starting at one would leave this mode with no official vector coverage at all. The same +//! choice is what makes a message here identical to one from an implementation handed +//! `nonce || 00000000` as a whole-block IV, which is how CTR is usually driven in practice. +//! +//! One consequence: the counter takes `2^m` values rather than B.2's `n < 2^m`, so a message may be +//! a full `2^m` blocks. +//! +//! # The counter is finite, and running out is an error +//! +//! A `CTR_LEN`-byte counter has `2^(8 * CTR_LEN)` distinct values, so a message can be at most +//! that many blocks: 2^32 blocks (64 GiB) for a 4-byte counter, down to 256 blocks (4 KiB) for a +//! 1-byte one. Appendix B.1 is explicit that this is the bound -- counter blocks "satisfy the +//! uniqueness requirement within the given message provided that `n <= 2^m`" -- and past it the +//! counter would repeat, which for a keystream mode means reusing keystream: the two-time-pad +//! failure, within a single message. +//! +//! So [`Ctr`] **refuses** rather than wraps. A call that would need more keystream than the counter +//! can still supply returns [`SymmetricCipherError::StateError`] and consumes nothing -- the check +//! is made up front, against the whole call, so a message is never half-encrypted before the mode +//! notices. This is the failure the `Result` on the data methods exists for; the other modes in +//! this crate never return `Err` from them. +//! +//! # Everything is parallel +//! +//! Sec 6.5: "In both CTR encryption and CTR decryption, the forward cipher functions can be +//! performed in parallel". Counter blocks depend on nothing but the nonce and the index, so unlike +//! CBC and CFB there is no serial direction at all: **both** directions walk the block-aligned part +//! of the data in eights through [`ElectronicCodeBook::encrypt_blocks8`], then in pairs through +//! [`ElectronicCodeBook::encrypt_blocks2`]. Only the bytes that finish a partially-used keystream +//! block, and the short tail at the end, go one block at a time. +//! +//! Like the rest of CFB and CTR, only the **forward** cipher function is ever used, in both +//! directions, so a permutation that implements only `encrypt_block` works here. +//! +//! # Keystream that outlives a call +//! +//! A call can end part-way through a keystream block, and the remainder of that block is kept for +//! the next call so the caller's chunking is invisible in the output. Those bytes are unused +//! keystream: XORed with nothing, they reveal nothing about the message, but they *are* live +//! keystream for the next bytes of it, so the buffer is held in a `Secret` and zeroized on drop. +//! That is the difference from `Cfb`, whose retained bytes are `CIPH_K` of a public block and are +//! deliberately not wrapped. + +use crate::iv::random_iv; +use crate::{Decrypting, Encrypting}; +use bouncycastle_core::errors::SymmetricCipherError; +use bouncycastle_core::key_material::KeyMaterial; +use bouncycastle_core::traits::{ + Algorithm, ElectronicCodeBook, RNG, SecurityStrength, StreamCipherDecryptor, + StreamCipherEncryptor, +}; +use bouncycastle_rng::HashDRBG_SHA512; +use bouncycastle_utils::secret::Secret; +use core::marker::PhantomData; + +/// CTR mode over any [`ElectronicCodeBook`], with the direction encoded in the type. +/// +/// The counter block is the init data (the nonce) followed by a counter filling the rest of the +/// block, so `INIT_DATA_LEN` chooses the counter length; see the module docs. `Dir` is +/// [`Encrypting`] or [`Decrypting`]. +/// +/// # The counter width is checked at compile time +/// +/// The counter must be at least one byte and at most four, so on a 16-byte block the nonce is 12, +/// 13, 14 or 15 bytes. Both bounds are inline `const` assertions in the constructors, so a nonce +/// length outside that range is a **compile** error at the call site rather than a runtime `Err`. +/// +/// A nonce as long as the block would leave no counter at all, and could not count: +/// +/// ```compile_fail +/// use bouncycastle_aes_lowmemory::Aes128; +/// use bouncycastle_core::key_material::{KeyMaterial, KeyType}; +/// use bouncycastle_core::traits::StreamCipherEncryptor; +/// use bouncycastle_modes::{Ctr, Encrypting}; +/// +/// let key = KeyMaterial::<16>::from_bytes_as_type(&[0x42; 16], KeyType::SymmetricCipherKey).unwrap(); +/// // A 16-byte nonce on a 16-byte block leaves a zero-byte counter. +/// let _ = Ctr::::do_encrypt_init(&key); +/// ``` +/// +/// ...and a nonce shorter than `BLOCK_LEN - 4` would ask for a counter wider than this type +/// supports: +/// +/// ```compile_fail +/// use bouncycastle_aes_lowmemory::Aes128; +/// use bouncycastle_core::key_material::{KeyMaterial, KeyType}; +/// use bouncycastle_core::traits::StreamCipherEncryptor; +/// use bouncycastle_modes::{Ctr, Encrypting}; +/// +/// let key = KeyMaterial::<16>::from_bytes_as_type(&[0x42; 16], KeyType::SymmetricCipherKey).unwrap(); +/// // An 11-byte nonce would give a 5-byte counter, past the 4-byte cap. +/// let _ = Ctr::::do_encrypt_init(&key); +/// ``` +/// +/// The permitted lengths all work: +/// +/// ``` +/// use bouncycastle_aes_lowmemory::Aes128; +/// use bouncycastle_core::key_material::{KeyMaterial, KeyType}; +/// use bouncycastle_core::traits::StreamCipherEncryptor; +/// use bouncycastle_modes::{Ctr, Encrypting}; +/// +/// let key = KeyMaterial::<16>::from_bytes_as_type(&[0x42; 16], KeyType::SymmetricCipherKey).unwrap(); +/// let _ = Ctr::::do_encrypt_init(&key).unwrap(); // 4-byte counter +/// let _ = Ctr::::do_encrypt_init(&key).unwrap(); // 1-byte counter +/// ``` +/// +/// # State +/// +/// The permutation, the nonce, the next counter value, the current keystream block and how much of +/// it has been used. The nonce and the counter are both public, so they are plain fields; the +/// keystream block is live key material for the bytes not yet consumed, so it is a [`Secret`] and +/// is zeroized on drop. +pub struct Ctr +where + P: ElectronicCodeBook, +{ + perm: P, + /// `N`: the message nonce, the leading bytes of every counter block. + nonce: [u8; INIT_DATA_LEN], + /// The counter of the *next* block to use, as an integer: `Tj = N | [next_counter]m`. + /// + /// Held as a `u64` rather than as the counter bytes so that exhaustion is representable. The + /// counter field itself is at most 4 bytes, so it wraps to zero at `2^m` and a mode that read + /// its state back out of those bytes could not tell "just started" from "completely used up". + /// This counts to `BLOCK_LIMIT` and stops there. + next_counter: u64, + /// `Oj` for the block currently being consumed. Meaningful only while `used < BLOCK_LEN`. + keystream: Secret<[u8; BLOCK_LEN]>, + /// Bytes of `keystream` already consumed, `0..=BLOCK_LEN`. `BLOCK_LEN` means none is pending + /// and the next byte needs a fresh cipher call. + used: usize, + _dir: PhantomData, +} + +impl + Ctr +where + P: ElectronicCodeBook, +{ + /// Bytes of counter at the end of each block: whatever the nonce leaves. + const CTR_LEN: usize = BLOCK_LEN - INIT_DATA_LEN; + + /// The number of counter blocks available, `2^(8 * CTR_LEN)`. + /// + /// `CTR_LEN <= 4` is asserted at construction, so this is at most `2^32` and cannot overflow + /// the `u64`. + const BLOCK_LIMIT: u64 = 1u64 << (8 * Self::CTR_LEN as u64); + + /// The compile-time shape check, run from both constructors. + /// + /// A zero-length counter could not count, and this type caps the counter at 4 bytes; see the + /// module docs. Both are properties of the const parameters, so both are compile errors at the + /// call site rather than a runtime `Err`. + #[inline] + fn check_shape() { + const { + assert!( + INIT_DATA_LEN < BLOCK_LEN, + "CTR needs at least one byte of counter: the nonce must be shorter than the block" + ); + assert!( + BLOCK_LEN - INIT_DATA_LEN <= 4, + "CTR counter is capped at 4 bytes: the nonce must be at least BLOCK_LEN - 4 bytes" + ); + }; + } + + /// `T1 = N | [0]m`: the nonce, then a zero counter. No keystream is pending. + #[inline] + fn start(perm: P, nonce: [u8; INIT_DATA_LEN]) -> Self { + Self::check_shape(); + Self { + perm, + nonce, + next_counter: 0, + keystream: Secret::new(), + used: BLOCK_LEN, + _dir: PhantomData, + } + } + + /// `Tj = N | [j]m`: the nonce followed by the counter, big-endian, in the trailing `CTR_LEN` + /// bytes. + /// + /// Taking the low `CTR_LEN` bytes of the big-endian `u64` is the `mod 2^m` of Appendix B.1's + /// standard incrementing function, though the truncation never actually discards anything: + /// [`Self::check_capacity`] refuses the call before `next_counter` could reach `2^m`. + #[inline] + fn counter_block(&self) -> [u8; BLOCK_LEN] { + let mut t = [0u8; BLOCK_LEN]; + t[..INIT_DATA_LEN].copy_from_slice(&self.nonce); + let be = self.next_counter.to_be_bytes(); + t[INIT_DATA_LEN..].copy_from_slice(&be[be.len() - Self::CTR_LEN..]); + t + } + + /// How many more bytes of keystream this instance can still produce. + /// + /// The pending tail of the current block, plus a whole block for every counter value left. + #[inline] + fn remaining_capacity(&self) -> u64 { + let pending = (BLOCK_LEN - self.used) as u64; + let blocks_left = Self::BLOCK_LIMIT - self.next_counter; + pending + blocks_left * BLOCK_LEN as u64 + } + + /// Refuses a call that would run past the last counter block, before anything is consumed. + /// + /// # Errors + /// [`SymmetricCipherError::StateError`] if `len` exceeds what the counter can still cover. + #[inline] + fn check_capacity(&self, len: usize) -> Result<(), SymmetricCipherError> { + if len as u64 > self.remaining_capacity() { + return Err(SymmetricCipherError::StateError( + "CTR counter exhausted: this message would need more blocks than the counter has \ + distinct values, and continuing would repeat keystream", + )); + } + Ok(()) + } + + /// `Oj = CIPH_K(Tj)` into the keystream buffer, then `T` moves on. Only called when the current + /// block is used up and capacity has already been checked. + #[inline] + fn refill(&mut self) { + let mut block = self.counter_block(); + self.perm.encrypt_block(&mut block); + (*self.keystream).copy_from_slice(&block); + self.next_counter += 1; + self.used = 0; + } + + /// XORs `data` (shorter than a block, or the tail of a partly-used block) with the keystream, + /// refilling as it goes. Used for the bytes that finish an open block and for the final tail. + #[inline] + fn apply_bytes(&mut self, data: &mut [u8]) { + for byte in data.iter_mut() { + if self.used == BLOCK_LEN { + self.refill(); + } + *byte ^= self.keystream[self.used]; + self.used += 1; + } + } + + /// XORs `N` whole blocks with `N` counter blocks encrypted in one batched call. + /// + /// The counter blocks are built first -- they depend only on the nonce and the index, not on + /// the data or on each other's cipher output -- so the `N` forward ciphers are independent. + /// This is the parallelism Sec 6.5 describes, and it applies to both directions. + #[inline] + fn apply_batch( + &mut self, + blocks: &mut [[u8; BLOCK_LEN]; N], + batch: impl Fn(&P, &mut [[u8; BLOCK_LEN]; N]), + ) { + let mut keystream = [[0u8; BLOCK_LEN]; N]; + for slot in keystream.iter_mut() { + *slot = self.counter_block(); + self.next_counter += 1; + } + batch(&self.perm, &mut keystream); + for (block, o) in blocks.iter_mut().zip(keystream.iter()) { + for (b, o) in block.iter_mut().zip(o.iter()) { + *b ^= *o; + } + } + // The batch consumed whole blocks, so nothing is left pending. + self.used = BLOCK_LEN; + } + + /// XORs one whole block at a block boundary. + #[inline] + fn apply_one(&mut self, block: &mut [u8; BLOCK_LEN]) { + let mut o = self.counter_block(); + self.perm.encrypt_block(&mut o); + self.next_counter += 1; + for (b, o) in block.iter_mut().zip(o.iter()) { + *b ^= *o; + } + self.used = BLOCK_LEN; + } + + /// The whole data path, shared by both directions: CTR encryption and decryption are the same + /// operation (Sec 6.5), so there is one implementation and the direction is only a type. + /// + /// Splits into the bytes that finish an already-open keystream block, the whole blocks that + /// follow, and the short tail. The middle goes through the batch paths; only the two ends go + /// byte by byte. + /// + /// # Errors + /// [`SymmetricCipherError::StateError`] if the counter cannot cover the call; nothing is + /// consumed in that case. + fn apply(&mut self, data: &mut [u8]) -> Result<(), SymmetricCipherError> { + self.check_capacity(data.len())?; + + let head_len = core::cmp::min(BLOCK_LEN - self.used, data.len()); + let (head, rest) = data.split_at_mut(head_len); + self.apply_bytes(head); + + let (blocks, tail) = rest.as_chunks_mut::(); + let (eights, rest_blocks) = blocks.as_chunks_mut::<8>(); + for eight in eights.iter_mut() { + self.apply_batch(eight, P::encrypt_blocks8); + } + let (pairs, single) = rest_blocks.as_chunks_mut::<2>(); + for pair in pairs.iter_mut() { + self.apply_batch(pair, P::encrypt_blocks2); + } + for block in single.iter_mut() { + self.apply_one(block); + } + + self.apply_bytes(tail); + Ok(()) + } +} + +impl Algorithm + for Ctr +where + P: ElectronicCodeBook, +{ + /// The underlying permutation's name. The mode is not appended: `&'static str`s cannot be + /// concatenated in a `const`, and the mode is already in the type. + const ALG_NAME: &'static str = P::ALG_NAME; + /// A mode does not change the strength of the underlying cipher. + const MAX_SECURITY_STRENGTH: SecurityStrength = P::MAX_SECURITY_STRENGTH; +} + +impl + StreamCipherEncryptor + for Ctr +where + P: ElectronicCodeBook, +{ + /// Begins an encryption flow, generating the nonce from the library's default OS-backed DRBG. + fn do_encrypt_init( + key: &KeyMaterial, + ) -> Result<(Self, [u8; INIT_DATA_LEN]), SymmetricCipherError> { + let mut rng = HashDRBG_SHA512::new_from_os(); + Self::do_encrypt_init_rng(key, &mut rng) + } + + /// As [`StreamCipherEncryptor::do_encrypt_init`], but takes the nonce from the provided RNG. + fn do_encrypt_init_rng( + key: &KeyMaterial, + rng: &mut dyn RNG, + ) -> Result<(Self, [u8; INIT_DATA_LEN]), SymmetricCipherError> { + Self::check_shape(); + let perm = P::new(key)?; + let nonce = random_iv::(rng)?; + Ok((Self::start(perm, nonce), nonce)) + } + + /// Encrypts `data`, of any length, in place: `Cj = Pj XOR CIPH_K(Tj)`. + /// + /// # Errors + /// [`SymmetricCipherError::StateError`] if the counter cannot cover the call. Nothing is + /// consumed in that case; see the module docs. + fn do_encrypt(&mut self, data: &mut [u8]) -> Result<(), SymmetricCipherError> { + self.apply(data) + } +} + +impl + StreamCipherDecryptor + for Ctr +where + P: ElectronicCodeBook, +{ + /// Begins a decryption flow from the nonce returned by + /// [`StreamCipherEncryptor::do_encrypt_init`]. + fn do_decrypt_init( + key: &KeyMaterial, + init_data: &[u8; INIT_DATA_LEN], + ) -> Result { + Self::check_shape(); + let perm = P::new(key)?; + Ok(Self::start(perm, *init_data)) + } + + /// Decrypts `data`, of any length, in place: `Pj = Cj XOR CIPH_K(Tj)`, the same operation as + /// encryption (Sec 6.5). + /// + /// # Errors + /// As [`StreamCipherEncryptor::do_encrypt`]. + fn do_decrypt(&mut self, data: &mut [u8]) -> Result<(), SymmetricCipherError> { + self.apply(data) + } +} diff --git a/crypto/modes/src/ecb.rs b/crypto/modes/src/ecb.rs new file mode 100644 index 00000000..49d338f4 --- /dev/null +++ b/crypto/modes/src/ecb.rs @@ -0,0 +1,186 @@ +//! The Electronic Codebook mode of operation (NIST SP 800-38A Sec 6.1). +//! +//! # The specification +//! +//! Sec 6.1 defines the mode in one equation each way, quoted verbatim: +//! +//! ```text +//! ECB Encryption: Cj = CIPH_K(Pj) for j = 1 ... n. +//! ECB Decryption: Pj = CIPH^-1_K(Cj) for j = 1 ... n. +//! ``` +//! +//! "In ECB encryption, the forward cipher function is applied directly and independently to each +//! block of the plaintext. The resulting sequence of output blocks is the ciphertext. In ECB +//! decryption, the inverse cipher function is applied directly and independently to each block of +//! the ciphertext. The resulting sequence of output blocks is the plaintext." +//! +//! # A mode with no state +//! +//! There is no IV and no chaining: the mode *is* the keyed permutation applied block by block, +//! which is why the permutation trait itself is named [`ElectronicCodeBook`]. What this type adds is +//! the [`BlockCipherEncryptor`] / [`BlockCipherDecryptor`] shape shared with `Cbc` -- the direction +//! in the type, the streaming and one-shot methods with their compile-time length checks, and the +//! batching -- so ECB can stand wherever the other block modes can, including under the padding +//! layer and behind the CLI. (`Cfb` and `Cfb8` are stream ciphers and implement the stream traits +//! instead.) Its `INIT_DATA_LEN` is 0: [`BlockCipherEncryptor::do_encrypt_init`] +//! returns an empty array and draws nothing from the RNG, and +//! [`BlockCipherDecryptor::do_decrypt_init`] takes an empty one. +//! +//! # Why it is here at all +//! +//! Sec 6.1: "In the ECB mode, under a given key, any given plaintext block always gets encrypted to +//! the same ciphertext block. If this property is undesirable in a particular application, the ECB +//! mode should not be used." It is undesirable in nearly every application -- equal plaintext blocks +//! give equal ciphertext blocks, so the structure of the plaintext shows through the ciphertext, and +//! blocks can be reordered, repeated or removed without anything to detect it. ECB is provided for +//! interoperability with systems and specifications that use it, and for driving test vectors; it is +//! not a way to encrypt data. See the crate docs, "Security Considerations". +//! +//! # Both directions are parallel +//! +//! Sec 6.1: "In ECB encryption and ECB decryption, multiple forward cipher functions and inverse +//! cipher functions can be computed in parallel." Unlike CBC and CFB, whose encryption is serial, +//! both directions here batch through the permutation's eight-block and pair methods +//! ([`ElectronicCodeBook::encrypt_blocks8`] / [`ElectronicCodeBook::encrypt_blocks2`] and their +//! inverses), then finish the remaining block singly. + +use crate::{Decrypting, Encrypting}; +use bouncycastle_core::errors::SymmetricCipherError; +use bouncycastle_core::key_material::KeyMaterial; +use bouncycastle_core::traits::{ + Algorithm, BlockCipherDecryptor, BlockCipherEncryptor, ElectronicCodeBook, RNG, + SecurityStrength, +}; +use core::marker::PhantomData; + +/// ECB mode over any [`ElectronicCodeBook`], with the direction encoded in the type. +/// +/// **Not a confidentiality mode for data**: see the module docs and the crate's "Security +/// Considerations". Provided for interoperability and test vectors. +/// +/// `Dir` is [`Encrypting`] or [`Decrypting`]. [`BlockCipherEncryptor`] is implemented only for the +/// former and [`BlockCipherDecryptor`] only for the latter, so an `Ecb<_, Encrypting, _, _>` has no +/// decryption methods at all -- using one in the wrong direction is a compile error rather than a +/// runtime check. +/// +/// There is no initialization data, so `INIT_DATA_LEN == 0`. +/// +/// # State +/// +/// Only the permutation, which owns the key schedule and is responsible for keeping it in a +/// zeroize-on-drop wrapper. Nothing chains from one block to the next, so unlike `Cbc` and `Cfb` +/// there is no block of chaining value: `size_of::>() == size_of::

()`. +pub struct Ecb +where + P: ElectronicCodeBook, +{ + perm: P, + _dir: PhantomData

, +} + +impl Ecb +where + P: ElectronicCodeBook, +{ + /// Expands the key. Both `_init` constructors are this; there is nothing else to set up. + fn new(key: &KeyMaterial) -> Result { + Ok(Self { perm: P::new(key)?, _dir: PhantomData }) + } +} + +impl Algorithm + for Ecb +where + P: ElectronicCodeBook, +{ + /// The underlying permutation's name. The mode is not appended: `&'static str`s cannot be + /// concatenated in a `const`, and the mode is already in the type. + const ALG_NAME: &'static str = P::ALG_NAME; + /// A mode does not change the strength of the underlying cipher. (It does not make ECB + /// suitable for data either; strength is about the key, not about the codebook property.) + const MAX_SECURITY_STRENGTH: SecurityStrength = P::MAX_SECURITY_STRENGTH; +} + +impl BlockCipherEncryptor + for Ecb +where + P: ElectronicCodeBook, +{ + /// Expands the key. ECB has no initialization data (SP 800-38A Table D.2 lists the IV column + /// as "Not applicable"), so the returned init data is the empty array. + fn do_encrypt_init( + key: &KeyMaterial, + ) -> Result<(Self, [u8; 0]), SymmetricCipherError> { + Ok((Self::new(key)?, [])) + } + + /// As [`BlockCipherEncryptor::do_encrypt_init`]. Nothing is drawn from `rng`: there is no IV to + /// generate, so this exists only to satisfy the trait and is identical to the plain constructor. + fn do_encrypt_init_rng( + key: &KeyMaterial, + _rng: &mut dyn RNG, + ) -> Result<(Self, [u8; 0]), SymmetricCipherError> { + Self::do_encrypt_init(key) + } + + /// The implementor hook (the flat `do_encrypt` is provided over it): `Cj = CIPH_K(Pj)` for every + /// block, in place. + /// + /// Sec 6.1 allows the forward cipher functions to "be computed in parallel", so the blocks go + /// to the permutation in eights, then pairs, then the remaining block singly. `as_chunks_mut` + /// splits into exactly those shapes with no runtime length check. Never fails: ECB has no + /// per-initialization data limit. + fn do_encrypt_blocks( + &mut self, + blocks: &mut [[u8; BLOCK_LEN]], + ) -> Result<(), SymmetricCipherError> { + let (eights, rest) = blocks.as_chunks_mut::<8>(); + for eight in eights.iter_mut() { + self.perm.encrypt_blocks8(eight); + } + let (pairs, tail) = rest.as_chunks_mut::<2>(); + for pair in pairs.iter_mut() { + self.perm.encrypt_blocks2(pair); + } + for block in tail.iter_mut() { + self.perm.encrypt_block(block); + } + Ok(()) + } +} + +impl BlockCipherDecryptor + for Ecb +where + P: ElectronicCodeBook, +{ + /// Expands the key. The init data is the empty array [`BlockCipherEncryptor::do_encrypt_init`] + /// returned; there is nothing in it to use. + fn do_decrypt_init( + key: &KeyMaterial, + _init_data: &[u8; 0], + ) -> Result { + Self::new(key) + } + + /// The implementor hook (the flat `do_decrypt` is provided over it): `Pj = CIPH^-1_K(Cj)` for + /// every block, in place -- eights, then pairs, then the remaining block, as on the encrypt + /// side. Never fails. + fn do_decrypt_blocks( + &mut self, + blocks: &mut [[u8; BLOCK_LEN]], + ) -> Result<(), SymmetricCipherError> { + let (eights, rest) = blocks.as_chunks_mut::<8>(); + for eight in eights.iter_mut() { + self.perm.decrypt_blocks8(eight); + } + let (pairs, tail) = rest.as_chunks_mut::<2>(); + for pair in pairs.iter_mut() { + self.perm.decrypt_blocks2(pair); + } + for block in tail.iter_mut() { + self.perm.decrypt_block(block); + } + Ok(()) + } +} diff --git a/crypto/modes/src/iv.rs b/crypto/modes/src/iv.rs new file mode 100644 index 00000000..d2b60c02 --- /dev/null +++ b/crypto/modes/src/iv.rs @@ -0,0 +1,26 @@ +//! Initialization-vector generation, shared by the modes that need one. + +use bouncycastle_core::errors::SymmetricCipherError; +use bouncycastle_core::traits::RNG; + +/// Generates a random initialization vector. +/// +/// NIST SP 800-38A Appendix C gives two recommended methods for producing the unpredictable IVs +/// that CBC and CFB require. This is the second one verbatim: "to generate a random data block +/// using a FIPS-approved random number generator". +/// +/// The first method -- applying the forward cipher function to a nonce under the same key -- is not +/// implemented, because it needs a nonce the caller has to guarantee unique, and the API +/// deliberately does not accept caller-supplied initialization data at all. +/// +/// Appendix C also notes the IV "need not be secret", so this is not wrapped in a `Secret`: it is +/// returned to the caller to transmit alongside the ciphertext. Its *integrity* is a different +/// matter -- see the `cbc` module docs on Appendix D. +pub(crate) fn random_iv( + rng: &mut dyn RNG, +) -> Result<[u8; N], SymmetricCipherError> { + let mut iv = [0u8; N]; + // `RNGError` converts into `SymmetricCipherError` via the `From` impl in core::errors. + rng.next_bytes_out(&mut iv)?; + Ok(iv) +} diff --git a/crypto/modes/src/lib.rs b/crypto/modes/src/lib.rs new file mode 100644 index 00000000..3f65074a --- /dev/null +++ b/crypto/modes/src/lib.rs @@ -0,0 +1,540 @@ +//! Block cipher modes of operation (NIST SP 800-38A). +//! +//! A mode turns a keyed block permutation -- `bouncycastle-aes-lowmemory`'s `Aes128` and friends, +//! or anything else implementing [`ElectronicCodeBook`] -- into something that can encrypt more than +//! one block. This crate provides: +//! +//! | Mode | Type | Spec | Notes | +//! |---|---|---|---| +//! | ECB | [`Ecb`] | SP 800-38A Sec 6.1 | Electronic Codebook. **Not confidential for data**; interoperability and test vectors only | +//! | CBC | [`Cbc`] | SP 800-38A Sec 6.2 | Cipher Block Chaining | +//! | CFB | [`Cfb`] | SP 800-38A Sec 6.3 | Cipher Feedback, full-block segment (`s = b`), i.e. CFB128 for AES | +//! | CFB8 | [`Cfb8`] | SP 800-38A Sec 6.3 | Cipher Feedback, 8-bit segment (`s = 8`) | +//! | CTR | [`Ctr`] | SP 800-38A Sec 6.5 | Counter. Nonce plus counter, both directions parallel | +//! +//! They divide two ways. **ECB and CBC are block ciphers** ([`BlockCipherEncryptor`] / +//! [`BlockCipherDecryptor`]): whole blocks in, whole blocks out, and arbitrary-length data needs +//! the padding layer. **CFB, CFB8 and CTR are stream ciphers** ([`StreamCipherEncryptor`] / +//! [`StreamCipherDecryptor`]): any length in, the same length out, no padding, no finalization -- +//! see [Block alignment, and which modes need it](#block-alignment-and-which-modes-need-it). +//! +//! CBC, CFB, CFB8 and CTR all generate their own init data: an IV for the first three, a nonce for +//! CTR, which is shorter than a block because the rest of the counter block is the counter. ECB has +//! none at all (`INIT_DATA_LEN = 0`) and is the raw permutation applied block by block -- see +//! [ECB is not a confidentiality mode for data](#ecb-is-not-a-confidentiality-mode-for-data) and +//! [Choosing between the modes](#choosing-between-the-modes). +//! +//! [`Cfb`] and [`Cfb8`] are the same construction at two segment sizes, but they are **different, +//! non-interoperable modes** whose ciphertexts differ from the first byte. "CFB" unqualified is +//! ambiguous between them; see [`Cfb8`] for the cost difference, which is a factor of 16 on AES. +//! +//! The crate is deliberately cipher-agnostic: it depends on no concrete block cipher, only on the +//! trait. Define a one-line alias for the combination you use -- or use the ready-made +//! `AES_CBC_128` / `AES_CFB_128` / `AES_CFB8_128` / `AES_CTR_128` / `AES_ECB_128` and friends from +//! `bouncycastle-aes-lowmemory`: +//! +//! ``` +//! use bouncycastle_aes_lowmemory::{Aes128, Aes192, Aes256}; +//! use bouncycastle_modes::{Cbc, Cfb, Cfb8, Ctr, Ecb}; +//! +//! type Aes128Cbc = Cbc; +//! type Aes192Cbc = Cbc; +//! type Aes256Cbc = Cbc; +//! +//! type Aes128Cfb = Cfb; +//! type Aes192Cfb = Cfb; +//! type Aes256Cfb = Cfb; +//! +//! type Aes128Cfb8 = Cfb8; +//! +//! // CTR takes one more parameter: the nonce length, which fixes the counter width at +//! // `BLOCK_LEN - NONCE_LEN`. 12 bytes of nonce leaves the maximum 4-byte counter. +//! type Aes128Ctr = Ctr; +//! +//! type Aes128Ecb = Ecb; +//! ``` +//! +//! # Usage Examples +//! +//! The direction is part of the type: [`Cbc`](Cbc) implements +//! [`BlockCipherEncryptor`] and nothing else, and [`Cbc`](Cbc) implements +//! [`BlockCipherDecryptor`] and nothing else. [`Cfb`] and [`Cfb8`] are the same, with +//! [`StreamCipherEncryptor`] / [`StreamCipherDecryptor`] in place of the block traits. The IV is +//! generated for you and returned; there is no API for supplying your own (see +//! [Security Considerations](#security-considerations)). +//! +//! ``` +//! use bouncycastle_aes_lowmemory::Aes128; +//! use bouncycastle_core::key_material::{KeyMaterial, KeyType}; +//! use bouncycastle_core::traits::{BlockCipherDecryptor, BlockCipherEncryptor}; +//! use bouncycastle_modes::{Cbc, Decrypting, Encrypting}; +//! +//! type Aes128Cbc = Cbc; +//! +//! let key = KeyMaterial::<16>::from_bytes_as_type(&[0x42; 16], KeyType::SymmetricCipherKey) +//! .expect("a 16-byte symmetric cipher key"); +//! +//! // 48 bytes: three whole blocks. A length that is not a multiple of 16 would not compile. +//! let plaintext: [u8; 48] = *b"The quick brown fox jumps over the lazy dog. OK!"; +//! +//! // One shot, in place: encrypts under a freshly generated IV, which is returned. +//! let mut data = plaintext; +//! let iv = Aes128Cbc::::encrypt(&key, &mut data).expect("encryption"); +//! assert_ne!(data, plaintext); +//! +//! Aes128Cbc::::decrypt(&key, &iv, &mut data).expect("decryption"); +//! assert_eq!(data, plaintext); +//! ``` +//! +//! Streaming, for data that arrives in pieces. A sequence of calls is equivalent to one call over +//! the concatenation: +//! +//! ``` +//! use bouncycastle_aes_lowmemory::Aes256; +//! use bouncycastle_core::key_material::{KeyMaterial, KeyType}; +//! use bouncycastle_core::traits::{BlockCipherDecryptor, BlockCipherEncryptor}; +//! use bouncycastle_modes::{Cbc, Decrypting, Encrypting}; +//! +//! type Aes256Cbc = Cbc; +//! +//! let key = KeyMaterial::<32>::from_bytes_as_type(&[0x07; 32], KeyType::SymmetricCipherKey) +//! .expect("a 32-byte symmetric cipher key"); +//! +//! let (mut encryptor, iv) = +//! Aes256Cbc::::do_encrypt_init(&key).expect("encrypt init"); +//! let mut first = [0xAAu8; 16]; +//! let mut rest = [0xBBu8; 32]; +//! encryptor.do_encrypt(&mut first).expect("block 1"); +//! encryptor.do_encrypt(&mut rest).expect("blocks 2-3"); +//! +//! let mut decryptor = Aes256Cbc::::do_decrypt_init(&key, &iv).expect("decrypt init"); +//! decryptor.do_decrypt(&mut first).unwrap(); +//! decryptor.do_decrypt(&mut rest).unwrap(); +//! assert_eq!(first, [0xAAu8; 16]); +//! assert_eq!(rest, [0xBBu8; 32]); +//! ``` +//! +//! CFB and CFB8 have the same shape and the same IV convention, but they take a `&mut [u8]` of any +//! length rather than a block-aligned array, so there is no padding layer and the ciphertext is +//! exactly as long as the plaintext: +//! +//! ``` +//! use bouncycastle_aes_lowmemory::Aes128; +//! use bouncycastle_core::key_material::{KeyMaterial, KeyType}; +//! use bouncycastle_core::traits::{StreamCipherDecryptor, StreamCipherEncryptor}; +//! use bouncycastle_modes::{Cfb, Cfb8, Decrypting, Encrypting}; +//! +//! type Aes128Cfb = Cfb; +//! type Aes128Cfb8 = Cfb8; +//! +//! let key = KeyMaterial::<16>::from_bytes_as_type(&[0x42; 16], KeyType::SymmetricCipherKey) +//! .expect("a 16-byte symmetric cipher key"); +//! // 21 bytes: not a whole number of blocks, which a stream cipher does not care about. +//! let plaintext = *b"the quick brown fox!!"; +//! +//! let mut ciphertext = plaintext; +//! let iv = Aes128Cfb::::encrypt(&key, &mut ciphertext).expect("encryption"); +//! assert_eq!(ciphertext.len(), plaintext.len()); +//! +//! let mut recovered = ciphertext; +//! Aes128Cfb::::decrypt(&key, &iv, &mut recovered).expect("decryption"); +//! assert_eq!(recovered, plaintext); +//! +//! // CFB8 is a *different mode*, not a variant: nothing at the type level stops you pairing it +//! // with a CFB ciphertext, and it will not recover the plaintext. +//! let mut as_if_cfb8 = ciphertext; +//! Aes128Cfb8::::decrypt(&key, &iv, &mut as_if_cfb8).expect("decryption"); +//! assert_ne!(as_if_cfb8, plaintext); +//! ``` +//! +//! Streaming works at any byte boundary, and the chunking is not visible in the output: +//! +//! ``` +//! use bouncycastle_aes_lowmemory::Aes128; +//! use bouncycastle_core::key_material::{KeyMaterial, KeyType}; +//! use bouncycastle_core::traits::{StreamCipherDecryptor, StreamCipherEncryptor}; +//! use bouncycastle_modes::{Cfb, Decrypting, Encrypting}; +//! +//! type Aes128Cfb = Cfb; +//! +//! let key = KeyMaterial::<16>::from_bytes_as_type(&[0x42; 16], KeyType::SymmetricCipherKey) +//! .expect("a 16-byte symmetric cipher key"); +//! let plaintext = [0x5Au8; 40]; +//! +//! let (mut encryptor, iv) = Aes128Cfb::::do_encrypt_init(&key).expect("init"); +//! let mut chunked = plaintext; +//! // 7 bytes, then 33: neither is a whole block, and the second call finishes the segment the +//! // first one left open. +//! encryptor.do_encrypt(&mut chunked[..7]).expect("first chunk"); +//! encryptor.do_encrypt(&mut chunked[7..]).expect("the rest"); +//! +//! // A single call under the same key and IV gives the identical ciphertext. +//! let (mut encryptor, _) = Aes128Cfb::::do_encrypt_init(&key).expect("init"); +//! let mut decryptor = Aes128Cfb::::do_decrypt_init(&key, &iv).expect("init"); +//! let mut recovered = chunked; +//! // Decrypting in yet another chunking must also agree. +//! decryptor.do_decrypt(&mut recovered[..19]).expect("first chunk"); +//! decryptor.do_decrypt(&mut recovered[19..]).expect("the rest"); +//! assert_eq!(recovered, plaintext); +//! let _ = &mut encryptor; +//! ``` +//! +//! ECB has the same shape with no IV: `encrypt` returns an empty array and `decrypt` takes one. +//! The codebook property that makes it unsuitable for data is visible in the ciphertext: +//! +//! ``` +//! use bouncycastle_aes_lowmemory::Aes128; +//! use bouncycastle_core::key_material::{KeyMaterial, KeyType}; +//! use bouncycastle_core::traits::{BlockCipherDecryptor, BlockCipherEncryptor}; +//! use bouncycastle_modes::{Decrypting, Ecb, Encrypting}; +//! +//! type Aes128Ecb = Ecb; +//! +//! let key = KeyMaterial::<16>::from_bytes_as_type(&[0x42; 16], KeyType::SymmetricCipherKey) +//! .expect("a 16-byte symmetric cipher key"); +//! let plaintext = [0x5Au8; 32]; // two equal blocks +//! +//! let mut data = plaintext; +//! let no_iv: [u8; 0] = Aes128Ecb::::encrypt(&key, &mut data).expect("encryption"); +//! assert_eq!(data[..16], data[16..], "equal plaintext blocks give equal ciphertext blocks"); +//! +//! Aes128Ecb::::decrypt(&key, &no_iv, &mut data).expect("decryption"); +//! assert_eq!(data, plaintext); +//! ``` +//! +//! Using the wrong direction does not compile: +//! +//! ```compile_fail +//! use bouncycastle_aes_lowmemory::Aes128; +//! use bouncycastle_core::key_material::{KeyMaterial, KeyType}; +//! use bouncycastle_core::traits::BlockCipherDecryptor; +//! use bouncycastle_modes::{Cbc, Encrypting}; +//! +//! type Aes128Cbc = Cbc; +//! let key = KeyMaterial::<16>::from_bytes_as_type(&[0x42; 16], KeyType::SymmetricCipherKey).unwrap(); +//! +//! // `Encrypting` does not implement `BlockCipherDecryptor`. +//! let _ = Aes128Cbc::::do_decrypt_init(&key, &[0u8; 16]); +//! ``` +//! +//! # Choosing between the modes +//! +//! None is authenticated, so the honest answer for new designs is "none of them -- use an AEAD". +//! ECB is not a candidate for data at all (below). Between the rest: +//! +//! * **Only CBC needs padding.** CFB and CFB8 are stream ciphers: any length in, the same length +//! out. CBC needs the data padded to a whole number of blocks, which means a padding layer and +//! the padding-oracle care that comes with it. +//! * **Error propagation differs**, and it is the sharpest practical difference. SP 800-38A +//! Appendix D, Table D.2: a bit error in `Cj` gives CBC a *randomised* `Pj` plus the **same bit** +//! flipped in `Pj+1`, and gives CFB the **same bit** flipped in `Pj` plus a randomised `Pj+1`. +//! So under CFB an attacker who can flip a ciphertext bit flips the corresponding plaintext bit +//! directly, in the segment they targeted. All are malleable; authenticate the ciphertext. +//! * **CFB and CFB8 need only the forward cipher function**, in both directions (Sec 6.3). That +//! halves what a permutation has to provide, and where the inverse costs more than the forward +//! direction it makes CFB decryption faster: with `bouncycastle-aes-lowmemory` this crate's +//! benches measure CFB decryption at about 1.37x CBC decryption (AES-128, 16 KiB, `N = 8`). +//! Encryption is the same speed in CBC and CFB, since both are serial and both use only the +//! forward function. +//! * **CFB8 costs a full cipher call per byte** -- 16x the work of CFB on AES, since `MSB_8(Oj)` +//! keeps one byte of each output block and discards the other fifteen. Choose it only when a +//! byte-granular self-synchronising stream is required or an existing format demands it. +//! * **"CFB" alone is ambiguous.** [`Cfb`] is `s = b` (CFB128 on AES) and [`Cfb8`] is `s = 8`; they +//! are different, non-interoperable modes, and SP 800-38A's `s = 1` variant is a third. If you +//! are matching an existing system, check which segment size it means. CBC has no such ambiguity. +//! * CBC, CFB and CFB8 all encrypt serially and decrypt in parallel, so their scaling with `N` +//! matches. +//! * **CTR is parallel in both directions**, the only one here that is. Its counter blocks depend +//! on nothing but the nonce and the index (Sec 6.5), so encryption batches exactly as decryption +//! does and the two run at the same speed -- roughly what the feedback modes reach only when +//! decrypting. It needs only the forward cipher function, like the CFB modes. +//! * **CTR has a per-message limit and enforces it.** The counter is `BLOCK_LEN - NONCE_LEN` bytes, +//! capped at 4, so a message is at most `2^(8 * counter bytes)` blocks; past that [`Ctr`] returns +//! an error rather than repeating keystream. None of the other modes can fail on a data method. +//! * **CTR is the most malleable.** A flipped ciphertext bit flips exactly the corresponding +//! plaintext bit and disturbs nothing else, so tampering leaves no garbling behind at all; the +//! feedback modes at least randomise a neighbouring block. Authenticate the ciphertext. +//! +//! # Block alignment, and which modes need it +//! +//! SP 800-38A Sec 5.2 sets the requirement per mode, and this crate follows it exactly: +//! +//! * **ECB and CBC** -- "the total number of bits in the plaintext must be a multiple of the block +//! size, b". [`Ecb`] and [`Cbc`] are therefore **strictly block-aligned**: whole blocks in, whole +//! blocks out, no finalization step, and a misaligned length is a compile error at the call site. +//! * **CFB and CFB8** -- "the total number of bits in the plaintext must be a multiple of a +//! parameter, denoted s". For [`Cfb8`], `s = 8`, so every byte string qualifies and there is +//! nothing to align. For [`Cfb`], `s = b`, so strictly the message should be a whole number of +//! blocks; [`Cfb`] accepts any length anyway and treats a short final segment as `s = 8r` for +//! that segment only, which is what every streaming CFB128 implementation does and what makes +//! the ciphertexts interoperate. Its module docs derive that from the Sec 6.3 equations. +//! * **CTR** -- "the plaintext need not be a multiple of the block size", and Sec 6.5 says what to +//! do with the last, possibly partial, block: XOR it with `MSB_u(On)` and discard the rest of the +//! output block. So [`Ctr`] has no alignment requirement at all, by the recommendation's own +//! terms rather than by extension. +//! +//! Appendix A puts the formatting of non-aligned data outside the scope of the recommendation. +//! +//! So arbitrary-length data needs a padding layer **for CBC only**. That layer is not in this +//! crate: it is `bouncycastle-padding`, whose `PaddedEncryptor` / `PaddedDecryptor` wrap any +//! [`BlockCipherEncryptor`] / [`BlockCipherDecryptor`] pair, so a block mode gets arbitrary-length +//! support by being wrapped rather than by growing padding logic of its own. The same adapters +//! over `bouncycastle-padding`'s `NoPadding` give the opposite guarantee -- an unaligned message is +//! an error at `do_final` rather than something padded -- for formats defined on whole blocks. +//! +//! ``` +//! use bouncycastle_aes_lowmemory::Aes128; +//! use bouncycastle_core::key_material::{KeyMaterial, KeyType}; +//! use bouncycastle_core::traits::{SymmetricCipherDecryptor, SymmetricCipherEncryptor}; +//! use bouncycastle_modes::{Cbc, Decrypting, Encrypting}; +//! use bouncycastle_padding::{PKCS7, PaddedDecryptor, PaddedEncryptor}; +//! +//! type Enc = PaddedEncryptor, PKCS7, 16, 16, 16>; +//! type Dec = PaddedDecryptor, PKCS7, 16, 16, 16>; +//! +//! let key = KeyMaterial::<16>::from_bytes_as_type(&[0x42; 16], KeyType::SymmetricCipherKey) +//! .expect("a 16-byte symmetric cipher key"); +//! +//! // 5 bytes: not a whole block, which the bare mode would refuse to compile. +//! let message = b"hello"; +//! let mut ciphertext = [0u8; 16]; +//! let (iv, written) = Enc::encrypt_out(&key, message, &mut ciphertext).expect("encryption"); +//! assert_eq!(written, 16); +//! +//! let mut plaintext = [0u8; 16]; +//! let n = Dec::decrypt_out(&key, &iv, &ciphertext, &mut plaintext).expect("decryption"); +//! assert_eq!(&plaintext[..n], message); +//! ``` +//! +//! # Memory Usage +//! +//! No heap allocation, and no lookup tables of its own. A CBC or CFB8 value is the permutation plus +//! one block of chaining value; a CFB value adds a `usize` to that; a CTR value carries the nonce, +//! a counter and a keystream block; an ECB value is just the permutation, since nothing chains: +//! +//! ```text +//! size_of::>() == size_of::

() + BLOCK_LEN +//! size_of::>() == size_of::

() + BLOCK_LEN +//! size_of::>() == size_of::

() + BLOCK_LEN + size_of::() +//! size_of::>() == size_of::

() +//! +//! // CTR, rounded up to the counter's 8-byte alignment: +//! size_of::>() +//! == align8(size_of::

() + NONCE_LEN + 8 + BLOCK_LEN + 8) +//! ``` +//! +//! | Combination | Permutation | Chain | Count | Total | +//! |---|---|---|---|---| +//! | AES-128 CBC or CFB8 | 176 B | 16 B | -- | 192 B | +//! | AES-192 CBC or CFB8 | 208 B | 16 B | -- | 224 B | +//! | AES-256 CBC or CFB8 | 240 B | 16 B | -- | 256 B | +//! | AES-128 CFB | 176 B | 16 B | 8 B | 200 B | +//! | AES-192 CFB | 208 B | 16 B | 8 B | 232 B | +//! | AES-256 CFB | 240 B | 16 B | 8 B | 264 B | +//! | AES-128 CTR | 176 B | 12 B nonce + 16 B keystream | 8 B | 224 B | +//! | AES-192 CTR | 208 B | 12 B nonce + 16 B keystream | 8 B | 256 B | +//! | AES-256 CTR | 240 B | 12 B nonce + 16 B keystream | 8 B | 288 B | +//! | AES-128 ECB | 176 B | 0 B | -- | 176 B | +//! | AES-192 ECB | 208 B | 0 B | -- | 208 B | +//! | AES-256 ECB | 240 B | 0 B | -- | 240 B | +//! +//! CFB8 is the same size as CBC because it stores the same thing: one block of input to the next +//! cipher call. CFB adds one `usize` because its segment is a whole block and a call may end +//! part-way through one, so it records how much of the current segment has been used; its single +//! block does triple duty as the input block, the output block and the next input block, which is +//! why there is no second buffer. (The 8 B figure is a 64-bit `usize`.) +//! +//! CTR is the largest because it is the only mode that must keep a keystream block *and* the state +//! that generates it: the nonce and the counter cannot be recovered from the keystream, and the +//! keystream cannot be recomputed without them. Its counter is a `u64` rather than the 1-to-4 +//! counter bytes so that exhaustion is representable -- the counter field itself wraps, and a mode +//! that read its position back out of those bytes could not tell "just started" from "used up". +//! The keystream block is the one buffer in this crate held in a `Secret`: unlike a chaining value +//! it is live key material for the bytes not yet consumed. +//! +//! The data methods work in place. The batch paths in a decryptor are the transient cost: a +//! `[[u8; BLOCK_LEN]; 8]` of stack for the eight-block path -- 128 B on AES -- and a +//! `[[u8; BLOCK_LEN]; 2]` for the pair path. CFB8's batch paths hold input blocks it builds itself; +//! CBC's and CFB's hold a copy of the ciphertext they need for the chaining value. +//! [`Encrypting`] and [`Decrypting`] are zero-sized and held in a `PhantomData`, so encoding the +//! direction in the type is free. The table is pinned by +//! `sizes_match_the_documented_memory_table` in `tests/cbc_tests.rs`, `tests/cfb_tests.rs`, +//! `tests/cfb8_tests.rs` and `tests/ecb_tests.rs`. +//! +//! # Security Considerations +//! +//! ## ECB is not a confidentiality mode for data +//! +//! SP 800-38A Sec 6.1: "In the ECB mode, under a given key, any given plaintext block always gets +//! encrypted to the same ciphertext block. If this property is undesirable in a particular +//! application, the ECB mode should not be used." It is undesirable for data: equal plaintext +//! blocks give equal ciphertext blocks, so patterns in the plaintext show through the ciphertext; +//! the same message encrypts to the same ciphertext every time, so an observer learns when a message +//! repeats; and with nothing tying blocks together, ciphertext blocks can be reordered, duplicated or +//! deleted, or spliced in from another message under the same key, and the result decrypts to +//! plaintext that looks valid block by block. +//! +//! [`Ecb`] is in this crate because ECB is what some specifications and existing systems require -- +//! a raw permutation exposed through the same mode API as the others, so that a key-wrapping scheme, +//! a legacy protocol or a test-vector harness can use it -- and because it is the natural way to +//! drive an [`ElectronicCodeBook`] implementation's known-answer tests. Do not use it to encrypt +//! data. If you find yourself reaching for it because it needs no IV, that is the problem the IV +//! solves. +//! +//! ## None of the modes is authenticated +//! +//! All four provide, at best, confidentiality only. None detects tampering, and each is malleable +//! in specific, exploitable ways -- SP 800-38A Appendix D, Table D.2, whose CFB row is +//! "SBE in the decryption of `Cj`" plus "RBE in the decryption of `Cj+1`,...,`Cj+b/s`" (SBE = +//! specific bit errors, the same positions; RBE = random bit errors): +//! +//! * **ECB:** flipping a bit of `Cj` randomises the decryption of `Cj` and nothing else, and whole +//! blocks can be reordered, repeated or dropped undetectably (above). +//! * **CBC:** flipping a bit of `Cj` flips the same bit of the decryption of `Cj+1`, and randomises +//! the decryption of `Cj` itself. +//! * **CFB:** flipping a bit of `Cj` flips the same bit of the decryption of `Cj` -- the segment +//! the attacker aimed at -- and randomises the decryption of `Cj+1`, `b/s` being 1 here. So the +//! controlled flip lands in the targeted block rather than the next one. +//! * **CTR:** flipping a bit of `Cj` flips the same bit of the decryption of `Cj` and affects +//! **nothing else at all** -- Table D.2's CTR row is "SBE in the decryption of Cj" with no second +//! clause. That makes it the most malleable of the five: an attacker can edit any plaintext bit +//! they can locate, leaving no garbled block anywhere to betray the change. +//! * **CFB8:** the same controlled flip in the targeted byte, but `b/s` is 16 on a 16-byte block, +//! so the randomised run is the **next 16 bytes** rather than the next one. After that the shift +//! register has flushed and decryption resynchronises, which is the self-synchronising property +//! CFB8 is chosen for -- and it also means a tampered byte damages a bounded, predictable window +//! rather than the rest of the message. +//! +//! **Authenticate the ciphertext.** Prefer an AEAD; if you must use one of these, MAC the +//! ciphertext *and* the IV, and verify before decrypting. +//! +//! Combining decryption with a padding check is the classic padding-oracle setup. It applies to CBC +//! here, the one mode that needs padding; do not report padding failures distinguishably, and do +//! not decrypt unauthenticated ciphertext. `bouncycastle-padding`'s `unpad` is constant-time for +//! exactly this reason, but constant-time unpadding is not a substitute for authentication. +//! +//! ## The IV must be unpredictable, and this crate generates it +//! +//! (ECB has no IV; Table D.2 lists its IV column as "Not applicable". This section is about CBC, +//! CFB and CFB8.) +//! +//! SP 800-38A Sec 5.3 requires that "for the CBC and CFB modes, the IV for any particular execution +//! of the encryption process must be unpredictable" -- not merely unique. Appendix C spells out +//! that "for any given plaintext, it must not be possible to predict the IV that will be associated +//! to the plaintext in advance of the generation of the IV". +//! +//! Rather than accept an IV and hope, `do_encrypt_init` generates one from the library's default +//! OS-backed DRBG and returns it, in both the block traits and the stream traits. There is +//! deliberately **no** API for supplying your own. Known-answer tests drive `do_encrypt_init_rng` +//! with a fixed-output test RNG instead. +//! +//! ## IV integrity +//! +//! Appendix D: "for the CBC mode, the decryption of the first ciphertext block is vulnerable to the +//! (deliberate) introduction of bit errors in specific bit positions of the IV if the integrity of +//! the IV is not protected". Under CBC a flipped IV bit flips exactly that bit of `P1`. +//! +//! CFB damages `P1` too, but unpredictably rather than controllably: the IV is the first thing fed +//! to the cipher, so Table D.2 gives *random* bit errors in the decryption of `C1` -- and, because +//! [`Cfb`] fixes `s = b`, in `C1` only (Appendix D's "a bit error in the ith most significant bit +//! position affects the decryptions of the first `i/s` (rounding up) ciphertext segments" is one +//! segment for every `i` when `s = b`). Later blocks are unaffected. +//! +//! Under CFB8 that same rule reaches further: with `s = 8` it randomises up to the first 16 +//! segments, the count depending on the position of the rightmost corrupted bit, because a byte +//! near the end of the IV stays in the shift register for 16 steps while the leading byte is shifted +//! out after one. +//! +//! Either way the IV need not be secret, but it must be authenticated along with the ciphertext. +//! +//! ## Key and IV reuse +//! +//! Nothing here stops one key being used for many messages, which is fine for any of them provided +//! each gets a fresh unpredictable IV. It is the IV, not the key, that must not repeat. +//! +//! For **CTR** a repeated nonce is not merely unwise, it is fatal, and in a way the IV modes are +//! not: the counter blocks are a pure function of the nonce and the index, so the same nonce under +//! the same key reproduces the *entire keystream* from the first byte, and two messages encrypted +//! under it differ by exactly the XOR of their plaintexts. Sec 6.5 states the requirement as an +//! absolute: "across all of the messages that are encrypted under the given key, all of the +//! counters must be distinct". [`Ctr`] draws its nonce from the DRBG and enforces the within-message +//! half of that by refusing to run past the counter's last value; the across-message half is what +//! the nonce is for. +//! +//! Repeating one matters more for CFB and CFB8. Both XOR a keystream, so two messages encrypted +//! under the same key *and* IV satisfy `C1 XOR C1' == P1 XOR P1'` -- the plaintext XOR leaks +//! directly, the classic two-time-pad failure, and it continues for as long as the two ciphertexts +//! agree. CBC under a repeated IV leaks only whether the blocks were equal, not their XOR. Since +//! every mode's `do_encrypt_init` draws its IV from the DRBG, neither case arises through this API; +//! it is a reason not to add an IV-accepting one. +//! +//! # Not yet implemented +//! +//! * **CFB1**, the `s = 1` segment size (SP 800-38A Appendix F.3.1-F.3.6). Its segment is a single +//! *bit*, so unlike [`Cfb`] and [`Cfb8`] it does not fit a byte-oriented API at all: a message is +//! a bit string whose length need not be a multiple of 8, which this crate has no type for. +//! * **OFB**, the one remaining mode of the recommendation. It is a keystream mode and, like CFB, +//! CFB8 and CTR, would implement [`StreamCipherEncryptor`] / [`StreamCipherDecryptor`]. +//! +//! # Command line +//! +//! The `bc-rust` CLI exposes all five modes for all three AES key lengths: `aes{128,192,256}-cbc`, +//! `-cfb`, `-cfb8`, `-ctr` and `-ecb`, each taking `encrypt` or `decrypt` and streaming stdin to +//! stdout. There is no API for caller-supplied init data anywhere, so `encrypt` writes what it +//! generated at the front of its output and `decrypt` reads it back, and the two compose. That is +//! one block for CBC, CFB and CFB8, **12 bytes** for CTR, and nothing at all for `-ecb`: +//! +//! ```text +//! bc-rust aes256-cbc encrypt --key-file k.bin < plain.bin > cipher.bin +//! bc-rust aes256-cbc decrypt --key-file k.bin < cipher.bin | cmp - plain.bin +//! +//! bc-rust aes256-cfb encrypt --key-file k.bin < plain.bin > cipher.bin +//! bc-rust aes256-cfb decrypt --key-file k.bin < cipher.bin | cmp - plain.bin +//! +//! bc-rust aes256-ctr encrypt --key-file k.bin < plain.bin > cipher.bin # 12-byte nonce first +//! bc-rust aes256-ctr decrypt --key-file k.bin < cipher.bin | cmp - plain.bin +//! +//! bc-rust aes128-ecb encrypt --key-file k.bin < plain.bin > cipher.bin # same length out as in +//! ``` +//! +//! The `-cfb` commands are CFB128, matching [`Cfb`], and the `-cfb8` commands are CFB8, matching +//! [`Cfb8`]; the two are not interoperable. The `-ctr` commands use a 12-byte nonce and so a 4-byte +//! counter, matching `AES_CTR_*`. Input must be block-aligned for the `-cbc` and `-ecb` commands, +//! and may be any length for `-cfb`, `-cfb8` and `-ctr`, for the reason given above. + +#![no_std] +#![forbid(unsafe_code)] +#![forbid(missing_docs)] + +mod cbc; +mod cfb; +mod cfb8; +mod ctr; +mod ecb; +mod iv; + +pub use cbc::Cbc; +pub use cfb::Cfb; +pub use cfb8::Cfb8; +pub use ctr::Ctr; +pub use ecb::Ecb; + +// Imports needed for docs +#[allow(unused_imports)] +use bouncycastle_core::traits::{ + BlockCipherDecryptor, BlockCipherEncryptor, ElectronicCodeBook, StreamCipherDecryptor, + StreamCipherEncryptor, +}; +// end of imports needed for docs + +/// Direction marker for a mode that encrypts. See [`Cbc`], [`Cfb`], [`Cfb8`], [`Ctr`] and [`Ecb`]. +/// +/// Zero-sized: encoding the direction in the type costs no memory. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub struct Encrypting; + +/// Direction marker for a mode that decrypts. See [`Cbc`], [`Cfb`], [`Cfb8`], [`Ctr`] and [`Ecb`]. +/// +/// Zero-sized: encoding the direction in the type costs no memory. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub struct Decrypting; diff --git a/crypto/modes/tests/acvp_cfb8_tests.rs b/crypto/modes/tests/acvp_cfb8_tests.rs new file mode 100644 index 00000000..a67c62f8 --- /dev/null +++ b/crypto/modes/tests/acvp_cfb8_tests.rs @@ -0,0 +1,287 @@ +//! Known-answer tests against the NIST ACVP `ACVP-AES-CFB8` vectors from the `bc-test-data` repo. +//! +//! Requires `bc-test-data` to be cloned alongside this repository, i.e. at `../bc-test-data` +//! relative to the root of this git project. If it is absent the test prints a warning and passes, +//! matching the convention used by the ML-KEM, ML-DSA, `aes-lowmemory` and AES-CBC suites -- +//! `cargo test` must stay green for someone who has only cloned this repository. +//! +//! This is the CFB8 counterpart to `acvp_cfb_tests.rs` (AES-CFB128), `acvp_tests.rs` (AES-CBC) and +//! `crypto/aes-lowmemory/tests/acvp_tests.rs` (AES-ECB, the raw permutation). `ACVP-AES-CFB1` is +//! the one remaining segment size, which this crate does not implement, and is not read. +//! +//! # Joining the request and response files +//! +//! As with CBC, the response file carries **only the answer** (`ct` for an encrypt group, `pt` for a +//! decrypt group) against a `tcId`. The key, IV and input live in the request file, and the group +//! metadata that says which direction a case is -- `direction` and `keyLen` -- lives only there too. +//! So both files are read and joined on `tcId`. +//! +//! # Coverage +//! +//! 2138 AFT (Algorithm Functional Test) cases across all three key lengths and both directions. +//! Most are a single byte -- CFB8's segment -- and 60 carry 16 to 160 bytes, which are the ones +//! that reach the batch paths. Every case is run **four times**: as one call over the whole +//! payload, byte by byte, in 8-byte calls, and in 3-byte calls that never line up with the +//! 8-byte batch. Between them those put the multi-byte cases through +//! [`ElectronicCodeBook::encrypt_blocks8`] and [`ElectronicCodeBook::encrypt_blocks2`] -- the +//! *forward* function, even on the decrypt side -- and through the single-byte path, with the +//! shift register carried across calls at every alignment. So all of that is exercised against real +//! vectors and not only against the toys in `cfb8_tests.rs`. +//! +//! The 6 MCT (Monte Carlo Test) groups are **not** implemented: their expected output is a +//! `resultsArray` produced by a chained update rule defined in the ACVP AES specification rather +//! than in SP 800-38A, and implementing it from anything else would be guesswork. The test reports +//! how many it skipped so the gap stays visible. + +use bouncycastle_aes_lowmemory::{Aes128, Aes192, Aes256}; +use bouncycastle_core::key_material::{ + KeyMaterial, KeyMaterialTrait, KeyType, do_hazardous_operations, +}; +use bouncycastle_core::traits::{ + ElectronicCodeBook, SecurityStrength, StreamCipherDecryptor, StreamCipherEncryptor, +}; +use bouncycastle_core_test_framework::FixedSeedRNG; +use bouncycastle_hex as hex; +use bouncycastle_modes::{Cfb8, Decrypting, Encrypting}; +use serde_json::Value; +use std::collections::BTreeMap; +use std::fs; +use std::path::{Path, PathBuf}; + +const BLOCK_LEN: usize = 16; + +/// Candidate locations, covering `cargo test` run from the crate root or from the repo root. +const TEST_DATA_PATHS: [&str; 2] = [ + "../../../bc-test-data/crypto/aes_tdes_vectors/AES", + "../bc-test-data/crypto/aes_tdes_vectors/AES", +]; + +const REQUEST_FILE: &str = "ACVP-AES-CFB8.4014529.req.json"; +const RESPONSE_FILE: &str = "ACVP-AES-CFB8.4014529.rsp.json"; + +fn test_data_dir() -> Option { + for candidate in TEST_DATA_PATHS { + let path = Path::new(candidate); + if path.join(REQUEST_FILE).exists() && path.join(RESPONSE_FILE).exists() { + return Some(path.to_path_buf()); + } + } + println!( + "WARNING: bc-test-data not found (looked in {TEST_DATA_PATHS:?}); \ + ACVP AES-CFB8 tests will be skipped" + ); + None +} + +/// Builds a `KeyMaterial` from raw ACVP key bytes, including the all-zero keys. +/// +/// The ACVP set deliberately includes an all-zero key. `KeyMaterial` tags an all-zero buffer as +/// `KeyType::Zeroized` and will not promote it outside a `do_hazardous_operations` closure, which +/// is the right default -- so this opts in explicitly rather than the engine weakening its guard. +fn cipher_key(bytes: &[u8]) -> KeyMaterial { + assert_eq!(bytes.len(), N, "key length should match the parameter set"); + let mut key = KeyMaterial::::from_bytes_as_type(bytes, KeyType::SymmetricCipherKey) + .expect("ACVP key bytes fit the buffer"); + + if key.key_type() != KeyType::SymmetricCipherKey { + do_hazardous_operations(&mut key, |k| { + k.set_key_type(KeyType::SymmetricCipherKey)?; + k.set_security_strength(SecurityStrength::from_bytes(N)) + }) + .expect("promoting a NIST all-zero test key"); + } + key +} + +/// How to walk the bytes of one case. +#[derive(Clone, Copy, PartialEq, Eq, Debug)] +enum Grouping { + /// The whole payload in one call: eights, then pairs, then the remaining bytes singly. + Whole, + /// One byte per call. Never batches. + Bytes, + /// Eight bytes per call: every call is exactly one `encrypt_blocks8` batch. + Eights, + /// Three bytes per call, so no call lines up with the 8-byte batch and the shift register has + /// to carry across calls at every alignment. + Threes, +} + +impl Grouping { + fn chunk_len(self, payload_len: usize) -> usize { + match self { + Grouping::Whole => payload_len.max(1), + Grouping::Bytes => 1, + Grouping::Eights => 8, + Grouping::Threes => 3, + } + } +} + +/// Runs one CFB8 case in one direction, for a given permutation, under the given grouping. +/// +/// Encryption is driven through `do_encrypt_init_rng` with a `FixedSeedRNG` emitting the vector's +/// IV, and the returned init data is checked against that IV before any ciphertext is compared -- +/// so a change that ignored the RNG could not pass silently. +fn run_case( + key_bytes: &[u8], + iv: [u8; BLOCK_LEN], + input: &[u8], + encrypt: bool, + grouping: Grouping, +) -> Vec +where + P: ElectronicCodeBook, +{ + let key = cipher_key::(key_bytes); + let mut data = input.to_vec(); + let chunk = grouping.chunk_len(data.len()); + + if encrypt { + let (mut enc, got_iv) = Cfb8::::do_encrypt_init_rng( + &key, + &mut FixedSeedRNG::::new(iv), + ) + .expect("encrypt init"); + assert_eq!(got_iv, iv, "the pinned RNG should reproduce the vector's IV"); + for piece in data.chunks_mut(chunk) { + enc.do_encrypt(piece).unwrap(); + } + } else { + let mut dec = Cfb8::::do_decrypt_init(&key, &iv) + .expect("dec init"); + for piece in data.chunks_mut(chunk) { + dec.do_decrypt(piece).unwrap(); + } + } + + data +} + +/// Dispatches on key length, which is what selects the AES parameter set. +fn run_case_for_key_len( + key_bytes: &[u8], + iv: [u8; BLOCK_LEN], + input: &[u8], + encrypt: bool, + grouping: Grouping, +) -> Vec { + match key_bytes.len() { + 16 => run_case::(key_bytes, iv, input, encrypt, grouping), + 24 => run_case::(key_bytes, iv, input, encrypt, grouping), + 32 => run_case::(key_bytes, iv, input, encrypt, grouping), + other => panic!("ACVP AES vectors should only use 16, 24 or 32 byte keys, got {other}"), + } +} + +fn decode(value: &Value, field: &str, tc_id: u64) -> Vec { + let s = value + .get(field) + .and_then(Value::as_str) + .unwrap_or_else(|| panic!("tcId {tc_id}: missing field {field}")); + hex::decode(s).unwrap_or_else(|_| panic!("tcId {tc_id}: bad hex in {field}")) +} + +#[test] +fn acvp_aes_cfb8_known_answer_tests() { + let Some(dir) = test_data_dir() else { return }; + + let req: Value = serde_json::from_str( + &fs::read_to_string(dir.join(REQUEST_FILE)).expect("readable request file"), + ) + .expect("valid ACVP request JSON"); + let rsp: Value = serde_json::from_str( + &fs::read_to_string(dir.join(RESPONSE_FILE)).expect("readable response file"), + ) + .expect("valid ACVP response JSON"); + + // The response file carries only the answer, against a tcId. Index it. + let mut answers: BTreeMap = BTreeMap::new(); + for group in rsp + .get(1) + .and_then(|s| s.get("testGroups")) + .and_then(Value::as_array) + .expect("response testGroups") + { + for test in group.get("tests").and_then(Value::as_array).expect("response tests") { + let tc_id = test.get("tcId").and_then(Value::as_u64).expect("tcId"); + answers.insert(tc_id, test.clone()); + } + } + + let groups = req + .get(1) + .and_then(|s| s.get("testGroups")) + .and_then(Value::as_array) + .expect("request testGroups"); + + let mut checked = 0usize; + let mut multi_block = 0usize; + let mut skipped_mct = 0usize; + let mut per_kind: BTreeMap = BTreeMap::new(); + + for group in groups { + let test_type = group.get("testType").and_then(Value::as_str).expect("testType"); + let direction = group.get("direction").and_then(Value::as_str).expect("direction"); + let encrypt = match direction { + "encrypt" => true, + "decrypt" => false, + other => panic!("unexpected direction {other}"), + }; + + for test in group.get("tests").and_then(Value::as_array).expect("tests") { + let tc_id = test.get("tcId").and_then(Value::as_u64).expect("tcId"); + + if test_type == "MCT" { + skipped_mct += 1; + continue; + } + + let answer = answers.get(&tc_id).unwrap_or_else(|| panic!("tcId {tc_id}: no answer")); + if answer.get("resultsArray").is_some() { + skipped_mct += 1; + continue; + } + + let key_bytes = decode(test, "key", tc_id); + let iv: [u8; BLOCK_LEN] = decode(test, "iv", tc_id).try_into().expect("a 16-byte IV"); + + // Input comes from the request, expected output from the response. + let (input_field, output_field) = if encrypt { ("pt", "ct") } else { ("ct", "pt") }; + let input = decode(test, input_field, tc_id); + let expected = decode(answer, output_field, tc_id); + + assert_eq!(input.len(), expected.len(), "tcId {tc_id}: length mismatch"); + if input.len() > 1 { + multi_block += 1; + } + + for grouping in [Grouping::Whole, Grouping::Bytes, Grouping::Eights, Grouping::Threes] { + let got = run_case_for_key_len(&key_bytes, iv, &input, encrypt, grouping); + assert_eq!( + got, + expected, + "tcId {tc_id}: AES-{} CFB8 {direction}, {} bytes, {grouping:?} grouping", + key_bytes.len() * 8, + input.len() + ); + } + + *per_kind.entry(format!("AES-{} {direction}", key_bytes.len() * 8)).or_default() += 1; + checked += 1; + } + } + + for (kind, n) in &per_kind { + println!("ACVP AES-CFB8 {kind}: {n} cases"); + } + println!( + "ACVP AES-CFB8: {checked} AFT cases checked in four groupings each \ + ({multi_block} of them multi-byte); {skipped_mct} MCT cases skipped" + ); + + // Guard against a silently-empty or partial run. + assert!(checked > 2000, "expected the full ACVP AFT set, only checked {checked}"); + assert!(multi_block >= 50, "expected the multi-byte cases, found {multi_block}"); + assert_eq!(per_kind.len(), 6, "expected all three key lengths in both directions"); +} diff --git a/crypto/modes/tests/acvp_cfb_tests.rs b/crypto/modes/tests/acvp_cfb_tests.rs new file mode 100644 index 00000000..933b01d4 --- /dev/null +++ b/crypto/modes/tests/acvp_cfb_tests.rs @@ -0,0 +1,297 @@ +//! Known-answer tests against the NIST ACVP `ACVP-AES-CFB128` vectors from the `bc-test-data` repo. +//! +//! Requires `bc-test-data` to be cloned alongside this repository, i.e. at `../bc-test-data` +//! relative to the root of this git project. If it is absent the test prints a warning and passes, +//! matching the convention used by the ML-KEM, ML-DSA, `aes-lowmemory` and AES-CBC suites -- +//! `cargo test` must stay green for someone who has only cloned this repository. +//! +//! This is the CFB128 counterpart to `acvp_tests.rs` (AES-CBC) and to +//! `crypto/aes-lowmemory/tests/acvp_tests.rs` (AES-ECB, the raw permutation). The `CFB128` file is +//! the one that matches [`Cfb`]; `ACVP-AES-CFB8` matches `Cfb8` and is read by +//! `acvp_cfb8_tests.rs`. `ACVP-AES-CFB1` is the one segment size this crate does not implement, +//! and is deliberately not read. +//! +//! # Joining the request and response files +//! +//! As with CBC, the response file carries **only the answer** (`ct` for an encrypt group, `pt` for a +//! decrypt group) against a `tcId`. The key, IV and input live in the request file, and the group +//! metadata that says which direction a case is -- `direction` and `keyLen` -- lives only there too. +//! So both files are read and joined on `tcId`. +//! +//! # Coverage +//! +//! 2138 AFT (Algorithm Functional Test) cases across all three key lengths and both directions, +//! including 54 whose payload spans 2 to 10 blocks. Every case is run **four times**: block by +//! block, in pairs with a one-block remainder for odd lengths, as one call over the whole payload, +//! and in 5-byte calls that never line up with a block. The second and third passes are what put +//! the multi-block cases through the pair and eight-block paths -- which for CFB are +//! [`ElectronicCodeBook::encrypt_blocks2`] and [`ElectronicCodeBook::encrypt_blocks8`], the +//! *forward* function, even on the decrypt side -- and the fourth is what puts them through the +//! byte path with segments left open between calls. So all of that is exercised against real +//! vectors and not only against the toys in `cfb_tests.rs`. Every ACVP CFB128 payload is a whole +//! number of blocks, so the short final segment is not covered here (it is not covered by any +//! official vector); `cfb_tests.rs` pins it against the raw permutation. +//! +//! The 6 MCT (Monte Carlo Test) groups are **not** implemented: their expected output is a +//! `resultsArray` produced by a chained update rule defined in the ACVP AES specification rather +//! than in SP 800-38A, and implementing it from anything else would be guesswork. The test reports +//! how many it skipped so the gap stays visible. + +use bouncycastle_aes_lowmemory::{Aes128, Aes192, Aes256}; +use bouncycastle_core::key_material::{ + KeyMaterial, KeyMaterialTrait, KeyType, do_hazardous_operations, +}; +use bouncycastle_core::traits::{ + ElectronicCodeBook, SecurityStrength, StreamCipherDecryptor, StreamCipherEncryptor, +}; +use bouncycastle_core_test_framework::FixedSeedRNG; +use bouncycastle_hex as hex; +use bouncycastle_modes::{Cfb, Decrypting, Encrypting}; +use serde_json::Value; +use std::collections::BTreeMap; +use std::fs; +use std::path::{Path, PathBuf}; + +const BLOCK_LEN: usize = 16; + +/// Candidate locations, covering `cargo test` run from the crate root or from the repo root. +const TEST_DATA_PATHS: [&str; 2] = [ + "../../../bc-test-data/crypto/aes_tdes_vectors/AES", + "../bc-test-data/crypto/aes_tdes_vectors/AES", +]; + +const REQUEST_FILE: &str = "ACVP-AES-CFB128.4014530.req.json"; +const RESPONSE_FILE: &str = "ACVP-AES-CFB128.4014530.rsp.json"; + +fn test_data_dir() -> Option { + for candidate in TEST_DATA_PATHS { + let path = Path::new(candidate); + if path.join(REQUEST_FILE).exists() && path.join(RESPONSE_FILE).exists() { + return Some(path.to_path_buf()); + } + } + println!( + "WARNING: bc-test-data not found (looked in {TEST_DATA_PATHS:?}); \ + ACVP AES-CFB128 tests will be skipped" + ); + None +} + +/// Builds a `KeyMaterial` from raw ACVP key bytes, including the all-zero keys. +/// +/// The ACVP set deliberately includes an all-zero key. `KeyMaterial` tags an all-zero buffer as +/// `KeyType::Zeroized` and will not promote it outside a `do_hazardous_operations` closure, which +/// is the right default -- so this opts in explicitly rather than the engine weakening its guard. +fn cipher_key(bytes: &[u8]) -> KeyMaterial { + assert_eq!(bytes.len(), N, "key length should match the parameter set"); + let mut key = KeyMaterial::::from_bytes_as_type(bytes, KeyType::SymmetricCipherKey) + .expect("ACVP key bytes fit the buffer"); + + if key.key_type() != KeyType::SymmetricCipherKey { + do_hazardous_operations(&mut key, |k| { + k.set_key_type(KeyType::SymmetricCipherKey)?; + k.set_security_strength(SecurityStrength::from_bytes(N)) + }) + .expect("promoting a NIST all-zero test key"); + } + key +} + +/// How to walk the bytes of one case. +#[derive(Clone, Copy, PartialEq, Eq, Debug)] +enum Grouping { + /// One block per call. Never forms a pair. + Single, + /// Two blocks per call, with a one-block remainder for odd lengths. Uses the pair path. + Pairs, + /// The whole payload in one call: eights, then pairs, then the remaining block. The cases + /// spanning 8 to 10 blocks are the ones that reach `encrypt_blocks8`. + Whole, + /// Five bytes per call, so every call but the first starts mid-segment and none is a whole + /// block: the byte path, with the unused keystream carried between calls. + Bytes, +} + +impl Grouping { + fn chunk_len(self, payload_len: usize) -> usize { + match self { + Grouping::Single => BLOCK_LEN, + Grouping::Pairs => 2 * BLOCK_LEN, + Grouping::Whole => payload_len.max(1), + Grouping::Bytes => 5, + } + } +} + +/// Runs one CFB128 case in one direction, for a given permutation, under the given grouping. +/// +/// Encryption is driven through `do_encrypt_init_rng` with a `FixedSeedRNG` emitting the vector's +/// IV, and the returned init data is checked against that IV before any ciphertext is compared -- +/// so a change that ignored the RNG could not pass silently. +fn run_case( + key_bytes: &[u8], + iv: [u8; BLOCK_LEN], + input: &[u8], + encrypt: bool, + grouping: Grouping, +) -> Vec +where + P: ElectronicCodeBook, +{ + let key = cipher_key::(key_bytes); + let mut data = input.to_vec(); + let chunk = grouping.chunk_len(data.len()); + + if encrypt { + let (mut enc, got_iv) = Cfb::::do_encrypt_init_rng( + &key, + &mut FixedSeedRNG::::new(iv), + ) + .expect("encrypt init"); + assert_eq!(got_iv, iv, "the pinned RNG should reproduce the vector's IV"); + for piece in data.chunks_mut(chunk) { + enc.do_encrypt(piece).unwrap(); + } + } else { + let mut dec = + Cfb::::do_decrypt_init(&key, &iv).expect("dec init"); + for piece in data.chunks_mut(chunk) { + dec.do_decrypt(piece).unwrap(); + } + } + + data +} + +/// Dispatches on key length, which is what selects the AES parameter set. +fn run_case_for_key_len( + key_bytes: &[u8], + iv: [u8; BLOCK_LEN], + input: &[u8], + encrypt: bool, + grouping: Grouping, +) -> Vec { + match key_bytes.len() { + 16 => run_case::(key_bytes, iv, input, encrypt, grouping), + 24 => run_case::(key_bytes, iv, input, encrypt, grouping), + 32 => run_case::(key_bytes, iv, input, encrypt, grouping), + other => panic!("ACVP AES vectors should only use 16, 24 or 32 byte keys, got {other}"), + } +} + +fn decode(value: &Value, field: &str, tc_id: u64) -> Vec { + let s = value + .get(field) + .and_then(Value::as_str) + .unwrap_or_else(|| panic!("tcId {tc_id}: missing field {field}")); + hex::decode(s).unwrap_or_else(|_| panic!("tcId {tc_id}: bad hex in {field}")) +} + +#[test] +fn acvp_aes_cfb128_known_answer_tests() { + let Some(dir) = test_data_dir() else { return }; + + let req: Value = serde_json::from_str( + &fs::read_to_string(dir.join(REQUEST_FILE)).expect("readable request file"), + ) + .expect("valid ACVP request JSON"); + let rsp: Value = serde_json::from_str( + &fs::read_to_string(dir.join(RESPONSE_FILE)).expect("readable response file"), + ) + .expect("valid ACVP response JSON"); + + // The response file carries only the answer, against a tcId. Index it. + let mut answers: BTreeMap = BTreeMap::new(); + for group in rsp + .get(1) + .and_then(|s| s.get("testGroups")) + .and_then(Value::as_array) + .expect("response testGroups") + { + for test in group.get("tests").and_then(Value::as_array).expect("response tests") { + let tc_id = test.get("tcId").and_then(Value::as_u64).expect("tcId"); + answers.insert(tc_id, test.clone()); + } + } + + let groups = req + .get(1) + .and_then(|s| s.get("testGroups")) + .and_then(Value::as_array) + .expect("request testGroups"); + + let mut checked = 0usize; + let mut multi_block = 0usize; + let mut skipped_mct = 0usize; + let mut per_kind: BTreeMap = BTreeMap::new(); + + for group in groups { + let test_type = group.get("testType").and_then(Value::as_str).expect("testType"); + let direction = group.get("direction").and_then(Value::as_str).expect("direction"); + let encrypt = match direction { + "encrypt" => true, + "decrypt" => false, + other => panic!("unexpected direction {other}"), + }; + + for test in group.get("tests").and_then(Value::as_array).expect("tests") { + let tc_id = test.get("tcId").and_then(Value::as_u64).expect("tcId"); + + if test_type == "MCT" { + skipped_mct += 1; + continue; + } + + let answer = answers.get(&tc_id).unwrap_or_else(|| panic!("tcId {tc_id}: no answer")); + if answer.get("resultsArray").is_some() { + skipped_mct += 1; + continue; + } + + let key_bytes = decode(test, "key", tc_id); + let iv: [u8; BLOCK_LEN] = decode(test, "iv", tc_id).try_into().expect("a 16-byte IV"); + + // Input comes from the request, expected output from the response. + let (input_field, output_field) = if encrypt { ("pt", "ct") } else { ("ct", "pt") }; + let input = decode(test, input_field, tc_id); + let expected = decode(answer, output_field, tc_id); + + assert_eq!(input.len(), expected.len(), "tcId {tc_id}: length mismatch"); + assert_eq!( + input.len() % BLOCK_LEN, + 0, + "tcId {tc_id}: ACVP CFB128 payloads are block-aligned" + ); + if input.len() > BLOCK_LEN { + multi_block += 1; + } + + for grouping in [Grouping::Single, Grouping::Pairs, Grouping::Whole, Grouping::Bytes] { + let got = run_case_for_key_len(&key_bytes, iv, &input, encrypt, grouping); + assert_eq!( + got, + expected, + "tcId {tc_id}: AES-{} CFB128 {direction}, {} blocks, {grouping:?} grouping", + key_bytes.len() * 8, + input.len() / BLOCK_LEN + ); + } + + *per_kind.entry(format!("AES-{} {direction}", key_bytes.len() * 8)).or_default() += 1; + checked += 1; + } + } + + for (kind, n) in &per_kind { + println!("ACVP AES-CFB128 {kind}: {n} cases"); + } + println!( + "ACVP AES-CFB128: {checked} AFT cases checked in four groupings each \ + ({multi_block} of them multi-block); {skipped_mct} MCT cases skipped" + ); + + // Guard against a silently-empty or partial run. + assert!(checked > 2000, "expected the full ACVP AFT set, only checked {checked}"); + assert!(multi_block >= 50, "expected the multi-block cases, found {multi_block}"); + assert_eq!(per_kind.len(), 6, "expected all three key lengths in both directions"); +} diff --git a/crypto/modes/tests/acvp_ctr_tests.rs b/crypto/modes/tests/acvp_ctr_tests.rs new file mode 100644 index 00000000..8dcbb3df --- /dev/null +++ b/crypto/modes/tests/acvp_ctr_tests.rs @@ -0,0 +1,307 @@ +//! Known-answer tests against the NIST ACVP `ACVP-AES-CTR` vectors from the `bc-test-data` repo. +//! +//! Requires `bc-test-data` to be cloned alongside this repository, i.e. at `../bc-test-data` +//! relative to the root of this git project. If it is absent the test prints a warning and passes, +//! matching the convention used by the other ACVP suites -- `cargo test` must stay green for +//! someone who has only cloned this repository. +//! +//! # Only the zero-counter cases apply, and that is most of them +//! +//! ACVP gives each case a full 16-byte `iv`, which for CTR is the **initial counter block**. +//! [`Ctr`] takes a *nonce* and starts its counter at zero, so a case is expressible through this +//! API exactly when its initial counter block ends in `CTR_LEN` zero bytes: then the nonce is the +//! leading bytes and the counter is already where this mode starts. +//! +//! With the 12-byte nonce used here (a 4-byte counter), **1853 of the 2138** functional cases +//! qualify. The other 285 begin at a non-zero counter and are skipped with the count reported, so +//! the gap stays visible; they test the cipher and the XOR, both of which the qualifying cases +//! already cover, and not the counter construction, which `ctr_tests.rs` pins against the spec. +//! +//! # Joining the request and response files +//! +//! As with the other AES sets, the response file carries **only the answer** (`ct` for an encrypt +//! group, `pt` for a decrypt group) against a `tcId`. The key, IV and input live in the request +//! file, and the group metadata that says which direction a case is lives only there too. So both +//! files are read and joined on `tcId`. +//! +//! # Coverage +//! +//! Every qualifying case is run in four groupings -- the whole payload in one call, block by block, +//! in 8-byte calls and in 3-byte calls -- so the batch paths and the byte path are both exercised +//! against real vectors. The payloads are a single block each, so counter *increment* is not +//! covered here; `ctr_tests.rs` covers it against the raw permutation across a 255-to-256 carry, +//! and the OpenSSL cross-check in `cli/tests/aes_ctr_cli_tests.rs` covers it end to end. +//! +//! The 6 MCT (Monte Carlo Test) groups are **not** implemented: their expected output is a +//! `resultsArray` produced by a chained update rule defined in the ACVP AES specification rather +//! than in SP 800-38A, and implementing it from anything else would be guesswork. + +use bouncycastle_aes_lowmemory::{Aes128, Aes192, Aes256}; +use bouncycastle_core::key_material::{ + KeyMaterial, KeyMaterialTrait, KeyType, do_hazardous_operations, +}; +use bouncycastle_core::traits::{ + ElectronicCodeBook, SecurityStrength, StreamCipherDecryptor, StreamCipherEncryptor, +}; +use bouncycastle_core_test_framework::FixedSeedRNG; +use bouncycastle_hex as hex; +use bouncycastle_modes::{Ctr, Decrypting, Encrypting}; +use serde_json::Value; +use std::collections::BTreeMap; +use std::fs; +use std::path::{Path, PathBuf}; + +const BLOCK_LEN: usize = 16; +/// The nonce length under test; the remaining 4 bytes of the block are the counter. +const NONCE_LEN: usize = 12; + +/// Candidate locations, covering `cargo test` run from the crate root or from the repo root. +const TEST_DATA_PATHS: [&str; 2] = [ + "../../../bc-test-data/crypto/aes_tdes_vectors/AES", + "../bc-test-data/crypto/aes_tdes_vectors/AES", +]; + +const REQUEST_FILE: &str = "ACVP-AES-CTR.4014537.req.json"; +const RESPONSE_FILE: &str = "ACVP-AES-CTR.4014537.rsp.json"; + +fn test_data_dir() -> Option { + for candidate in TEST_DATA_PATHS { + let path = Path::new(candidate); + if path.join(REQUEST_FILE).exists() && path.join(RESPONSE_FILE).exists() { + return Some(path.to_path_buf()); + } + } + println!( + "WARNING: bc-test-data not found (looked in {TEST_DATA_PATHS:?}); \ + ACVP AES-CTR tests will be skipped" + ); + None +} + +/// Builds a `KeyMaterial` from raw ACVP key bytes, including the all-zero keys. +/// +/// The ACVP set deliberately includes an all-zero key. `KeyMaterial` tags an all-zero buffer as +/// `KeyType::Zeroized` and will not promote it outside a `do_hazardous_operations` closure, which +/// is the right default -- so this opts in explicitly rather than the engine weakening its guard. +fn cipher_key(bytes: &[u8]) -> KeyMaterial { + assert_eq!(bytes.len(), N, "key length should match the parameter set"); + let mut key = KeyMaterial::::from_bytes_as_type(bytes, KeyType::SymmetricCipherKey) + .expect("ACVP key bytes fit the buffer"); + + if key.key_type() != KeyType::SymmetricCipherKey { + do_hazardous_operations(&mut key, |k| { + k.set_key_type(KeyType::SymmetricCipherKey)?; + k.set_security_strength(SecurityStrength::from_bytes(N)) + }) + .expect("promoting a NIST all-zero test key"); + } + key +} + +/// How to walk the bytes of one case. +#[derive(Clone, Copy, PartialEq, Eq, Debug)] +enum Grouping { + /// The whole payload in one call: eights, then pairs, then the remaining bytes singly. + Whole, + /// One whole block per call. + Blocks, + /// Eight bytes per call, so no call is a whole block and the keystream carries across calls. + Eights, + /// Three bytes per call, a size that lines up with neither the block nor the batch. + Threes, +} + +impl Grouping { + fn chunk_len(self, payload_len: usize) -> usize { + match self { + Grouping::Whole => payload_len.max(1), + Grouping::Blocks => BLOCK_LEN, + Grouping::Eights => 8, + Grouping::Threes => 3, + } + } +} + +/// Runs one CTR case in one direction, for a given permutation, under the given grouping. +/// +/// Encryption is driven through `do_encrypt_init_rng` with a `FixedSeedRNG` emitting the vector's +/// IV, and the returned init data is checked against that IV before any ciphertext is compared -- +/// so a change that ignored the RNG could not pass silently. +fn run_case( + key_bytes: &[u8], + nonce: [u8; NONCE_LEN], + input: &[u8], + encrypt: bool, + grouping: Grouping, +) -> Vec +where + P: ElectronicCodeBook, +{ + let key = cipher_key::(key_bytes); + let mut data = input.to_vec(); + let chunk = grouping.chunk_len(data.len()); + + if encrypt { + let (mut enc, got_iv) = + Ctr::::do_encrypt_init_rng( + &key, + &mut FixedSeedRNG::::new(nonce), + ) + .expect("encrypt init"); + assert_eq!(got_iv, nonce, "the pinned RNG should reproduce the vector's nonce"); + for piece in data.chunks_mut(chunk) { + enc.do_encrypt(piece).unwrap(); + } + } else { + let mut dec = + Ctr::::do_decrypt_init(&key, &nonce) + .expect("dec init"); + for piece in data.chunks_mut(chunk) { + dec.do_decrypt(piece).unwrap(); + } + } + + data +} + +/// Dispatches on key length, which is what selects the AES parameter set. +fn run_case_for_key_len( + key_bytes: &[u8], + nonce: [u8; NONCE_LEN], + input: &[u8], + encrypt: bool, + grouping: Grouping, +) -> Vec { + match key_bytes.len() { + 16 => run_case::(key_bytes, nonce, input, encrypt, grouping), + 24 => run_case::(key_bytes, nonce, input, encrypt, grouping), + 32 => run_case::(key_bytes, nonce, input, encrypt, grouping), + other => panic!("ACVP AES vectors should only use 16, 24 or 32 byte keys, got {other}"), + } +} + +fn decode(value: &Value, field: &str, tc_id: u64) -> Vec { + let s = value + .get(field) + .and_then(Value::as_str) + .unwrap_or_else(|| panic!("tcId {tc_id}: missing field {field}")); + hex::decode(s).unwrap_or_else(|_| panic!("tcId {tc_id}: bad hex in {field}")) +} + +#[test] +fn acvp_aes_ctr_known_answer_tests() { + let Some(dir) = test_data_dir() else { return }; + + let req: Value = serde_json::from_str( + &fs::read_to_string(dir.join(REQUEST_FILE)).expect("readable request file"), + ) + .expect("valid ACVP request JSON"); + let rsp: Value = serde_json::from_str( + &fs::read_to_string(dir.join(RESPONSE_FILE)).expect("readable response file"), + ) + .expect("valid ACVP response JSON"); + + // The response file carries only the answer, against a tcId. Index it. + let mut answers: BTreeMap = BTreeMap::new(); + for group in rsp + .get(1) + .and_then(|s| s.get("testGroups")) + .and_then(Value::as_array) + .expect("response testGroups") + { + for test in group.get("tests").and_then(Value::as_array).expect("response tests") { + let tc_id = test.get("tcId").and_then(Value::as_u64).expect("tcId"); + answers.insert(tc_id, test.clone()); + } + } + + let groups = req + .get(1) + .and_then(|s| s.get("testGroups")) + .and_then(Value::as_array) + .expect("request testGroups"); + + let mut checked = 0usize; + let mut skipped_mct = 0usize; + let mut skipped_nonzero_counter = 0usize; + let mut per_kind: BTreeMap = BTreeMap::new(); + + for group in groups { + let test_type = group.get("testType").and_then(Value::as_str).expect("testType"); + let direction = group.get("direction").and_then(Value::as_str).expect("direction"); + let encrypt = match direction { + "encrypt" => true, + "decrypt" => false, + other => panic!("unexpected direction {other}"), + }; + + for test in group.get("tests").and_then(Value::as_array).expect("tests") { + let tc_id = test.get("tcId").and_then(Value::as_u64).expect("tcId"); + + // Anything that is not a functional test is a Monte Carlo group. This file labels + // those "CTR" rather than "MCT", unlike the CBC and CFB sets, so the test is written + // against what an AFT case *is* rather than against one spelling of what it is not. + if test_type != "AFT" { + skipped_mct += 1; + continue; + } + + let answer = answers.get(&tc_id).unwrap_or_else(|| panic!("tcId {tc_id}: no answer")); + if answer.get("resultsArray").is_some() { + skipped_mct += 1; + continue; + } + + let key_bytes = decode(test, "key", tc_id); + let iv: [u8; BLOCK_LEN] = decode(test, "iv", tc_id).try_into().expect("a 16-byte IV"); + + // Only an initial counter block whose counter is already zero is expressible through + // this API; see the module docs. + if iv[NONCE_LEN..] != [0u8; BLOCK_LEN - NONCE_LEN] { + skipped_nonzero_counter += 1; + continue; + } + let nonce: [u8; NONCE_LEN] = iv[..NONCE_LEN].try_into().expect("the nonce"); + + // Input comes from the request, expected output from the response. + let (input_field, output_field) = if encrypt { ("pt", "ct") } else { ("ct", "pt") }; + let input = decode(test, input_field, tc_id); + let expected = decode(answer, output_field, tc_id); + + assert_eq!(input.len(), expected.len(), "tcId {tc_id}: length mismatch"); + for grouping in [Grouping::Whole, Grouping::Blocks, Grouping::Eights, Grouping::Threes] + { + let got = run_case_for_key_len(&key_bytes, nonce, &input, encrypt, grouping); + assert_eq!( + got, + expected, + "tcId {tc_id}: AES-{} CTR {direction}, {} bytes, {grouping:?} grouping", + key_bytes.len() * 8, + input.len() + ); + } + + *per_kind.entry(format!("AES-{} {direction}", key_bytes.len() * 8)).or_default() += 1; + checked += 1; + } + } + + for (kind, n) in &per_kind { + println!("ACVP AES-CTR {kind}: {n} cases"); + } + println!( + "ACVP AES-CTR: {checked} AFT cases checked in four groupings each; \ + {skipped_nonzero_counter} skipped for a non-zero initial counter, \ + {skipped_mct} MCT cases skipped" + ); + + // Guard against a silently-empty or partial run. + assert!(checked > 1800, "expected the zero-counter ACVP AFT cases, only checked {checked}"); + assert_eq!( + checked + skipped_nonzero_counter, + 2138, + "every AFT case should be either checked or explicitly skipped for its counter" + ); + assert_eq!(skipped_mct, 6, "the six Monte Carlo groups should be skipped, and only those"); + assert_eq!(per_kind.len(), 6, "expected all three key lengths in both directions"); +} diff --git a/crypto/modes/tests/acvp_ecb_tests.rs b/crypto/modes/tests/acvp_ecb_tests.rs new file mode 100644 index 00000000..e33d0593 --- /dev/null +++ b/crypto/modes/tests/acvp_ecb_tests.rs @@ -0,0 +1,221 @@ +//! Known-answer tests against the NIST ACVP `ACVP-AES-ECB` vectors from the `bc-test-data` repo, +//! driven through [`Ecb`] -- the mode API -- rather than the raw permutation. +//! +//! Requires `bc-test-data` to be cloned alongside this repository, i.e. at `../bc-test-data` +//! relative to the root of this git project. If it is absent the test prints a warning and passes, +//! matching the convention used by the other ACVP suites -- `cargo test` must stay green for someone +//! who has only cloned this repository. +//! +//! `crypto/aes-lowmemory/tests/acvp_tests.rs` runs the same file against the permutation's block +//! methods; this file is what pins that the mode adds nothing and loses nothing on the way: every +//! case is run through the `BlockCipherEncryptor` / `BlockCipherDecryptor` API in three groupings +//! -- block by block, in pairs with a remainder, and the whole payload in one hook call (which for +//! the 8-to-10-block cases reaches the eight-block path) -- in both directions. +//! +//! Unlike the CBC and CFB response files, the ECB one records `key`, `pt` and `ct` for every case, +//! so it is read alone and each case is checked in both directions regardless of its group's +//! declared direction. The MCT (Monte Carlo) groups carry a `resultsArray` defined by the ACVP AES +//! specification rather than SP 800-38A and are skipped, with the count reported. + +use bouncycastle_aes_lowmemory::{Aes128, Aes192, Aes256}; +use bouncycastle_core::key_material::{ + KeyMaterial, KeyMaterialTrait, KeyType, do_hazardous_operations, +}; +use bouncycastle_core::traits::{ + BlockCipherDecryptor, BlockCipherEncryptor, ElectronicCodeBook, SecurityStrength, +}; +use bouncycastle_hex as hex; +use bouncycastle_modes::{Decrypting, Ecb, Encrypting}; +use serde_json::Value; +use std::collections::BTreeMap; +use std::fs; +use std::path::{Path, PathBuf}; + +const BLOCK_LEN: usize = 16; + +/// Candidate locations, covering `cargo test` run from the crate root or from the repo root. +const TEST_DATA_PATHS: [&str; 2] = [ + "../../../bc-test-data/crypto/aes_tdes_vectors/AES", + "../bc-test-data/crypto/aes_tdes_vectors/AES", +]; + +const RESPONSE_FILE: &str = "ACVP-AES-ECB.4014527.rsp.json"; + +fn test_data_dir() -> Option { + for candidate in TEST_DATA_PATHS { + let path = Path::new(candidate); + if path.join(RESPONSE_FILE).exists() { + return Some(path.to_path_buf()); + } + } + println!( + "WARNING: bc-test-data not found (looked in {TEST_DATA_PATHS:?}); \ + ACVP AES-ECB mode tests will be skipped" + ); + None +} + +/// Builds a `KeyMaterial` from raw ACVP key bytes, including the all-zero keys the set contains. +fn cipher_key(bytes: &[u8]) -> KeyMaterial { + assert_eq!(bytes.len(), N, "key length should match the parameter set"); + let mut key = KeyMaterial::::from_bytes_as_type(bytes, KeyType::SymmetricCipherKey) + .expect("ACVP key bytes fit the buffer"); + if key.key_type() != KeyType::SymmetricCipherKey { + do_hazardous_operations(&mut key, |k| { + k.set_key_type(KeyType::SymmetricCipherKey)?; + k.set_security_strength(SecurityStrength::from_bytes(N)) + }) + .expect("promoting a NIST all-zero test key"); + } + key +} + +/// How to walk the blocks of one case. +#[derive(Clone, Copy, PartialEq, Eq, Debug)] +enum Grouping { + /// One block per call. + Single, + /// Two blocks per call, with a one-block remainder for odd lengths. + Pairs, + /// The whole payload in one hook call: eights, then pairs, then the remainder. + Whole, +} + +fn run_case( + key_bytes: &[u8], + input: &[[u8; BLOCK_LEN]], + encrypt: bool, + grouping: Grouping, +) -> Vec<[u8; BLOCK_LEN]> +where + P: ElectronicCodeBook, +{ + let key = cipher_key::(key_bytes); + let mut out = input.to_vec(); + + // Both directions have the same shape; `step` applies the right one to a slice of blocks. + let mut enc = encrypt + .then(|| Ecb::::do_encrypt_init(&key).expect("init").0); + let mut dec = (!encrypt).then(|| { + Ecb::::do_decrypt_init(&key, &[]).expect("init") + }); + let mut step = |blocks: &mut [[u8; BLOCK_LEN]]| { + if let Some(e) = enc.as_mut() { + e.do_encrypt_blocks(blocks).unwrap(); + } else { + dec.as_mut().unwrap().do_decrypt_blocks(blocks).unwrap(); + } + }; + + match grouping { + Grouping::Single => { + for block in out.iter_mut() { + step(core::slice::from_mut(block)); + } + } + Grouping::Pairs => { + let (pairs, tail) = out.as_chunks_mut::<2>(); + for pair in pairs { + step(pair); + } + step(tail); + } + Grouping::Whole => step(&mut out), + } + out +} + +fn run_case_for_key_len( + key_bytes: &[u8], + input: &[[u8; BLOCK_LEN]], + encrypt: bool, + grouping: Grouping, +) -> Vec<[u8; BLOCK_LEN]> { + match key_bytes.len() { + 16 => run_case::(key_bytes, input, encrypt, grouping), + 24 => run_case::(key_bytes, input, encrypt, grouping), + 32 => run_case::(key_bytes, input, encrypt, grouping), + other => panic!("ACVP AES vectors should only use 16, 24 or 32 byte keys, got {other}"), + } +} + +fn to_blocks(bytes: &[u8]) -> Vec<[u8; BLOCK_LEN]> { + assert_eq!(bytes.len() % BLOCK_LEN, 0, "ACVP ECB payloads are block-aligned"); + bytes.chunks(BLOCK_LEN).map(|c| c.try_into().unwrap()).collect() +} + +#[test] +fn acvp_aes_ecb_through_the_mode_api() { + let Some(dir) = test_data_dir() else { return }; + + let parsed: Value = serde_json::from_str( + &fs::read_to_string(dir.join(RESPONSE_FILE)).expect("readable response file"), + ) + .expect("valid ACVP JSON"); + let groups = parsed + .get(1) + .and_then(|set| set.get("testGroups")) + .and_then(Value::as_array) + .expect("testGroups array"); + + let mut checked = 0usize; + let mut multi_block = 0usize; + let mut eight_or_more = 0usize; + let mut skipped_mct = 0usize; + let mut per_key_len: BTreeMap = BTreeMap::new(); + + for group in groups { + for test in group.get("tests").and_then(Value::as_array).expect("tests array") { + let tc_id = test.get("tcId").and_then(Value::as_u64).expect("tcId"); + if test.get("resultsArray").is_some() { + skipped_mct += 1; + continue; + } + let get = |name: &str| -> Vec { + let s = test + .get(name) + .and_then(Value::as_str) + .unwrap_or_else(|| panic!("tcId {tc_id}: missing field {name}")); + hex::decode(s).unwrap_or_else(|_| panic!("tcId {tc_id}: bad hex in {name}")) + }; + let key = get("key"); + let pt = to_blocks(&get("pt")); + let ct = to_blocks(&get("ct")); + assert_eq!(pt.len(), ct.len(), "tcId {tc_id}: pt and ct differ in length"); + multi_block += usize::from(pt.len() > 1); + eight_or_more += usize::from(pt.len() >= 8); + + for grouping in [Grouping::Single, Grouping::Pairs, Grouping::Whole] { + assert_eq!( + run_case_for_key_len(&key, &pt, true, grouping), + ct, + "tcId {tc_id}: AES-{} ECB encrypt, {} blocks, {grouping:?}", + key.len() * 8, + pt.len() + ); + assert_eq!( + run_case_for_key_len(&key, &ct, false, grouping), + pt, + "tcId {tc_id}: AES-{} ECB decrypt, {} blocks, {grouping:?}", + key.len() * 8, + pt.len() + ); + } + *per_key_len.entry(key.len() * 8).or_default() += 1; + checked += 1; + } + } + + for (bits, n) in &per_key_len { + println!("ACVP AES-ECB via Ecb, AES-{bits}: {n} cases, both directions"); + } + println!( + "ACVP AES-ECB via Ecb: {checked} AFT cases checked in three groupings each \ + ({multi_block} multi-block, {eight_or_more} of eight or more blocks); {skipped_mct} MCT cases skipped" + ); + + // Guard against a silently-empty or partial run. + assert!(checked > 2000, "expected the full ACVP AFT set, only checked {checked}"); + assert!(eight_or_more > 0, "expected cases that reach the eight-block path"); + assert_eq!(per_key_len.len(), 3, "expected all three key lengths"); +} diff --git a/crypto/modes/tests/acvp_tests.rs b/crypto/modes/tests/acvp_tests.rs new file mode 100644 index 00000000..37b48d96 --- /dev/null +++ b/crypto/modes/tests/acvp_tests.rs @@ -0,0 +1,311 @@ +//! Known-answer tests against the NIST ACVP `ACVP-AES-CBC` vectors from the `bc-test-data` repo. +//! +//! Requires `bc-test-data` to be cloned alongside this repository, i.e. at `../bc-test-data` +//! relative to the root of this git project. If it is absent the test prints a warning and passes, +//! matching the convention used by the ML-KEM, ML-DSA and `aes-lowmemory` suites -- `cargo test` +//! must stay green for someone who has only cloned this repository. +//! +//! These are the counterpart to `crypto/aes-lowmemory/tests/acvp_tests.rs`, which consumes the +//! `ACVP-AES-ECB` file to test the raw permutation. CBC is a mode, so its vectors belong here. +//! +//! # Joining the request and response files +//! +//! Unlike the ECB response file, which echoes `key`, `pt` and `ct` for every case, the CBC response +//! file carries **only the answer** (`ct` for an encrypt group, `pt` for a decrypt group) against a +//! `tcId`. The key, IV and input live in the request file, and the group metadata that says which +//! direction a case is -- `direction` and `keyLen` -- lives only there too. So both files are read +//! and joined on `tcId`; there is no way to drive this from the response file alone. +//! +//! # Coverage +//! +//! 2150 AFT (Algorithm Functional Test) cases across all three key lengths and both directions, +//! including 60 whose payload spans 2 to 10 blocks. Every case is run **twice**: once block by +//! block, and once in pairs with a one-block remainder for odd lengths. The second pass is what +//! puts the multi-block cases through `ElectronicCodeBook::decrypt_blocks2`, so the pair path is +//! exercised against real vectors and not only against the toy in `cbc_tests.rs`. +//! +//! The 6 MCT (Monte Carlo Test) groups are **not** implemented: their expected output is a +//! `resultsArray` produced by a chained update rule defined in the ACVP AES specification rather +//! than in SP 800-38A, and implementing it from anything else would be guesswork. The test reports +//! how many it skipped so the gap stays visible. + +use bouncycastle_aes_lowmemory::{Aes128, Aes192, Aes256}; +use bouncycastle_core::key_material::{ + KeyMaterial, KeyMaterialTrait, KeyType, do_hazardous_operations, +}; +use bouncycastle_core::traits::{ + BlockCipherDecryptor, BlockCipherEncryptor, ElectronicCodeBook, SecurityStrength, +}; +use bouncycastle_core_test_framework::FixedSeedRNG; +use bouncycastle_hex as hex; +use bouncycastle_modes::{Cbc, Decrypting, Encrypting}; +use serde_json::Value; +use std::collections::BTreeMap; +use std::fs; +use std::path::{Path, PathBuf}; + +const BLOCK_LEN: usize = 16; + +/// Candidate locations, covering `cargo test` run from the crate root or from the repo root. +const TEST_DATA_PATHS: [&str; 2] = [ + "../../../bc-test-data/crypto/aes_tdes_vectors/AES", + "../bc-test-data/crypto/aes_tdes_vectors/AES", +]; + +const REQUEST_FILE: &str = "ACVP-AES-CBC.4014528.req.json"; +const RESPONSE_FILE: &str = "ACVP-AES-CBC.4014528.rsp.json"; + +fn test_data_dir() -> Option { + for candidate in TEST_DATA_PATHS { + let path = Path::new(candidate); + if path.join(REQUEST_FILE).exists() && path.join(RESPONSE_FILE).exists() { + return Some(path.to_path_buf()); + } + } + println!( + "WARNING: bc-test-data not found (looked in {TEST_DATA_PATHS:?}); \ + ACVP AES-CBC tests will be skipped" + ); + None +} + +/// Builds a `KeyMaterial` from raw ACVP key bytes, including the all-zero keys. +/// +/// The ACVP set deliberately includes an all-zero key. `KeyMaterial` tags an all-zero buffer as +/// `KeyType::Zeroized` and will not promote it outside a `do_hazardous_operations` closure, which +/// is the right default -- so this opts in explicitly rather than the engine weakening its guard. +fn cipher_key(bytes: &[u8]) -> KeyMaterial { + assert_eq!(bytes.len(), N, "key length should match the parameter set"); + let mut key = KeyMaterial::::from_bytes_as_type(bytes, KeyType::SymmetricCipherKey) + .expect("ACVP key bytes fit the buffer"); + + if key.key_type() != KeyType::SymmetricCipherKey { + do_hazardous_operations(&mut key, |k| { + k.set_key_type(KeyType::SymmetricCipherKey)?; + k.set_security_strength(SecurityStrength::from_bytes(N)) + }) + .expect("promoting a NIST all-zero test key"); + } + key +} + +/// How to walk the blocks of one case. +#[derive(Clone, Copy, PartialEq, Eq, Debug)] +enum Grouping { + /// One block per call. Never forms a pair. + Single, + /// Two blocks per call, with a one-block remainder for odd lengths. Uses the pair path. + Pairs, +} + +/// Runs one CBC case in one direction, for a given permutation, under the given grouping. +/// +/// Encryption is driven through `do_encrypt_init_rng` with a `FixedSeedRNG` emitting the vector's +/// IV, and the returned init data is checked against that IV before any ciphertext is compared -- +/// so a change that ignored the RNG could not pass silently. +fn run_case( + key_bytes: &[u8], + iv: [u8; BLOCK_LEN], + input: &[[u8; BLOCK_LEN]], + encrypt: bool, + grouping: Grouping, +) -> Vec<[u8; BLOCK_LEN]> +where + P: ElectronicCodeBook, +{ + let key = cipher_key::(key_bytes); + let mut out: Vec<[u8; BLOCK_LEN]> = Vec::with_capacity(input.len()); + + if encrypt { + let (mut enc, got_iv) = Cbc::::do_encrypt_init_rng( + &key, + &mut FixedSeedRNG::::new(iv), + ) + .expect("encrypt init"); + assert_eq!(got_iv, iv, "the pinned RNG should reproduce the vector's IV"); + + match grouping { + Grouping::Single => { + for block in input { + let mut c = *block; + enc.do_encrypt(&mut c).unwrap(); + out.push(c); + } + } + Grouping::Pairs => { + let (pairs, tail) = input.as_chunks::<2>(); + for pair in pairs { + let mut c = *pair; + enc.do_encrypt_blocks(&mut c).unwrap(); + out.extend_from_slice(&c); + } + for block in tail { + let mut c = *block; + enc.do_encrypt(&mut c).unwrap(); + out.push(c); + } + } + } + } else { + let mut dec = + Cbc::::do_decrypt_init(&key, &iv).expect("dec init"); + + match grouping { + Grouping::Single => { + for block in input { + let mut p = *block; + dec.do_decrypt(&mut p).unwrap(); + out.push(p); + } + } + Grouping::Pairs => { + let (pairs, tail) = input.as_chunks::<2>(); + for pair in pairs { + let mut p = *pair; + dec.do_decrypt_blocks(&mut p).unwrap(); + out.extend_from_slice(&p); + } + for block in tail { + let mut p = *block; + dec.do_decrypt(&mut p).unwrap(); + out.push(p); + } + } + } + } + + out +} + +/// Dispatches on key length, which is what selects the AES parameter set. +fn run_case_for_key_len( + key_bytes: &[u8], + iv: [u8; BLOCK_LEN], + input: &[[u8; BLOCK_LEN]], + encrypt: bool, + grouping: Grouping, +) -> Vec<[u8; BLOCK_LEN]> { + match key_bytes.len() { + 16 => run_case::(key_bytes, iv, input, encrypt, grouping), + 24 => run_case::(key_bytes, iv, input, encrypt, grouping), + 32 => run_case::(key_bytes, iv, input, encrypt, grouping), + other => panic!("ACVP AES vectors should only use 16, 24 or 32 byte keys, got {other}"), + } +} + +fn to_blocks(bytes: &[u8]) -> Vec<[u8; BLOCK_LEN]> { + assert_eq!(bytes.len() % BLOCK_LEN, 0, "ACVP CBC payloads are block-aligned"); + bytes.chunks(BLOCK_LEN).map(|c| c.try_into().unwrap()).collect() +} + +fn decode(value: &Value, field: &str, tc_id: u64) -> Vec { + let s = value + .get(field) + .and_then(Value::as_str) + .unwrap_or_else(|| panic!("tcId {tc_id}: missing field {field}")); + hex::decode(s).unwrap_or_else(|_| panic!("tcId {tc_id}: bad hex in {field}")) +} + +#[test] +fn acvp_aes_cbc_known_answer_tests() { + let Some(dir) = test_data_dir() else { return }; + + let req: Value = serde_json::from_str( + &fs::read_to_string(dir.join(REQUEST_FILE)).expect("readable request file"), + ) + .expect("valid ACVP request JSON"); + let rsp: Value = serde_json::from_str( + &fs::read_to_string(dir.join(RESPONSE_FILE)).expect("readable response file"), + ) + .expect("valid ACVP response JSON"); + + // The response file carries only the answer, against a tcId. Index it. + let mut answers: BTreeMap = BTreeMap::new(); + for group in rsp + .get(1) + .and_then(|s| s.get("testGroups")) + .and_then(Value::as_array) + .expect("response testGroups") + { + for test in group.get("tests").and_then(Value::as_array).expect("response tests") { + let tc_id = test.get("tcId").and_then(Value::as_u64).expect("tcId"); + answers.insert(tc_id, test.clone()); + } + } + + let groups = req + .get(1) + .and_then(|s| s.get("testGroups")) + .and_then(Value::as_array) + .expect("request testGroups"); + + let mut checked = 0usize; + let mut multi_block = 0usize; + let mut skipped_mct = 0usize; + let mut per_kind: BTreeMap = BTreeMap::new(); + + for group in groups { + let test_type = group.get("testType").and_then(Value::as_str).expect("testType"); + let direction = group.get("direction").and_then(Value::as_str).expect("direction"); + let encrypt = match direction { + "encrypt" => true, + "decrypt" => false, + other => panic!("unexpected direction {other}"), + }; + + for test in group.get("tests").and_then(Value::as_array).expect("tests") { + let tc_id = test.get("tcId").and_then(Value::as_u64).expect("tcId"); + + if test_type == "MCT" { + skipped_mct += 1; + continue; + } + + let answer = answers.get(&tc_id).unwrap_or_else(|| panic!("tcId {tc_id}: no answer")); + if answer.get("resultsArray").is_some() { + skipped_mct += 1; + continue; + } + + let key_bytes = decode(test, "key", tc_id); + let iv: [u8; BLOCK_LEN] = decode(test, "iv", tc_id).try_into().expect("a 16-byte IV"); + + // Input comes from the request, expected output from the response. + let (input_field, output_field) = if encrypt { ("pt", "ct") } else { ("ct", "pt") }; + let input = to_blocks(&decode(test, input_field, tc_id)); + let expected = to_blocks(&decode(answer, output_field, tc_id)); + + assert_eq!(input.len(), expected.len(), "tcId {tc_id}: length mismatch"); + if input.len() > 1 { + multi_block += 1; + } + + for grouping in [Grouping::Single, Grouping::Pairs] { + let got = run_case_for_key_len(&key_bytes, iv, &input, encrypt, grouping); + assert_eq!( + got, + expected, + "tcId {tc_id}: AES-{} CBC {direction}, {} blocks, {grouping:?} grouping", + key_bytes.len() * 8, + input.len() + ); + } + + *per_kind.entry(format!("AES-{} {direction}", key_bytes.len() * 8)).or_default() += 1; + checked += 1; + } + } + + for (kind, n) in &per_kind { + println!("ACVP AES-CBC {kind}: {n} cases"); + } + println!( + "ACVP AES-CBC: {checked} AFT cases checked in two groupings each \ + ({multi_block} of them multi-block); {skipped_mct} MCT cases skipped" + ); + + // Guard against a silently-empty or partial run. + assert!(checked > 2000, "expected the full ACVP AFT set, only checked {checked}"); + assert!(multi_block >= 60, "expected the multi-block cases, found {multi_block}"); + assert_eq!(per_kind.len(), 6, "expected all three key lengths in both directions"); +} diff --git a/crypto/modes/tests/cbc_tests.rs b/crypto/modes/tests/cbc_tests.rs new file mode 100644 index 00000000..28185e83 --- /dev/null +++ b/crypto/modes/tests/cbc_tests.rs @@ -0,0 +1,435 @@ +//! Structural tests for CBC, driven by a toy permutation. +//! +//! These check the properties of the *mode* -- chaining, call sequencing, the pair/remainder split, +//! direction typing, SP 800-38A Appendix D error propagation -- independently of any real cipher. +//! The known-answer tests against SP 800-38A Appendix F.2 are in `sp800_38a_tests.rs`. + +mod common; + +use bouncycastle_aes_lowmemory::{Aes128, Aes192, Aes256}; +use bouncycastle_core::key_material::{KeyMaterial, KeyType}; +use bouncycastle_core::traits::{BlockCipherDecryptor, BlockCipherEncryptor}; +use bouncycastle_core_test_framework::electronic_code_book::TestFrameworkElectronicCodeBook; +use bouncycastle_core_test_framework::symmetric_ciphers::TestFrameworkBlockCipher; +use bouncycastle_modes::{Cbc, Decrypting, Encrypting}; +use common::{SwappedEightToy, SwappedPairToy, TOY_LEN, Toy, toy_key}; + +type ToyCbc

= Cbc; +type SwappedCbc = Cbc; +type SwappedEightCbc = Cbc; + +/// The implementor hook `do_encrypt_blocks`, by value, for tests whose data is block-shaped. +fn enc_blocks( + enc: &mut impl BlockCipherEncryptor, + plaintext: &[[u8; TOY_LEN]; N], +) -> [[u8; TOY_LEN]; N] { + let mut blocks = *plaintext; + enc.do_encrypt_blocks(&mut blocks).unwrap(); + blocks +} + +/// The implementor hook `do_decrypt_blocks`, by value. +fn dec_blocks( + dec: &mut impl BlockCipherDecryptor, + ciphertext: &[[u8; TOY_LEN]; N], +) -> [[u8; TOY_LEN]; N] { + let mut blocks = *ciphertext; + dec.do_decrypt_blocks(&mut blocks).unwrap(); + blocks +} + +/// The flat streaming method `do_encrypt`, by value. +fn enc_flat( + enc: &mut impl BlockCipherEncryptor, + plaintext: &[u8; LEN], +) -> [u8; LEN] { + let mut data = *plaintext; + enc.do_encrypt(&mut data).unwrap(); + data +} + +/// The flat streaming method `do_decrypt`, by value. +fn dec_flat( + dec: &mut impl BlockCipherDecryptor, + ciphertext: &[u8; LEN], +) -> [u8; LEN] { + let mut data = *ciphertext; + dec.do_decrypt(&mut data).unwrap(); + data +} + +// ---- the toy itself, and the mode, against the shared frameworks ------------------------- + +/// The toy must be a real permutation before any conclusion drawn from it is worth anything. +#[test] +fn the_toy_permutation_conforms_to_the_trait() { + TestFrameworkElectronicCodeBook::new().test::(); +} + +#[test] +fn cbc_conforms_to_the_block_cipher_framework() { + TestFrameworkBlockCipher::new() + .test::, ToyCbc>(); +} + +// ---- chaining and call sequencing -------------------------------------------------------- + +/// Encrypting `n` blocks must not depend on how the calls are grouped, and likewise for +/// decryption. This is the "a sequence of calls is equivalent to one call over the concatenation" +/// contract of the trait, and for CBC it is entirely about the chaining value surviving across +/// calls. +/// +/// The odd groupings matter for decryption specifically: `N = 3` and `N = 5` leave a one-block +/// remainder after the pair loop, and `N = 1` skips the pair loop altogether. +#[test] +fn call_grouping_does_not_change_the_result() { + let key = toy_key(); + let plaintext: [[u8; TOY_LEN]; 8] = + core::array::from_fn(|i| core::array::from_fn(|j| (i * TOY_LEN + j) as u8)); + + // Both encryption runs must use the same IV to be comparable, so pin it with the fixed RNG + // rather than letting `do_encrypt_init` generate a fresh one. + let iv: [u8; TOY_LEN] = core::array::from_fn(|i| 0xF0 ^ (i as u8)); + let pinned_rng = || bouncycastle_core_test_framework::FixedSeedRNG::::new(iv); + + // Reference: all eight blocks in one call. + let (mut enc, got_iv) = + ToyCbc::::do_encrypt_init_rng(&key, &mut pinned_rng()).unwrap(); + assert_eq!(got_iv, iv, "the pinned RNG should reproduce the IV"); + let reference = enc_blocks(&mut enc, &plaintext); + + // The same eight blocks, grouped every way that exercises a different code path. + let (mut enc, _) = ToyCbc::::do_encrypt_init_rng(&key, &mut pinned_rng()).unwrap(); + let mut got = [[0u8; TOY_LEN]; 8]; + let a = enc_flat(&mut enc, &plaintext[0]); // one block, flat + let b = enc_blocks(&mut enc, &[plaintext[1], plaintext[2]]); // N = 2 + let c = enc_blocks(&mut enc, &[plaintext[3], plaintext[4], plaintext[5]]); // N = 3 + let d = enc_blocks(&mut enc, &[plaintext[6], plaintext[7]]); // N = 2 + got[0] = a; + got[1..3].copy_from_slice(&b); + got[3..6].copy_from_slice(&c); + got[6..8].copy_from_slice(&d); + + assert_eq!(got, reference, "grouping must not change the ciphertext"); + + // Now the decrypt side: one call vs several groupings, all from the same ciphertext. + let ct = reference; + + let mut dec = ToyCbc::::do_decrypt_init(&key, &iv).unwrap(); + let all_at_once = dec_blocks(&mut dec, &ct); + assert_eq!(all_at_once, plaintext); + + for grouping in [1usize, 2, 4] { + let mut dec = ToyCbc::::do_decrypt_init(&key, &iv).unwrap(); + let mut out = [[0u8; TOY_LEN]; 8]; + let mut at = 0; + while at < 8 { + match grouping { + 1 => { + out[at] = dec_flat(&mut dec, &ct[at]); + } + 2 => { + let p = dec_blocks(&mut dec, &[ct[at], ct[at + 1]]); + out[at..at + 2].copy_from_slice(&p); + } + _ => { + let p = dec_blocks(&mut dec, &[ct[at], ct[at + 1], ct[at + 2], ct[at + 3]]); + out[at..at + 4].copy_from_slice(&p); + } + } + at += grouping; + } + assert_eq!(out, plaintext, "decrypting in groups of {grouping}"); + } + + // N = 3 and N = 5 both leave a one-block remainder after the pair loop. + let mut dec = ToyCbc::::do_decrypt_init(&key, &iv).unwrap(); + let three = dec_blocks(&mut dec, &[ct[0], ct[1], ct[2]]); + let five = dec_blocks(&mut dec, &[ct[3], ct[4], ct[5], ct[6], ct[7]]); + assert_eq!(three, [plaintext[0], plaintext[1], plaintext[2]]); + assert_eq!(five, [plaintext[3], plaintext[4], plaintext[5], plaintext[6], plaintext[7]]); +} + +/// The pair path in `do_decrypt_blocks` must actually be taken. +/// +/// [`SwappedPairToy`] returns its two pair results in the wrong order while its single-block +/// methods are correct. So a CBC decryptor that uses `decrypt_blocks2` gives the wrong answer for +/// even-length input, and the right answer for a single block. If both came out right, the pair +/// path would be dead code and every claim about it would be untested. +#[test] +fn the_pair_path_is_really_used() { + let key = toy_key(); + let plaintext = [[0xA5u8; TOY_LEN], [0x5Au8; TOY_LEN]]; + + // The correct toy round-trips. + let (mut enc, iv) = ToyCbc::::do_encrypt_init(&key).unwrap(); + let ct = enc_blocks(&mut enc, &plaintext); + let mut dec = ToyCbc::::do_decrypt_init(&key, &iv).unwrap(); + assert_eq!(dec_blocks(&mut dec, &ct), plaintext); + + // The swapped-pair toy encrypts identically (encryption is serial and never pairs)... + let (mut enc, iv) = SwappedCbc::::do_encrypt_init(&key).unwrap(); + let ct = enc_blocks(&mut enc, &plaintext); + + // ...but decrypting the pair together must now be wrong, because the pair path is used. + let mut dec = SwappedCbc::::do_decrypt_init(&key, &iv).unwrap(); + assert_ne!( + dec_blocks(&mut dec, &ct), + plaintext, + "decrypting a pair must go through decrypt_blocks2" + ); + + // Decrypting one block at a time avoids the pair path, so it is correct even for this toy. + let mut dec = SwappedCbc::::do_decrypt_init(&key, &iv).unwrap(); + let p0 = dec_flat(&mut dec, &ct[0]); + let p1 = dec_flat(&mut dec, &ct[1]); + assert_eq!([p0, p1], plaintext, "the single-block path must not pair"); +} + +/// The eight-block path in `do_decrypt_blocks` must actually be taken, and only for full eights. +/// +/// [`SwappedEightToy`] returns its eight results rotated while its pair and single-block methods +/// are correct. So a CBC decryptor that uses `decrypt_blocks8` gives the wrong answer for eight +/// blocks handed over together, and the right answer for the same eight blocks handed over as +/// two fours (pairs) or one at a time. Nine blocks are wrong too: eight, then one. +#[test] +fn the_eight_block_path_is_really_used() { + let key = toy_key(); + let plaintext: [[u8; TOY_LEN]; 9] = core::array::from_fn(|i| [0x10 * i as u8 + 1; TOY_LEN]); + + // The correct toy round-trips nine blocks. + let (mut enc, iv) = ToyCbc::::do_encrypt_init(&key).unwrap(); + let ct = enc_blocks(&mut enc, &plaintext); + let mut dec = ToyCbc::::do_decrypt_init(&key, &iv).unwrap(); + assert_eq!(dec_blocks(&mut dec, &ct), plaintext); + + // The rotated-eight toy encrypts identically (encryption is serial and never batches)... + let (mut enc, iv) = SwappedEightCbc::::do_encrypt_init(&key).unwrap(); + let ct = enc_blocks(&mut enc, &plaintext); + + // ...but decrypting nine together must be wrong, because the first eight take the eight path. + let mut dec = SwappedEightCbc::::do_decrypt_init(&key, &iv).unwrap(); + assert_ne!( + dec_blocks(&mut dec, &ct), + plaintext, + "eight blocks must go through decrypt_blocks8" + ); + + // Exactly eight together is wrong for the same reason. + let eight: [[u8; TOY_LEN]; 8] = ct[..8].try_into().unwrap(); + let mut dec = SwappedEightCbc::::do_decrypt_init(&key, &iv).unwrap(); + assert_ne!(&dec_blocks(&mut dec, &eight)[..], &plaintext[..8]); + + // Two fours go through the pair path and are correct; so is the ninth block on its own. + let mut dec = SwappedEightCbc::::do_decrypt_init(&key, &iv).unwrap(); + let first: [[u8; TOY_LEN]; 4] = ct[..4].try_into().unwrap(); + let second: [[u8; TOY_LEN]; 4] = ct[4..8].try_into().unwrap(); + assert_eq!( + &dec_blocks(&mut dec, &first)[..], + &plaintext[..4], + "fewer than eight must not batch" + ); + assert_eq!(&dec_blocks(&mut dec, &second)[..], &plaintext[4..8]); + assert_eq!(dec_flat(&mut dec, &ct[8]), plaintext[8]); +} + +/// The flat streaming method must agree with the block-shaped implementor hook. +#[test] +fn flat_streaming_agrees_with_the_block_hook() { + let key = toy_key(); + let plaintext = [[0x11u8; TOY_LEN], [0x22u8; TOY_LEN], [0x33u8; TOY_LEN]]; + let flat_plaintext: [u8; 3 * TOY_LEN] = plaintext.as_flattened().try_into().unwrap(); + + let (mut enc, iv) = ToyCbc::::do_encrypt_init(&key).unwrap(); + let flat_ct = enc_flat(&mut enc, &flat_plaintext); + + let (mut enc, iv2) = ToyCbc::::do_encrypt_init_rng( + &key, + &mut bouncycastle_core_test_framework::FixedSeedRNG::::new(iv), + ) + .unwrap(); + assert_eq!(iv2, iv, "the pinned RNG should reproduce the IV"); + let block_ct = enc_blocks(&mut enc, &plaintext); + assert_eq!(*block_ct.as_flattened(), flat_ct, "flat streaming must equal the block hook"); + + let mut dec = ToyCbc::::do_decrypt_init(&key, &iv).unwrap(); + assert_eq!(dec_blocks(&mut dec, &block_ct), plaintext); + let mut dec = ToyCbc::::do_decrypt_init(&key, &iv).unwrap(); + assert_eq!(dec_flat(&mut dec, &flat_ct), flat_plaintext); +} + +// ---- SP 800-38A Appendix D error propagation --------------------------------------------- + +/// Appendix D: "In the CBC mode, if bit errors occur in the IV, then the first ciphertext block +/// will be decrypted incorrectly, and bit errors will occur in exactly the same bit positions as +/// in the IV; the decryptions of the other ciphertext blocks are not affected." +/// +/// This is a property of the construction (`P1 = CIPH^-1(C1) XOR IV`), so it holds for any +/// permutation, and getting it wrong would mean the IV is not being XOR-ed where the spec says. +#[test] +fn an_iv_bit_error_flips_exactly_that_bit_of_the_first_block() { + let key = toy_key(); + let plaintext = [[0x00u8; TOY_LEN], [0x11u8; TOY_LEN], [0x22u8; TOY_LEN]]; + + let (mut enc, iv) = ToyCbc::::do_encrypt_init(&key).unwrap(); + let ct = enc_blocks(&mut enc, &plaintext); + + for byte in 0..TOY_LEN { + for bit in 0..8 { + let mut corrupt_iv = iv; + corrupt_iv[byte] ^= 1 << bit; + + let mut dec = ToyCbc::::do_decrypt_init(&key, &corrupt_iv).unwrap(); + let got = dec_blocks(&mut dec, &ct); + + let mut expected = plaintext; + expected[0][byte] ^= 1 << bit; + assert_eq!( + got, expected, + "IV byte {byte} bit {bit}: only that bit of P1 should change" + ); + } + } +} + +/// Appendix D, the ciphertext half: bit errors in `Cj` randomise the decryption of `Cj` and flip +/// the same bit positions of `Cj+1`'s decryption, leaving later blocks alone. +#[test] +fn a_ciphertext_bit_error_affects_only_two_blocks() { + let key = toy_key(); + let plaintext = [[0x00u8; TOY_LEN], [0x11u8; TOY_LEN], [0x22u8; TOY_LEN], [0x33u8; TOY_LEN]]; + + let (mut enc, iv) = ToyCbc::::do_encrypt_init(&key).unwrap(); + let ct = enc_blocks(&mut enc, &plaintext); + + let mut corrupt = ct; + corrupt[1][3] ^= 0b0010_0000; + + let mut dec = ToyCbc::::do_decrypt_init(&key, &iv).unwrap(); + let got = dec_blocks(&mut dec, &corrupt); + + assert_eq!(got[0], plaintext[0], "P1 depends only on C1 and the IV"); + assert_ne!(got[1], plaintext[1], "P2 comes from the corrupted C2"); + // P3 = CIPH^-1(C3) XOR C2, so the flipped bit of C2 appears verbatim in P3. + let mut expected_p3 = plaintext[2]; + expected_p3[3] ^= 0b0010_0000; + assert_eq!(got[2], expected_p3, "P3 should show the same bit flipped, and nothing else"); + assert_eq!(got[3], plaintext[3], "P4 is unaffected"); +} + +// ---- IV handling ------------------------------------------------------------------------- + +/// Two encryption flows under the same key must not reuse an IV. The framework checks this too; +/// repeated here because for CBC it is the single most important operational requirement. +#[test] +fn each_encryption_gets_a_fresh_iv() { + let key = toy_key(); + let mut seen = std::collections::BTreeSet::new(); + for _ in 0..64 { + let (_, iv) = ToyCbc::::do_encrypt_init(&key).unwrap(); + assert!(seen.insert(iv), "IV repeated across encryptions: {iv:02x?}"); + } +} + +/// Identical plaintext under the same key must give different ciphertext, because the IV differs. +/// This is the property ECB lacks and the reason CBC needs an IV at all. +#[test] +fn identical_plaintext_gives_different_ciphertext() { + let key = toy_key(); + let plaintext = [0x77u8; 2 * TOY_LEN]; + + let mut first = plaintext; + ToyCbc::::encrypt(&key, &mut first).unwrap(); + let mut second = plaintext; + ToyCbc::::encrypt(&key, &mut second).unwrap(); + assert_ne!(first, second); + + // ...and, within one message, two identical plaintext blocks must not give identical + // ciphertext blocks either, because the chaining value differs. + assert_ne!( + first[..TOY_LEN], + first[TOY_LEN..], + "chaining should break the ECB pattern within a message" + ); +} + +// ---- key handling ------------------------------------------------------------------------ + +#[test] +fn a_key_of_the_wrong_type_is_rejected() { + let bytes: [u8; TOY_LEN] = core::array::from_fn(|i| (i as u8) + 1); + let seed = KeyMaterial::::from_bytes_as_type(&bytes, KeyType::Seed).unwrap(); + assert!(ToyCbc::::do_encrypt_init(&seed).is_err()); + assert!(ToyCbc::::do_decrypt_init(&seed, &[0u8; TOY_LEN]).is_err()); +} + +// ---- memory ------------------------------------------------------------------------------ + +/// Pins the "Memory Usage" table in the crate docs. +#[test] +fn sizes_match_the_documented_memory_table() { + use core::mem::size_of; + + assert_eq!(size_of::>(), 176 + 16); + assert_eq!(size_of::>(), 208 + 16); + assert_eq!(size_of::>(), 240 + 16); + + // The direction marker is free, and does not change the layout. + assert_eq!( + size_of::>(), + size_of::>() + ); + assert_eq!(size_of::(), 0); + assert_eq!(size_of::(), 0); + + // ...and the general rule the docs state. + assert_eq!(size_of::>(), size_of::() + 16); +} + +/// The one-shots (`encrypt` / `decrypt` on a `[u8; LEN]`, in place) must produce exactly what the +/// streaming API produces over the same blocks, for an odd block count (pairs plus a one-block +/// tail) and an even one (pairs only), in both directions. +#[test] +fn one_shots_agree_with_the_streaming_api() { + let key = toy_key(); + let iv: [u8; TOY_LEN] = core::array::from_fn(|i| 0x0F ^ (i as u8)); + let pinned_rng = || bouncycastle_core_test_framework::FixedSeedRNG::::new(iv); + + // 3 blocks = 48 bytes: one pair and a tail. + let flat3: [u8; 3 * TOY_LEN] = core::array::from_fn(|i| (i * 7) as u8); + let blocks3: [[u8; TOY_LEN]; 3] = + core::array::from_fn(|b| flat3[b * TOY_LEN..][..TOY_LEN].try_into().unwrap()); + let (iv_a, ct_blocks) = { + let (mut enc, iv) = + ToyCbc::::do_encrypt_init_rng(&key, &mut pinned_rng()).unwrap(); + (iv, enc_blocks(&mut enc, &blocks3)) + }; + let mut buf = flat3; + let iv_b = ToyCbc::::encrypt_rng(&key, &mut pinned_rng(), &mut buf).unwrap(); + assert_eq!(iv_a, iv_b); + assert_eq!(buf, *ct_blocks.as_flattened(), "3 blocks: one-shot must equal streaming"); + ToyCbc::::decrypt(&key, &iv, &mut buf).unwrap(); + assert_eq!(buf, flat3); + + // 4 blocks = 64 bytes: pairs only, no tail. + let flat4: [u8; 4 * TOY_LEN] = core::array::from_fn(|i| (i * 13 + 1) as u8); + let blocks4: [[u8; TOY_LEN]; 4] = + core::array::from_fn(|b| flat4[b * TOY_LEN..][..TOY_LEN].try_into().unwrap()); + let ct_blocks = { + let (mut enc, _) = + ToyCbc::::do_encrypt_init_rng(&key, &mut pinned_rng()).unwrap(); + enc_blocks(&mut enc, &blocks4) + }; + let mut buf = flat4; + ToyCbc::::encrypt_rng(&key, &mut pinned_rng(), &mut buf).unwrap(); + assert_eq!(buf, *ct_blocks.as_flattened(), "4 blocks: one-shot must equal streaming"); + ToyCbc::::decrypt(&key, &iv, &mut buf).unwrap(); + assert_eq!(buf, flat4); + + // The OS-RNG variant round-trips too. + let mut buf = flat3; + let iv_fresh = ToyCbc::::encrypt(&key, &mut buf).unwrap(); + assert_ne!(buf, flat3); + ToyCbc::::decrypt(&key, &iv_fresh, &mut buf).unwrap(); + assert_eq!(buf, flat3); +} diff --git a/crypto/modes/tests/cfb8_tests.rs b/crypto/modes/tests/cfb8_tests.rs new file mode 100644 index 00000000..bfea1b17 --- /dev/null +++ b/crypto/modes/tests/cfb8_tests.rs @@ -0,0 +1,709 @@ +//! Structural tests for CFB8, driven by a toy permutation. +//! +//! These check the properties of the *mode* -- the shift register, the one-byte segment, call +//! sequencing at arbitrary byte boundaries, the batch split on the decrypt side, direction typing, +//! SP 800-38A Appendix D error propagation, and the "forward cipher function only" rule of +//! Sec 6.3 -- independently of any real cipher. The known-answer tests against SP 800-38A +//! Appendix F.3.7-F.3.12 are in `sp800_38a_cfb8_tests.rs`, and the ACVP CFB8 set is in +//! `acvp_cfb8_tests.rs`. +//! +//! The toy's own conformance to [`ElectronicCodeBook`] is pinned once, by +//! `the_toy_permutation_conforms_to_the_trait` in `cbc_tests.rs`; it is the same `Toy` here, so it +//! is not re-run. + +mod common; + +use bouncycastle_aes_lowmemory::{Aes128, Aes192, Aes256}; +use bouncycastle_core::key_material::{KeyMaterial, KeyType}; +use bouncycastle_core::traits::{ElectronicCodeBook, StreamCipherDecryptor, StreamCipherEncryptor}; +use bouncycastle_core_test_framework::FixedSeedRNG; +use bouncycastle_core_test_framework::symmetric_ciphers::TestFrameworkStreamCipher; +use bouncycastle_modes::{Cbc, Cfb, Cfb8, Decrypting, Encrypting}; +use common::{ForwardOnlyToy, SwappedEightToy, SwappedPairToy, TOY_LEN, Toy, toy_key}; + +type ToyCfb8 = Cfb8; +type SwappedCfb8 = Cfb8; +type ForwardOnlyCfb8 = Cfb8; +type SwappedEightCfb8 = Cfb8; + +/// `do_encrypt`, by value. +fn enc(e: &mut impl StreamCipherEncryptor, plaintext: &[u8]) -> Vec { + let mut data = plaintext.to_vec(); + e.do_encrypt(&mut data).unwrap(); + data +} + +/// `do_decrypt`, by value. +fn dec(d: &mut impl StreamCipherDecryptor, ciphertext: &[u8]) -> Vec { + let mut data = ciphertext.to_vec(); + d.do_decrypt(&mut data).unwrap(); + data +} + +/// `do_decrypt` in `chunk`-byte calls, by value. The last call may be shorter. +fn dec_chunked( + d: &mut impl StreamCipherDecryptor, + ciphertext: &[u8], + chunk: usize, +) -> Vec { + let mut data = ciphertext.to_vec(); + for piece in data.chunks_mut(chunk) { + d.do_decrypt(piece).unwrap(); + } + data +} + +/// A pinned IV, so two runs are comparable. Encryption never accepts one, so it is fed through the +/// fixed-output RNG that `do_encrypt_init_rng` takes. +fn pinned_iv() -> [u8; TOY_LEN] { + core::array::from_fn(|i| 0xF0 ^ (i as u8)) +} + +fn pinned_rng(iv: [u8; TOY_LEN]) -> FixedSeedRNG { + FixedSeedRNG::::new(iv) +} + +fn pinned_encryptor(iv: [u8; TOY_LEN]) -> ToyCfb8 { + let (enc, got) = ToyCfb8::::do_encrypt_init_rng(&toy_key(), &mut pinned_rng(iv)) + .expect("encrypt init"); + assert_eq!(got, iv, "the pinned RNG should reproduce the IV"); + enc +} + +fn pinned_decryptor(iv: [u8; TOY_LEN]) -> ToyCfb8 { + ToyCfb8::::do_decrypt_init(&toy_key(), &iv).expect("decrypt init") +} + +/// A test message of `len` bytes with no repeating structure at the block size. +fn message(len: usize) -> Vec { + (0..len).map(|i| (i * 7 + (i / TOY_LEN) * 31 + 1) as u8).collect() +} + +/// The chunk sizes every "chunking must not matter" test uses: below, at, either side of and above +/// both the 8-byte batch and the 16-byte block. +const CHUNKINGS: [usize; 11] = [1, 2, 3, 7, 8, 9, 15, 16, 17, 32, 100]; + +// ---- the mode against the shared framework ------------------------------------------------ + +#[test] +fn cfb8_conforms_to_the_stream_cipher_framework() { + TestFrameworkStreamCipher::new() + .test::, ToyCfb8>(); +} + +// ---- the spec equations ------------------------------------------------------------------- + +/// CFB with `s = 8` from SP 800-38A Sec 6.3, written out longhand against the raw permutation: +/// +/// ```text +/// I1 = IV; Ij = LSB_{b-8}(I_{j-1}) | C_{j-1}; Oj = CIPH_K(Ij); Cj = Pj XOR MSB_8(Oj) +/// ``` +/// +/// The shift is written here as an explicit copy of `Ij[1..]` followed by the ciphertext byte, so +/// it is an independent statement of the rule rather than a second call to the same `rotate_left` +/// the implementation uses. +/// +/// This is the independent reference the mode is checked against below. It uses only +/// [`ElectronicCodeBook::encrypt_block`], because that is all the spec calls for. +fn reference_cfb8(perm: &Toy, iv: [u8; TOY_LEN], input: &[u8], encrypt: bool) -> Vec { + let mut chain = iv; // I1 = IV + let mut out = Vec::with_capacity(input.len()); + for &byte in input { + let mut o = chain; + perm.encrypt_block(&mut o); // Oj = CIPH_K(Ij) + let result = byte ^ o[0]; // Cj = Pj XOR MSB_8(Oj) + + // I_{j+1} = LSB_{b-8}(Ij) | C#_j -- always the *ciphertext* byte, whichever direction. + let cj = if encrypt { result } else { byte }; + let mut next = [0u8; TOY_LEN]; + next[..TOY_LEN - 1].copy_from_slice(&chain[1..]); + next[TOY_LEN - 1] = cj; + chain = next; + + out.push(result); + } + out +} + +/// The mode must reproduce the Sec 6.3 `s = 8` equations exactly, in both directions, at lengths +/// either side of the shift register's own width. +/// +/// A reference implementation is a weak test on its own -- both could be wrong the same way -- so +/// this also pins the anchors that follow directly from the equations and that no plausible +/// mistake preserves: `C1 = P1 XOR MSB_8(CIPH_K(IV))`, and the second input block. +#[test] +fn the_mode_matches_the_spec_equations() { + let key = toy_key(); + let iv = pinned_iv(); + let perm = >::new(&key).unwrap(); + + for len in [1, 2, TOY_LEN - 1, TOY_LEN, TOY_LEN + 1, 3 * TOY_LEN + 5] { + let plaintext = message(len); + + let ct = enc(&mut pinned_encryptor(iv), &plaintext); + assert_eq!( + ct, + reference_cfb8(&perm, iv, &plaintext, true), + "len {len}: encryption must match the Sec 6.3 equations at s = 8" + ); + + let recovered = dec(&mut pinned_decryptor(iv), &ct); + assert_eq!(recovered, plaintext, "len {len}: round trip"); + assert_eq!( + recovered, + reference_cfb8(&perm, iv, &ct, false), + "len {len}: decryption must match the Sec 6.3 equations at s = 8" + ); + } + + let plaintext = message(4); + let ct = enc(&mut pinned_encryptor(iv), &plaintext); + + // Anchor 1: `O1 = CIPH_K(IV)` and `C1 = P1 XOR MSB_8(O1)` -- the *first* byte of the output + // block, the other b - 8 bits discarded. + let mut o1 = iv; + perm.encrypt_block(&mut o1); + assert_eq!(ct[0], plaintext[0] ^ o1[0], "C1 = P1 XOR MSB_8(CIPH_K(IV))"); + + // Anchor 2: `I2 = LSB_{b-8}(IV) | C1`, i.e. the IV without its leading byte, then C1. + let mut i2 = [0u8; TOY_LEN]; + i2[..TOY_LEN - 1].copy_from_slice(&iv[1..]); + i2[TOY_LEN - 1] = ct[0]; + let mut o2 = i2; + perm.encrypt_block(&mut o2); + assert_eq!(ct[1], plaintext[1] ^ o2[0], "C2 = P2 XOR MSB_8(CIPH_K(LSB(IV) | C1))"); + + // Anchor 3: with `P = 0`, the ciphertext is the keystream itself. + assert_eq!( + enc(&mut pinned_encryptor(iv), &[0u8; 2]), + vec![o1[0], { + let mut i = [0u8; TOY_LEN]; + i[..TOY_LEN - 1].copy_from_slice(&iv[1..]); + i[TOY_LEN - 1] = o1[0]; + let mut o = i; + perm.encrypt_block(&mut o); + o[0] + }], + "encrypting zero yields the keystream" + ); +} + +/// CFB8 and CFB128 are different, non-interoperable modes, and they differ from the very first +/// byte: with `s = b` the whole output block is used and the next input block is the ciphertext +/// block, whereas with `s = 8` one byte is used and the register shifts. +/// +/// The first byte of ciphertext is the same in both -- `P1 XOR MSB_8(CIPH_K(IV))` either way -- and +/// everything from the second byte differs. That is the sharp statement of "not a variant", and it +/// is what catches a CFB8 that has quietly become CFB128 or vice versa. +#[test] +fn cfb8_is_not_cfb128() { + let key = toy_key(); + let iv = pinned_iv(); + let plaintext = message(2 * TOY_LEN); + + let cfb8 = enc(&mut pinned_encryptor(iv), &plaintext); + + let (mut cfb, got) = + Cfb::::do_encrypt_init_rng(&key, &mut pinned_rng(iv)) + .unwrap(); + assert_eq!(got, iv); + let mut cfb128 = plaintext.clone(); + cfb.do_encrypt(&mut cfb128).unwrap(); + + assert_eq!(cfb8[0], cfb128[0], "both modes start O1 = CIPH_K(IV), so C1 agrees"); + assert_ne!(cfb8[1..], cfb128[1..], "everything after the first byte must differ"); + + // ...and neither can decrypt the other's ciphertext. + let mut wrong = cfb128.clone(); + ToyCfb8::::decrypt(&key, &iv, &mut wrong).unwrap(); + assert_ne!(wrong, plaintext, "CFB8 must not decrypt a CFB128 ciphertext"); + + let mut wrong = cfb8.clone(); + Cfb::::decrypt(&key, &iv, &mut wrong).unwrap(); + assert_ne!(wrong, plaintext, "CFB128 must not decrypt a CFB8 ciphertext"); +} + +/// A stream cipher's ciphertext for a prefix of the message is the prefix of the ciphertext. +#[test] +fn the_ciphertext_of_a_prefix_is_a_prefix_of_the_ciphertext() { + let iv = pinned_iv(); + let plaintext = message(2 * TOY_LEN + 3); + let full = enc(&mut pinned_encryptor(iv), &plaintext); + + for k in 0..=plaintext.len() { + assert_eq!( + enc(&mut pinned_encryptor(iv), &plaintext[..k]), + full[..k], + "encrypting the first {k} bytes" + ); + assert_eq!( + dec(&mut pinned_decryptor(iv), &full[..k]), + plaintext[..k], + "decrypting the first {k} bytes" + ); + } +} + +// ---- the forward-cipher-only rule --------------------------------------------------------- + +/// SP 800-38A Sec 6.3: "The *forward cipher* function is applied to each input block to produce the +/// output blocks" -- in CFB *decryption* as well as encryption. +/// +/// [`ForwardOnlyToy`] panics from `decrypt_block`, `decrypt_blocks2` and `decrypt_blocks8`, so this +/// test fails loudly if either direction of the mode ever reaches the inverse cipher. Every decrypt +/// path is exercised -- eights, pairs and single bytes -- and the result is required to agree with +/// the plain [`Toy`], otherwise the test could pass by not really encrypting anything. +#[test] +fn neither_direction_uses_the_inverse_cipher() { + let key = toy_key(); + let iv = pinned_iv(); + let plaintext = message(19); + + let (mut e, _) = + ForwardOnlyCfb8::::do_encrypt_init_rng(&key, &mut pinned_rng(iv)).unwrap(); + let ct = enc(&mut e, &plaintext); + + // One call: two eights, then a pair, then a single byte. + let mut d = ForwardOnlyCfb8::::do_decrypt_init(&key, &iv).unwrap(); + assert_eq!(dec(&mut d, &ct), plaintext, "all paths, forward cipher only"); + + // Byte by byte: the single-byte path only. + let mut d = ForwardOnlyCfb8::::do_decrypt_init(&key, &iv).unwrap(); + assert_eq!(dec_chunked(&mut d, &ct, 1), plaintext, "single-byte path, forward cipher only"); + + // The forward-only toy must agree with the real one, or the above proves nothing. + assert_eq!( + enc(&mut pinned_encryptor(iv), &plaintext), + ct, + "the two toys must agree going forward" + ); +} + +/// The decryptor must shift the **ciphertext** byte into the register, not the plaintext it just +/// recovered. +/// +/// Getting this wrong is invisible in the first byte -- `O1 = CIPH_K(IV)` either way -- and wrong +/// from the second onwards. An encryptor run over ciphertext is exactly that mistake, so byte 1 +/// agreeing while byte 2 disagrees is the signature of the bug, and is what this asserts. +#[test] +fn the_decryptor_shifts_in_ciphertext_not_plaintext() { + let iv = pinned_iv(); + let plaintext = message(2 * TOY_LEN); + let ct = enc(&mut pinned_encryptor(iv), &plaintext); + assert_ne!(ct[0], plaintext[0], "the two feedback choices must actually differ here"); + + let wrong = enc(&mut pinned_encryptor(iv), &ct); + assert_eq!(wrong[0], plaintext[0], "byte 1 cannot tell the two apart"); + assert_ne!(wrong[1..], plaintext[1..], "byte 2 onwards must, so the feedback source is pinned"); +} + +// ---- chaining and call sequencing -------------------------------------------------------- + +/// Encrypting a message must not depend on how the calls are chunked, and likewise for decryption, +/// at byte granularity. Every chunking in [`CHUNKINGS`] is checked against the one-call reference in +/// both directions, and every encrypt chunking against every decrypt chunking. +/// +/// For CFB8 the decrypt side is where this bites: chunk sizes that are not multiples of 8 leave the +/// eight-byte batch loop with a different remainder each call, so the register has to carry across +/// calls correctly for every alignment. +#[test] +fn call_chunking_does_not_change_the_result() { + let iv = pinned_iv(); + let plaintext = message(3 * TOY_LEN + 7); + + let reference = enc(&mut pinned_encryptor(iv), &plaintext); + assert_eq!(dec(&mut pinned_decryptor(iv), &reference), plaintext); + + for &enc_chunk in &CHUNKINGS { + let mut ct = plaintext.clone(); + let mut e = pinned_encryptor(iv); + for piece in ct.chunks_mut(enc_chunk) { + e.do_encrypt(piece).unwrap(); + } + assert_eq!(ct, reference, "encrypting in {enc_chunk}-byte calls"); + + for &dec_chunk in &CHUNKINGS { + let pt = dec_chunked(&mut pinned_decryptor(iv), &ct, dec_chunk); + assert_eq!( + pt, plaintext, + "encrypted in {enc_chunk}-byte calls, decrypted in {dec_chunk}-byte calls" + ); + } + } + + // Empty calls anywhere are no-ops. + let mut e = pinned_encryptor(iv); + e.do_encrypt(&mut []).unwrap(); + let mut ct = plaintext.clone(); + e.do_encrypt(&mut ct[..5]).unwrap(); + e.do_encrypt(&mut []).unwrap(); + e.do_encrypt(&mut ct[5..]).unwrap(); + e.do_encrypt(&mut []).unwrap(); + assert_eq!(ct, reference, "empty calls must not disturb the state"); +} + +/// The same equivalence with **real AES**, at all three key lengths. +/// +/// `call_chunking_does_not_change_the_result` proves the property over the toy permutation. This +/// repeats it with the cipher the mode is actually used with, so a chunking bug that only appears +/// under a real key schedule cannot hide. The AES coverage elsewhere +/// (`sp800_38a_cfb8_tests.rs`, `acvp_cfb8_tests.rs`) chunks against *published* ciphertext; this is +/// the direct single-call-versus-chunked comparison. +/// +/// The message is 171 bytes, which is 21 eight-byte batches and a 3-byte tail, so the chunkings +/// leave the batch loop with a different remainder each time. +#[test] +fn aes_chunking_matches_a_single_call() { + fn check(name: &str) + where + P: ElectronicCodeBook, + { + let key_bytes: [u8; KEY_LEN] = + core::array::from_fn(|i| (i as u8).wrapping_mul(31).wrapping_add(7)); + let key = + KeyMaterial::::from_bytes_as_type(&key_bytes, KeyType::SymmetricCipherKey) + .expect("a valid AES key"); + let iv: [u8; 16] = core::array::from_fn(|i| 0xC3 ^ (i as u8)); + let plaintext: Vec = (0..171).map(|i| (i * 7 + i / 16) as u8).collect(); + + let encryptor = || { + let (enc, got) = Cfb8::::do_encrypt_init_rng( + &key, + &mut FixedSeedRNG::<16>::new(iv), + ) + .expect("encrypt init"); + assert_eq!(got, iv, "{name}: the pinned RNG should reproduce the IV"); + enc + }; + let decryptor = || { + Cfb8::::do_decrypt_init(&key, &iv).expect("decrypt init") + }; + + // The reference: the whole message in one call. + let mut reference = plaintext.clone(); + encryptor().do_encrypt(&mut reference).expect("one-call encryption"); + assert_ne!(reference, plaintext, "{name}: the data must actually be encrypted"); + + // ...and the round trip of that, also in one call. + let mut back = reference.clone(); + decryptor().do_decrypt(&mut back).expect("one-call decryption"); + assert_eq!(back, plaintext, "{name}: one-call round trip"); + + for &enc_chunk in &CHUNKINGS { + let mut ct = plaintext.clone(); + let mut e = encryptor(); + for piece in ct.chunks_mut(enc_chunk) { + e.do_encrypt(piece).expect("chunked encryption"); + } + assert_eq!(ct, reference, "{name}: encrypting in {enc_chunk}-byte calls"); + + for &dec_chunk in &CHUNKINGS { + let mut pt = ct.clone(); + let mut d = decryptor(); + for piece in pt.chunks_mut(dec_chunk) { + d.do_decrypt(piece).expect("chunked decryption"); + } + assert_eq!( + pt, plaintext, + "{name}: encrypted in {enc_chunk}-byte calls, decrypted in {dec_chunk}-byte calls" + ); + } + } + } + + check::("AES-128"); + check::("AES-192"); + check::("AES-256"); +} + +/// The pair path in `do_decrypt` must actually be taken. +/// +/// [`SwappedPairToy`] returns its two pair results in the wrong order while its single-block method +/// is correct. CFB8 decryption batches through `encrypt_blocks2`, so with this permutation six +/// bytes handed over together come out wrong while the same bytes one at a time come out right. +/// +/// Six, not eight: the trait's default `encrypt_blocks8` is four `encrypt_blocks2` calls, so eight +/// bytes would also be wrong and would not distinguish the two paths. +#[test] +fn the_pair_path_is_really_used() { + let key = toy_key(); + let iv = pinned_iv(); + let plaintext = message(6); + + // The correct toy round-trips. + let ct = enc(&mut pinned_encryptor(iv), &plaintext); + assert_eq!(dec(&mut pinned_decryptor(iv), &ct), plaintext); + + // The swapped-pair toy encrypts identically -- CFB8 encryption is serial and never batches. + let (mut e, _) = + SwappedCfb8::::do_encrypt_init_rng(&key, &mut pinned_rng(iv)).unwrap(); + assert_eq!(enc(&mut e, &plaintext), ct, "CFB8 encryption must not use the pair path"); + + // ...but decrypting six bytes together must now be wrong, because the pair path is used. + let mut d = SwappedCfb8::::do_decrypt_init(&key, &iv).unwrap(); + assert_ne!(dec(&mut d, &ct), plaintext, "three pairs must go through encrypt_blocks2"); + + // One byte at a time avoids the pair path, so it is correct even for this toy. + let mut d = SwappedCfb8::::do_decrypt_init(&key, &iv).unwrap(); + assert_eq!(dec_chunked(&mut d, &ct, 1), plaintext, "the single-byte path must not pair"); +} + +/// The eight-byte batch path in `do_decrypt` must actually be taken, and only for full eights. +/// +/// [`SwappedEightToy`] returns its eight `encrypt_blocks8` results rotated while its pair and +/// single-block methods are correct. So nine bytes handed over together decrypt wrongly (eight +/// batched, then one), while six bytes (pairs) or one at a time decrypt correctly. +#[test] +fn the_eight_byte_path_is_really_used() { + let key = toy_key(); + let iv = pinned_iv(); + let plaintext = message(9); + + let ct = enc(&mut pinned_encryptor(iv), &plaintext); + assert_eq!(dec(&mut pinned_decryptor(iv), &ct), plaintext); + + // The rotated-eight toy encrypts identically: CFB8 encryption is serial and never batches. + let (mut e, _) = + SwappedEightCfb8::::do_encrypt_init_rng(&key, &mut pinned_rng(iv)).unwrap(); + assert_eq!(enc(&mut e, &plaintext), ct, "CFB8 encryption must not use the eight path"); + + // ...but nine bytes together must now be wrong, because the first eight go through + // encrypt_blocks8. + let mut d = SwappedEightCfb8::::do_decrypt_init(&key, &iv).unwrap(); + assert_ne!(dec(&mut d, &ct), plaintext, "nine bytes must go through encrypt_blocks8"); + + // Six bytes use the pair path only, so they are correct even for this toy... + let six = &ct[..6]; + let mut d = SwappedEightCfb8::::do_decrypt_init(&key, &iv).unwrap(); + assert_eq!(dec(&mut d, six), plaintext[..6], "pairs must not use the eight path"); + + // ...and so is one byte at a time. + let mut d = SwappedEightCfb8::::do_decrypt_init(&key, &iv).unwrap(); + assert_eq!(dec_chunked(&mut d, &ct, 1), plaintext, "the single-byte path must not batch"); +} + +/// The one-shots must produce exactly what the streaming API produces. +#[test] +fn one_shots_agree_with_the_streaming_api() { + let key = toy_key(); + let iv = pinned_iv(); + + for len in [1, 9, 2 * TOY_LEN + 3] { + let plaintext = message(len); + let streamed = enc(&mut pinned_encryptor(iv), &plaintext); + + let mut buf = plaintext.clone(); + let iv_b = ToyCfb8::::encrypt_rng(&key, &mut pinned_rng(iv), &mut buf).unwrap(); + assert_eq!(iv_b, iv); + assert_eq!(buf, streamed, "len {len}: one-shot must equal streaming"); + ToyCfb8::::decrypt(&key, &iv, &mut buf).unwrap(); + assert_eq!(buf, plaintext); + + // The OS-RNG variant round-trips too. Whether the ciphertext *differs* from the plaintext + // is only worth asserting once the message is long enough that coinciding with the + // keystream by chance is negligible -- see `every_length_round_trips_without_padding`. + let mut buf = plaintext.clone(); + let iv_fresh = ToyCfb8::::encrypt(&key, &mut buf).unwrap(); + if len >= 8 { + assert_ne!(buf, plaintext); + } + ToyCfb8::::decrypt(&key, &iv_fresh, &mut buf).unwrap(); + assert_eq!(buf, plaintext); + } +} + +// ---- SP 800-38A Appendix D error propagation --------------------------------------------- + +/// Appendix D, Table D.2 for CFB: a bit error in `Cj` gives "SBE in the decryption of `Cj`" plus +/// "RBE in the decryption of `Cj+1`,...,`Cj+b/s`". With `s = 8` on a 16-byte block, `b/s` is **16**: +/// the flipped bit lands in exactly the byte the attacker aimed at, the next 16 bytes are +/// randomised, and byte 17 onwards is **exactly correct** -- the corrupted byte has been shifted +/// out of the register and decryption has resynchronised. +/// +/// That self-synchronisation is the property CFB8 is chosen for, and the exact-equality assertion +/// on the tail is what pins it. Checked with AES-128, because "randomised" is a property of the +/// block cipher's diffusion rather than of the mode, and the byte-local toy cannot show it. +#[test] +fn a_ciphertext_bit_error_damages_exactly_sixteen_following_bytes() { + type Aes128Cfb8 = Cfb8; + const LEN: usize = 48; + + let key = KeyMaterial::<16>::from_bytes_as_type(&[0x42; 16], KeyType::SymmetricCipherKey) + .expect("a valid AES-128 key"); + let iv: [u8; 16] = core::array::from_fn(|i| 0x0F ^ (i as u8)); + let plaintext: Vec = (0..LEN).map(|i| (i * 11 + 3) as u8).collect(); + + let mut ct = plaintext.clone(); + let (mut e, got_iv) = + Aes128Cfb8::::do_encrypt_init_rng(&key, &mut FixedSeedRNG::<16>::new(iv)) + .unwrap(); + assert_eq!(got_iv, iv); + e.do_encrypt(&mut ct).unwrap(); + + // Byte 8, so there is a clean prefix, a full 16-byte damage window and a clean tail. + const J: usize = 8; + for bit in 0..8 { + let mut corrupt = ct.clone(); + corrupt[J] ^= 1 << bit; + + let mut d = Aes128Cfb8::::do_decrypt_init(&key, &iv).unwrap(); + let mut got = corrupt; + d.do_decrypt(&mut got).unwrap(); + + assert_eq!(&got[..J], &plaintext[..J], "bit {bit}: earlier bytes are unaffected"); + assert_eq!( + got[J], + plaintext[J] ^ (1 << bit), + "bit {bit}: SBE -- exactly the flipped bit, in the targeted byte" + ); + // The 16 bytes after it are randomised. Asserting each one differs would be a 1-in-256 + // coin flip per byte, so the window is compared as a whole. + assert_ne!( + &got[J + 1..J + 1 + 16], + &plaintext[J + 1..J + 1 + 16], + "bit {bit}: the next b/s = 16 bytes should be randomised" + ); + // ...and then it resynchronises, exactly. + assert_eq!( + &got[J + 1 + 16..], + &plaintext[J + 1 + 16..], + "bit {bit}: byte j + 17 onwards must be exactly right again" + ); + } +} + +/// The same claim in the direction that needs no cipher diffusion, and so holds for *any* +/// permutation: the damage window is bounded by `b/s` segments, and the SBE lands in the targeted +/// byte. With the toy this is exact arithmetic rather than a statistical argument. +#[test] +fn a_ciphertext_bit_error_flips_exactly_that_bit_of_its_own_byte() { + let iv = pinned_iv(); + let plaintext = message(3 * TOY_LEN); + let ct = enc(&mut pinned_encryptor(iv), &plaintext); + + for j in [0usize, 1, 5, TOY_LEN, 2 * TOY_LEN] { + for bit in 0..8 { + let mut corrupt = ct.clone(); + corrupt[j] ^= 1 << bit; + let got = dec(&mut pinned_decryptor(iv), &corrupt); + + assert_eq!(&got[..j], &plaintext[..j], "byte {j} bit {bit}: earlier bytes unaffected"); + assert_eq!( + got[j], + plaintext[j] ^ (1 << bit), + "byte {j} bit {bit}: exactly that bit of that byte" + ); + // Damage cannot reach past b/s = TOY_LEN segments. + let resync = core::cmp::min(j + 1 + TOY_LEN, plaintext.len()); + assert_eq!( + &got[resync..], + &plaintext[resync..], + "byte {j} bit {bit}: must resynchronise after b/s = {TOY_LEN} segments" + ); + } + } +} + +// ---- IV handling ------------------------------------------------------------------------- + +/// Two encryption flows under the same key must not reuse an IV. +#[test] +fn each_encryption_gets_a_fresh_iv() { + let key = toy_key(); + let mut seen = std::collections::BTreeSet::new(); + for _ in 0..64 { + let (_, iv) = ToyCfb8::::do_encrypt_init(&key).unwrap(); + assert!(seen.insert(iv), "IV repeated across encryptions: {iv:02x?}"); + } +} + +/// Identical plaintext under the same key must give different ciphertext, because the IV differs. +#[test] +fn identical_plaintext_gives_different_ciphertext() { + let key = toy_key(); + let plaintext = [0x77u8; 2 * TOY_LEN]; + + let mut first = plaintext; + ToyCfb8::::encrypt(&key, &mut first).unwrap(); + let mut second = plaintext; + ToyCfb8::::encrypt(&key, &mut second).unwrap(); + assert_ne!(first, second); + + // ...and, within one message, a run of identical plaintext bytes must not give a run of + // identical ciphertext bytes: the register changes on every byte. Compared a block at a time + // rather than byte against byte, because two single bytes coincide once in 256 runs by chance + // while two 16-byte halves do so once in 2^128. + assert_ne!( + first[..TOY_LEN], + first[TOY_LEN..], + "the shifting register should break the pattern within a message" + ); +} + +// ---- key handling ------------------------------------------------------------------------ + +#[test] +fn a_key_of_the_wrong_type_is_rejected() { + let bytes: [u8; TOY_LEN] = core::array::from_fn(|i| (i as u8) + 1); + let seed = KeyMaterial::::from_bytes_as_type(&bytes, KeyType::Seed).unwrap(); + assert!(ToyCfb8::::do_encrypt_init(&seed).is_err()); + assert!(ToyCfb8::::do_decrypt_init(&seed, &[0u8; TOY_LEN]).is_err()); +} + +// ---- every length, no padding ------------------------------------------------------------ + +/// CFB8 is a stream cipher with a one-byte segment: every length round-trips, the ciphertext is +/// exactly as long as the plaintext, and no padding layer is involved. +#[test] +fn every_length_round_trips_without_padding() { + let key = toy_key(); + for len in 0..=(2 * TOY_LEN + 1) { + let plaintext = message(len); + let mut data = plaintext.clone(); + let iv = ToyCfb8::::encrypt(&key, &mut data).expect("encryption"); + assert_eq!(data.len(), len, "len {len}: the ciphertext is as long as the plaintext"); + // Only meaningful once the message is long enough that agreeing with the keystream by + // chance is negligible: a 1-byte message coincides with its own ciphertext whenever the + // single keystream byte is zero, which a fresh random IV makes happen about once in 256 + // runs. At 8 bytes the odds are 2^-64. (This is why the assertion is guarded rather than + // dropped: it is worth making, just not at every length.) + if len >= 8 { + assert_ne!(data, plaintext, "len {len}: the data must actually be encrypted"); + } + ToyCfb8::::decrypt(&key, &iv, &mut data).expect("decryption"); + assert_eq!(data, plaintext, "len {len}: round trip"); + } +} + +// ---- memory ------------------------------------------------------------------------------ + +/// Pins the "Memory Usage" table in the crate docs, and the claim that CFB8 costs exactly what CBC +/// costs -- one block of shift register and nothing else, since its segment is a single byte and +/// so there is never a partial segment to remember. +#[test] +fn sizes_match_the_documented_memory_table() { + use core::mem::size_of; + + assert_eq!(size_of::>(), 176 + 16); + assert_eq!(size_of::>(), 208 + 16); + assert_eq!(size_of::>(), 240 + 16); + + // The direction marker is free, and does not change the layout. + assert_eq!( + size_of::>(), + size_of::>() + ); + + // ...and the general rule the docs state. + assert_eq!(size_of::>(), size_of::() + 16); + + // The docs say CFB8 is the same size as CBC, and one `usize` smaller than CFB. + assert_eq!( + size_of::>(), + size_of::>() + ); + assert_eq!( + size_of::>() + size_of::(), + size_of::>() + ); +} diff --git a/crypto/modes/tests/cfb_tests.rs b/crypto/modes/tests/cfb_tests.rs new file mode 100644 index 00000000..863afd79 --- /dev/null +++ b/crypto/modes/tests/cfb_tests.rs @@ -0,0 +1,788 @@ +//! Structural tests for CFB, driven by a toy permutation. +//! +//! These check the properties of the *mode* -- the keystream construction, chaining, call +//! sequencing at arbitrary byte boundaries, the short final segment, the pair/eight-block split on +//! the decrypt side, direction typing, SP 800-38A Appendix D error propagation, and the "forward +//! cipher function only" rule of Sec 6.3 -- independently of any real cipher. The known-answer +//! tests against SP 800-38A Appendix F.3.13-F.3.18 are in `sp800_38a_cfb_tests.rs`, and the ACVP +//! CFB128 set is in `acvp_cfb_tests.rs`. +//! +//! The toy's own conformance to [`ElectronicCodeBook`] is pinned once, by +//! `the_toy_permutation_conforms_to_the_trait` in `cbc_tests.rs`; it is the same `Toy` here, so it +//! is not re-run. + +mod common; + +use bouncycastle_aes_lowmemory::{Aes128, Aes192, Aes256}; +use bouncycastle_core::key_material::{KeyMaterial, KeyType}; +use bouncycastle_core::traits::{ + BlockCipherEncryptor, ElectronicCodeBook, StreamCipherDecryptor, StreamCipherEncryptor, +}; +use bouncycastle_core_test_framework::FixedSeedRNG; +use bouncycastle_core_test_framework::symmetric_ciphers::TestFrameworkStreamCipher; +use bouncycastle_modes::{Cbc, Cfb, Decrypting, Encrypting}; +use common::{ForwardOnlyToy, SwappedEightToy, SwappedPairToy, TOY_LEN, Toy, toy_key}; + +type ToyCfb = Cfb; +type SwappedCfb = Cfb; +type ForwardOnlyCfb = Cfb; +type SwappedEightCfb = Cfb; + +/// `do_encrypt`, by value. +fn enc(e: &mut impl StreamCipherEncryptor, plaintext: &[u8]) -> Vec { + let mut data = plaintext.to_vec(); + e.do_encrypt(&mut data).unwrap(); + data +} + +/// `do_decrypt`, by value. +fn dec(d: &mut impl StreamCipherDecryptor, ciphertext: &[u8]) -> Vec { + let mut data = ciphertext.to_vec(); + d.do_decrypt(&mut data).unwrap(); + data +} + +/// `do_encrypt` in `chunk`-byte calls, by value. The last call may be shorter. +fn enc_chunked( + e: &mut impl StreamCipherEncryptor, + plaintext: &[u8], + chunk: usize, +) -> Vec { + let mut data = plaintext.to_vec(); + for piece in data.chunks_mut(chunk) { + e.do_encrypt(piece).unwrap(); + } + data +} + +/// `do_decrypt` in `chunk`-byte calls, by value. The last call may be shorter. +fn dec_chunked( + d: &mut impl StreamCipherDecryptor, + ciphertext: &[u8], + chunk: usize, +) -> Vec { + let mut data = ciphertext.to_vec(); + for piece in data.chunks_mut(chunk) { + d.do_decrypt(piece).unwrap(); + } + data +} + +/// A pinned IV, so two runs are comparable. Encryption never accepts one, so it is fed through the +/// fixed-output RNG that `do_encrypt_init_rng` takes. +fn pinned_iv() -> [u8; TOY_LEN] { + core::array::from_fn(|i| 0xF0 ^ (i as u8)) +} + +fn pinned_rng(iv: [u8; TOY_LEN]) -> FixedSeedRNG { + FixedSeedRNG::::new(iv) +} + +fn pinned_encryptor(iv: [u8; TOY_LEN]) -> ToyCfb { + let (enc, got) = ToyCfb::::do_encrypt_init_rng(&toy_key(), &mut pinned_rng(iv)) + .expect("encrypt init"); + assert_eq!(got, iv, "the pinned RNG should reproduce the IV"); + enc +} + +fn pinned_decryptor(iv: [u8; TOY_LEN]) -> ToyCfb { + ToyCfb::::do_decrypt_init(&toy_key(), &iv).expect("decrypt init") +} + +/// A test message of `len` bytes with no repeating structure at the block size. +fn message(len: usize) -> Vec { + (0..len).map(|i| (i * 7 + (i / TOY_LEN) * 31 + 1) as u8).collect() +} + +/// The chunk sizes every "chunking must not matter" test uses: below, at, just either side of, and +/// well above the block, plus primes that never line up with it. +const CHUNKINGS: [usize; 12] = [1, 3, 5, 7, 15, 16, 17, 31, 32, 33, 64, 100]; + +// ---- the mode against the shared framework ------------------------------------------------ + +#[test] +fn cfb_conforms_to_the_stream_cipher_framework() { + TestFrameworkStreamCipher::new() + .test::, ToyCfb>(); +} + +// ---- the spec equations ------------------------------------------------------------------- + +/// CFB with `s = b` from SP 800-38A Sec 6.3, written out longhand against the raw permutation: +/// +/// ```text +/// I1 = IV; Ij = C_{j-1} (j >= 2); Oj = CIPH_K(Ij); Cj = Pj XOR Oj +/// ``` +/// +/// extended to a message that is not a whole number of blocks by the rule in the [`Cfb`] docs: the +/// last `r` bytes are a short segment, `C#_n = P#_n XOR MSB_{8r}(On)`, and no input block is formed +/// after it. +/// +/// This is the independent reference the mode is checked against below. It uses only +/// [`ElectronicCodeBook::encrypt_block`], because that is all the spec calls for. +fn reference_cfb(perm: &Toy, iv: [u8; TOY_LEN], input: &[u8], encrypt: bool) -> Vec { + let mut chain = iv; // I1 = IV + let mut out = Vec::with_capacity(input.len()); + for segment in input.chunks(TOY_LEN) { + let mut o = chain; + perm.encrypt_block(&mut o); // Oj = CIPH_K(Ij) + // C#_j = P#_j XOR MSB_s(Oj): a whole block, or the leading bytes of Oj for a short segment. + let result: Vec = segment.iter().zip(o.iter()).map(|(d, o)| d ^ o).collect(); + if segment.len() == TOY_LEN { + // I_{j+1} is always the *ciphertext* block, whichever direction we are going. + let cj = if encrypt { &result[..] } else { segment }; + chain.copy_from_slice(cj); + } + out.extend_from_slice(&result); + } + out +} + +/// The mode must reproduce the Sec 6.3 equations exactly, in both directions, for whole blocks and +/// for a message ending in a short segment. +/// +/// A reference implementation is a weak test on its own -- both could be wrong the same way -- so +/// this also pins the two anchors that follow directly from the equations and that no plausible +/// mistake preserves: `C1 = P1 XOR CIPH_K(IV)`, and encrypting an all-zero block reveals the +/// keystream block itself. +#[test] +fn the_mode_matches_the_spec_equations() { + let key = toy_key(); + let iv = pinned_iv(); + let perm = >::new(&key).unwrap(); + + for len in [5 * TOY_LEN, 5 * TOY_LEN + 9, TOY_LEN - 1, 1] { + let plaintext = message(len); + + let ct = enc(&mut pinned_encryptor(iv), &plaintext); + assert_eq!( + ct, + reference_cfb(&perm, iv, &plaintext, true), + "len {len}: encryption must match the Sec 6.3 equations" + ); + + let recovered = dec(&mut pinned_decryptor(iv), &ct); + assert_eq!(recovered, plaintext, "len {len}: round trip"); + assert_eq!( + recovered, + reference_cfb(&perm, iv, &ct, false), + "len {len}: decryption must match the Sec 6.3 equations" + ); + } + + let plaintext = message(3 * TOY_LEN); + let ct = enc(&mut pinned_encryptor(iv), &plaintext); + + // Anchor 1: `O1 = CIPH_K(IV)` and `C1 = P1 XOR O1`. + let mut o1 = iv; + perm.encrypt_block(&mut o1); + let expected_c1: Vec = + plaintext[..TOY_LEN].iter().zip(o1.iter()).map(|(p, o)| p ^ o).collect(); + assert_eq!(&ct[..TOY_LEN], &expected_c1[..], "C1 = P1 XOR CIPH_K(IV)"); + + // Anchor 2: with `P1 = 0`, `C1 = O1`. CFB is a keystream mode, and this is what that means. + assert_eq!( + enc(&mut pinned_encryptor(iv), &[0u8; TOY_LEN]), + &o1[..], + "encrypting zero yields the keystream" + ); + + // ...and CFB is not CBC: CBC computes `CIPH_K(P1 XOR IV)`, CFB computes `P1 XOR CIPH_K(IV)`. + let (mut cbc, _) = + Cbc::::do_encrypt_init_rng(&key, &mut pinned_rng(iv)) + .unwrap(); + let mut cbc_c1: [u8; TOY_LEN] = plaintext[..TOY_LEN].try_into().unwrap(); + cbc.do_encrypt(&mut cbc_c1).unwrap(); + assert_ne!(&cbc_c1[..], &ct[..TOY_LEN], "CFB must not agree with CBC"); +} + +// ---- the short final segment -------------------------------------------------------------- + +/// A message that is not a whole number of blocks ends in a short segment, and its ciphertext is +/// the plaintext XOR the *leading* bytes of the output block -- `MSB_{8r}(On)` -- for every `r`. +/// +/// Checked at the first segment (against `CIPH_K(IV)`) and after two whole blocks (against +/// `CIPH_K(C2)`), so both the "only segment" and "final segment" cases are covered. +#[test] +fn the_final_short_segment_is_xored_with_the_leading_keystream_bytes() { + let key = toy_key(); + let iv = pinned_iv(); + let perm = >::new(&key).unwrap(); + + let mut o1 = iv; + perm.encrypt_block(&mut o1); + + let two_blocks = message(2 * TOY_LEN); + let two_blocks_ct = enc(&mut pinned_encryptor(iv), &two_blocks); + let mut o3: [u8; TOY_LEN] = two_blocks_ct[TOY_LEN..].try_into().unwrap(); + perm.encrypt_block(&mut o3); + + for r in 1..TOY_LEN { + // The only segment. + let short = message(r); + let ct = enc(&mut pinned_encryptor(iv), &short); + let expected: Vec = short.iter().zip(o1.iter()).map(|(p, o)| p ^ o).collect(); + assert_eq!(ct, expected, "r = {r}: C#_1 = P#_1 XOR MSB(O1)"); + assert_eq!(dec(&mut pinned_decryptor(iv), &ct), short, "r = {r}: round trip"); + + // The final segment after two whole blocks. + let mut long = two_blocks.clone(); + long.extend_from_slice(&message(2 * TOY_LEN + r)[2 * TOY_LEN..]); + let ct = enc(&mut pinned_encryptor(iv), &long); + assert_eq!( + &ct[..2 * TOY_LEN], + &two_blocks_ct[..], + "r = {r}: the whole blocks are unchanged" + ); + let expected: Vec = + long[2 * TOY_LEN..].iter().zip(o3.iter()).map(|(p, o)| p ^ o).collect(); + assert_eq!(&ct[2 * TOY_LEN..], &expected[..], "r = {r}: C#_3 = P#_3 XOR MSB(O3)"); + assert_eq!(dec(&mut pinned_decryptor(iv), &ct), long, "r = {r}: round trip"); + } +} + +/// A stream cipher's ciphertext for a prefix of the message is the prefix of the ciphertext: the +/// bytes after position `k` cannot influence the bytes before it. For CFB that follows from the +/// equations -- `Oj` depends only on `C_{j-1}` -- and it is what makes the short final segment +/// well defined: truncating the message truncates the ciphertext, nothing more. +#[test] +fn the_ciphertext_of_a_prefix_is_a_prefix_of_the_ciphertext() { + let iv = pinned_iv(); + let plaintext = message(4 * TOY_LEN + 3); + let full = enc(&mut pinned_encryptor(iv), &plaintext); + + for k in 0..=plaintext.len() { + let ct = enc(&mut pinned_encryptor(iv), &plaintext[..k]); + assert_eq!(&ct[..], &full[..k], "encrypting the first {k} bytes"); + let pt = dec(&mut pinned_decryptor(iv), &full[..k]); + assert_eq!(&pt[..], &plaintext[..k], "decrypting the first {k} bytes"); + } +} + +// ---- the forward-cipher-only rule --------------------------------------------------------- + +/// SP 800-38A Sec 6.3: "The *forward cipher* function is applied to each input block to produce the +/// output blocks" -- in CFB *decryption* as well as encryption. +/// +/// [`ForwardOnlyToy`] panics from `decrypt_block`, `decrypt_blocks2` and `decrypt_blocks8`, so this +/// test fails loudly if either direction of the mode ever reaches the inverse cipher. Every +/// decrypt path is exercised -- the eight-block, pair, single-block and byte paths -- and the result +/// is required to agree with the plain [`Toy`], otherwise the test could pass by not really +/// encrypting anything. +#[test] +fn neither_direction_uses_the_inverse_cipher() { + let key = toy_key(); + let iv = pinned_iv(); + let plaintext = message(11 * TOY_LEN + 5); + + let (mut e, _) = + ForwardOnlyCfb::::do_encrypt_init_rng(&key, &mut pinned_rng(iv)).unwrap(); + let ct = enc(&mut e, &plaintext); + + // One call: eight blocks, then a pair, then a single, then the short segment. + let mut d = ForwardOnlyCfb::::do_decrypt_init(&key, &iv).unwrap(); + assert_eq!(dec(&mut d, &ct), plaintext, "all paths, forward cipher only"); + + // Byte by byte: the byte path only. + let mut d = ForwardOnlyCfb::::do_decrypt_init(&key, &iv).unwrap(); + assert_eq!(dec_chunked(&mut d, &ct, 1), plaintext, "byte path, forward cipher only"); + + // The forward-only toy must agree with the real one, or the above proves nothing. + assert_eq!( + enc(&mut pinned_encryptor(iv), &plaintext), + ct, + "the two toys must agree going forward" + ); +} + +/// The decryptor must feed the **ciphertext** back, not the plaintext it just recovered. +/// +/// Getting this wrong is invisible in the first block -- `O1 = CIPH_K(IV)` either way -- and wrong +/// from the second onwards. An encryptor run over ciphertext is exactly that mistake: it XORs the +/// right keystream into block 1 and then chains on its own output. So block 1 agreeing while +/// block 2 disagrees is the signature of the bug, and is what this asserts -- once for whole-block +/// calls and once byte by byte, since the two paths feed back separately. +#[test] +fn the_decryptor_chains_on_ciphertext_not_plaintext() { + let iv = pinned_iv(); + let plaintext = message(3 * TOY_LEN); + let ct = enc(&mut pinned_encryptor(iv), &plaintext); + assert_ne!( + &ct[..TOY_LEN], + &plaintext[..TOY_LEN], + "the two feedback choices must actually differ here" + ); + + for chunk in [3 * TOY_LEN, 1] { + let wrong = enc_chunked(&mut pinned_encryptor(iv), &ct, chunk); + assert_eq!( + &wrong[..TOY_LEN], + &plaintext[..TOY_LEN], + "chunk {chunk}: block 1 cannot tell the two apart" + ); + assert_ne!( + &wrong[TOY_LEN..2 * TOY_LEN], + &plaintext[TOY_LEN..2 * TOY_LEN], + "chunk {chunk}: block 2 must, so the feedback source is pinned" + ); + } +} + +// ---- chaining and call sequencing -------------------------------------------------------- + +/// Encrypting a message must not depend on how the calls are chunked, and likewise for decryption, +/// at *byte* granularity. This is the "a sequence of calls is equivalent to one call over the +/// concatenation" contract of the trait, and for CFB it is about the input block surviving across +/// calls and, when a call ends mid-segment, the unused keystream surviving too. +/// +/// Every chunking in [`CHUNKINGS`] is checked against the one-call reference in both directions, +/// and every encrypt chunking against every decrypt chunking. Chunk sizes that are not multiples +/// of the block put every call through the head-blocks-tail split with all three parts non-empty at +/// some point; 1 never reaches the block path at all; 16 and 32 never leave it. +#[test] +fn call_chunking_does_not_change_the_result() { + let iv = pinned_iv(); + let plaintext = message(10 * TOY_LEN + 11); + + let reference = enc(&mut pinned_encryptor(iv), &plaintext); + assert_eq!(dec(&mut pinned_decryptor(iv), &reference), plaintext); + + for &enc_chunk in &CHUNKINGS { + let ct = enc_chunked(&mut pinned_encryptor(iv), &plaintext, enc_chunk); + assert_eq!(ct, reference, "encrypting in {enc_chunk}-byte calls"); + + for &dec_chunk in &CHUNKINGS { + let pt = dec_chunked(&mut pinned_decryptor(iv), &ct, dec_chunk); + assert_eq!( + pt, plaintext, + "encrypted in {enc_chunk}-byte calls, decrypted in {dec_chunk}-byte calls" + ); + } + } + + // Empty calls anywhere are no-ops, including mid-segment. + let mut e = pinned_encryptor(iv); + e.do_encrypt(&mut []).unwrap(); + let mut ct = plaintext.clone(); + e.do_encrypt(&mut ct[..5]).unwrap(); + e.do_encrypt(&mut []).unwrap(); + e.do_encrypt(&mut ct[5..]).unwrap(); + e.do_encrypt(&mut []).unwrap(); + assert_eq!(ct, reference, "empty calls must not disturb the state"); +} + +/// The same equivalence with **real AES**, at all three key lengths. +/// +/// `call_chunking_does_not_change_the_result` proves the property over the toy permutation, where +/// the mode's own bookkeeping is the only thing that can be wrong. This repeats it with the cipher +/// the mode is actually used with, so a chunking bug that only shows up for a 16-byte block under +/// a real key schedule -- rather than for the toy -- cannot hide. The AES coverage elsewhere +/// (`sp800_38a_cfb_tests.rs`, `acvp_cfb_tests.rs`) chunks against *published* ciphertext; this is +/// the direct single-call-versus-chunked comparison. +/// +/// The message is 171 bytes: not a whole number of blocks, so every chunking ends on a short final +/// segment, and long enough to run the decryptor's eight-block batch ten times over. +#[test] +fn aes_chunking_matches_a_single_call() { + fn check(name: &str) + where + P: ElectronicCodeBook, + { + let key_bytes: [u8; KEY_LEN] = + core::array::from_fn(|i| (i as u8).wrapping_mul(31).wrapping_add(7)); + let key = + KeyMaterial::::from_bytes_as_type(&key_bytes, KeyType::SymmetricCipherKey) + .expect("a valid AES key"); + let iv: [u8; 16] = core::array::from_fn(|i| 0xC3 ^ (i as u8)); + let plaintext: Vec = (0..171).map(|i| (i * 7 + i / 16) as u8).collect(); + + let encryptor = || { + let (enc, got) = Cfb::::do_encrypt_init_rng( + &key, + &mut FixedSeedRNG::<16>::new(iv), + ) + .expect("encrypt init"); + assert_eq!(got, iv, "{name}: the pinned RNG should reproduce the IV"); + enc + }; + let decryptor = + || Cfb::::do_decrypt_init(&key, &iv).expect("decrypt init"); + + // The reference: the whole message in one call. + let mut reference = plaintext.clone(); + encryptor().do_encrypt(&mut reference).expect("one-call encryption"); + assert_ne!(reference, plaintext, "{name}: the data must actually be encrypted"); + + // ...and the round trip of that, also in one call. + let mut back = reference.clone(); + decryptor().do_decrypt(&mut back).expect("one-call decryption"); + assert_eq!(back, plaintext, "{name}: one-call round trip"); + + for &enc_chunk in &CHUNKINGS { + let mut ct = plaintext.clone(); + let mut e = encryptor(); + for piece in ct.chunks_mut(enc_chunk) { + e.do_encrypt(piece).expect("chunked encryption"); + } + assert_eq!(ct, reference, "{name}: encrypting in {enc_chunk}-byte calls"); + + for &dec_chunk in &CHUNKINGS { + let mut pt = ct.clone(); + let mut d = decryptor(); + for piece in pt.chunks_mut(dec_chunk) { + d.do_decrypt(piece).expect("chunked decryption"); + } + assert_eq!( + pt, plaintext, + "{name}: encrypted in {enc_chunk}-byte calls, decrypted in {dec_chunk}-byte calls" + ); + } + } + } + + check::("AES-128"); + check::("AES-192"); + check::("AES-256"); +} + +/// The pair path in `do_decrypt` must actually be taken, and only where a pair of whole blocks sits +/// at a segment boundary. +/// +/// [`SwappedPairToy`] returns its two pair results in the wrong order while its single-block methods +/// are correct. CFB decryption pairs through `encrypt_blocks2`, so with this permutation two blocks +/// handed over together come out wrong, while the same bytes handed over one block at a time, or +/// offset by a partial segment so that no two whole blocks line up, come out right. If everything +/// came out right, the pair path would be dead code and every claim about it would be untested. +#[test] +fn the_pair_path_is_really_used() { + let key = toy_key(); + let iv = pinned_iv(); + let plaintext = message(2 * TOY_LEN); + + // The correct toy round-trips. + let ct = enc(&mut pinned_encryptor(iv), &plaintext); + assert_eq!(dec(&mut pinned_decryptor(iv), &ct), plaintext); + + // The swapped-pair toy encrypts identically -- CFB encryption is serial and never pairs, so its + // `encrypt_blocks2` override is not reached from the encryptor at all. + let (mut e, _) = + SwappedCfb::::do_encrypt_init_rng(&key, &mut pinned_rng(iv)).unwrap(); + assert_eq!(enc(&mut e, &plaintext), ct, "CFB encryption must not use the pair path"); + + // ...but decrypting the pair together must now be wrong, because the pair path is used. + let mut d = SwappedCfb::::do_decrypt_init(&key, &iv).unwrap(); + assert_ne!(dec(&mut d, &ct), plaintext, "decrypting a pair must go through encrypt_blocks2"); + + // Decrypting one block at a time avoids the pair path, so it is correct even for this toy. + let mut d = SwappedCfb::::do_decrypt_init(&key, &iv).unwrap(); + assert_eq!(dec_chunked(&mut d, &ct, TOY_LEN), plaintext, "the single-block path must not pair"); + + // So does splitting the pair across a segment boundary: 5 bytes, then 27. The second call has + // an 11-byte head, one whole block and no tail, so there is no pair to form. + let mut d = SwappedCfb::::do_decrypt_init(&key, &iv).unwrap(); + let mut got = ct.clone(); + d.do_decrypt(&mut got[..5]).unwrap(); + d.do_decrypt(&mut got[5..]).unwrap(); + assert_eq!(got, plaintext, "a pair not at a segment boundary is not a pair"); +} + +/// The eight-block path in `do_decrypt` must actually be taken, and only for full eights. +/// +/// [`SwappedEightToy`] returns its eight `encrypt_blocks8` results rotated while its pair and +/// single-block methods are correct. CFB decryption batches eights through the *forward* +/// `encrypt_blocks8`, so with this permutation nine blocks handed over together decrypt wrongly +/// (eight rotated, then one), while the same blocks handed over as two fours (pairs) or one at a +/// time decrypt correctly. Encryption is serial and never batches, so it is unaffected. +#[test] +fn the_eight_block_path_is_really_used() { + let key = toy_key(); + let iv = pinned_iv(); + let plaintext = message(9 * TOY_LEN); + + // The correct toy round-trips nine blocks. + let ct = enc(&mut pinned_encryptor(iv), &plaintext); + assert_eq!(dec(&mut pinned_decryptor(iv), &ct), plaintext); + + // The rotated-eight toy encrypts identically: CFB encryption is serial and never batches. + let (mut e, _) = + SwappedEightCfb::::do_encrypt_init_rng(&key, &mut pinned_rng(iv)).unwrap(); + assert_eq!(enc(&mut e, &plaintext), ct, "CFB encryption must not use the eight path"); + + // ...but nine blocks together must now be wrong, because the first eight go through + // encrypt_blocks8. + let mut d = SwappedEightCfb::::do_decrypt_init(&key, &iv).unwrap(); + assert_ne!(dec(&mut d, &ct), plaintext, "nine blocks must go through encrypt_blocks8"); + + // Two fours use the pair path only, so they are correct even for this toy... + let mut d = SwappedEightCfb::::do_decrypt_init(&key, &iv).unwrap(); + assert_eq!( + dec_chunked(&mut d, &ct, 4 * TOY_LEN), + plaintext, + "fours must not use the eight path" + ); + + // ...and so is one block at a time. + let mut d = SwappedEightCfb::::do_decrypt_init(&key, &iv).unwrap(); + assert_eq!( + dec_chunked(&mut d, &ct, TOY_LEN), + plaintext, + "the single-block path must not batch" + ); +} + +/// The one-shots (`encrypt` / `decrypt`, in place) must produce exactly what the streaming API +/// produces, for a message ending in a short segment and one that does not, in both directions. +#[test] +fn one_shots_agree_with_the_streaming_api() { + let key = toy_key(); + let iv = pinned_iv(); + + for len in [3 * TOY_LEN + 7, 4 * TOY_LEN] { + let plaintext = message(len); + let streamed = enc(&mut pinned_encryptor(iv), &plaintext); + + let mut buf = plaintext.clone(); + let iv_b = ToyCfb::::encrypt_rng(&key, &mut pinned_rng(iv), &mut buf).unwrap(); + assert_eq!(iv_b, iv); + assert_eq!(buf, streamed, "len {len}: one-shot must equal streaming"); + ToyCfb::::decrypt(&key, &iv, &mut buf).unwrap(); + assert_eq!(buf, plaintext); + + // The OS-RNG variant round-trips too. + let mut buf = plaintext.clone(); + let iv_fresh = ToyCfb::::encrypt(&key, &mut buf).unwrap(); + assert_ne!(buf, plaintext); + ToyCfb::::decrypt(&key, &iv_fresh, &mut buf).unwrap(); + assert_eq!(buf, plaintext); + } +} + +// ---- SP 800-38A Appendix D error propagation --------------------------------------------- + +/// The parts of Appendix D that follow from the equations and hold for *any* permutation. +/// +/// Table D.2 for CFB: a bit error in `Cj` gives "SBE in the decryption of `Cj`" -- specific bit +/// errors, i.e. the same bit positions -- because `Pj = Cj XOR Oj` and `Oj = CIPH_K(C_{j-1})` does +/// not depend on `Cj` at all. Earlier blocks are untouched, and with `s = b` the damage reaches +/// exactly one block further (`Cj+1`, since `b/s = 1`). A bit error in the short final segment is +/// the same story with nothing after it: the same bit of the same segment, and nothing else. +#[test] +fn a_ciphertext_bit_error_flips_exactly_that_bit_of_its_own_block() { + let iv = pinned_iv(); + let plaintext = message(4 * TOY_LEN + 5); + let ct = enc(&mut pinned_encryptor(iv), &plaintext); + + // Every bit of C2, so the SBE claim is checked exhaustively rather than at one position. + for byte in TOY_LEN..2 * TOY_LEN { + for bit in 0..8 { + let mut corrupt = ct.clone(); + corrupt[byte] ^= 1 << bit; + let got = dec(&mut pinned_decryptor(iv), &corrupt); + + assert_eq!(&got[..TOY_LEN], &plaintext[..TOY_LEN], "P1 depends only on the IV and C1"); + + let mut expected_p2 = plaintext[TOY_LEN..2 * TOY_LEN].to_vec(); + expected_p2[byte - TOY_LEN] ^= 1 << bit; + assert_eq!( + &got[TOY_LEN..2 * TOY_LEN], + &expected_p2[..], + "C2 byte {byte} bit {bit}: exactly that bit of P2 should change" + ); + + assert_ne!( + &got[2 * TOY_LEN..3 * TOY_LEN], + &plaintext[2 * TOY_LEN..3 * TOY_LEN], + "P3 comes from CIPH_K of the corrupted C2" + ); + assert_eq!( + &got[3 * TOY_LEN..], + &plaintext[3 * TOY_LEN..], + "P4 and the final segment are unaffected: b/s = 1, so damage stops at P3" + ); + } + } + + // Every bit of the short final segment. + for byte in 4 * TOY_LEN..plaintext.len() { + for bit in 0..8 { + let mut corrupt = ct.clone(); + corrupt[byte] ^= 1 << bit; + let got = dec(&mut pinned_decryptor(iv), &corrupt); + let mut expected = plaintext.clone(); + expected[byte] ^= 1 << bit; + assert_eq!( + got, expected, + "final segment byte {byte} bit {bit}: exactly that bit, and nothing else" + ); + } + } +} + +/// The parts of Appendix D that need a real cipher's diffusion, checked with AES-128. +/// +/// Table D.2 for CFB says the *other* affected block gets "RBE" -- random bit errors, "bit errors +/// occur independently in any bit position with an expected probability of 1/2". That is a property +/// of the block cipher, not of the mode, so the toy (whose rounds are byte-local) cannot show it. +/// +/// The point worth pinning is that CFB and CBC differ here, and in which direction: under CBC a +/// corrupted IV flips *exactly* the corresponding bit of `P1` (Appendix D, and +/// `an_iv_bit_error_flips_exactly_that_bit_of_the_first_block` in `cbc_tests.rs`), whereas under CFB +/// the IV goes through the cipher first, so `P1` is randomised instead. Confusing the two would be a +/// real bug and this is what catches it. +#[test] +fn an_iv_bit_error_randomises_only_the_first_block() { + type Aes128Cfb = Cfb; + const LEN: usize = 16; + + let key = KeyMaterial::<16>::from_bytes_as_type(&[0x42; 16], KeyType::SymmetricCipherKey) + .expect("a valid AES-128 key"); + let iv: [u8; LEN] = core::array::from_fn(|i| 0x0F ^ (i as u8)); + let plaintext = [[0x00u8; LEN], [0x11u8; LEN], [0x22u8; LEN]]; + + let (mut e, got_iv) = + Aes128Cfb::::do_encrypt_init_rng(&key, &mut FixedSeedRNG::::new(iv)) + .unwrap(); + assert_eq!(got_iv, iv); + let mut ct = plaintext; + e.do_encrypt(ct.as_flattened_mut()).unwrap(); + + let mut first_blocks = std::collections::BTreeSet::new(); + + for byte in 0..LEN { + for bit in 0..8 { + let mut corrupt_iv = iv; + corrupt_iv[byte] ^= 1 << bit; + + let mut d = Aes128Cfb::::do_decrypt_init(&key, &corrupt_iv).unwrap(); + let mut got = ct; + d.do_decrypt(got.as_flattened_mut()).unwrap(); + + // Only P1 is affected: with s = b, Appendix D's "first i/s (rounding up) ciphertext + // segments" is one segment for every bit position i. + assert_eq!(got[1], plaintext[1], "IV byte {byte} bit {bit}: P2 must be unaffected"); + assert_eq!(got[2], plaintext[2], "IV byte {byte} bit {bit}: P3 must be unaffected"); + + // ...and it is randomised, not flipped in place. The CBC behaviour would be a + // single-bit difference in exactly the position that was corrupted. + let differing_bits: u32 = + got[0].iter().zip(plaintext[0].iter()).map(|(a, b)| (a ^ b).count_ones()).sum(); + assert!( + differing_bits > 1, + "IV byte {byte} bit {bit}: P1 should be randomised, not flipped in place \ + ({differing_bits} bit(s) differ)" + ); + + let mut cbc_style = plaintext[0]; + cbc_style[byte] ^= 1 << bit; + assert_ne!(got[0], cbc_style, "CFB must not behave like CBC for a corrupted IV"); + + assert!(first_blocks.insert(got[0]), "distinct IVs should give distinct P1"); + } + } + + assert_eq!(first_blocks.len(), LEN * 8, "every corrupted IV should have been tried"); +} + +// ---- IV handling ------------------------------------------------------------------------- + +/// Two encryption flows under the same key must not reuse an IV. The framework checks this too; +/// repeated here because a repeated IV is worse for CFB than for CBC -- it leaks the XOR of the two +/// plaintexts, not merely their equality (see the crate docs, "Key and IV reuse"). +#[test] +fn each_encryption_gets_a_fresh_iv() { + let key = toy_key(); + let mut seen = std::collections::BTreeSet::new(); + for _ in 0..64 { + let (_, iv) = ToyCfb::::do_encrypt_init(&key).unwrap(); + assert!(seen.insert(iv), "IV repeated across encryptions: {iv:02x?}"); + } +} + +/// Identical plaintext under the same key must give different ciphertext, because the IV differs. +#[test] +fn identical_plaintext_gives_different_ciphertext() { + let key = toy_key(); + let plaintext = [0x77u8; 2 * TOY_LEN]; + + let mut first = plaintext; + ToyCfb::::encrypt(&key, &mut first).unwrap(); + let mut second = plaintext; + ToyCfb::::encrypt(&key, &mut second).unwrap(); + assert_ne!(first, second); + + // ...and, within one message, two identical plaintext blocks must not give identical ciphertext + // blocks either, because the keystream block differs. + assert_ne!( + first[..TOY_LEN], + first[TOY_LEN..], + "feedback should break the ECB pattern within a message" + ); +} + +// ---- key handling ------------------------------------------------------------------------ + +#[test] +fn a_key_of_the_wrong_type_is_rejected() { + let bytes: [u8; TOY_LEN] = core::array::from_fn(|i| (i as u8) + 1); + let seed = KeyMaterial::::from_bytes_as_type(&bytes, KeyType::Seed).unwrap(); + assert!(ToyCfb::::do_encrypt_init(&seed).is_err()); + assert!(ToyCfb::::do_decrypt_init(&seed, &[0u8; TOY_LEN]).is_err()); +} + +// ---- every length, no padding ------------------------------------------------------------ + +/// CFB is a stream cipher: every length round-trips, the ciphertext is exactly as long as the +/// plaintext, and no padding layer is involved. Every length from empty to just past three blocks +/// covers the empty message, a lone short segment, exact multiples and every partial final segment. +#[test] +fn every_length_round_trips_without_padding() { + let key = toy_key(); + for len in 0..=(3 * TOY_LEN + 1) { + let plaintext = message(len); + let mut data = plaintext.clone(); + let iv = ToyCfb::::encrypt(&key, &mut data).expect("encryption"); + assert_eq!(data.len(), len, "len {len}: the ciphertext is as long as the plaintext"); + // Only meaningful once the message is long enough that agreeing with the keystream by + // chance is negligible: a 1-byte message coincides with its own ciphertext whenever the + // single keystream byte is zero, which a fresh random IV makes happen about once in 256 + // runs. At 8 bytes the odds are 2^-64. (This is why the assertion is guarded rather than + // dropped: it is worth making, just not at every length.) + if len >= 8 { + assert_ne!(data, plaintext, "len {len}: the data must actually be encrypted"); + } + ToyCfb::::decrypt(&key, &iv, &mut data).expect("decryption"); + assert_eq!(data, plaintext, "len {len}: round trip"); + } +} + +// ---- memory ------------------------------------------------------------------------------ + +/// Pins the "Memory Usage" table in the crate docs, and the claim that CFB costs one `usize` more +/// than CBC: the block that is `Ij`, `Oj` and `I_{j+1}` in turn, plus the count of how much of it +/// has been used. +#[test] +fn sizes_match_the_documented_memory_table() { + use core::mem::size_of; + + assert_eq!(size_of::>(), 176 + 16 + 8); + assert_eq!(size_of::>(), 208 + 16 + 8); + assert_eq!(size_of::>(), 240 + 16 + 8); + + // The direction marker is free, and does not change the layout. + assert_eq!( + size_of::>(), + size_of::>() + ); + + // ...and the general rule the docs state. + assert_eq!( + size_of::>(), + size_of::() + 16 + size_of::() + ); + + // The docs say CFB is one `usize` bigger than CBC. + assert_eq!( + size_of::>(), + size_of::>() + size_of::() + ); +} diff --git a/crypto/modes/tests/common/mod.rs b/crypto/modes/tests/common/mod.rs new file mode 100644 index 00000000..306b3052 --- /dev/null +++ b/crypto/modes/tests/common/mod.rs @@ -0,0 +1,222 @@ +//! Toy [`ElectronicCodeBook`] implementations, for testing the mode independently of any real cipher. +//! +//! These are **not** cryptography. They exist so the structural properties of a mode -- chaining, +//! sequencing, the pair/remainder split, direction typing -- can be tested without an AES +//! dependency and without a real cipher's vectors getting in the way. The real known-answer tests +//! are in `sp800_38a_tests.rs`. +//! +//! # Why not XOR +//! +//! The obvious toy, `block[i] ^= key[i]`, is its own inverse. That would make `encrypt_block` and +//! `decrypt_block` the same function, which hides exactly the bugs these tests are for: a CBC +//! decryptor that called the forward function, or an encryptor that called the inverse, would still +//! round-trip. [`Toy`] is therefore asymmetric: it rotates before XOR-ing, so the two directions are +//! genuinely different functions. + +// Each test binary that includes this module uses a subset of it -- `cfb_tests.rs` needs +// `ForwardOnlyToy`, `cbc_tests.rs` does not -- and an unused item in an integration test's private +// module is otherwise a dead-code warning. +#![allow(dead_code)] + +use bouncycastle_core::errors::{KeyMaterialError, SymmetricCipherError}; +use bouncycastle_core::key_material::{KeyMaterial, KeyMaterialTrait, KeyType}; +use bouncycastle_core::traits::{Algorithm, ElectronicCodeBook, SecurityStrength}; + +/// Block and key length of the toy ciphers, chosen to match AES so the tests exercise the same +/// shapes the real thing will. +pub const TOY_LEN: usize = 16; + +/// Shared key validation, so the toys reject the same keys a real permutation would and the +/// framework's key-handling checks are meaningful. +fn validate(key: &dyn KeyMaterialTrait) -> Result<(), SymmetricCipherError> { + if key.key_type() != KeyType::SymmetricCipherKey { + return Err( + KeyMaterialError::InvalidKeyType("toy cipher needs a SymmetricCipherKey").into() + ); + } + if key.key_len() != TOY_LEN { + return Err(KeyMaterialError::InvalidLength.into()); + } + if key.security_strength() < SecurityStrength::_128bit { + return Err(KeyMaterialError::SecurityStrength("toy cipher needs a 128-bit key").into()); + } + Ok(()) +} + +/// An asymmetric toy permutation: `encrypt` is `rotate_left(1)` then XOR with the key byte. +/// +/// A true permutation on each byte, so it is a true permutation on the block, and its inverse is +/// distinctly different code (XOR then `rotate_right(1)`). +pub struct Toy { + key: [u8; TOY_LEN], +} + +impl Algorithm for Toy { + const ALG_NAME: &'static str = "Toy"; + const MAX_SECURITY_STRENGTH: SecurityStrength = SecurityStrength::_128bit; +} + +impl ElectronicCodeBook for Toy { + fn new(key: &KeyMaterial) -> Result { + validate(key)?; + let mut bytes = [0u8; TOY_LEN]; + bytes.copy_from_slice(key.ref_to_bytes()); + Ok(Self { key: bytes }) + } + + fn encrypt_block(&self, block: &mut [u8; TOY_LEN]) { + for (b, k) in block.iter_mut().zip(self.key.iter()) { + *b = b.rotate_left(1) ^ *k; + } + } + + fn decrypt_block(&self, block: &mut [u8; TOY_LEN]) { + for (b, k) in block.iter_mut().zip(self.key.iter()) { + *b = (*b ^ *k).rotate_right(1); + } + } +} + +/// A deliberately broken toy whose pair methods **swap** their two results. +/// +/// Used to prove that the mode really does take the pair path: with this permutation, a CBC +/// decryptor that uses `decrypt_blocks2` must produce something other than the correct plaintext. +/// If a test using this still round-trips, the pair path is dead code and the coverage claimed for +/// it is false. +/// +/// Its single-block methods are identical to [`Toy`]'s, so the two agree on odd-length input. +pub struct SwappedPairToy { + inner: Toy, +} + +impl Algorithm for SwappedPairToy { + const ALG_NAME: &'static str = "SwappedPairToy"; + const MAX_SECURITY_STRENGTH: SecurityStrength = SecurityStrength::_128bit; +} + +impl ElectronicCodeBook for SwappedPairToy { + fn new(key: &KeyMaterial) -> Result { + Ok(Self { inner: Toy::new(key)? }) + } + + fn encrypt_block(&self, block: &mut [u8; TOY_LEN]) { + self.inner.encrypt_block(block); + } + + fn decrypt_block(&self, block: &mut [u8; TOY_LEN]) { + self.inner.decrypt_block(block); + } + + fn encrypt_blocks2(&self, blocks: &mut [[u8; TOY_LEN]; 2]) { + self.inner.encrypt_block(&mut blocks[0]); + self.inner.encrypt_block(&mut blocks[1]); + blocks.swap(0, 1); + } + + fn decrypt_blocks2(&self, blocks: &mut [[u8; TOY_LEN]; 2]) { + self.inner.decrypt_block(&mut blocks[0]); + self.inner.decrypt_block(&mut blocks[1]); + blocks.swap(0, 1); + } +} + +/// A toy whose **inverse cipher function panics**. +/// +/// SP 800-38A Sec 6.3 applies the forward cipher function in both directions of CFB, so a correct +/// `Cfb` never touches `decrypt_block`, `decrypt_blocks2` or `decrypt_blocks8`. Running a full CFB round trip over this +/// permutation turns that claim into a test: if either decryption entry point is ever reached, the +/// test panics with the message below rather than quietly producing a right answer for the wrong +/// reason. +/// +/// This is deliberately not a valid [`ElectronicCodeBook`] -- it cannot pass +/// `TestFrameworkElectronicCodeBook`, which exercises both directions -- so it is only ever used with +/// `Cfb`. Its forward methods delegate to [`Toy`], including the pair and eight-block methods, so a CFB round trip +/// over it must agree with one over `Toy`. +pub struct ForwardOnlyToy { + inner: Toy, +} + +impl Algorithm for ForwardOnlyToy { + const ALG_NAME: &'static str = "ForwardOnlyToy"; + const MAX_SECURITY_STRENGTH: SecurityStrength = SecurityStrength::_128bit; +} + +impl ElectronicCodeBook for ForwardOnlyToy { + fn new(key: &KeyMaterial) -> Result { + Ok(Self { inner: Toy::new(key)? }) + } + + fn encrypt_block(&self, block: &mut [u8; TOY_LEN]) { + self.inner.encrypt_block(block); + } + + fn decrypt_block(&self, _block: &mut [u8; TOY_LEN]) { + panic!("CFB must never call the inverse cipher function (SP 800-38A Sec 6.3)"); + } + + fn encrypt_blocks2(&self, blocks: &mut [[u8; TOY_LEN]; 2]) { + self.inner.encrypt_blocks2(blocks); + } + + fn decrypt_blocks2(&self, _blocks: &mut [[u8; TOY_LEN]; 2]) { + panic!("CFB must never call the inverse cipher pair function (SP 800-38A Sec 6.3)"); + } + + fn encrypt_blocks8(&self, blocks: &mut [[u8; TOY_LEN]; 8]) { + self.inner.encrypt_blocks8(blocks); + } + + fn decrypt_blocks8(&self, _blocks: &mut [[u8; TOY_LEN]; 8]) { + panic!("CFB must never call the inverse cipher eight-block function (SP 800-38A Sec 6.3)"); + } +} + +/// A [`Toy`] whose `encrypt_blocks8` / `decrypt_blocks8` return their eight results rotated by one +/// slot, while every other method -- single block and pair -- is correct. +/// +/// The eight-block analogue of [`SwappedPairToy`]: a CBC decryptor that uses `decrypt_blocks8` +/// must produce something other than the correct plaintext for eight or more blocks, while fewer +/// than eight, which go through the pair and single paths, still round-trip. +pub struct SwappedEightToy { + inner: Toy, +} + +impl Algorithm for SwappedEightToy { + const ALG_NAME: &'static str = "SwappedEightToy"; + const MAX_SECURITY_STRENGTH: SecurityStrength = SecurityStrength::_128bit; +} + +impl ElectronicCodeBook for SwappedEightToy { + fn new(key: &KeyMaterial) -> Result { + Ok(Self { inner: Toy::new(key)? }) + } + + fn encrypt_block(&self, block: &mut [u8; TOY_LEN]) { + self.inner.encrypt_block(block); + } + + fn decrypt_block(&self, block: &mut [u8; TOY_LEN]) { + self.inner.decrypt_block(block); + } + + fn encrypt_blocks8(&self, blocks: &mut [[u8; TOY_LEN]; 8]) { + for block in blocks.iter_mut() { + self.inner.encrypt_block(block); + } + blocks.rotate_left(1); + } + + fn decrypt_blocks8(&self, blocks: &mut [[u8; TOY_LEN]; 8]) { + for block in blocks.iter_mut() { + self.inner.decrypt_block(block); + } + blocks.rotate_left(1); + } +} + +/// Builds a `KeyMaterial` for the toys from a fixed non-zero pattern. +pub fn toy_key() -> KeyMaterial { + let bytes: [u8; TOY_LEN] = core::array::from_fn(|i| (i as u8).wrapping_mul(7).wrapping_add(1)); + KeyMaterial::::from_bytes_as_type(&bytes, KeyType::SymmetricCipherKey) + .expect("a valid toy key") +} diff --git a/crypto/modes/tests/ctr_bc_java_tests.rs b/crypto/modes/tests/ctr_bc_java_tests.rs new file mode 100644 index 00000000..b0babd62 --- /dev/null +++ b/crypto/modes/tests/ctr_bc_java_tests.rs @@ -0,0 +1,167 @@ +//! Cross-implementation tests for CTR against **BC Java's `SICBlockCipher`**. +//! +//! # Why this is the closest comparison available +//! +//! `ctr_vector_tests.rs` checks against OpenSSL, but OpenSSL's `-aes-*-ctr` takes the whole 16-byte +//! initial counter block as its IV: it has no notion of a nonce, and its counter is always the full +//! block. It can therefore only ever agree with this type at the one width where the two coincide, +//! and it cannot exercise a **narrow** counter at all. +//! +//! BC Java's `SICBlockCipher` (Segmented Integer Counter, its name for CTR) is built the same way +//! this type is. Given an IV shorter than the block it +//! +//! * copies the IV into the leading bytes and **zero-fills the rest**, so the counter starts at 0 +//! (`reset()`); +//! * increments the trailing bytes big-endian with carry (`incrementCounter()`); +//! * and **throws** `IllegalStateException("Counter in CTR/SIC mode out of range.")` once the carry +//! would reach the IV, which `checkCounter()` detects by comparing the leading bytes back against +//! the IV. +//! +//! That is the same construction, the same starting value and the same overflow rule, so it can +//! check the counter widths OpenSSL cannot reach. The one difference is the cap: BC Java allows a +//! counter up to `min(8, blockSize / 2)` bytes, which is 8 for AES, where this type stops at 4. Ours +//! is a subset, and on the overlap (nonce 12 to 15 bytes) the two agree exactly. +//! +//! # Provenance +//! +//! The blocks below are the **keystream**, i.e. `Oj = CIPH_K(N | j)`, obtained by encrypting zeros +//! with `SICBlockCipher.newInstance(AESEngine.newInstance())` under AES-128 key +//! `2b7e151628aed2a6abf7158809cf4f3c`, from the working tree of `bc-java` at +//! `core/src/main/java/org/bouncycastle/crypto/modes/SICBlockCipher.java`. Encrypting zeros is used +//! so the values are the keystream itself rather than a keystream XORed with something, which makes +//! a mismatch point straight at the counter block that produced it. +//! +//! Whole-message agreement with BC Java was also checked while these were generated -- the 69-byte +//! vectors of `ctr_vector_tests.rs` and a 5000-byte message across the 255-to-256 carry, at all +//! three key lengths -- and it is exact. Those cases are covered there and by the ACVP suite, so +//! what is pinned here is specifically the part neither of them reaches: the narrow counters. + +use bouncycastle_aes_lowmemory::Aes128; +use bouncycastle_core::key_material::{KeyMaterial, KeyType}; +use bouncycastle_core::traits::StreamCipherEncryptor; +use bouncycastle_core_test_framework::FixedSeedRNG; +use bouncycastle_hex as hex; +use bouncycastle_modes::{Ctr, Encrypting}; + +/// The AES-128 key used for every vector in this file: SP 800-38A Appendix F's first key. +const KEY: &str = "2b7e151628aed2a6abf7158809cf4f3c"; + +fn key() -> KeyMaterial<16> { + let raw = hex::decode(KEY).expect("valid hex"); + KeyMaterial::<16>::from_bytes_as_type(&raw, KeyType::SymmetricCipherKey).expect("a valid key") +} + +/// Produces `blocks` blocks of keystream by encrypting zeros under the given nonce. +fn keystream(nonce_hex: &str, blocks: usize) -> Vec { + let nonce: [u8; NONCE_LEN] = + hex::decode(nonce_hex).expect("valid hex").try_into().expect("nonce length"); + let (mut enc, got) = Ctr::::do_encrypt_init_rng( + &key(), + &mut FixedSeedRNG::::new(nonce), + ) + .expect("encrypt init"); + assert_eq!(got, nonce, "the pinned RNG should reproduce the nonce"); + + let mut data = vec![0u8; blocks * 16]; + enc.do_encrypt(&mut data).expect("encryption"); + data +} + +/// Checks the numbered keystream blocks against BC Java's. +fn check(name: &str, keystream: &[u8], expected: &[(usize, &str)]) { + for (j, want) in expected { + let got = &keystream[j * 16..(j + 1) * 16]; + let got_hex: String = got.iter().map(|b| format!("{b:02x}")).collect(); + assert_eq!( + &got_hex, want, + "{name}: keystream block {j} must match BC Java's SICBlockCipher" + ); + } +} + +/// A **1-byte** counter (15-byte nonce): the narrowest this type allows, and a width OpenSSL cannot +/// express at all. Blocks 254 and 255 are the last two the counter can produce, so this pins the top +/// of the range as well as the bottom. +#[test] +fn one_byte_counter_matches_bc_java() { + const NONCE: &str = "5a5b5c5d5e5f606162636465666768"; + let ks = keystream::<15>(NONCE, 256); + check( + "1-byte counter", + &ks, + &[ + (0, "419c915d236c793736311df5d96395aa"), + (1, "23af650ed9d051ac2d5ed6365ff36b1e"), + (2, "1e1723bab8f7a67f152ae5bf5e0a6156"), + (254, "da78aa259930654dec5fd7b1bd194ee9"), + (255, "3e0caa53956c10ee5c3959d588b79cf3"), + ], + ); +} + +/// A **2-byte** counter (14-byte nonce), spanning the 255-to-256 boundary. +/// +/// That boundary is the carry from one counter byte into the next, and it is the case a per-byte +/// increment that forgot to carry, or one that wrote the counter little-endian, would get wrong. +/// BC Java carries the same way, so agreement across blocks 255 and 256 pins it. +#[test] +fn two_byte_counter_matches_bc_java_across_the_carry() { + const NONCE: &str = "3c3d3e3f40414243444546474849"; + let ks = keystream::<14>(NONCE, 260); + check( + "2-byte counter", + &ks, + &[ + (0, "2f79f802e5baf1eea03e079c55fa43ff"), + (254, "7ef19c2ab2e750a19741a653edabd4e2"), + (255, "a30a0d0c6c2c58bb04befb8aa32675ee"), + (256, "580080107847864b8589e21a9fb3cdff"), + (257, "fd85537add6a73476e13928f49eba5ee"), + ], + ); +} + +/// A **3-byte** counter (13-byte nonce), the remaining width between the two above and the 4-byte +/// counter the ACVP and OpenSSL suites cover. +#[test] +fn three_byte_counter_matches_bc_java() { + const NONCE: &str = "0102030405060708090a0b0c0d"; + let ks = keystream::<13>(NONCE, 3); + check( + "3-byte counter", + &ks, + &[ + (0, "e24be69cfe7c13dd7a94807fb91f95a7"), + (1, "234790f73eb542c18dbfc2a6f7a06795"), + (2, "95e5a3963bcdf6183357da61878861bc"), + ], + ); +} + +/// The counter limit falls in the same place as BC Java's. +/// +/// BC Java throws `IllegalStateException("Counter in CTR/SIC mode out of range.")` on the byte after +/// the counter's last value; this type returns `SymmetricCipherError::StateError` on the same byte. +/// Checked here at the same 15-byte nonce as above, where the boundary is 256 blocks -- 4096 bytes +/// exactly -- and confirmed against BC Java at the 14-byte nonce too, where it is 1 MiB. +#[test] +fn the_counter_limit_falls_where_bc_java_throws() { + let nonce: [u8; 15] = + hex::decode("5a5b5c5d5e5f606162636465666768").unwrap().try_into().unwrap(); + let (mut enc, _) = Ctr::::do_encrypt_init_rng( + &key(), + &mut FixedSeedRNG::<15>::new(nonce), + ) + .unwrap(); + + // BC Java encrypts 4096 bytes under this IV without complaint. + let mut data = vec![0u8; 4096]; + enc.do_encrypt(&mut data).expect("4096 bytes must be accepted, as BC Java accepts them"); + + // ...and throws on the next byte. + let mut one = [0u8; 1]; + assert!( + enc.do_encrypt(&mut one).is_err(), + "byte 4097 must be refused, where BC Java throws IllegalStateException" + ); +} diff --git a/crypto/modes/tests/ctr_tests.rs b/crypto/modes/tests/ctr_tests.rs new file mode 100644 index 00000000..f9af6444 --- /dev/null +++ b/crypto/modes/tests/ctr_tests.rs @@ -0,0 +1,738 @@ +//! Structural tests for CTR, driven by a toy permutation. +//! +//! These check the properties of the *mode* -- the counter block construction, the standard +//! incrementing function, the counter limit and its error, call sequencing at arbitrary byte +//! boundaries, the batch paths in both directions, direction typing, and the "forward cipher +//! function only" rule -- independently of any real cipher. The known-answer tests against the NIST +//! ACVP `ACVP-AES-CTR` set are in `acvp_ctr_tests.rs`. +//! +//! The toy's own conformance to [`ElectronicCodeBook`] is pinned once, by +//! `the_toy_permutation_conforms_to_the_trait` in `cbc_tests.rs`; it is the same `Toy` here, so it +//! is not re-run. +//! +//! # Why there is no SP 800-38A Appendix F.5 suite +//! +//! F.5 gives each vector a full 16-byte "Init. Counter" -- `f0f1f2f3f4f5f6f7f8f9fafbfcfdfeff` -- +//! whose counter part starts at `0xfcfdfeff`, not at zero. [`Ctr`] takes a *nonce* as its init data +//! and always starts the counter at zero, so those vectors cannot be expressed through its API. +//! What the F.5 counter blocks do confirm is the shape of the split this type uses: across the four +//! blocks they increment only within the last four bytes (`fcfdfeff`, `fcfdff00`, `fcfdff01`, +//! `fcfdff02`), leaving the leading twelve fixed, which is exactly a 12-byte nonce and a 4-byte +//! counter. `the_f5_counter_blocks_have_the_shape_this_type_assumes` pins that reading, and the +//! ACVP suite supplies the actual known-answer coverage. + +mod common; + +use bouncycastle_aes_lowmemory::{Aes128, Aes192, Aes256}; +use bouncycastle_core::errors::SymmetricCipherError; +use bouncycastle_core::key_material::{KeyMaterial, KeyType}; +use bouncycastle_core::traits::{ElectronicCodeBook, StreamCipherDecryptor, StreamCipherEncryptor}; +use bouncycastle_core_test_framework::FixedSeedRNG; +use bouncycastle_core_test_framework::symmetric_ciphers::TestFrameworkStreamCipher; +use bouncycastle_modes::{Ctr, Decrypting, Encrypting}; +use common::{ForwardOnlyToy, SwappedEightToy, SwappedPairToy, TOY_LEN, Toy, toy_key}; + +/// The default shape under test: a 12-byte nonce, so a 4-byte counter. +const NONCE_LEN: usize = 12; +type ToyCtr = Ctr; +type SwappedCtr = Ctr; +type ForwardOnlyCtr = Ctr; +type SwappedEightCtr = Ctr; + +/// A 15-byte nonce leaves a **1-byte** counter, so the whole counter space is 256 blocks -- 4 KiB +/// of keystream. That makes the exhaustion behaviour reachable in a test. +const SHORT_CTR_NONCE_LEN: usize = 15; +type TinyCtr = Ctr; +/// Capacity of a 1-byte counter, in bytes. +const TINY_CAPACITY: usize = 256 * TOY_LEN; + +fn enc(e: &mut impl StreamCipherEncryptor, plaintext: &[u8]) -> Vec { + let mut data = plaintext.to_vec(); + e.do_encrypt(&mut data).unwrap(); + data +} + +fn dec(d: &mut impl StreamCipherDecryptor, ciphertext: &[u8]) -> Vec { + let mut data = ciphertext.to_vec(); + d.do_decrypt(&mut data).unwrap(); + data +} + +fn dec_chunked( + d: &mut impl StreamCipherDecryptor, + ciphertext: &[u8], + chunk: usize, +) -> Vec { + let mut data = ciphertext.to_vec(); + for piece in data.chunks_mut(chunk) { + d.do_decrypt(piece).unwrap(); + } + data +} + +fn pinned_nonce() -> [u8; NONCE_LEN] { + core::array::from_fn(|i| 0xA0 ^ (i as u8)) +} + +fn pinned_rng(nonce: [u8; NONCE_LEN]) -> FixedSeedRNG { + FixedSeedRNG::::new(nonce) +} + +fn pinned_encryptor(nonce: [u8; NONCE_LEN]) -> ToyCtr { + let (e, got) = + ToyCtr::::do_encrypt_init_rng(&toy_key(), &mut pinned_rng(nonce)).unwrap(); + assert_eq!(got, nonce, "the pinned RNG should reproduce the nonce"); + e +} + +fn pinned_decryptor(nonce: [u8; NONCE_LEN]) -> ToyCtr { + ToyCtr::::do_decrypt_init(&toy_key(), &nonce).unwrap() +} + +fn message(len: usize) -> Vec { + (0..len).map(|i| (i * 7 + (i / TOY_LEN) * 31 + 1) as u8).collect() +} + +const CHUNKINGS: [usize; 12] = [1, 3, 5, 7, 15, 16, 17, 31, 32, 33, 64, 100]; + +// ---- the mode against the shared framework ------------------------------------------------ + +#[test] +fn ctr_conforms_to_the_stream_cipher_framework() { + TestFrameworkStreamCipher::new() + .test::, ToyCtr>(); +} + +// ---- the spec equations ------------------------------------------------------------------- + +/// CTR from SP 800-38A Sec 6.5, written out longhand against the raw permutation: +/// +/// ```text +/// Tj = N | [j - 1]m; Oj = CIPH_K(Tj); Cj = Pj XOR Oj; C*_n = P*_n XOR MSB_u(On) +/// ``` +/// +/// The counter block is built here from scratch on every block, from the nonce and the index, so it +/// is an independent statement of the construction rather than a second call to the same +/// incrementing code the implementation uses. +fn reference_ctr(perm: &Toy, nonce: [u8; NONCE_LEN], input: &[u8]) -> Vec { + let mut out = Vec::with_capacity(input.len()); + for (j, chunk) in input.chunks(TOY_LEN).enumerate() { + let mut t = [0u8; TOY_LEN]; + t[..NONCE_LEN].copy_from_slice(&nonce); + t[NONCE_LEN..].copy_from_slice(&(j as u32).to_be_bytes()); + let mut o = t; + perm.encrypt_block(&mut o); // Oj = CIPH_K(Tj) + // Cj = Pj XOR Oj, and for a short final block only its leading bytes: MSB_u(On). + out.extend(chunk.iter().zip(o.iter()).map(|(d, o)| d ^ o)); + } + out +} + +/// The mode must reproduce the Sec 6.5 equations exactly, for whole blocks and for a message ending +/// in a partial block. +/// +/// A reference implementation is a weak test on its own, so this also pins the anchors that follow +/// directly from the equations: the first counter block is the nonce with a zero counter, and +/// encrypting zeros reveals the keystream itself. +#[test] +fn the_mode_matches_the_spec_equations() { + let key = toy_key(); + let nonce = pinned_nonce(); + let perm = >::new(&key).unwrap(); + + for len in [1, TOY_LEN - 1, TOY_LEN, TOY_LEN + 1, 5 * TOY_LEN, 5 * TOY_LEN + 9] { + let plaintext = message(len); + let ct = enc(&mut pinned_encryptor(nonce), &plaintext); + assert_eq!( + ct, + reference_ctr(&perm, nonce, &plaintext), + "len {len}: encryption must match the Sec 6.5 equations" + ); + assert_eq!(dec(&mut pinned_decryptor(nonce), &ct), plaintext, "len {len}: round trip"); + } + + // Anchor 1: `T1 = N | 0`, so `O1 = CIPH_K(N | 0)` and encrypting a zero block yields it. + let mut t1 = [0u8; TOY_LEN]; + t1[..NONCE_LEN].copy_from_slice(&nonce); + let mut o1 = t1; + perm.encrypt_block(&mut o1); + assert_eq!( + enc(&mut pinned_encryptor(nonce), &[0u8; TOY_LEN]), + o1.to_vec(), + "encrypting a zero block yields O1 = CIPH_K(N | 0)" + ); + + // Anchor 2: the cipher never touches the data. The keystream depends only on the key and the + // counter blocks, so two messages encrypted under the same nonce satisfy + // `C XOR C' == P XOR P'` -- the defining property of a keystream mode, and the reason a nonce + // must never repeat. A mode that put the plaintext through the cipher could not satisfy it. + let p1 = message(3 * TOY_LEN + 4); + let p2: Vec = p1.iter().map(|b| b ^ 0x5A).collect(); + let c1 = enc(&mut pinned_encryptor(nonce), &p1); + let c2 = enc(&mut pinned_encryptor(nonce), &p2); + let ct_xor: Vec = c1.iter().zip(c2.iter()).map(|(a, b)| a ^ b).collect(); + let pt_xor: Vec = p1.iter().zip(p2.iter()).map(|(a, b)| a ^ b).collect(); + assert_eq!(ct_xor, pt_xor, "C XOR C' must equal P XOR P' under a repeated nonce"); +} + +/// **Encryption and decryption are the same operation** (Sec 6.5): both compute `CIPH_K(Tj)` and +/// XOR it in. Running the encryptor over ciphertext must therefore recover the plaintext, which is +/// the sharpest statement of that property and would fail for every other mode in this crate. +#[test] +fn encryption_and_decryption_are_the_same_operation() { + let nonce = pinned_nonce(); + let plaintext = message(3 * TOY_LEN + 5); + + let ct = enc(&mut pinned_encryptor(nonce), &plaintext); + assert_eq!(enc(&mut pinned_encryptor(nonce), &ct), plaintext, "the encryptor decrypts too"); + assert_eq!(dec(&mut pinned_decryptor(nonce), &ct), plaintext, "and so does the decryptor"); +} + +// ---- the counter --------------------------------------------------------------------------- + +/// The counter blocks are the nonce followed by a big-endian counter from zero, incremented by +/// Appendix B.1's standard incrementing function -- **at every permitted counter width**. +/// +/// Read out of the keystream rather than out of the mode's private state: encrypting zeros gives +/// `Oj`, and `Oj` must equal `CIPH_K(N | [j]m)` computed independently here from the nonce and the +/// index. +/// +/// Running this at all four widths matters more than it looks. The counter occupies the trailing +/// `CTR_LEN` bytes, so writing it involves a width-dependent slice, and getting that wrong is a bug +/// that **round-trip tests cannot see**: encryption and decryption would build the same wrong +/// counter block and still recover the plaintext, while producing ciphertext no other +/// implementation agrees with. Only checking the keystream against an independently built counter +/// block catches it. +/// +/// Where the counter is wide enough, the run crosses the 255 -> 256 boundary, which is the carry +/// between counter bytes that a per-byte increment could get wrong. +fn check_counter_blocks(blocks: usize) { + const fn ctr_len() -> usize { + TOY_LEN - N + } + + let key = toy_key(); + let perm = >::new(&key).unwrap(); + let nonce: [u8; N] = core::array::from_fn(|i| (i as u8).wrapping_mul(13).wrapping_add(5)); + + let (mut e, got) = Ctr::::do_encrypt_init_rng( + &key, + &mut FixedSeedRNG::::new(nonce), + ) + .unwrap(); + assert_eq!(got, nonce); + let mut keystream = vec![0u8; blocks * TOY_LEN]; + e.do_encrypt(&mut keystream).expect("the run must fit in the counter space"); + + for j in 0..blocks { + let mut expected = [0u8; TOY_LEN]; + expected[..N].copy_from_slice(&nonce); + // The counter, big-endian, in the trailing CTR_LEN bytes: the low CTR_LEN bytes of the + // index written big-endian. + let be = (j as u64).to_be_bytes(); + expected[N..].copy_from_slice(&be[be.len() - ctr_len::()..]); + perm.encrypt_block(&mut expected); + assert_eq!( + &keystream[j * TOY_LEN..(j + 1) * TOY_LEN], + &expected[..], + "counter width {}: block {j} must be CIPH_K(nonce | {j} big-endian)", + ctr_len::() + ); + } +} + +#[test] +fn counter_blocks_are_the_nonce_then_a_big_endian_counter_from_zero() { + // A 1-byte counter has exactly 256 blocks, so that is the whole space and there is no internal + // carry to cross. The wider ones run past 256 so that the 255 -> 256 carry is exercised. + check_counter_blocks::<15>(256); // 1-byte counter, its entire space + check_counter_blocks::<14>(258); // 2-byte counter, across the carry + check_counter_blocks::<13>(258); // 3-byte counter, across the carry + check_counter_blocks::<12>(258); // 4-byte counter, across the carry +} + +/// SP 800-38A Appendix F.5's counter blocks increment only within their last four bytes +/// (`fcfdfeff`, `fcfdff00`, `fcfdff01`, `fcfdff02`), leaving the leading twelve fixed. +/// +/// That is the nonce-and-counter split this type is built on, so the spec's own example vectors +/// corroborate the shape even though their non-zero starting counter puts them out of reach of this +/// API. See the module docs. +#[test] +fn the_f5_counter_blocks_have_the_shape_this_type_assumes() { + /// F.5.1 CTR-AES128.Encrypt, the four tabulated "Input Block" values. + const F5_COUNTER_BLOCKS: [[u8; 16]; 4] = [ + [ + 0xf0, 0xf1, 0xf2, 0xf3, 0xf4, 0xf5, 0xf6, 0xf7, 0xf8, 0xf9, 0xfa, 0xfb, 0xfc, 0xfd, + 0xfe, 0xff, + ], + [ + 0xf0, 0xf1, 0xf2, 0xf3, 0xf4, 0xf5, 0xf6, 0xf7, 0xf8, 0xf9, 0xfa, 0xfb, 0xfc, 0xfd, + 0xff, 0x00, + ], + [ + 0xf0, 0xf1, 0xf2, 0xf3, 0xf4, 0xf5, 0xf6, 0xf7, 0xf8, 0xf9, 0xfa, 0xfb, 0xfc, 0xfd, + 0xff, 0x01, + ], + [ + 0xf0, 0xf1, 0xf2, 0xf3, 0xf4, 0xf5, 0xf6, 0xf7, 0xf8, 0xf9, 0xfa, 0xfb, 0xfc, 0xfd, + 0xff, 0x02, + ], + ]; + + // The leading 12 bytes are identical in all four: that is the nonce. + for (i, block) in F5_COUNTER_BLOCKS.iter().enumerate() { + assert_eq!( + &block[..12], + &F5_COUNTER_BLOCKS[0][..12], + "F.5 block {i}: the leading 12 bytes must be fixed, i.e. a nonce" + ); + } + + // ...and the trailing 4 are a big-endian counter incremented by one each time, carrying. + for (i, block) in F5_COUNTER_BLOCKS.iter().enumerate() { + let counter = u32::from_be_bytes(block[12..].try_into().unwrap()); + let first = u32::from_be_bytes(F5_COUNTER_BLOCKS[0][12..].try_into().unwrap()); + assert_eq!( + counter, + first.wrapping_add(i as u32), + "F.5 block {i}: the trailing 4 bytes must be the counter, incremented by one" + ); + } +} + +/// The mode must **error** rather than let the counter repeat, and it must do so without consuming +/// anything. +/// +/// Appendix B.1: counter blocks satisfy the uniqueness requirement "provided that `n <= 2^m`". With +/// a 1-byte counter that is 256 blocks, so exactly 4 KiB of keystream is available; the byte after +/// that would reuse `T1` and hence `O1`, which is keystream reuse within one message. +/// +/// `the_counter_limit_is_enforced_at_two_bytes_too` repeats the boundary one width up, where the +/// limit is 65536 blocks rather than 256, so the check is not tied to the one width whose counter +/// happens to be a single byte. +#[test] +fn the_counter_limit_is_enforced() { + let key = toy_key(); + let nonce: [u8; SHORT_CTR_NONCE_LEN] = core::array::from_fn(|i| 0x5A ^ (i as u8)); + + let encryptor = || { + let (e, got) = TinyCtr::::do_encrypt_init_rng( + &key, + &mut FixedSeedRNG::::new(nonce), + ) + .unwrap(); + assert_eq!(got, nonce); + e + }; + + // Exactly the capacity is allowed, in one call. + let mut data = vec![0u8; TINY_CAPACITY]; + encryptor().do_encrypt(&mut data).expect("the full counter space must be usable"); + + // One byte more is refused. + let mut data = vec![0u8; TINY_CAPACITY + 1]; + match encryptor().do_encrypt(&mut data) { + Err(SymmetricCipherError::StateError(msg)) => { + assert!(msg.contains("counter"), "the error should name the counter: {msg}"); + } + other => panic!("expected a StateError past the counter limit, got {other:?}"), + } + assert_eq!(data, vec![0u8; TINY_CAPACITY + 1], "a refused call must not touch the data"); + + // The same limit reached across many calls, not just one. + let mut e = encryptor(); + let mut sixteenth = vec![0u8; TINY_CAPACITY / 16]; + for i in 0..16 { + e.do_encrypt(&mut sixteenth).unwrap_or_else(|err| panic!("call {i} should fit: {err:?}")); + } + let mut one = [0u8; 1]; + assert!(e.do_encrypt(&mut one).is_err(), "the next byte must be refused"); + assert_eq!(one, [0u8; 1], "a refused call must not touch the data"); + + // ...and a refused call must not disturb the state either: the mode is exhausted, so it stays + // exhausted, and a smaller call is refused too rather than silently wrapping. + let mut one = [0u8; 1]; + assert!(e.do_encrypt(&mut one).is_err(), "still exhausted on a second attempt"); + + // A call refused part-way through the counter space leaves the state untouched, so the bytes + // that *do* fit are unchanged by the attempt. + let mut e = encryptor(); + let mut half = vec![0u8; TINY_CAPACITY / 2]; + e.do_encrypt(&mut half).unwrap(); + let mut too_big = vec![0u8; TINY_CAPACITY]; // more than the half that is left + assert!(e.do_encrypt(&mut too_big).is_err(), "must refuse what does not fit"); + assert_eq!(too_big, vec![0u8; TINY_CAPACITY], "refused call must not touch the data"); + // The remaining half still encrypts, and to exactly what an uninterrupted run would give. + let mut rest = vec![0u8; TINY_CAPACITY / 2]; + e.do_encrypt(&mut rest).expect("the untouched remainder must still be usable"); + let mut whole = vec![0u8; TINY_CAPACITY]; + encryptor().do_encrypt(&mut whole).unwrap(); + assert_eq!( + &rest[..], + &whole[TINY_CAPACITY / 2..], + "the refused call must not have advanced the counter" + ); +} + +/// The same boundary with a **2-byte** counter: 65536 blocks, so 1 MiB exactly. +/// +/// Cheap enough to run, and it shows the limit tracks the counter width rather than being a +/// property of the one-byte case. Three and four byte counters put the boundary at 256 MiB and +/// 64 GiB, which is why they are not tested here; the width-generic capacity arithmetic is shared, +/// and `check_counter_blocks` pins the counter construction at all four widths. +#[test] +fn the_counter_limit_is_enforced_at_two_bytes_too() { + const NONCE: usize = 14; + const CAPACITY: usize = 65536 * TOY_LEN; + let key = toy_key(); + let nonce: [u8; NONCE] = core::array::from_fn(|i| 0x3C ^ (i as u8)); + + let encryptor = || { + let (e, got) = Ctr::::do_encrypt_init_rng( + &key, + &mut FixedSeedRNG::::new(nonce), + ) + .unwrap(); + assert_eq!(got, nonce); + e + }; + + let mut data = vec![0u8; CAPACITY]; + encryptor().do_encrypt(&mut data).expect("the full 2-byte counter space must be usable"); + + let mut data = vec![0u8; CAPACITY + 1]; + assert!(encryptor().do_encrypt(&mut data).is_err(), "one byte past the limit must be refused"); + assert_eq!(data, vec![0u8; CAPACITY + 1], "a refused call must not touch the data"); +} + +/// The decryptor enforces the same limit: a ciphertext longer than the counter can cover is refused +/// rather than decrypted with repeated keystream. +#[test] +fn the_counter_limit_is_enforced_when_decrypting_too() { + let key = toy_key(); + let nonce: [u8; SHORT_CTR_NONCE_LEN] = core::array::from_fn(|i| 0x5A ^ (i as u8)); + let mut d = TinyCtr::::do_decrypt_init(&key, &nonce).unwrap(); + let mut data = vec![0u8; TINY_CAPACITY + 1]; + assert!(d.do_decrypt(&mut data).is_err(), "decryption must refuse past the counter limit"); + assert_eq!(data, vec![0u8; TINY_CAPACITY + 1], "a refused call must not touch the data"); +} + +// ---- the forward-cipher-only rule --------------------------------------------------------- + +/// CTR applies `CIPH_K` to counter blocks in both directions and never inverts anything, so neither +/// direction may reach the inverse cipher. [`ForwardOnlyToy`] panics from every inverse entry point. +#[test] +fn neither_direction_uses_the_inverse_cipher() { + let key = toy_key(); + let nonce = pinned_nonce(); + let plaintext = message(11 * TOY_LEN + 5); + + let (mut e, _) = ForwardOnlyCtr::::do_encrypt_init_rng( + &key, + &mut FixedSeedRNG::::new(nonce), + ) + .unwrap(); + let mut ct = plaintext.clone(); + e.do_encrypt(&mut ct).unwrap(); + + let mut d = ForwardOnlyCtr::::do_decrypt_init(&key, &nonce).unwrap(); + let mut back = ct.clone(); + d.do_decrypt(&mut back).unwrap(); + assert_eq!(back, plaintext, "all paths, forward cipher only"); + + // Byte by byte, so the single-block path runs too. + let mut d = ForwardOnlyCtr::::do_decrypt_init(&key, &nonce).unwrap(); + let mut back = ct.clone(); + for piece in back.chunks_mut(1) { + d.do_decrypt(piece).unwrap(); + } + assert_eq!(back, plaintext, "byte path, forward cipher only"); + + // The forward-only toy must agree with the real one, or the above proves nothing. + assert_eq!(enc(&mut pinned_encryptor(nonce), &plaintext), ct, "the two toys must agree"); +} + +// ---- call sequencing ----------------------------------------------------------------------- + +/// Chunking must not change the result, in either direction, at byte granularity -- and every +/// encrypt chunking must decrypt under every decrypt chunking. +#[test] +fn call_chunking_does_not_change_the_result() { + let nonce = pinned_nonce(); + let plaintext = message(10 * TOY_LEN + 11); + + let reference = enc(&mut pinned_encryptor(nonce), &plaintext); + assert_eq!(dec(&mut pinned_decryptor(nonce), &reference), plaintext); + + for &enc_chunk in &CHUNKINGS { + let mut ct = plaintext.clone(); + let mut e = pinned_encryptor(nonce); + for piece in ct.chunks_mut(enc_chunk) { + e.do_encrypt(piece).unwrap(); + } + assert_eq!(ct, reference, "encrypting in {enc_chunk}-byte calls"); + + for &dec_chunk in &CHUNKINGS { + assert_eq!( + dec_chunked(&mut pinned_decryptor(nonce), &ct, dec_chunk), + plaintext, + "encrypted in {enc_chunk}-byte calls, decrypted in {dec_chunk}-byte calls" + ); + } + } + + // Empty calls anywhere are no-ops, including mid-block. + let mut e = pinned_encryptor(nonce); + e.do_encrypt(&mut []).unwrap(); + let mut ct = plaintext.clone(); + e.do_encrypt(&mut ct[..5]).unwrap(); + e.do_encrypt(&mut []).unwrap(); + e.do_encrypt(&mut ct[5..]).unwrap(); + assert_eq!(ct, reference, "empty calls must not disturb the state"); +} + +/// The same equivalence with **real AES**, at all three key lengths, as for the other stream modes. +#[test] +fn aes_chunking_matches_a_single_call() { + fn check(name: &str) + where + P: ElectronicCodeBook, + { + let key_bytes: [u8; KEY_LEN] = + core::array::from_fn(|i| (i as u8).wrapping_mul(31).wrapping_add(7)); + let key = + KeyMaterial::::from_bytes_as_type(&key_bytes, KeyType::SymmetricCipherKey) + .expect("a valid AES key"); + let nonce: [u8; 12] = core::array::from_fn(|i| 0xC3 ^ (i as u8)); + let plaintext: Vec = (0..171).map(|i| (i * 7 + i / 16) as u8).collect(); + + let encryptor = || { + let (e, got) = Ctr::::do_encrypt_init_rng( + &key, + &mut FixedSeedRNG::<12>::new(nonce), + ) + .expect("encrypt init"); + assert_eq!(got, nonce, "{name}: the pinned RNG should reproduce the nonce"); + e + }; + let decryptor = || { + Ctr::::do_decrypt_init(&key, &nonce) + .expect("decrypt init") + }; + + let mut reference = plaintext.clone(); + encryptor().do_encrypt(&mut reference).expect("one-call encryption"); + assert_ne!(reference, plaintext, "{name}: the data must actually be encrypted"); + + let mut back = reference.clone(); + decryptor().do_decrypt(&mut back).expect("one-call decryption"); + assert_eq!(back, plaintext, "{name}: one-call round trip"); + + for &enc_chunk in &CHUNKINGS { + let mut ct = plaintext.clone(); + let mut e = encryptor(); + for piece in ct.chunks_mut(enc_chunk) { + e.do_encrypt(piece).expect("chunked encryption"); + } + assert_eq!(ct, reference, "{name}: encrypting in {enc_chunk}-byte calls"); + + for &dec_chunk in &CHUNKINGS { + let mut pt = ct.clone(); + let mut d = decryptor(); + for piece in pt.chunks_mut(dec_chunk) { + d.do_decrypt(piece).expect("chunked decryption"); + } + assert_eq!( + pt, plaintext, + "{name}: encrypted in {enc_chunk}-byte, decrypted in {dec_chunk}-byte calls" + ); + } + } + } + + check::("AES-128"); + check::("AES-192"); + check::("AES-256"); +} + +/// The pair path must be taken, **in both directions** -- unlike CBC and CFB, CTR encryption +/// batches too, because counter blocks do not depend on cipher output (Sec 6.5). +#[test] +fn the_pair_path_is_really_used_in_both_directions() { + let key = toy_key(); + let nonce = pinned_nonce(); + let plaintext = message(2 * TOY_LEN); + + let ct = enc(&mut pinned_encryptor(nonce), &plaintext); + assert_eq!(dec(&mut pinned_decryptor(nonce), &ct), plaintext); + + // Encryption: two blocks together must go through encrypt_blocks2, so the swapped toy differs. + let (mut e, _) = + SwappedCtr::::do_encrypt_init_rng(&key, &mut pinned_rng(nonce)).unwrap(); + let mut swapped = plaintext.clone(); + e.do_encrypt(&mut swapped).unwrap(); + assert_ne!(swapped, ct, "CTR encryption must use the pair path"); + + // ...but one block at a time avoids it, and then it agrees with the correct toy. + let (mut e, _) = + SwappedCtr::::do_encrypt_init_rng(&key, &mut pinned_rng(nonce)).unwrap(); + let mut single = plaintext.clone(); + for piece in single.chunks_mut(TOY_LEN) { + e.do_encrypt(piece).unwrap(); + } + assert_eq!(single, ct, "the single-block path must not pair"); + + // Decryption: the same, on the correct ciphertext. + let mut d = SwappedCtr::::do_decrypt_init(&key, &nonce).unwrap(); + let mut back = ct.clone(); + d.do_decrypt(&mut back).unwrap(); + assert_ne!(back, plaintext, "CTR decryption must use the pair path"); +} + +/// The eight-block path must be taken, in both directions, and only for full eights. +#[test] +fn the_eight_block_path_is_really_used_in_both_directions() { + let key = toy_key(); + let nonce = pinned_nonce(); + let plaintext = message(9 * TOY_LEN); + + let ct = enc(&mut pinned_encryptor(nonce), &plaintext); + + let (mut e, _) = + SwappedEightCtr::::do_encrypt_init_rng(&key, &mut pinned_rng(nonce)).unwrap(); + let mut swapped = plaintext.clone(); + e.do_encrypt(&mut swapped).unwrap(); + assert_ne!(swapped, ct, "nine blocks must go through encrypt_blocks8"); + + // Four blocks at a time uses pairs only, so the rotated-eight toy is correct there. + let (mut e, _) = + SwappedEightCtr::::do_encrypt_init_rng(&key, &mut pinned_rng(nonce)).unwrap(); + let mut fours = plaintext.clone(); + for piece in fours.chunks_mut(4 * TOY_LEN) { + e.do_encrypt(piece).unwrap(); + } + assert_eq!(fours, ct, "fours must not use the eight path"); + + let mut d = SwappedEightCtr::::do_decrypt_init(&key, &nonce).unwrap(); + let mut back = ct.clone(); + d.do_decrypt(&mut back).unwrap(); + assert_ne!(back, plaintext, "decryption must batch eights too"); +} + +// ---- nonce handling ------------------------------------------------------------------------ + +/// Two encryption flows under the same key must not reuse a nonce. For CTR this is the whole +/// security argument: a repeated nonce repeats the counter blocks and so the keystream. +#[test] +fn each_encryption_gets_a_fresh_nonce() { + let key = toy_key(); + let mut seen = std::collections::BTreeSet::new(); + for _ in 0..64 { + let (_, nonce) = ToyCtr::::do_encrypt_init(&key).unwrap(); + assert!(seen.insert(nonce), "nonce repeated across encryptions: {nonce:02x?}"); + } +} + +#[test] +fn identical_plaintext_gives_different_ciphertext() { + let key = toy_key(); + let plaintext = [0x77u8; 2 * TOY_LEN]; + + let mut first = plaintext; + ToyCtr::::encrypt(&key, &mut first).unwrap(); + let mut second = plaintext; + ToyCtr::::encrypt(&key, &mut second).unwrap(); + assert_ne!(first, second); + + // ...and two identical plaintext blocks within one message differ, because the counter moves. + assert_ne!(first[..TOY_LEN], first[TOY_LEN..], "the counter should change the keystream"); +} + +// ---- key handling -------------------------------------------------------------------------- + +#[test] +fn a_key_of_the_wrong_type_is_rejected() { + let bytes: [u8; TOY_LEN] = core::array::from_fn(|i| (i as u8) + 1); + let seed = KeyMaterial::::from_bytes_as_type(&bytes, KeyType::Seed).unwrap(); + assert!(ToyCtr::::do_encrypt_init(&seed).is_err()); + assert!(ToyCtr::::do_decrypt_init(&seed, &[0u8; NONCE_LEN]).is_err()); +} + +// ---- every length -------------------------------------------------------------------------- + +/// CTR is a stream cipher: every length round-trips and the ciphertext is exactly as long as the +/// plaintext. +#[test] +fn every_length_round_trips_without_padding() { + let key = toy_key(); + for len in 0..=(3 * TOY_LEN + 1) { + let plaintext = message(len); + let mut data = plaintext.clone(); + let nonce = ToyCtr::::encrypt(&key, &mut data).expect("encryption"); + assert_eq!(data.len(), len, "len {len}: the ciphertext is as long as the plaintext"); + if len >= 8 { + assert_ne!(data, plaintext, "len {len}: the data must actually be encrypted"); + } + ToyCtr::::decrypt(&key, &nonce, &mut data).expect("decryption"); + assert_eq!(data, plaintext, "len {len}: round trip"); + } +} + +// ---- nonce lengths ------------------------------------------------------------------------- + +/// Every permitted nonce length works and gives a different counter width. 12, 13, 14 and 15 bytes +/// on a 16-byte block are counters of 4, 3, 2 and 1 bytes; a 16-byte nonce (no counter) and an +/// 11-byte one (a 5-byte counter) are compile errors, so they cannot be tested here. +#[test] +fn every_permitted_nonce_length_works() { + fn round_trip() { + let key = toy_key(); + let nonce: [u8; N] = core::array::from_fn(|i| (i as u8).wrapping_mul(11).wrapping_add(3)); + let plaintext = (0..100u8).collect::>(); + + let (mut e, got) = Ctr::::do_encrypt_init_rng( + &key, + &mut FixedSeedRNG::::new(nonce), + ) + .unwrap(); + assert_eq!(got, nonce); + let mut ct = plaintext.clone(); + e.do_encrypt(&mut ct).unwrap(); + assert_ne!(ct, plaintext, "nonce length {N}: must actually encrypt"); + + Ctr::::decrypt(&key, &nonce, &mut ct).unwrap(); + assert_eq!(ct, plaintext, "nonce length {N}: round trip"); + } + + round_trip::<12>(); + round_trip::<13>(); + round_trip::<14>(); + round_trip::<15>(); +} + +// ---- memory --------------------------------------------------------------------------------- + +/// Pins the "Memory Usage" table in the crate docs. +#[test] +fn sizes_match_the_documented_memory_table() { + use core::mem::size_of; + + // permutation + nonce + counter (u64) + keystream block + the used offset, rounded up to the + // u64's alignment. For a 12-byte nonce on AES that is 176/208/240 + 12 + 8 + 16 + 8 = 220/252/284, + // padded to 224/256/288. + assert_eq!(size_of::>(), 224); + assert_eq!(size_of::>(), 256); + assert_eq!(size_of::>(), 288); + + // The direction marker is free, and the nonce length does not change the layout: the counter + // block is always a whole block. + assert_eq!( + size_of::>(), + size_of::>() + ); + // A longer nonce fits in the same padding, so the total is unchanged. + assert_eq!( + size_of::>(), + size_of::>() + ); +} diff --git a/crypto/modes/tests/ctr_vector_tests.rs b/crypto/modes/tests/ctr_vector_tests.rs new file mode 100644 index 00000000..9a93c6f8 --- /dev/null +++ b/crypto/modes/tests/ctr_vector_tests.rs @@ -0,0 +1,181 @@ +//! Multi-block known-answer tests for CTR, generated with OpenSSL. +//! +//! # Why these exist alongside the ACVP suite +//! +//! `acvp_ctr_tests.rs` runs 1853 official NIST vectors, but **every one of them is a single +//! block**, so all of them use counter 0 and none exercises the increment. A counter that never +//! advanced -- or advanced the wrong way, or wrote its bytes little-endian -- would pass the entire +//! ACVP set. (That is not hypothetical: a deliberately little-endian counter was checked against +//! the ACVP suite while these tests were written, and it passed.) +//! +//! `ctr_tests.rs` covers the increment against the raw permutation, which is sound because that +//! permutation is itself ACVP-validated, but it is our own code on both sides of the comparison. +//! These vectors close that gap with an **independent implementation**: the ciphertexts below were +//! produced by OpenSSL 3.0.13, following the same convention the SM3 and HMAC suites use for +//! openssl-sourced values. They span five counter blocks, so they pin the increment end to end, +//! and their last block is partial, so they also pin Sec 6.5's `MSB_u(On)` handling. +//! +//! # How they were generated +//! +//! ```text +//! openssl enc -aes-128-ctr -K -iv 000102030405060708090a0b00000000 -in plaintext.bin +//! ``` +//! +//! OpenSSL takes the whole 16-byte initial counter block as its `-iv`. Ours is a 12-byte nonce with +//! the counter starting at zero, so the two line up exactly when the IV's low four bytes are zero, +//! which is why the IV above ends in `00000000`. See the [`Ctr`] module docs. + +use bouncycastle_aes_lowmemory::{Aes128, Aes192, Aes256}; +use bouncycastle_core::key_material::{KeyMaterial, KeyType}; +use bouncycastle_core::traits::{ElectronicCodeBook, StreamCipherDecryptor, StreamCipherEncryptor}; +use bouncycastle_core_test_framework::FixedSeedRNG; +use bouncycastle_hex as hex; +use bouncycastle_modes::{Ctr, Decrypting, Encrypting}; + +const BLOCK_LEN: usize = 16; +const NONCE_LEN: usize = 12; + +/// The nonce: the leading 12 bytes of the OpenSSL IV `000102030405060708090a0b00000000`. +const NONCE: &str = "000102030405060708090a0b"; + +/// The four SP 800-38A Appendix F plaintext blocks followed by five more bytes, so the message is +/// 69 bytes: five counter blocks, the last of them partial. +const PLAINTEXT: &str = concat!( + "6bc1bee22e409f96e93d7e117393172a", + "ae2d8a571e03ac9c9eb76fac45af8e51", + "30c81c46a35ce411e5fbc1191a0a52ef", + "f69f2445df4f9b17ad2b417be66c3710", + "0011223344", +); + +/// The three keys used throughout SP 800-38A Appendix F. +const KEY_128: &str = "2b7e151628aed2a6abf7158809cf4f3c"; +const KEY_192: &str = "8e73b0f7da0e6452c810f32b809079e562f8ead2522c6b7b"; +const KEY_256: &str = "603deb1015ca71be2b73aef0857d77811f352c073b6108d72d9810a30914dff4"; + +/// `openssl enc -aes-128-ctr`, OpenSSL 3.0.13. +const CT_128: &str = concat!( + "ffd8816338abebca17491bc67fe6751c", + "093833c279e946d49804c6b03df09f9d", + "6b0727101b346a530523d59fb883e678", + "fda525b39296cfc5a821d4dcda5a6227", + "06efd63405", +); +/// `openssl enc -aes-192-ctr`, OpenSSL 3.0.13. +const CT_192: &str = concat!( + "c85f24d60a6fd4593209730ecd1ed507", + "deae5f770708a1e162d04d42fe3dd6e6", + "acf360f5c5f25e53a09396547d8b7f9b", + "9d12dc684df141cd0b5462450a8d1900", + "4a271f6e8e", +); +/// `openssl enc -aes-256-ctr`, OpenSSL 3.0.13. +const CT_256: &str = concat!( + "b66c7ac8885c5ff473855203b36048ff", + "5e7e0746b6e3ad4c2b84aaf440b1b987", + "38a9ad1527187f6f435b83b09734cb04", + "b3e3a2a77d2a02c4759cbd9b8fc822b3", + "1223c7e590", +); + +fn unhex(s: &str) -> Vec { + hex::decode(s).expect("valid hex") +} + +fn key_material(hex_str: &str) -> KeyMaterial { + let raw = unhex(hex_str); + assert_eq!(raw.len(), N, "key length"); + KeyMaterial::::from_bytes_as_type(&raw, KeyType::SymmetricCipherKey) + .expect("a valid symmetric cipher key") +} + +/// Chunk sizes that cut across the block and the eight-block batch, so the vectors are reproduced +/// through every path rather than only the batched one. +const CHUNKINGS: [usize; 6] = [1, 5, 16, 17, 33, 69]; + +fn check(name: &str, key_hex: &str, expected_hex: &str) +where + P: ElectronicCodeBook, +{ + let key = key_material::(key_hex); + let nonce: [u8; NONCE_LEN] = unhex(NONCE).try_into().expect("a 12-byte nonce"); + let plaintext = unhex(PLAINTEXT); + let expected = unhex(expected_hex); + assert_eq!(plaintext.len(), 69, "the message should be five counter blocks, the last partial"); + assert_eq!(expected.len(), plaintext.len(), "CTR does not change the length"); + + // Encryption, in one call and in every chunking. + for chunk in [plaintext.len()].into_iter().chain(CHUNKINGS) { + let (mut enc, got) = + Ctr::::do_encrypt_init_rng( + &key, + &mut FixedSeedRNG::::new(nonce), + ) + .expect("encrypt init"); + assert_eq!(got, nonce, "{name}: the pinned RNG should reproduce the nonce"); + + let mut data = plaintext.clone(); + for piece in data.chunks_mut(chunk) { + enc.do_encrypt(piece).expect("encryption"); + } + assert_eq!(data, expected, "{name}: encrypting in {chunk}-byte calls"); + } + + // Decryption, likewise. + for chunk in [expected.len()].into_iter().chain(CHUNKINGS) { + let mut dec = + Ctr::::do_decrypt_init(&key, &nonce) + .expect("decrypt init"); + let mut data = expected.clone(); + for piece in data.chunks_mut(chunk) { + dec.do_decrypt(piece).expect("decryption"); + } + assert_eq!(data, plaintext, "{name}: decrypting in {chunk}-byte calls"); + } + + // ...and the one-shot. + let mut data = expected.clone(); + Ctr::::decrypt(&key, &nonce, &mut data) + .expect("one-shot decryption"); + assert_eq!(data, plaintext, "{name}: one-shot"); +} + +#[test] +fn aes128_ctr_matches_openssl() { + check::("AES-128", KEY_128, CT_128); +} + +#[test] +fn aes192_ctr_matches_openssl() { + check::("AES-192", KEY_192, CT_192); +} + +#[test] +fn aes256_ctr_matches_openssl() { + check::("AES-256", KEY_256, CT_256); +} + +/// The vectors must actually depend on the counter advancing: the second block of ciphertext must +/// differ from what a mode that reused counter 0 would produce. +/// +/// Without this, a vector could in principle be satisfied by a stuck counter if the plaintext +/// happened to cooperate. Here the first two plaintext blocks differ, so `C1 XOR C2` would equal +/// `P1 XOR P2` if the keystream were the same for both -- and it must not. +#[test] +fn the_vectors_depend_on_the_counter_advancing() { + let plaintext = unhex(PLAINTEXT); + let ciphertext = unhex(CT_128); + + let ks_xor: Vec = ciphertext[..BLOCK_LEN] + .iter() + .zip(ciphertext[BLOCK_LEN..2 * BLOCK_LEN].iter()) + .zip(plaintext[..BLOCK_LEN].iter().zip(plaintext[BLOCK_LEN..2 * BLOCK_LEN].iter())) + .map(|((c1, c2), (p1, p2))| c1 ^ c2 ^ p1 ^ p2) + .collect(); + + assert_ne!( + ks_xor, + vec![0u8; BLOCK_LEN], + "O1 and O2 must differ, i.e. the counter must have advanced between them" + ); +} diff --git a/crypto/modes/tests/ecb_tests.rs b/crypto/modes/tests/ecb_tests.rs new file mode 100644 index 00000000..db1f2c66 --- /dev/null +++ b/crypto/modes/tests/ecb_tests.rs @@ -0,0 +1,429 @@ +//! Structural tests for ECB, driven by a toy permutation. +//! +//! These check the properties of the *mode* -- that it is the permutation applied block by block +//! with nothing chained, that both directions batch through the pair and eight-block paths, call +//! sequencing, direction typing, the empty init data, SP 800-38A Appendix D error propagation, and +//! the codebook property that makes ECB unsuitable for data -- independently of any real cipher. The +//! known-answer tests against SP 800-38A Appendix F.1 are in `sp800_38a_ecb_tests.rs`, and the ACVP +//! set is in `acvp_ecb_tests.rs`. +//! +//! The toy's own conformance to [`ElectronicCodeBook`] is pinned once, by +//! `the_toy_permutation_conforms_to_the_trait` in `cbc_tests.rs`; it is the same `Toy` here. + +mod common; + +use bouncycastle_aes_lowmemory::{Aes128, Aes192, Aes256}; +use bouncycastle_core::key_material::{KeyMaterial, KeyType}; +use bouncycastle_core::traits::{ + BlockCipherDecryptor, BlockCipherEncryptor, ElectronicCodeBook, SymmetricCipherDecryptor, + SymmetricCipherEncryptor, +}; +use bouncycastle_core_test_framework::FixedSeedRNG; +use bouncycastle_core_test_framework::symmetric_ciphers::TestFrameworkBlockCipher; +use bouncycastle_modes::{Cbc, Decrypting, Ecb, Encrypting}; +use bouncycastle_padding::{PKCS7, PaddedDecryptor, PaddedEncryptor}; +use common::{SwappedEightToy, SwappedPairToy, TOY_LEN, Toy, toy_key}; + +type ToyEcb = Ecb; +type SwappedEcb = Ecb; +type SwappedEightEcb = Ecb; + +/// The implementor hook `do_encrypt_blocks`, by value, for tests whose data is block-shaped. +fn enc_blocks( + enc: &mut impl BlockCipherEncryptor, + plaintext: &[[u8; TOY_LEN]; N], +) -> [[u8; TOY_LEN]; N] { + let mut blocks = *plaintext; + enc.do_encrypt_blocks(&mut blocks).unwrap(); + blocks +} + +/// The implementor hook `do_decrypt_blocks`, by value. +fn dec_blocks( + dec: &mut impl BlockCipherDecryptor, + ciphertext: &[[u8; TOY_LEN]; N], +) -> [[u8; TOY_LEN]; N] { + let mut blocks = *ciphertext; + dec.do_decrypt_blocks(&mut blocks).unwrap(); + blocks +} + +/// The flat streaming method `do_encrypt`, by value. +fn enc_flat( + enc: &mut impl BlockCipherEncryptor, + plaintext: &[u8; LEN], +) -> [u8; LEN] { + let mut data = *plaintext; + enc.do_encrypt(&mut data).unwrap(); + data +} + +/// The flat streaming method `do_decrypt`, by value. +fn dec_flat( + dec: &mut impl BlockCipherDecryptor, + ciphertext: &[u8; LEN], +) -> [u8; LEN] { + let mut data = *ciphertext; + dec.do_decrypt(&mut data).unwrap(); + data +} + +fn encryptor() -> ToyEcb { + ToyEcb::::do_encrypt_init(&toy_key()).unwrap().0 +} + +fn decryptor() -> ToyEcb { + ToyEcb::::do_decrypt_init(&toy_key(), &[]).unwrap() +} + +// ---- the mode against the shared framework ------------------------------------------------ + +#[test] +fn ecb_conforms_to_the_block_cipher_framework() { + TestFrameworkBlockCipher::new() + .test::, ToyEcb>(); +} + +// ---- the spec equations ------------------------------------------------------------------- + +/// SP 800-38A Sec 6.1, written out longhand against the raw permutation: +/// +/// ```text +/// Cj = CIPH_K(Pj); Pj = CIPH^-1_K(Cj) for j = 1 ... n +/// ``` +/// +/// Each block is transformed "directly and independently", so this reference uses only the +/// single-block methods and never looks at a neighbouring block. +fn reference_ecb(perm: &Toy, input: &[[u8; TOY_LEN]], encrypt: bool) -> Vec<[u8; TOY_LEN]> { + input + .iter() + .map(|block| { + let mut b = *block; + if encrypt { + perm.encrypt_block(&mut b) + } else { + perm.decrypt_block(&mut b) + } + b + }) + .collect() +} + +/// The mode must reproduce the Sec 6.1 equations exactly, in both directions, and must therefore +/// agree with the raw permutation block for block. It must also *differ* from CBC from the very +/// first block, since CBC XORs the IV in before the cipher call. +#[test] +fn the_mode_matches_the_spec_equations() { + let key = toy_key(); + let perm = >::new(&key).unwrap(); + let plaintext: [[u8; TOY_LEN]; 5] = + core::array::from_fn(|i| core::array::from_fn(|j| (i * 31 + j * 7 + 1) as u8)); + + let (mut enc, init) = ToyEcb::::do_encrypt_init(&key).unwrap(); + assert_eq!(init, [], "ECB has no init data"); + let ct = enc_blocks(&mut enc, &plaintext); + assert_eq!( + ct.to_vec(), + reference_ecb(&perm, &plaintext, true), + "encryption is CIPH_K per block" + ); + + let mut dec = decryptor(); + let recovered = dec_blocks(&mut dec, &ct); + assert_eq!(recovered, plaintext, "round trip"); + assert_eq!( + recovered.to_vec(), + reference_ecb(&perm, &ct, false), + "decryption is CIPH^-1_K per block" + ); + + // Each block is exactly the permutation of that block, whatever surrounds it. + for (p, c) in plaintext.iter().zip(ct.iter()) { + let mut alone = *p; + perm.encrypt_block(&mut alone); + assert_eq!(&alone, c, "a block's ciphertext does not depend on its neighbours"); + } + + // ...and ECB is not CBC: CBC computes CIPH_K(P1 XOR IV), ECB computes CIPH_K(P1). + let iv: [u8; TOY_LEN] = core::array::from_fn(|i| 0xF0 ^ (i as u8)); + let (mut cbc, _) = Cbc::::do_encrypt_init_rng( + &key, + &mut FixedSeedRNG::::new(iv), + ) + .unwrap(); + let mut first = plaintext[0]; + cbc.do_encrypt(&mut first).unwrap(); + assert_ne!(first, ct[0], "ECB must not agree with CBC"); +} + +// ---- no state: determinism and the codebook property -------------------------------------- + +/// ECB is a function of the key and the block alone. Sec 6.1: "under a given key, any given +/// plaintext block always gets encrypted to the same ciphertext block." This is the property that +/// makes it unusable for data, and it is pinned here so the mode cannot quietly grow an IV or a +/// counter and stop being ECB. +#[test] +fn ecb_is_deterministic_and_leaks_equal_blocks() { + let key = toy_key(); + let block = [0x5Au8; TOY_LEN]; + let plaintext = [block, [0x11; TOY_LEN], block, block]; + + let ct_a = enc_blocks(&mut encryptor(), &plaintext); + let ct_b = enc_blocks(&mut encryptor(), &plaintext); + assert_eq!(ct_a, ct_b, "the same plaintext under the same key gives the same ciphertext"); + + assert_eq!(ct_a[0], ct_a[2], "equal plaintext blocks give equal ciphertext blocks"); + assert_eq!(ct_a[0], ct_a[3]); + assert_ne!(ct_a[0], ct_a[1], "different plaintext blocks give different ciphertext blocks"); + + // The one-shots see the same thing: `encrypt` returns the empty init data and is repeatable. + let flat: [u8; 4 * TOY_LEN] = plaintext.as_flattened().try_into().unwrap(); + let mut once = flat; + let init_a: [u8; 0] = ToyEcb::::encrypt(&key, &mut once).unwrap(); + let mut twice = flat; + let init_b = ToyEcb::::encrypt_rng( + &key, + &mut FixedSeedRNG::::new([0xAB; TOY_LEN]), + &mut twice, + ) + .unwrap(); + assert_eq!(init_a, init_b); + assert_eq!(once, twice, "the RNG variant draws nothing, so it changes nothing"); + assert_eq!(once, *ct_a.as_flattened()); +} + +/// The RNG-taking constructor must not consume from the RNG: there is no IV to generate. A +/// fixed-seed RNG of the wrong width would panic on its first draw, so this is observable. +#[test] +fn the_rng_constructor_draws_nothing() { + let key = toy_key(); + let mut rng = FixedSeedRNG::<0>::new([]); + let (mut enc, init) = ToyEcb::::do_encrypt_init_rng(&key, &mut rng).unwrap(); + assert_eq!(init, []); + let mut block = [0x42u8; TOY_LEN]; + enc.do_encrypt(&mut block).unwrap(); + assert_eq!(block, enc_flat(&mut encryptor(), &[0x42u8; TOY_LEN])); +} + +// ---- batching: pairs and eights, in both directions --------------------------------------- + +/// Sec 6.1: "multiple forward cipher functions and inverse cipher functions can be computed in +/// parallel" -- so, unlike CBC and CFB, *both* directions batch. [`SwappedPairToy`] swaps its two +/// pair results, so a pair handed over together comes out wrong in either direction, while blocks +/// handed over singly come out right. +#[test] +fn the_pair_path_is_used_in_both_directions() { + let key = toy_key(); + let plaintext = [[0xA5u8; TOY_LEN], [0x5Au8; TOY_LEN]]; + let ct = enc_blocks(&mut encryptor(), &plaintext); + + // Encryption: a pair goes through encrypt_blocks2, so the swapped toy returns them swapped. + let (mut enc, _) = SwappedEcb::::do_encrypt_init(&key).unwrap(); + let swapped_ct = enc_blocks(&mut enc, &plaintext); + assert_eq!(swapped_ct, [ct[1], ct[0]], "encrypting a pair must go through encrypt_blocks2"); + + // ...and one block at a time avoids the pair path. + let (mut enc, _) = SwappedEcb::::do_encrypt_init(&key).unwrap(); + assert_eq!([enc_flat(&mut enc, &plaintext[0]), enc_flat(&mut enc, &plaintext[1])], ct); + + // Decryption likewise. + let mut dec = SwappedEcb::::do_decrypt_init(&key, &[]).unwrap(); + assert_eq!( + dec_blocks(&mut dec, &ct), + [plaintext[1], plaintext[0]], + "decrypting a pair must go through decrypt_blocks2" + ); + let mut dec = SwappedEcb::::do_decrypt_init(&key, &[]).unwrap(); + assert_eq!([dec_flat(&mut dec, &ct[0]), dec_flat(&mut dec, &ct[1])], plaintext); +} + +/// The eight-block path must be taken, and only for full eights, in both directions. +/// [`SwappedEightToy`] rotates its eight results while its pair and single-block methods are +/// correct, so nine blocks handed over together are wrong (eight rotated, then one right) and the +/// same blocks as two fours or singly are right. +#[test] +fn the_eight_block_path_is_used_in_both_directions() { + let key = toy_key(); + let plaintext: [[u8; TOY_LEN]; 9] = core::array::from_fn(|i| [0x10 * i as u8 + 1; TOY_LEN]); + let ct = enc_blocks(&mut encryptor(), &plaintext); + assert_eq!(dec_blocks(&mut decryptor(), &ct), plaintext); + + let (mut enc, _) = SwappedEightEcb::::do_encrypt_init(&key).unwrap(); + let rotated = enc_blocks(&mut enc, &plaintext); + assert_ne!(rotated, ct, "nine blocks must go through encrypt_blocks8"); + assert_eq!(rotated[8], ct[8], "the ninth block goes through the single path and is right"); + assert_eq!( + &rotated[..8], + &[ct[1], ct[2], ct[3], ct[4], ct[5], ct[6], ct[7], ct[0]], + "eight rotated" + ); + + let (mut enc, _) = SwappedEightEcb::::do_encrypt_init(&key).unwrap(); + let a = enc_blocks(&mut enc, &[plaintext[0], plaintext[1], plaintext[2], plaintext[3]]); + let b = enc_blocks(&mut enc, &[plaintext[4], plaintext[5], plaintext[6], plaintext[7]]); + assert_eq!([a, b].as_flattened(), &ct[..8], "fours use the pair path only"); + + let mut dec = SwappedEightEcb::::do_decrypt_init(&key, &[]).unwrap(); + assert_ne!(dec_blocks(&mut dec, &ct), plaintext, "nine blocks must go through decrypt_blocks8"); + let mut dec = SwappedEightEcb::::do_decrypt_init(&key, &[]).unwrap(); + for (c, p) in ct.iter().zip(plaintext.iter()) { + assert_eq!(&dec_flat(&mut dec, c), p, "the single-block path must not batch"); + } +} + +/// Grouping cannot matter -- there is no state to carry between calls -- but the contract is the +/// same as for the other modes and the batching paths differ per grouping, so it is pinned. +#[test] +fn call_grouping_does_not_change_the_result() { + let plaintext: [[u8; TOY_LEN]; 11] = + core::array::from_fn(|i| core::array::from_fn(|j| (i * TOY_LEN + j) as u8)); + let reference = enc_blocks(&mut encryptor(), &plaintext); + + let mut enc = encryptor(); + let mut got = [[0u8; TOY_LEN]; 11]; + got[0] = enc_flat(&mut enc, &plaintext[0]); + got[1..3].copy_from_slice(&enc_blocks(&mut enc, &[plaintext[1], plaintext[2]])); + let rest: [[u8; TOY_LEN]; 8] = plaintext[3..11].try_into().unwrap(); + got[3..11].copy_from_slice(&enc_blocks(&mut enc, &rest)); + assert_eq!(got, reference); + + for grouping in [1usize, 2, 8, 11] { + let mut dec = decryptor(); + let mut out = Vec::new(); + for chunk in reference.chunks(grouping) { + let mut buf = chunk.to_vec(); + dec.do_decrypt_blocks(&mut buf).unwrap(); + out.extend_from_slice(&buf); + } + assert_eq!(out, plaintext.to_vec(), "decrypting in groups of {grouping}"); + } +} + +/// The flat streaming method and the one-shots must agree with the block-shaped hook. +#[test] +fn flat_streaming_and_one_shots_agree_with_the_block_hook() { + let key = toy_key(); + let plaintext = [[0x11u8; TOY_LEN], [0x22u8; TOY_LEN], [0x33u8; TOY_LEN]]; + let flat_plaintext: [u8; 3 * TOY_LEN] = plaintext.as_flattened().try_into().unwrap(); + + let block_ct = enc_blocks(&mut encryptor(), &plaintext); + assert_eq!(*block_ct.as_flattened(), enc_flat(&mut encryptor(), &flat_plaintext)); + + let mut buf = flat_plaintext; + let init = ToyEcb::::encrypt(&key, &mut buf).unwrap(); + assert_eq!(buf, *block_ct.as_flattened(), "one-shot must equal streaming"); + ToyEcb::::decrypt(&key, &init, &mut buf).unwrap(); + assert_eq!(buf, flat_plaintext); + + assert_eq!(dec_blocks(&mut decryptor(), &block_ct), plaintext); + let flat_ct: [u8; 3 * TOY_LEN] = block_ct.as_flattened().try_into().unwrap(); + assert_eq!(dec_flat(&mut decryptor(), &flat_ct), flat_plaintext); +} + +// ---- SP 800-38A Appendix D error propagation --------------------------------------------- + +/// Table D.2 for ECB: a bit error in `Cj` gives "RBE in the decryption of Cj" and nothing else -- +/// Appendix D: "For the ECB, OFB, and CTR modes, bit errors within a ciphertext block do not affect +/// the decryption of any other blocks." The toy is byte-local, so it can show only the "no other +/// block" half exactly; the randomisation is checked with real AES below. +#[test] +fn a_ciphertext_bit_error_affects_only_its_own_block() { + let plaintext = [[0x00u8; TOY_LEN], [0x11u8; TOY_LEN], [0x22u8; TOY_LEN], [0x33u8; TOY_LEN]]; + let ct = enc_blocks(&mut encryptor(), &plaintext); + + for byte in 0..TOY_LEN { + for bit in 0..8 { + let mut corrupt = ct; + corrupt[1][byte] ^= 1 << bit; + let got = dec_blocks(&mut decryptor(), &corrupt); + assert_eq!(got[0], plaintext[0]); + assert_ne!(got[1], plaintext[1], "C2 byte {byte} bit {bit}: P2 must change"); + assert_eq!(got[2], plaintext[2], "P3 is unaffected: nothing chains"); + assert_eq!(got[3], plaintext[3]); + } + } +} + +/// The randomisation half of Table D.2, with AES-128: every one of the 128 bit positions of `C2` +/// must randomise `P2` (more than one bit differs) and leave `P1` and `P3` untouched. +#[test] +fn with_aes_a_ciphertext_bit_error_randomises_its_block() { + type Aes128Ecb = Ecb; + let key = + KeyMaterial::<16>::from_bytes_as_type(&[0x42; 16], KeyType::SymmetricCipherKey).unwrap(); + let plaintext = [[0x00u8; 16], [0x11u8; 16], [0x22u8; 16]]; + let mut ct = plaintext; + let flat: &mut [u8; 48] = ct.as_flattened_mut().try_into().unwrap(); + Aes128Ecb::::encrypt(&key, flat).unwrap(); + + for byte in 0..16 { + for bit in 0..8 { + let mut corrupt = ct; + corrupt[1][byte] ^= 1 << bit; + let flat: &mut [u8; 48] = corrupt.as_flattened_mut().try_into().unwrap(); + Aes128Ecb::::decrypt(&key, &[], flat).unwrap(); + assert_eq!(corrupt[0], plaintext[0], "C2 byte {byte} bit {bit}: P1 unaffected"); + assert_eq!(corrupt[2], plaintext[2], "C2 byte {byte} bit {bit}: P3 unaffected"); + let differing: u32 = + corrupt[1].iter().zip(plaintext[1].iter()).map(|(a, b)| (a ^ b).count_ones()).sum(); + assert!( + differing > 1, + "C2 byte {byte} bit {bit}: P2 should be randomised ({differing} bit(s) differ)" + ); + } + } +} + +// ---- key handling ------------------------------------------------------------------------ + +#[test] +fn a_key_of_the_wrong_type_is_rejected() { + let bytes: [u8; TOY_LEN] = core::array::from_fn(|i| (i as u8) + 1); + let seed = KeyMaterial::::from_bytes_as_type(&bytes, KeyType::Seed).unwrap(); + assert!(ToyEcb::::do_encrypt_init(&seed).is_err()); + assert!(ToyEcb::::do_decrypt_init(&seed, &[]).is_err()); +} + +// ---- composition with the padding layer -------------------------------------------------- + +/// ECB is block-aligned by contract, so arbitrary-length data goes through `bouncycastle-padding` +/// like the other modes; its `INIT_DATA_LEN` of 0 flows through the adapters as an empty array. +#[test] +fn the_padding_layer_round_trips_every_length() { + type Enc = PaddedEncryptor, PKCS7, TOY_LEN, 0, TOY_LEN>; + type Dec = PaddedDecryptor, PKCS7, TOY_LEN, 0, TOY_LEN>; + + for len in 0..=(3 * TOY_LEN + 1) { + let plaintext: Vec = (0..len).map(|i| (i * 5 + 3) as u8).collect(); + let mut ciphertext = vec![0u8; Enc::encrypt_out_len(len)]; + let (init, written) = + Enc::encrypt_out(&toy_key(), &plaintext, &mut ciphertext).expect("padded encryption"); + assert_eq!(init, []); + assert_eq!(written, ciphertext.len(), "len {len}"); + let mut recovered = vec![0u8; Dec::decrypt_out_max_len(written)]; + let n = Dec::decrypt_out(&toy_key(), &init, &ciphertext, &mut recovered) + .expect("padded decryption"); + assert_eq!(&recovered[..n], &plaintext[..], "len {len}: round trip through PKCS7"); + } +} + +// ---- memory ------------------------------------------------------------------------------ + +/// Pins the "Memory Usage" table in the crate docs: an ECB value is exactly the permutation. +#[test] +fn sizes_match_the_documented_memory_table() { + use core::mem::size_of; + assert_eq!(size_of::>(), 176); + assert_eq!(size_of::>(), 208); + assert_eq!(size_of::>(), 240); + assert_eq!( + size_of::>(), + size_of::>() + ); + assert_eq!(size_of::>(), size_of::()); + // One block smaller than CBC, which stores a chaining value. + assert_eq!( + size_of::>() + 16, + size_of::>() + ); +} diff --git a/crypto/modes/tests/sp800_38a_cfb8_tests.rs b/crypto/modes/tests/sp800_38a_cfb8_tests.rs new file mode 100644 index 00000000..d9fa1468 --- /dev/null +++ b/crypto/modes/tests/sp800_38a_cfb8_tests.rs @@ -0,0 +1,301 @@ +//! Known-answer tests from NIST SP 800-38A Appendix F.3, "CFB Example Vectors". +//! +//! Sections **F.3.7 through F.3.12**: CFB8-AES128, CFB8-AES192 and CFB8-AES256, Encrypt and +//! Decrypt. These are the `s = 8` subsections, the ones [`Cfb8`] implements. The `s = b` +//! subsections F.3.13-F.3.18 belong to [`Cfb`](bouncycastle_modes::Cfb) and are in +//! `sp800_38a_cfb_tests.rs`; F.3.1-F.3.6 are CFB1, which this crate does not provide. +//! +//! All six share the same IV. The plaintext is the **first 18 bytes** of the Appendix F plaintext: +//! the preamble notes that the CFB1 and CFB8 subsections truncate it, and each of these tabulates +//! 18 one-byte segments. Only the key and the resulting ciphertext differ between key lengths, and +//! the three keys are the same three used throughout Appendix F. +//! +//! Transcribed from the published SP 800-38A PDF (2001 edition). +//! +//! # The shift register is checked against the spec's own table +//! +//! Each F.3 subsection tabulates the **input block** and the **output block** for every segment. +//! For CFB8 those columns are the whole mechanism: the input block is the shift register, and the +//! output block is what `MSB_8` takes its byte from. `the_tabulated_blocks_are_the_shift_register` +//! transcribes all 18 of each for F.3.7 and checks them three ways -- that each input block is the +//! previous one shifted left by a byte with the ciphertext byte appended, that each output block is +//! the raw permutation applied to it, and that the ciphertext is the plaintext XOR its first byte. +//! A mode that produced the right ciphertext by some other route would still have to match them. +//! That check is key-independent, so it is done once rather than for all three key lengths. +//! +//! # Driving the IV +//! +//! There is no API for supplying an IV -- see the crate docs. Encryption is therefore driven +//! through [`StreamCipherEncryptor::do_encrypt_init_rng`] with a [`FixedSeedRNG`] whose stream is +//! the vector's IV, and the test asserts the returned init data really is that IV before comparing +//! any ciphertext. Decryption takes the IV directly, as init data. + +use bouncycastle_aes_lowmemory::{Aes128, Aes192, Aes256}; +use bouncycastle_core::key_material::{KeyMaterial, KeyType}; +use bouncycastle_core::traits::{ElectronicCodeBook, StreamCipherDecryptor, StreamCipherEncryptor}; +use bouncycastle_core_test_framework::FixedSeedRNG; +use bouncycastle_hex as hex; +use bouncycastle_modes::{Cfb8, Decrypting, Encrypting}; + +const BLOCK_LEN: usize = 16; + +/// The IV shared by every Appendix F.3 subsection. +const IV: &str = "000102030405060708090a0b0c0d0e0f"; + +/// The 18 one-byte plaintext segments shared by every CFB8 subsection: the first 18 bytes of the +/// Appendix F plaintext, which the CFB1 and CFB8 subsections truncate to. +const PLAINTEXT: &str = "6bc1bee22e409f96e93d7e117393172aae2d"; + +/// F.3.7 / F.3.8 key. +const KEY_128: &str = "2b7e151628aed2a6abf7158809cf4f3c"; +/// F.3.7 CFB8-AES128.Encrypt ciphertext segments. +const CIPHERTEXT_128: &str = "3b79424c9c0dd436bace9e0ed4586a4f32b9"; + +/// F.3.9 / F.3.10 key. +const KEY_192: &str = "8e73b0f7da0e6452c810f32b809079e562f8ead2522c6b7b"; +/// F.3.9 CFB8-AES192.Encrypt ciphertext segments. +const CIPHERTEXT_192: &str = "cda2521ef0a905ca44cd057cbf0d47a0678a"; + +/// F.3.11 / F.3.12 key. +const KEY_256: &str = "603deb1015ca71be2b73aef0857d77811f352c073b6108d72d9810a30914dff4"; +/// F.3.11 CFB8-AES256.Encrypt ciphertext segments. +const CIPHERTEXT_256: &str = "dc1f1a8520a64db55fcc8ac554844e889700"; + +/// F.3.7 CFB8-AES128.Encrypt, the "Input Block" column: the shift register at each segment. +const INPUT_BLOCKS_128: [&str; 18] = [ + "000102030405060708090a0b0c0d0e0f", + "0102030405060708090a0b0c0d0e0f3b", + "02030405060708090a0b0c0d0e0f3b79", + "030405060708090a0b0c0d0e0f3b7942", + "0405060708090a0b0c0d0e0f3b79424c", + "05060708090a0b0c0d0e0f3b79424c9c", + "060708090a0b0c0d0e0f3b79424c9c0d", + "0708090a0b0c0d0e0f3b79424c9c0dd4", + "08090a0b0c0d0e0f3b79424c9c0dd436", + "090a0b0c0d0e0f3b79424c9c0dd436ba", + "0a0b0c0d0e0f3b79424c9c0dd436bace", + "0b0c0d0e0f3b79424c9c0dd436bace9e", + "0c0d0e0f3b79424c9c0dd436bace9e0e", + "0d0e0f3b79424c9c0dd436bace9e0ed4", + "0e0f3b79424c9c0dd436bace9e0ed458", + "0f3b79424c9c0dd436bace9e0ed4586a", + "3b79424c9c0dd436bace9e0ed4586a4f", + "79424c9c0dd436bace9e0ed4586a4f32", +]; + +/// F.3.7 CFB8-AES128.Encrypt, the "Output Block" column: `Oj = CIPH_K(Ij)`, of which CFB8 uses +/// only the first byte. +const OUTPUT_BLOCKS_128: [&str; 18] = [ + "50fe67cc996d32b6da0937e99bafec60", + "b8eb865a2b026381abb1d6560ed20f68", + "fce6033b4edce64cbaed3f61ff5b927c", + "ae4e5e7ffe805f7a4395b180004f8ca8", + "b205eb89445b62116f1deb988a81e6dd", + "4d21d456a5e239064fff4be0c0f85488", + "4b2f5c3895b9efdc85ee0c5178c7fd33", + "a0976d856da260a34104d1a80953db4c", + "53674e5890a2c71b0f6a27a094e5808c", + "f34cd32ffed495f8bc8adba194eccb7a", + "e08cf2407d7ed676c9049586f1d48ba6", + "1f5c88a19b6ca28e99c9aeb8982a6dd8", + "a70e63df781cf395a208bd2365c8779b", + "cbcfe8b3bcf9ac202ce18420013319ab", + "7d9fac6604b3c8c5b1f8c5a00956cf56", + "65c3fa64bf0343986825c636f4a1efd2", + "9cff5e5ff4f554d56c924b9d6a6de21d", + "946c3dc1584cc18400ecd8c6052c44b1", +]; + +fn block(hex_str: &str) -> [u8; BLOCK_LEN] { + hex::decode(hex_str).expect("valid hex").try_into().expect("16 bytes") +} + +fn bytes(hex_str: &str) -> Vec { + hex::decode(hex_str).expect("valid hex") +} + +fn key_material(hex_str: &str) -> KeyMaterial { + let raw = hex::decode(hex_str).expect("valid hex"); + assert_eq!(raw.len(), N, "key length"); + KeyMaterial::::from_bytes_as_type(&raw, KeyType::SymmetricCipherKey) + .expect("a valid symmetric cipher key") +} + +/// Chunk sizes that cut across the eight-byte batch and the 16-byte block: 1 is the single-byte +/// path only, 8 is exactly the batch, and the rest leave a different remainder each call. +const CHUNKINGS: [usize; 6] = [1, 3, 8, 9, 17, 18]; + +/// Runs one Appendix F.3 CFB8 encrypt subsection. +/// +/// Checks the whole message in one call, then in every chunking above -- the vector should not care +/// how the calls are grouped. +fn check_encrypt(section: &str, key_hex: &str, expected_hex: &str) +where + P: ElectronicCodeBook, +{ + let key = key_material::(key_hex); + let iv = block(IV); + let plaintext = bytes(PLAINTEXT); + let expected = bytes(expected_hex); + assert_eq!(plaintext.len(), 18, "{section}: the CFB8 subsections use 18 one-byte segments"); + + for chunk in [plaintext.len()].into_iter().chain(CHUNKINGS) { + let (mut enc, got_iv) = Cfb8::::do_encrypt_init_rng( + &key, + &mut FixedSeedRNG::::new(iv), + ) + .unwrap(); + assert_eq!(got_iv, iv, "{section}: the pinned RNG should produce the vector's IV"); + + let mut data = plaintext.clone(); + for piece in data.chunks_mut(chunk) { + enc.do_encrypt(piece).unwrap(); + } + assert_eq!(data, expected, "{section}: {chunk}-byte calls"); + } +} + +/// Runs one Appendix F.3 CFB8 decrypt subsection. +fn check_decrypt(section: &str, key_hex: &str, ciphertext_hex: &str) +where + P: ElectronicCodeBook, +{ + let key = key_material::(key_hex); + let iv = block(IV); + let plaintext = bytes(PLAINTEXT); + let ciphertext = bytes(ciphertext_hex); + + for chunk in [ciphertext.len()].into_iter().chain(CHUNKINGS) { + let mut dec = + Cfb8::::do_decrypt_init(&key, &iv).unwrap(); + let mut data = ciphertext.clone(); + for piece in data.chunks_mut(chunk) { + dec.do_decrypt(piece).unwrap(); + } + assert_eq!(data, plaintext, "{section}: {chunk}-byte calls"); + } + + // ...and the one-shot, where the IV is an input. + let mut data = ciphertext.clone(); + Cfb8::::decrypt(&key, &iv, &mut data).unwrap(); + assert_eq!(data, plaintext, "{section}: one-shot"); +} + +#[test] +fn f_3_7_cfb8_aes128_encrypt() { + check_encrypt::("F.3.7", KEY_128, CIPHERTEXT_128); +} + +#[test] +fn f_3_8_cfb8_aes128_decrypt() { + check_decrypt::("F.3.8", KEY_128, CIPHERTEXT_128); +} + +#[test] +fn f_3_9_cfb8_aes192_encrypt() { + check_encrypt::("F.3.9", KEY_192, CIPHERTEXT_192); +} + +#[test] +fn f_3_10_cfb8_aes192_decrypt() { + check_decrypt::("F.3.10", KEY_192, CIPHERTEXT_192); +} + +#[test] +fn f_3_11_cfb8_aes256_encrypt() { + check_encrypt::("F.3.11", KEY_256, CIPHERTEXT_256); +} + +#[test] +fn f_3_12_cfb8_aes256_decrypt() { + check_decrypt::("F.3.12", KEY_256, CIPHERTEXT_256); +} + +/// The spec's tabulated **Input Blocks** are the shift register and its **Output Blocks** are +/// `CIPH_K` of them. Both fall straight out of Sec 6.3 with `s = 8`: +/// +/// ```text +/// I1 = IV; Ij = LSB_{b-8}(I_{j-1}) | C_{j-1}; Oj = CIPH_K(Ij); Cj = Pj XOR MSB_8(Oj) +/// ``` +/// +/// Checking all three relations against F.3.7's own table pins the mode's internals rather than +/// just its final output, and it confirms the transcription: the input, output, plaintext and +/// ciphertext columns are related by a shift, a cipher call and an XOR, none of which would survive +/// a typo in any of them. +#[test] +fn the_tabulated_blocks_are_the_shift_register() { + let key = key_material::<16>(KEY_128); + let perm = >::new(&key).expect("a valid key"); + let plaintext = bytes(PLAINTEXT); + let ciphertext = bytes(CIPHERTEXT_128); + + for j in 0..18 { + let input_block = block(INPUT_BLOCKS_128[j]); + let output_block = block(OUTPUT_BLOCKS_128[j]); + + // I1 = IV, and Ij = LSB_{b-8}(I_{j-1}) | C_{j-1} thereafter. + if j == 0 { + assert_eq!(input_block, block(IV), "F.3.7: I1 must be the IV"); + } else { + let previous = block(INPUT_BLOCKS_128[j - 1]); + let mut expected = [0u8; BLOCK_LEN]; + expected[..BLOCK_LEN - 1].copy_from_slice(&previous[1..]); + expected[BLOCK_LEN - 1] = ciphertext[j - 1]; + assert_eq!( + input_block, + expected, + "F.3.7: I{} should be I{} shifted left one byte with C{} appended", + j + 1, + j, + j + ); + } + + // Oj = CIPH_K(Ij) -- the *forward* cipher function, which is all CFB ever uses. + let mut computed = input_block; + perm.encrypt_block(&mut computed); + assert_eq!( + computed, + output_block, + "F.3.7: tabulated output block #{} should be CIPH_K of input block #{}", + j + 1, + j + 1 + ); + + // Cj = Pj XOR MSB_8(Oj): the first byte of the output block, the rest discarded. + assert_eq!( + ciphertext[j], + plaintext[j] ^ output_block[0], + "F.3.7: Cj = Pj XOR MSB_8(Oj) for segment #{}", + j + 1 + ); + } +} + +/// CFB8 and CFB128 agree on the **first** byte and on nothing after it. +/// +/// Both set `I1 = IV` and `O1 = CIPH_K(IV)`, and both XOR the leading byte of `O1` into the first +/// plaintext byte, so `C1` is necessarily the same. They diverge immediately after, because CFB128 +/// replaces the whole input block with the ciphertext block while CFB8 shifts one byte in. +/// +/// The values below are quoted from **F.3.13 (CFB128-AES128.Encrypt)**, a different subsection from +/// the ones this file is testing, so agreement on byte 1 is an independent check that the F.3.7 +/// transcription is right, and disagreement on byte 2 is a check that [`Cfb8`] is CFB8 and not +/// CFB128. +#[test] +fn cfb8_agrees_with_cfb128_on_the_first_byte_only() { + /// F.3.13 CFB128-AES128.Encrypt, ciphertext segment #1 (16 bytes). + const CFB128_C1: &str = "3b3fd92eb72dad20333449f8e83cfb4a"; + + let cfb128_c1 = bytes(CFB128_C1); + let cfb8_ct = bytes(CIPHERTEXT_128); + + assert_eq!( + cfb8_ct[0], cfb128_c1[0], + "F.3.7 and F.3.13 must agree on the first byte: both are P1 XOR MSB_8(CIPH_K(IV))" + ); + assert_ne!( + cfb8_ct[1], cfb128_c1[1], + "the second byte must differ: CFB8 shifts the register, CFB128 replaces it" + ); +} diff --git a/crypto/modes/tests/sp800_38a_cfb_tests.rs b/crypto/modes/tests/sp800_38a_cfb_tests.rs new file mode 100644 index 00000000..9463f7bd --- /dev/null +++ b/crypto/modes/tests/sp800_38a_cfb_tests.rs @@ -0,0 +1,377 @@ +//! Known-answer tests from NIST SP 800-38A Appendix F.3, "CFB Example Vectors". +//! +//! Sections **F.3.13 through F.3.18**: CFB128-AES128, CFB128-AES192 and CFB128-AES256, Encrypt and +//! Decrypt. These are the `s = b` subsections, the ones [`Cfb`] implements. The rest of Appendix F.3 +//! -- F.3.1-F.3.6 (CFB1) and F.3.7-F.3.12 (CFB8) -- covers segment sizes this crate does not +//! provide, and is deliberately not transcribed; see the [`Cfb`] module docs. +//! +//! [`Cfb`] is a stream cipher, so besides the segment-at-a-time and whole-message calls the vectors +//! are also driven in chunks that do not line up with the segments at all. The expected output is +//! the same: the chunking of the calls is not visible in the ciphertext. +//! +//! All six share the same IV and the same four plaintext blocks (Appendix F preamble: the plaintext +//! is the same for every subsection except the CFB1 and CFB8 ones, which truncate it); only the key +//! and the resulting ciphertext differ. The three keys are the same three used by SP 800-38A F.1 +//! (ECB) and F.2 (CBC), so these vectors also re-check each AES key expansion through a third +//! construction. +//! +//! Transcribed from the published SP 800-38A PDF (2001 edition). +//! +//! # The intermediate values are checked too +//! +//! Unlike Appendix F.2, whose "Input Block" is just `Pj XOR Cj-1`, the F.3 subsections tabulate the +//! CFB **output blocks** -- the keystream `Oj` -- alongside the input blocks. Those are the mode's +//! internals, so `the_tabulated_output_blocks_are_the_keystream` checks them against the raw +//! permutation rather than only comparing final ciphertext. A mode that produced the right +//! ciphertext by a different route would still have to match them. +//! +//! # Driving the IV +//! +//! There is no API for supplying an IV -- see the crate docs. Encryption is therefore driven +//! through [`StreamCipherEncryptor::do_encrypt_init_rng`] with a [`FixedSeedRNG`] whose stream is +//! the vector's IV, and the test asserts the returned init data really is that IV before comparing +//! any ciphertext. Decryption takes the IV directly, as init data. + +use bouncycastle_aes_lowmemory::{Aes128, Aes192, Aes256}; +use bouncycastle_core::key_material::{KeyMaterial, KeyType}; +use bouncycastle_core::traits::{ElectronicCodeBook, StreamCipherDecryptor, StreamCipherEncryptor}; +use bouncycastle_core_test_framework::FixedSeedRNG; +use bouncycastle_hex as hex; +use bouncycastle_modes::{Cfb, Decrypting, Encrypting}; + +const BLOCK_LEN: usize = 16; + +/// The IV shared by every Appendix F.3 subsection. +const IV: &str = "000102030405060708090a0b0c0d0e0f"; + +/// The four plaintext blocks shared by every Appendix F subsection (Appendix F preamble). +const PLAINTEXTS: [&str; 4] = [ + "6bc1bee22e409f96e93d7e117393172a", + "ae2d8a571e03ac9c9eb76fac45af8e51", + "30c81c46a35ce411e5fbc1191a0a52ef", + "f69f2445df4f9b17ad2b417be66c3710", +]; + +/// F.3.13 / F.3.14 key. +const KEY_128: &str = "2b7e151628aed2a6abf7158809cf4f3c"; +/// F.3.13 CFB128-AES128.Encrypt ciphertext segments. +const CIPHERTEXTS_128: [&str; 4] = [ + "3b3fd92eb72dad20333449f8e83cfb4a", + "c8a64537a0b3a93fcde3cdad9f1ce58b", + "26751f67a3cbb140b1808cf187a4f4df", + "c04b05357c5d1c0eeac4c66f9ff7f2e6", +]; +/// F.3.13 CFB128-AES128.Encrypt output blocks, i.e. the keystream `Oj`. +const OUTPUT_BLOCKS_128: [&str; 4] = [ + "50fe67cc996d32b6da0937e99bafec60", + "668bcf60beb005a35354a201dab36bda", + "16bd032100975551547b4de89daea630", + "36d42170a312871947ef8714799bc5f6", +]; + +/// F.3.15 / F.3.16 key. +const KEY_192: &str = "8e73b0f7da0e6452c810f32b809079e562f8ead2522c6b7b"; +/// F.3.15 CFB128-AES192.Encrypt ciphertext segments. +const CIPHERTEXTS_192: [&str; 4] = [ + "cdc80d6fddf18cab34c25909c99a4174", + "67ce7f7f81173621961a2b70171d3d7a", + "2e1e8a1dd59b88b1c8e60fed1efac4c9", + "c05f9f9ca9834fa042ae8fba584b09ff", +]; +/// F.3.15 CFB128-AES192.Encrypt output blocks. +const OUTPUT_BLOCKS_192: [&str; 4] = [ + "a609b38df3b1133dddff2718ba09565e", + "c9e3f5289f149abd08ad44dc52b2b32b", + "1ed6965b76c76ca02d1dcef404f09626", + "36c0bbd976ccd4b7ef85cec1be273eef", +]; + +/// F.3.17 / F.3.18 key. +const KEY_256: &str = "603deb1015ca71be2b73aef0857d77811f352c073b6108d72d9810a30914dff4"; +/// F.3.17 CFB128-AES256.Encrypt ciphertext segments. +const CIPHERTEXTS_256: [&str; 4] = [ + "dc7e84bfda79164b7ecd8486985d3860", + "39ffed143b28b1c832113c6331e5407b", + "df10132415e54b92a13ed0a8267ae2f9", + "75a385741ab9cef82031623d55b1e471", +]; +/// F.3.17 CFB128-AES256.Encrypt output blocks. +const OUTPUT_BLOCKS_256: [&str; 4] = [ + "b7bf3a5df43989dd97f0fa97ebce2f4a", + "97d26743252b1d54aca653cf744ace2a", + "efd80f62b6b9af8344c511b13c70b016", + "833ca131c5f655ef8d1a2346b3ddd361", +]; + +fn block(hex_str: &str) -> [u8; BLOCK_LEN] { + hex::decode(hex_str).expect("valid hex").try_into().expect("16 bytes") +} + +fn blocks(hex_strs: &[&str; 4]) -> [[u8; BLOCK_LEN]; 4] { + core::array::from_fn(|i| block(hex_strs[i])) +} + +/// The same four blocks as 64 contiguous bytes, for the flat streaming and one-shot methods. +fn flat(hex_strs: &[&str; 4]) -> [u8; 4 * BLOCK_LEN] { + blocks(hex_strs).as_flattened().try_into().expect("4 blocks = 64 bytes") +} + +fn key_material(hex_str: &str) -> KeyMaterial { + let bytes = hex::decode(hex_str).expect("valid hex"); + assert_eq!(bytes.len(), N, "key length"); + KeyMaterial::::from_bytes_as_type(&bytes, KeyType::SymmetricCipherKey) + .expect("a valid symmetric cipher key") +} + +/// Chunk sizes that never line up with a 16-byte segment, for the stream-cipher checks. +const ODD_CHUNKS: [usize; 3] = [5, 23, 63]; + +/// Runs one Appendix F.3 encrypt subsection. +/// +/// Checks the whole message in one call, then again one segment at a time, then again in chunks +/// that straddle the segments -- the vector should not care how the calls are grouped. +fn check_encrypt(section: &str, key_hex: &str, expected: &[&str; 4]) +where + P: ElectronicCodeBook, +{ + let key = key_material::(key_hex); + let iv = block(IV); + let pt = blocks(&PLAINTEXTS); + let ct = blocks(expected); + + let init = || { + let (enc, got_iv) = Cfb::::do_encrypt_init_rng( + &key, + &mut FixedSeedRNG::::new(iv), + ) + .unwrap(); + assert_eq!(got_iv, iv, "{section}: the pinned RNG should produce the vector's IV"); + enc + }; + + // All four segments in one call. + let mut enc = init(); + let mut data = flat(&PLAINTEXTS); + enc.do_encrypt(&mut data).unwrap(); + assert_eq!(data, flat(expected), "{section}: four segments in one call"); + + // One segment at a time. + let mut enc = init(); + for (i, (p, c)) in pt.iter().zip(ct.iter()).enumerate() { + let mut got = *p; + enc.do_encrypt(&mut got).unwrap(); + assert_eq!(&got, c, "{section}: segment #{}", i + 1); + } + + // In chunks that cut across the segments. + for chunk in ODD_CHUNKS { + let mut enc = init(); + let mut data = flat(&PLAINTEXTS); + for piece in data.chunks_mut(chunk) { + enc.do_encrypt(piece).unwrap(); + } + assert_eq!(data, flat(expected), "{section}: {chunk}-byte calls"); + } +} + +/// Runs one Appendix F.3 decrypt subsection. +/// +/// Checks one call, one segment at a time, the odd grouping `3 + 1` -- which is the grouping that +/// leaves a one-block remainder after the pair loop in `do_decrypt` -- and chunks that straddle the +/// segments. +fn check_decrypt(section: &str, key_hex: &str, ciphertext: &[&str; 4]) +where + P: ElectronicCodeBook, +{ + let key = key_material::(key_hex); + let iv = block(IV); + let pt = blocks(&PLAINTEXTS); + let ct = blocks(ciphertext); + + type Dec = Cfb; + + // All four segments in one call (two pairs, no remainder). + let mut dec = Dec::::do_decrypt_init(&key, &iv).unwrap(); + let mut data = flat(ciphertext); + dec.do_decrypt(&mut data).unwrap(); + assert_eq!(data, flat(&PLAINTEXTS), "{section}: four segments in one call"); + + // One segment at a time (never takes the pair path). + let mut dec = Dec::::do_decrypt_init(&key, &iv).unwrap(); + for (i, (c, p)) in ct.iter().zip(pt.iter()).enumerate() { + let mut got = *c; + dec.do_decrypt(&mut got).unwrap(); + assert_eq!(&got, p, "{section}: segment #{}", i + 1); + } + + // 3 + 1: one pair plus a remainder, then a lone block. + let mut dec = Dec::::do_decrypt_init(&key, &iv).unwrap(); + let mut three: [u8; 3 * BLOCK_LEN] = ct[..3].as_flattened().try_into().unwrap(); + dec.do_decrypt(&mut three).unwrap(); + let mut one = ct[3]; + dec.do_decrypt(&mut one).unwrap(); + assert_eq!(&three[..], pt[..3].as_flattened(), "{section}: segments 1-3"); + assert_eq!(one, pt[3], "{section}: segment 4"); + + // In chunks that cut across the segments. + for chunk in ODD_CHUNKS { + let mut dec = Dec::::do_decrypt_init(&key, &iv).unwrap(); + let mut data = flat(ciphertext); + for piece in data.chunks_mut(chunk) { + dec.do_decrypt(piece).unwrap(); + } + assert_eq!(data, flat(&PLAINTEXTS), "{section}: {chunk}-byte calls"); + } +} + +#[test] +fn f_3_13_cfb128_aes128_encrypt() { + check_encrypt::("F.3.13", KEY_128, &CIPHERTEXTS_128); +} + +#[test] +fn f_3_14_cfb128_aes128_decrypt() { + check_decrypt::("F.3.14", KEY_128, &CIPHERTEXTS_128); +} + +#[test] +fn f_3_15_cfb128_aes192_encrypt() { + check_encrypt::("F.3.15", KEY_192, &CIPHERTEXTS_192); +} + +#[test] +fn f_3_16_cfb128_aes192_decrypt() { + check_decrypt::("F.3.16", KEY_192, &CIPHERTEXTS_192); +} + +#[test] +fn f_3_17_cfb128_aes256_encrypt() { + check_encrypt::("F.3.17", KEY_256, &CIPHERTEXTS_256); +} + +#[test] +fn f_3_18_cfb128_aes256_decrypt() { + check_decrypt::("F.3.18", KEY_256, &CIPHERTEXTS_256); +} + +/// The one-shot API must agree with the vectors too, on the decrypt side where the IV is an input. +/// The one-shots work in place, so the four ciphertext segments are presented as 64 contiguous +/// bytes and become the four plaintext blocks. +#[test] +fn the_one_shot_api_matches_the_vectors() { + let iv = block(IV); + let pt = flat(&PLAINTEXTS); + + let mut data = flat(&CIPHERTEXTS_128); + Cfb::::decrypt(&key_material::<16>(KEY_128), &iv, &mut data) + .unwrap(); + assert_eq!(data, pt); + + let mut data = flat(&CIPHERTEXTS_192); + Cfb::::decrypt(&key_material::<24>(KEY_192), &iv, &mut data) + .unwrap(); + assert_eq!(data, pt); + + let mut data = flat(&CIPHERTEXTS_256); + Cfb::::decrypt(&key_material::<32>(KEY_256), &iv, &mut data) + .unwrap(); + assert_eq!(data, pt); +} + +/// The spec's tabulated **Output Blocks** are the CFB keystream, and its **Input Blocks** are the +/// IV followed by the ciphertext segments. Both fall straight out of Sec 6.3 with `s = b`: +/// +/// ```text +/// I1 = IV; Ij = C_{j-1} (j >= 2); Oj = CIPH_K(Ij); Cj = Pj XOR Oj +/// ``` +/// +/// So each `Oj` in the table must equal the raw permutation applied to the previous ciphertext +/// segment (or to the IV, for `j = 1`), and XOR-ing it with the plaintext must give the ciphertext. +/// Checking this pins the mode's internals against the spec, not just its final output -- and in +/// particular it is what distinguishes CFB from a mode that happens to agree on the ciphertext. +/// +/// It also confirms the transcription: the ciphertext and output-block columns above are related by +/// an XOR that would not survive a typo in either. +fn check_output_blocks( + section: &str, + key_hex: &str, + ciphertexts: &[&str; 4], + output_blocks: &[&str; 4], +) where + P: ElectronicCodeBook, +{ + let key = key_material::(key_hex); + let perm = P::new(&key).expect("a valid key"); + let pt = blocks(&PLAINTEXTS); + let ct = blocks(ciphertexts); + let o = blocks(output_blocks); + + for j in 0..4 { + // Ij: the IV for j = 1, otherwise the previous ciphertext segment. + let input_block = if j == 0 { block(IV) } else { ct[j - 1] }; + + // Oj = CIPH_K(Ij) -- the *forward* cipher function, which is all CFB ever uses. + let mut computed = input_block; + perm.encrypt_block(&mut computed); + assert_eq!( + computed, + o[j], + "{section}: tabulated output block #{} should be CIPH_K of input block #{}", + j + 1, + j + 1 + ); + + // Cj = Pj XOR Oj. + let xored: [u8; BLOCK_LEN] = core::array::from_fn(|k| pt[j][k] ^ o[j][k]); + assert_eq!(xored, ct[j], "{section}: Cj = Pj XOR Oj for segment #{}", j + 1); + } +} + +#[test] +fn the_tabulated_output_blocks_are_the_keystream() { + check_output_blocks::("F.3.13", KEY_128, &CIPHERTEXTS_128, &OUTPUT_BLOCKS_128); + check_output_blocks::("F.3.15", KEY_192, &CIPHERTEXTS_192, &OUTPUT_BLOCKS_192); + check_output_blocks::("F.3.17", KEY_256, &CIPHERTEXTS_256, &OUTPUT_BLOCKS_256); +} + +/// CFB128 and OFB must agree on the **first** block and on nothing after it. +/// +/// Both modes set `I1 = IV` and `O1 = CIPH_K(IV)`, and both then XOR that into the plaintext, so +/// `C1` is necessarily the same. They diverge from the second block, because OFB feeds back the +/// output block `Oj` (Sec 6.4) while CFB feeds back the ciphertext `Cj` (Sec 6.3). +/// +/// Appendix F bears this out, and the values below are quoted from **F.4.1 (OFB-AES128.Encrypt)**, +/// a different subsection from the ones this file is testing. Agreement on block 1 is therefore an +/// independent check that the F.3.13 transcription is right; disagreement on block 2 is a check +/// that [`Cfb`] is CFB and not OFB. +#[test] +fn cfb128_agrees_with_ofb_on_the_first_block_only() { + /// F.4.1 OFB-AES128.Encrypt, Block #1 Output Block. Same key and IV, so the same `O1`. + const OFB_OUTPUT_BLOCK_1: &str = "50fe67cc996d32b6da0937e99bafec60"; + /// F.4.1 OFB-AES128.Encrypt, Block #1 and Block #2 Ciphertext. + const OFB_CIPHERTEXT_1: &str = "3b3fd92eb72dad20333449f8e83cfb4a"; + const OFB_CIPHERTEXT_2: &str = "7789508d16918f03f53c52dac54ed825"; + + assert_eq!( + OUTPUT_BLOCKS_128[0], OFB_OUTPUT_BLOCK_1, + "F.3.13 and F.4.1 must tabulate the same O1 = CIPH_K(IV)" + ); + + let key = key_material::<16>(KEY_128); + let iv = block(IV); + let (mut enc, got_iv) = Cfb::::do_encrypt_init_rng( + &key, + &mut FixedSeedRNG::<16>::new(iv), + ) + .unwrap(); + assert_eq!(got_iv, iv); + + let mut c1 = block(PLAINTEXTS[0]); + enc.do_encrypt(&mut c1).unwrap(); + assert_eq!(c1, block(OFB_CIPHERTEXT_1), "block 1 must match OFB, and F.3.13"); + + let mut c2 = block(PLAINTEXTS[1]); + enc.do_encrypt(&mut c2).unwrap(); + assert_eq!(c2, block(CIPHERTEXTS_128[1]), "block 2 must match F.3.13"); + assert_ne!(c2, block(OFB_CIPHERTEXT_2), "block 2 must NOT match OFB"); +} diff --git a/crypto/modes/tests/sp800_38a_ecb_tests.rs b/crypto/modes/tests/sp800_38a_ecb_tests.rs new file mode 100644 index 00000000..ea9a7539 --- /dev/null +++ b/crypto/modes/tests/sp800_38a_ecb_tests.rs @@ -0,0 +1,219 @@ +//! Known-answer tests from NIST SP 800-38A Appendix F.1, "ECB Example Vectors". +//! +//! Sections **F.1.1 through F.1.6**: ECB-AES128, ECB-AES192 and ECB-AES256, Encrypt and Decrypt. +//! All six use the same four plaintext blocks (Appendix F preamble) and the same three keys as F.2 +//! (CBC) and F.3 (CFB), so these vectors also re-check each AES key expansion through the plainest +//! possible construction. Transcribed from the published SP 800-38A PDF (2001 edition). +//! +//! # No IV to drive +//! +//! ECB has no initialization data, so -- unlike the CBC and CFB suites -- `encrypt` can be checked +//! against the published ciphertext directly, through the one-shot as well as the streaming API. +//! +//! # The mode is the permutation +//! +//! Sec 6.1 gives `Cj = CIPH_K(Pj)`, so each tabulated ciphertext block must equal the raw +//! permutation applied to the corresponding plaintext block. `each_block_is_the_raw_permutation` +//! checks that, which ties the mode to [`ElectronicCodeBook`] and confirms the transcription: a +//! typo in either column would break the equality. + +use bouncycastle_aes_lowmemory::{Aes128, Aes192, Aes256}; +use bouncycastle_core::key_material::{KeyMaterial, KeyType}; +use bouncycastle_core::traits::{BlockCipherDecryptor, BlockCipherEncryptor, ElectronicCodeBook}; +use bouncycastle_hex as hex; +use bouncycastle_modes::{Decrypting, Ecb, Encrypting}; + +const BLOCK_LEN: usize = 16; + +/// The four plaintext blocks shared by every Appendix F subsection (Appendix F preamble). +const PLAINTEXTS: [&str; 4] = [ + "6bc1bee22e409f96e93d7e117393172a", + "ae2d8a571e03ac9c9eb76fac45af8e51", + "30c81c46a35ce411e5fbc1191a0a52ef", + "f69f2445df4f9b17ad2b417be66c3710", +]; + +/// F.1.1 / F.1.2 key. +const KEY_128: &str = "2b7e151628aed2a6abf7158809cf4f3c"; +/// F.1.1 ECB-AES128.Encrypt ciphertext blocks. +const CIPHERTEXTS_128: [&str; 4] = [ + "3ad77bb40d7a3660a89ecaf32466ef97", + "f5d3d58503b9699de785895a96fdbaaf", + "43b1cd7f598ece23881b00e3ed030688", + "7b0c785e27e8ad3f8223207104725dd4", +]; + +/// F.1.3 / F.1.4 key. +const KEY_192: &str = "8e73b0f7da0e6452c810f32b809079e562f8ead2522c6b7b"; +/// F.1.3 ECB-AES192.Encrypt ciphertext blocks. +const CIPHERTEXTS_192: [&str; 4] = [ + "bd334f1d6e45f25ff712a214571fa5cc", + "974104846d0ad3ad7734ecb3ecee4eef", + "ef7afd2270e2e60adce0ba2face6444e", + "9a4b41ba738d6c72fb16691603c18e0e", +]; + +/// F.1.5 / F.1.6 key. +const KEY_256: &str = "603deb1015ca71be2b73aef0857d77811f352c073b6108d72d9810a30914dff4"; +/// F.1.5 ECB-AES256.Encrypt ciphertext blocks. +const CIPHERTEXTS_256: [&str; 4] = [ + "f3eed1bdb5d2a03c064b5a7e3db181f8", + "591ccb10d410ed26dc5ba74a31362870", + "b6ed21b99ca6f4f9f153e7b1beafed1d", + "23304b7a39f9f3ff067d8d8f9e24ecc7", +]; + +fn block(hex_str: &str) -> [u8; BLOCK_LEN] { + hex::decode(hex_str).expect("valid hex").try_into().expect("16 bytes") +} + +fn blocks(hex_strs: &[&str; 4]) -> [[u8; BLOCK_LEN]; 4] { + core::array::from_fn(|i| block(hex_strs[i])) +} + +/// The same four blocks as 64 contiguous bytes, for the flat streaming and one-shot methods. +fn flat(hex_strs: &[&str; 4]) -> [u8; 4 * BLOCK_LEN] { + blocks(hex_strs).as_flattened().try_into().expect("4 blocks = 64 bytes") +} + +fn key_material(hex_str: &str) -> KeyMaterial { + let bytes = hex::decode(hex_str).expect("valid hex"); + assert_eq!(bytes.len(), N, "key length"); + KeyMaterial::::from_bytes_as_type(&bytes, KeyType::SymmetricCipherKey) + .expect("a valid symmetric cipher key") +} + +/// Runs one Appendix F.1 encrypt subsection: the whole message in one call (two pairs), one block +/// at a time, the `3 + 1` grouping that leaves a remainder after the pair loop, the implementor +/// hook, and the one-shot. +fn check_encrypt(section: &str, key_hex: &str, expected: &[&str; 4]) +where + P: ElectronicCodeBook, +{ + type Enc = Ecb; + let key = key_material::(key_hex); + let pt = blocks(&PLAINTEXTS); + let ct = blocks(expected); + + let (mut enc, init) = Enc::::do_encrypt_init(&key).unwrap(); + assert_eq!(init, [], "{section}: ECB has no init data"); + let mut data = flat(&PLAINTEXTS); + enc.do_encrypt(&mut data).unwrap(); + assert_eq!(data, flat(expected), "{section}: four blocks in one call"); + + let (mut enc, _) = Enc::::do_encrypt_init(&key).unwrap(); + for (i, (p, c)) in pt.iter().zip(ct.iter()).enumerate() { + let mut got = *p; + enc.do_encrypt(&mut got).unwrap(); + assert_eq!(&got, c, "{section}: block #{}", i + 1); + } + + let (mut enc, _) = Enc::::do_encrypt_init(&key).unwrap(); + let mut three: [u8; 3 * BLOCK_LEN] = pt[..3].as_flattened().try_into().unwrap(); + enc.do_encrypt(&mut three).unwrap(); + let mut one = pt[3]; + enc.do_encrypt(&mut one).unwrap(); + assert_eq!(&three[..], ct[..3].as_flattened(), "{section}: blocks 1-3"); + assert_eq!(one, ct[3], "{section}: block 4"); + + let (mut enc, _) = Enc::::do_encrypt_init(&key).unwrap(); + let mut hook = pt; + enc.do_encrypt_blocks(&mut hook).unwrap(); + assert_eq!(hook, ct, "{section}: implementor hook"); + + let mut data = flat(&PLAINTEXTS); + let init = Enc::::encrypt(&key, &mut data).unwrap(); + assert_eq!(init, []); + assert_eq!(data, flat(expected), "{section}: one-shot"); +} + +/// Runs one Appendix F.1 decrypt subsection, in the same five groupings. +fn check_decrypt(section: &str, key_hex: &str, ciphertext: &[&str; 4]) +where + P: ElectronicCodeBook, +{ + type Dec = Ecb; + let key = key_material::(key_hex); + let pt = blocks(&PLAINTEXTS); + let ct = blocks(ciphertext); + + let mut dec = Dec::::do_decrypt_init(&key, &[]).unwrap(); + let mut data = flat(ciphertext); + dec.do_decrypt(&mut data).unwrap(); + assert_eq!(data, flat(&PLAINTEXTS), "{section}: four blocks in one call"); + + let mut dec = Dec::::do_decrypt_init(&key, &[]).unwrap(); + for (i, (c, p)) in ct.iter().zip(pt.iter()).enumerate() { + let mut got = *c; + dec.do_decrypt(&mut got).unwrap(); + assert_eq!(&got, p, "{section}: block #{}", i + 1); + } + + let mut dec = Dec::::do_decrypt_init(&key, &[]).unwrap(); + let mut three: [u8; 3 * BLOCK_LEN] = ct[..3].as_flattened().try_into().unwrap(); + dec.do_decrypt(&mut three).unwrap(); + let mut one = ct[3]; + dec.do_decrypt(&mut one).unwrap(); + assert_eq!(&three[..], pt[..3].as_flattened(), "{section}: blocks 1-3"); + assert_eq!(one, pt[3], "{section}: block 4"); + + let mut dec = Dec::::do_decrypt_init(&key, &[]).unwrap(); + let mut hook = ct; + dec.do_decrypt_blocks(&mut hook).unwrap(); + assert_eq!(hook, pt, "{section}: implementor hook"); + + let mut data = flat(ciphertext); + Dec::::decrypt(&key, &[], &mut data).unwrap(); + assert_eq!(data, flat(&PLAINTEXTS), "{section}: one-shot"); +} + +#[test] +fn f_1_1_ecb_aes128_encrypt() { + check_encrypt::("F.1.1", KEY_128, &CIPHERTEXTS_128); +} + +#[test] +fn f_1_2_ecb_aes128_decrypt() { + check_decrypt::("F.1.2", KEY_128, &CIPHERTEXTS_128); +} + +#[test] +fn f_1_3_ecb_aes192_encrypt() { + check_encrypt::("F.1.3", KEY_192, &CIPHERTEXTS_192); +} + +#[test] +fn f_1_4_ecb_aes192_decrypt() { + check_decrypt::("F.1.4", KEY_192, &CIPHERTEXTS_192); +} + +#[test] +fn f_1_5_ecb_aes256_encrypt() { + check_encrypt::("F.1.5", KEY_256, &CIPHERTEXTS_256); +} + +#[test] +fn f_1_6_ecb_aes256_decrypt() { + check_decrypt::("F.1.6", KEY_256, &CIPHERTEXTS_256); +} + +/// Sec 6.1: `Cj = CIPH_K(Pj)`. Every tabulated ciphertext block is the raw permutation of the +/// corresponding plaintext block, for all three key lengths. +fn check_raw(section: &str, key_hex: &str, ciphertexts: &[&str; 4]) +where + P: ElectronicCodeBook, +{ + let perm = P::new(&key_material::(key_hex)).expect("a valid key"); + for (j, (p, c)) in PLAINTEXTS.iter().zip(ciphertexts.iter()).enumerate() { + let mut computed = block(p); + perm.encrypt_block(&mut computed); + assert_eq!(computed, block(c), "{section}: block #{} should be CIPH_K(P{})", j + 1, j + 1); + } +} + +#[test] +fn each_block_is_the_raw_permutation() { + check_raw::("F.1.1", KEY_128, &CIPHERTEXTS_128); + check_raw::("F.1.3", KEY_192, &CIPHERTEXTS_192); + check_raw::("F.1.5", KEY_256, &CIPHERTEXTS_256); +} diff --git a/crypto/modes/tests/sp800_38a_tests.rs b/crypto/modes/tests/sp800_38a_tests.rs new file mode 100644 index 00000000..1dee9ac7 --- /dev/null +++ b/crypto/modes/tests/sp800_38a_tests.rs @@ -0,0 +1,262 @@ +//! Known-answer tests from NIST SP 800-38A Appendix F.2, "CBC Example Vectors". +//! +//! Sections F.2.1 through F.2.6: CBC-AES128, CBC-AES192 and CBC-AES256, Encrypt and Decrypt. All +//! six share the same IV and the same four plaintext blocks (Appendix F preamble); only the key and +//! the resulting ciphertext differ. The three keys are the same three used by FIPS 197 Appendix A +//! and SP 800-38A F.1, so these vectors also re-check each AES key expansion through a second +//! construction. +//! +//! Transcribed from the published SP 800-38A PDF (2001 edition). +//! +//! # Driving the IV +//! +//! There is no API for supplying an IV -- see the crate docs. Encryption is therefore driven +//! through [`BlockCipherEncryptor::do_encrypt_init_rng`] with a [`FixedSeedRNG`] whose stream is +//! the vector's IV, and the test asserts the returned init data really is that IV before comparing +//! any ciphertext. Decryption takes the IV directly, as init data. + +use bouncycastle_aes_lowmemory::{Aes128, Aes192, Aes256}; +use bouncycastle_core::key_material::{KeyMaterial, KeyType}; +use bouncycastle_core::traits::{BlockCipherDecryptor, BlockCipherEncryptor, ElectronicCodeBook}; +use bouncycastle_core_test_framework::FixedSeedRNG; +use bouncycastle_hex as hex; +use bouncycastle_modes::{Cbc, Decrypting, Encrypting}; + +const BLOCK_LEN: usize = 16; + +/// The IV shared by every Appendix F.2 subsection. +const IV: &str = "000102030405060708090a0b0c0d0e0f"; + +/// The four plaintext blocks shared by every Appendix F subsection (Appendix F preamble). +const PLAINTEXTS: [&str; 4] = [ + "6bc1bee22e409f96e93d7e117393172a", + "ae2d8a571e03ac9c9eb76fac45af8e51", + "30c81c46a35ce411e5fbc1191a0a52ef", + "f69f2445df4f9b17ad2b417be66c3710", +]; + +/// F.2.1 / F.2.2 key. +const KEY_128: &str = "2b7e151628aed2a6abf7158809cf4f3c"; +/// F.2.1 CBC-AES128.Encrypt output blocks. +const CIPHERTEXTS_128: [&str; 4] = [ + "7649abac8119b246cee98e9b12e9197d", + "5086cb9b507219ee95db113a917678b2", + "73bed6b8e3c1743b7116e69e22229516", + "3ff1caa1681fac09120eca307586e1a7", +]; + +/// F.2.3 / F.2.4 key. +const KEY_192: &str = "8e73b0f7da0e6452c810f32b809079e562f8ead2522c6b7b"; +/// F.2.3 CBC-AES192.Encrypt output blocks. +const CIPHERTEXTS_192: [&str; 4] = [ + "4f021db243bc633d7178183a9fa071e8", + "b4d9ada9ad7dedf4e5e738763f69145a", + "571b242012fb7ae07fa9baac3df102e0", + "08b0e27988598881d920a9e64f5615cd", +]; + +/// F.2.5 / F.2.6 key. +const KEY_256: &str = "603deb1015ca71be2b73aef0857d77811f352c073b6108d72d9810a30914dff4"; +/// F.2.5 CBC-AES256.Encrypt output blocks. +const CIPHERTEXTS_256: [&str; 4] = [ + "f58c4c04d6e5f1ba779eabfb5f7bfbd6", + "9cfc4e967edb808d679f777bc6702c7d", + "39f23369a9d9bacfa530e26304231461", + "b2eb05e2c39be9fcda6c19078c6a9d1b", +]; + +fn block(hex_str: &str) -> [u8; BLOCK_LEN] { + hex::decode(hex_str).expect("valid hex").try_into().expect("16 bytes") +} + +fn blocks(hex_strs: &[&str; 4]) -> [[u8; BLOCK_LEN]; 4] { + core::array::from_fn(|i| block(hex_strs[i])) +} + +/// The same four blocks as 64 contiguous bytes, for the flat streaming and one-shot methods. +fn flat(hex_strs: &[&str; 4]) -> [u8; 4 * BLOCK_LEN] { + blocks(hex_strs).as_flattened().try_into().expect("4 blocks = 64 bytes") +} + +fn key_material(hex_str: &str) -> KeyMaterial { + let bytes = hex::decode(hex_str).expect("valid hex"); + assert_eq!(bytes.len(), N, "key length"); + KeyMaterial::::from_bytes_as_type(&bytes, KeyType::SymmetricCipherKey) + .expect("a valid symmetric cipher key") +} + +/// Runs one Appendix F.2 encrypt subsection. +/// +/// Checks the whole message in one call, then again one block at a time, then again through the +/// implementor hook -- the vector should not care how the calls are grouped. +fn check_encrypt(section: &str, key_hex: &str, expected: &[&str; 4]) +where + P: ElectronicCodeBook, +{ + let key = key_material::(key_hex); + let iv = block(IV); + let pt = blocks(&PLAINTEXTS); + let ct = blocks(expected); + + // All four blocks in one call. + let (mut enc, got_iv) = Cbc::::do_encrypt_init_rng( + &key, + &mut FixedSeedRNG::::new(iv), + ) + .unwrap(); + assert_eq!(got_iv, iv, "{section}: the pinned RNG should produce the vector's IV"); + let mut data = flat(&PLAINTEXTS); + enc.do_encrypt(&mut data).unwrap(); + assert_eq!(data, flat(expected), "{section}: four blocks in one call"); + + // One block at a time. + let (mut enc, _) = Cbc::::do_encrypt_init_rng( + &key, + &mut FixedSeedRNG::::new(iv), + ) + .unwrap(); + for (i, (p, c)) in pt.iter().zip(ct.iter()).enumerate() { + let mut got = *p; + enc.do_encrypt(&mut got).unwrap(); + assert_eq!(&got, c, "{section}: block #{}", i + 1); + } + + // Through the implementor hook, `do_*_blocks`. + let (mut enc, _) = Cbc::::do_encrypt_init_rng( + &key, + &mut FixedSeedRNG::::new(iv), + ) + .unwrap(); + let mut blocks = pt; + enc.do_encrypt_blocks(&mut blocks).unwrap(); + assert_eq!(blocks, ct, "{section}: implementor hook"); +} + +/// Runs one Appendix F.2 decrypt subsection. +/// +/// Checks one call, one block at a time, and the odd grouping `3 + 1` -- which is the grouping that +/// leaves a one-block remainder after the pair loop in `do_decrypt_blocks`. +fn check_decrypt(section: &str, key_hex: &str, ciphertext: &[&str; 4]) +where + P: ElectronicCodeBook, +{ + let key = key_material::(key_hex); + let iv = block(IV); + let pt = blocks(&PLAINTEXTS); + let ct = blocks(ciphertext); + + type Dec = Cbc; + + // All four blocks in one call (two pairs, no remainder). + let mut dec = Dec::::do_decrypt_init(&key, &iv).unwrap(); + let mut data = flat(ciphertext); + dec.do_decrypt(&mut data).unwrap(); + assert_eq!(data, flat(&PLAINTEXTS), "{section}: four blocks in one call"); + + // One block at a time (never takes the pair path). + let mut dec = Dec::::do_decrypt_init(&key, &iv).unwrap(); + for (i, (c, p)) in ct.iter().zip(pt.iter()).enumerate() { + let mut got = *c; + dec.do_decrypt(&mut got).unwrap(); + assert_eq!(&got, p, "{section}: block #{}", i + 1); + } + + // 3 + 1: one pair plus a remainder, then a lone block. + let mut dec = Dec::::do_decrypt_init(&key, &iv).unwrap(); + let mut three: [u8; 3 * BLOCK_LEN] = ct[..3].as_flattened().try_into().unwrap(); + dec.do_decrypt(&mut three).unwrap(); + let mut one = ct[3]; + dec.do_decrypt(&mut one).unwrap(); + assert_eq!(&three[..], pt[..3].as_flattened(), "{section}: blocks 1-3"); + assert_eq!(one, pt[3], "{section}: block 4"); + + // Through the implementor hook, `do_*_blocks`. + let mut dec = Dec::::do_decrypt_init(&key, &iv).unwrap(); + let mut blocks = ct; + dec.do_decrypt_blocks(&mut blocks).unwrap(); + assert_eq!(blocks, pt, "{section}: implementor hook"); +} + +#[test] +fn f_2_1_cbc_aes128_encrypt() { + check_encrypt::("F.2.1", KEY_128, &CIPHERTEXTS_128); +} + +#[test] +fn f_2_2_cbc_aes128_decrypt() { + check_decrypt::("F.2.2", KEY_128, &CIPHERTEXTS_128); +} + +#[test] +fn f_2_3_cbc_aes192_encrypt() { + check_encrypt::("F.2.3", KEY_192, &CIPHERTEXTS_192); +} + +#[test] +fn f_2_4_cbc_aes192_decrypt() { + check_decrypt::("F.2.4", KEY_192, &CIPHERTEXTS_192); +} + +#[test] +fn f_2_5_cbc_aes256_encrypt() { + check_encrypt::("F.2.5", KEY_256, &CIPHERTEXTS_256); +} + +#[test] +fn f_2_6_cbc_aes256_decrypt() { + check_decrypt::("F.2.6", KEY_256, &CIPHERTEXTS_256); +} + +/// The one-shot API must agree with the vectors too, on the decrypt side where the IV is an input. +/// The one-shots take flat arrays and work in place, so the four ciphertext blocks are presented +/// as 64 contiguous bytes and become the four plaintext blocks. +#[test] +fn the_one_shot_api_matches_the_vectors() { + let iv = block(IV); + let pt = flat(&PLAINTEXTS); + + let mut data = flat(&CIPHERTEXTS_128); + Cbc::::decrypt(&key_material::<16>(KEY_128), &iv, &mut data) + .unwrap(); + assert_eq!(data, pt); + + let mut data = flat(&CIPHERTEXTS_192); + Cbc::::decrypt(&key_material::<24>(KEY_192), &iv, &mut data) + .unwrap(); + assert_eq!(data, pt); + + let mut data = flat(&CIPHERTEXTS_256); + Cbc::::decrypt(&key_material::<32>(KEY_256), &iv, &mut data) + .unwrap(); + assert_eq!(data, pt); +} + +/// The IV really is what distinguishes CBC from ECB here: the same key and plaintext under the +/// F.1 (ECB) conditions gives the F.1 ciphertext, and under F.2 gives a different one. +/// +/// F.1.1 block #1 for this key is `3ad77bb40d7a3660a89ecaf32466ef97`; F.2.1 block #1 is +/// `7649abac8119b246cee98e9b12e9197d`. They differ solely because CBC XORs the IV in first. +#[test] +fn cbc_differs_from_ecb_by_the_iv() { + let key = key_material::<16>(KEY_128); + let iv = block(IV); + + // The raw permutation on P1 alone is the ECB answer from F.1.1. + let mut ecb = block(PLAINTEXTS[0]); + >::encrypt_block( + &>::new(&key).unwrap(), + &mut ecb, + ); + assert_eq!(ecb, block("3ad77bb40d7a3660a89ecaf32466ef97"), "F.1.1 block #1"); + + // CBC's C1 = CIPH_K(P1 XOR IV) is the F.2.1 answer, and differs. + let (mut enc, _) = Cbc::::do_encrypt_init_rng( + &key, + &mut FixedSeedRNG::<16>::new(iv), + ) + .unwrap(); + let mut cbc = block(PLAINTEXTS[0]); + enc.do_encrypt(&mut cbc).unwrap(); + assert_eq!(cbc, block(CIPHERTEXTS_128[0]), "F.2.1 block #1"); + assert_ne!(cbc, ecb); +} diff --git a/crypto/padding/Cargo.toml b/crypto/padding/Cargo.toml new file mode 100644 index 00000000..315ce973 --- /dev/null +++ b/crypto/padding/Cargo.toml @@ -0,0 +1,17 @@ +[package] +name = "bouncycastle-padding" +version.workspace = true +edition.workspace = true + +[dependencies] +bouncycastle-core.workspace = true +bouncycastle-utils.workspace = true + +[dev-dependencies] +bouncycastle-core-test-framework.workspace = true +bouncycastle-rng.workspace = true +criterion.workspace = true + +[[bench]] +name = "padding_benches" +harness = false diff --git a/crypto/padding/benches/padding_benches.rs b/crypto/padding/benches/padding_benches.rs new file mode 100644 index 00000000..1e096af1 --- /dev/null +++ b/crypto/padding/benches/padding_benches.rs @@ -0,0 +1,27 @@ +use bouncycastle_core::traits::Padding; +use bouncycastle_padding::PKCS7; +use criterion::{Criterion, criterion_group, criterion_main}; +use std::hint::black_box; + +fn bench_pkcs7(c: &mut Criterion) { + let mut group = c.benchmark_group("padding::PKCS7"); + group.bench_function("pad/16", |b| { + let mut block = [0u8; 16]; + b.iter(|| { + >::pad(black_box(&mut block), black_box(5)).unwrap(); + black_box(&block); + }) + }); + group.bench_function("unpad/16", |b| { + let mut block = [0u8; 16]; + >::pad(&mut block, 5).unwrap(); + b.iter(|| { + let n = >::unpad(black_box(&block)).unwrap(); + black_box(n); + }) + }); + group.finish(); +} + +criterion_group!(benches, bench_pkcs7); +criterion_main!(benches); diff --git a/crypto/padding/src/lib.rs b/crypto/padding/src/lib.rs new file mode 100644 index 00000000..cdd5b8bf --- /dev/null +++ b/crypto/padding/src/lib.rs @@ -0,0 +1,176 @@ +//! Block padding schemes implementing [`bouncycastle_core::traits::Padding`]. +//! +//! * [`PKCS7`] — the padding scheme of RFC 5652 §6.3. +//! * [`NoPadding`] — adds nothing and refuses to: for data that must already be a whole number of +//! blocks, where a partial final block is a caller error rather than something to pad. +//! * [`PaddedEncryptor`] / [`PaddedDecryptor`] — adapt a block-aligned +//! [`BlockCipherEncryptor`](bouncycastle_core::traits::BlockCipherEncryptor) / +//! [`BlockCipherDecryptor`](bouncycastle_core::traits::BlockCipherDecryptor) to arbitrary-length +//! data, streaming or one-shot. With [`NoPadding`] they instead *enforce* block alignment: an +//! aligned message passes through unchanged in length, and an unaligned one fails at `do_final`. +//! +//! # Usage Examples +//! +//! ``` +//! use bouncycastle_core::traits::Padding; +//! use bouncycastle_padding::PKCS7; +//! +//! // 5 data bytes in a 16-byte block: pad with 11 bytes of value 0x0b. +//! let mut block = [0u8; 16]; +//! block[..5].copy_from_slice(b"hello"); +//! >::pad(&mut block, 5).unwrap(); +//! assert_eq!(&block[..5], b"hello"); +//! assert_eq!(&block[5..], &[0x0b; 11]); +//! +//! // Unpadding recovers the data length. +//! let data_len = >::unpad(&block).unwrap(); +//! assert_eq!(data_len, 5); +//! +//! // A block that is not well-formed padding is rejected. +//! block[15] = 0x00; +//! assert!(>::unpad(&block).is_err()); +//! ``` +//! +//! `NoPadding` never writes a byte: asking it to is the error that tells the caller their data was +//! not block-aligned, and a "padded" block is all data. +//! +//! ``` +//! use bouncycastle_core::errors::PaddingError; +//! use bouncycastle_core::traits::Padding; +//! use bouncycastle_padding::NoPadding; +//! +//! let mut block = [0x42u8; 16]; +//! assert_eq!(>::pad(&mut block, 5), Err(PaddingError::PaddingNotPermitted)); +//! assert_eq!(block, [0x42u8; 16], "nothing was written"); +//! assert_eq!(>::unpad(&block), Ok(16)); +//! ``` +//! +//! # Memory Usage +//! +//! | Operation | Stack (excluding the caller's buffers and the inner cipher) | +//! |-----------------------|-------------------------------------------------------------| +//! | `PKCS7::pad` | O(1) | +//! | `PKCS7::unpad` | O(1) | +//! | `NoPadding::pad` / `unpad` | O(1), touches no data | +//! | `PaddedEncryptor` | one `BLOCK_LEN` buffer (in a `Secret`) + a length | +//! | `PaddedDecryptor` | two `BLOCK_LEN` buffers + a length | +//! +//! # Security Considerations +//! +//! `unpad` is the classic padding-oracle site: if timing or the error depends on *which* byte was +//! malformed, an attacker who can submit ciphertexts can decrypt them byte by byte. [`PKCS7::unpad`] +//! inspects every byte with constant-time masks and returns a single undifferentiated +//! [`PaddingError::InvalidPadding`]. This does not make unauthenticated encryption safe: still +//! authenticate the ciphertext (MAC or AEAD) so the error is never reachable by an attacker. +//! +//! [`NoPadding`] has no padding to inspect and so no oracle of that kind; its `unpad` is a constant. +//! It does not make unauthenticated encryption safe either. + +#![forbid(unsafe_code)] +#![forbid(missing_docs)] +#![no_std] + +mod padded; +pub use padded::{PaddedDecryptor, PaddedEncryptor}; + +use bouncycastle_core::errors::PaddingError; +use bouncycastle_core::traits::Padding; +use bouncycastle_utils::ct::Condition; + +/// RFC 5652 §6.3 padding (the CMS successor to PKCS #7): "the input shall be padded at the trailing +/// end with `k-(lth mod k)` octets all having value `k-(lth mod k)`". Defined only for block lengths +/// `0 < k < 256`, enforced at compile time. +pub struct PKCS7; + +impl Padding for PKCS7 { + /// RFC 5652 §6.3 always adds at least one octet, so an aligned input gets a whole extra block + /// of padding (`pad(block, 0)`); otherwise the last block could not be unpadded unambiguously. + const ALWAYS_PADS: bool = true; + + fn pad(block: &mut [u8; BLOCK_LEN], data_len: usize) -> Result<(), PaddingError> { + const { + assert!( + BLOCK_LEN > 0 && BLOCK_LEN < 256, + "PKCS7 padding is only defined for block lengths 1..=255 (RFC 5652 §6.3)" + ) + } + if data_len >= BLOCK_LEN { + return Err(PaddingError::DataLengthTooLong(BLOCK_LEN - 1)); + } + // RFC 5652 §6.3: pad with k - (lth mod k) octets of value k - (lth mod k). Here the caller + // has already reduced lth mod k to data_len, so the value is simply BLOCK_LEN - data_len. + // `data_len < BLOCK_LEN < 256` so this fits in a u8. + let pad_byte = (BLOCK_LEN - data_len) as u8; + // Constant-time in data_len: every byte is visited, and a mask selects data vs padding. + for (i, b) in block.iter_mut().enumerate() { + let is_padding = Condition::::is_gte(i as i64, data_len as i64); + *b = is_padding.select(pad_byte as i64, *b as i64) as u8; + } + Ok(()) + } + + fn unpad(block: &[u8; BLOCK_LEN]) -> Result { + const { + assert!( + BLOCK_LEN > 0 && BLOCK_LEN < 256, + "PKCS7 padding is only defined for block lengths 1..=255 (RFC 5652 §6.3)" + ) + } + let k = BLOCK_LEN as i64; + // The last byte declares the padding length p; the block is valid iff 1 <= p <= k and the + // final p bytes all equal p. Every byte is examined regardless, so timing is independent of + // where (or whether) the padding is malformed. + let p = block[BLOCK_LEN - 1] as i64; + let mut valid = Condition::::is_within_range(p, 1, k); + for (i, b) in block.iter().enumerate() { + // Position i is a padding position iff i >= k - p. (If p is out of range this may select + // every position, but `valid` is already FALSE and cannot become TRUE again.) + let in_padding = Condition::::is_gte(i as i64, k - p); + let matches = Condition::::is_equal(*b as i64, p); + valid &= matches | !in_padding; + } + // Single public decision point: the caller learns only valid/invalid. + if valid.to_bool() { + // p is within 1..=k here, so k - p is in 0..k and the cast is lossless. + Ok((k - p) as usize) + } else { + Err(PaddingError::InvalidPadding) + } + } +} + +/// The absence of padding, as a [`Padding`] scheme: for data that must already be a whole number of +/// blocks. +/// +/// `pad` never writes anything -- it returns [`PaddingError::PaddingNotPermitted`] whenever it is +/// called, because being called means there was a partial block to pad -- and `unpad` reports the +/// whole block as data. Since [`ALWAYS_PADS`](Padding::ALWAYS_PADS) is `false`, a [`PaddedEncryptor`] +/// over it emits no final block for an aligned message and fails at `do_final` for an unaligned one, +/// and a [`PaddedDecryptor`] releases every block as data. The adapters thereby turn "the caller must +/// supply whole blocks" into a checked error instead of a silent assumption, which is what this +/// scheme is for: interoperating with formats that are defined on whole blocks (and, when used with +/// ECB, with the raw block-by-block operation they specify) while keeping the arbitrary-length API +/// shape. +/// +/// It offers nothing that authentication would; see the crate's "Security Considerations". +pub struct NoPadding; + +impl Padding for NoPadding { + /// Adds nothing to aligned data: an aligned message is finished with no final block. + const ALWAYS_PADS: bool = false; + + /// Always an error: this scheme adds no bytes, so being asked to means the data was not a + /// whole number of blocks. `block` is left untouched. `data_len >= BLOCK_LEN` is reported as + /// [`PaddingError::DataLengthTooLong`], as for every scheme. + fn pad(_block: &mut [u8; BLOCK_LEN], data_len: usize) -> Result<(), PaddingError> { + if data_len >= BLOCK_LEN { + return Err(PaddingError::DataLengthTooLong(BLOCK_LEN - 1)); + } + Err(PaddingError::PaddingNotPermitted) + } + + /// The whole block is data. Constant, so trivially constant-time. + fn unpad(_block: &[u8; BLOCK_LEN]) -> Result { + Ok(BLOCK_LEN) + } +} diff --git a/crypto/padding/src/padded.rs b/crypto/padding/src/padded.rs new file mode 100644 index 00000000..ee22d21e --- /dev/null +++ b/crypto/padding/src/padded.rs @@ -0,0 +1,332 @@ +//! [`PaddedEncryptor`] / [`PaddedDecryptor`]: adapt a block-aligned [`BlockCipherEncryptor`] / +//! [`BlockCipherDecryptor`] to arbitrary-length data using a [`Padding`] scheme. +//! +//! The public API is the [`SymmetricCipherEncryptor`] / [`SymmetricCipherDecryptor`] traits, whose +//! shape was drawn from these two types; the one-shot methods are the traits' provided ones. +//! `FINAL_LEN` is `BLOCK_LEN`: the final output is the padded block -- or, under a scheme with +//! [`Padding::ALWAYS_PADS`] `false` (`NoPadding`) and an aligned message, nothing at all, in which +//! case `do_final` reports 0 of the `FINAL_LEN` bytes as output. + +use bouncycastle_core::errors::SymmetricCipherError; +use bouncycastle_core::key_material::KeyMaterial; +use bouncycastle_core::traits::{ + Algorithm, BlockCipherDecryptor, BlockCipherEncryptor, Padding, RNG, SecurityStrength, + SymmetricCipherDecryptor, SymmetricCipherEncryptor, +}; +use bouncycastle_utils::secret::Secret; +use core::array::from_mut; +use core::marker::PhantomData; + +/// Blocks per inner-cipher call on the bulk path; the remainder is processed one at a time. +const GROUP: usize = 8; + +/// Encrypts arbitrary-length data with a block cipher `E`, padding the final block with `P`. +/// +/// Stream with [`SymmetricCipherEncryptor::do_update_out`] then [`SymmetricCipherEncryptor::do_final`], +/// or use the one-shot [`SymmetricCipherEncryptor::encrypt_out`]. Output is +/// `plaintext_len / BLOCK_LEN + 1` blocks for a scheme that always pads (PKCS7), and exactly the +/// input length for one that never does (`NoPadding`, which rejects an unaligned input at +/// `do_final`). The buffered partial plaintext block is held in a [`Secret`]. +pub struct PaddedEncryptor< + E, + P, + const KEY_LEN: usize, + const INIT_DATA_LEN: usize, + const BLOCK_LEN: usize, +> where + E: BlockCipherEncryptor, + P: Padding, +{ + inner: E, + /// Partial plaintext block; `buf_len < BLOCK_LEN` between calls. + buf: Secret<[u8; BLOCK_LEN]>, + buf_len: usize, + _padding: PhantomData

, +} + +impl + PaddedEncryptor +where + E: BlockCipherEncryptor, + P: Padding, +{ + fn wrap(inner: E) -> Self { + Self { inner, buf: Secret::new(), buf_len: 0, _padding: PhantomData } + } +} + +impl Algorithm + for PaddedEncryptor +where + E: BlockCipherEncryptor, + P: Padding, +{ + /// The inner cipher's name; padding does not change what the algorithm is. + const ALG_NAME: &'static str = E::ALG_NAME; + /// Padding does not change the strength of the inner cipher. + const MAX_SECURITY_STRENGTH: SecurityStrength = E::MAX_SECURITY_STRENGTH; +} + +impl + SymmetricCipherEncryptor + for PaddedEncryptor +where + E: BlockCipherEncryptor, + P: Padding, +{ + fn do_encrypt_init( + key: &KeyMaterial, + ) -> Result<(Self, [u8; INIT_DATA_LEN]), SymmetricCipherError> { + let (inner, init_data) = E::do_encrypt_init(key)?; + Ok((Self::wrap(inner), init_data)) + } + + fn do_encrypt_init_rng( + key: &KeyMaterial, + rng: &mut dyn RNG, + ) -> Result<(Self, [u8; INIT_DATA_LEN]), SymmetricCipherError> { + let (inner, init_data) = E::do_encrypt_init_rng(key, rng)?; + Ok((Self::wrap(inner), init_data)) + } + + /// Whole blocks among the buffered bytes plus `input_len`. + fn update_out_len(&self, input_len: usize) -> usize { + (self.buf_len + input_len) / BLOCK_LEN * BLOCK_LEN + } + + /// Encrypts all whole blocks available (buffered + `plaintext`) into `ciphertext`, buffering the + /// remainder. + fn do_update_out( + &mut self, + plaintext: &[u8], + ciphertext: &mut [u8], + ) -> Result { + let out_len = self.update_out_len(plaintext.len()); + if ciphertext.len() < out_len { + return Err(SymmetricCipherError::IncorrectOutputBufferLength("ciphertext", out_len)); + } + // out_len is a multiple of BLOCK_LEN, so the remainder of this split is empty. + let (mut out_blocks, _) = ciphertext[..out_len].as_chunks_mut::(); + let mut plaintext = plaintext; + + // 1. Top up a previously buffered partial block. + if self.buf_len > 0 { + let take = (BLOCK_LEN - self.buf_len).min(plaintext.len()); + self.buf[self.buf_len..self.buf_len + take].copy_from_slice(&plaintext[..take]); + self.buf_len += take; + plaintext = &plaintext[take..]; + if self.buf_len < BLOCK_LEN { + // All input absorbed into the partial block; nothing to emit (out_len == 0). + return Ok(0); + } + // Block completed. out_len >= BLOCK_LEN here, so `split_first_mut` always succeeds. + // The cipher works in place, so the block is encrypted inside the `Secret` and only + // ciphertext is copied out of it. + if let Some((first, rest)) = core::mem::take(&mut out_blocks).split_first_mut() { + self.inner.do_encrypt_blocks(from_mut(&mut *self.buf))?; + *first = *self.buf; + out_blocks = rest; + } + self.buf_len = 0; + } + + // 2. Bulk path: whole blocks are copied into the output and encrypted there, in place, in + // groups of GROUP then singly. + let (in_blocks, remainder) = plaintext.as_chunks::(); + debug_assert_eq!(in_blocks.len(), out_blocks.len()); + out_blocks.copy_from_slice(in_blocks); + let (out_groups, out_tail) = out_blocks.as_chunks_mut::(); + for group in out_groups.iter_mut() { + self.inner.do_encrypt_blocks(group)?; + } + for block in out_tail.iter_mut() { + self.inner.do_encrypt_blocks(from_mut(block))?; + } + + // 3. Buffer the trailing partial block (remainder.len() < BLOCK_LEN). + self.buf[..remainder.len()].copy_from_slice(remainder); + self.buf_len = remainder.len(); + Ok(out_len) + } + + /// Pads and encrypts the buffered partial block, returning the final ciphertext block and + /// `BLOCK_LEN` -- or, when the scheme adds nothing to aligned data and nothing is buffered, an + /// untouched buffer and 0: there is no final block. + /// + /// The block is padded and encrypted inside the `Secret`, so what is copied out is ciphertext. + /// A scheme that adds no padding turns a buffered partial block into + /// [`SymmetricCipherError::PaddingError`] here, which is the alignment check such a scheme + /// exists to provide. + fn do_final(self) -> Result<([u8; BLOCK_LEN], usize), SymmetricCipherError> { + let Self { mut inner, mut buf, buf_len, .. } = self; + if buf_len == 0 && !P::ALWAYS_PADS { + return Ok(([0u8; BLOCK_LEN], 0)); + } + P::pad(&mut buf, buf_len)?; + inner.do_encrypt(&mut buf)?; + Ok((*buf, BLOCK_LEN)) + } + + /// `(plaintext_len / BLOCK_LEN + 1) * BLOCK_LEN` -- always one extra block for the padding -- + /// for a scheme that always pads; `plaintext_len` itself for one that adds nothing (an + /// unaligned length is rejected by `do_final`, so this is exact for every accepted input). + fn encrypt_out_len(plaintext_len: usize) -> usize { + if P::ALWAYS_PADS { (plaintext_len / BLOCK_LEN + 1) * BLOCK_LEN } else { plaintext_len } + } +} + +/// Decrypts data produced by a [`PaddedEncryptor`] with the matching cipher and padding. +/// +/// Only the last block carries padding, so [`do_update_out`](Self::do_update_out) always withholds +/// the most recent complete block and [`do_final`](Self::do_final) unpads it. One-shot: +/// [`decrypt_out`](Self::decrypt_out). +pub struct PaddedDecryptor< + D, + P, + const KEY_LEN: usize, + const INIT_DATA_LEN: usize, + const BLOCK_LEN: usize, +> where + D: BlockCipherDecryptor, + P: Padding, +{ + inner: D, + /// Partial ciphertext block; `buf_len < BLOCK_LEN` between calls. + buf: [u8; BLOCK_LEN], + buf_len: usize, + /// Most recent complete ciphertext block, withheld in case it is the last. + held: Option<[u8; BLOCK_LEN]>, + _padding: PhantomData

, +} + +impl Algorithm + for PaddedDecryptor +where + D: BlockCipherDecryptor, + P: Padding, +{ + /// The inner cipher's name; padding does not change what the algorithm is. + const ALG_NAME: &'static str = D::ALG_NAME; + /// Padding does not change the strength of the inner cipher. + const MAX_SECURITY_STRENGTH: SecurityStrength = D::MAX_SECURITY_STRENGTH; +} + +impl + SymmetricCipherDecryptor + for PaddedDecryptor +where + D: BlockCipherDecryptor, + P: Padding, +{ + fn do_decrypt_init( + key: &KeyMaterial, + init_data: &[u8; INIT_DATA_LEN], + ) -> Result { + Ok(Self { + inner: D::do_decrypt_init(key, init_data)?, + buf: [0u8; BLOCK_LEN], + buf_len: 0, + held: None, + _padding: PhantomData, + }) + } + + /// All complete blocks but the most recent one are released. + fn update_out_len(&self, input_len: usize) -> usize { + let complete = self.held.is_some() as usize + (self.buf_len + input_len) / BLOCK_LEN; + complete.saturating_sub(1) * BLOCK_LEN + } + + /// Decrypts all complete blocks except the most recent into `plaintext`, buffering the remainder. + fn do_update_out( + &mut self, + ciphertext: &[u8], + plaintext: &mut [u8], + ) -> Result { + let out_len = self.update_out_len(ciphertext.len()); + if plaintext.len() < out_len { + return Err(SymmetricCipherError::IncorrectOutputBufferLength("plaintext", out_len)); + } + let (mut out_blocks, _) = plaintext[..out_len].as_chunks_mut::(); + let mut ciphertext = ciphertext; + + // 1. Top up a previously buffered partial block. + if self.buf_len > 0 { + let take = (BLOCK_LEN - self.buf_len).min(ciphertext.len()); + self.buf[self.buf_len..self.buf_len + take].copy_from_slice(&ciphertext[..take]); + self.buf_len += take; + ciphertext = &ciphertext[take..]; + if self.buf_len < BLOCK_LEN { + return Ok(0); + } + self.buf_len = 0; + // The completed block becomes the held block; the previously held block, if any, is + // now known not to be last and can be released. out_blocks has room for it by + // construction of out_len, so `split_first_mut` succeeds. + if let Some(prev) = self.held.replace(self.buf) + && let Some((first, rest)) = core::mem::take(&mut out_blocks).split_first_mut() + { + *first = prev; + self.inner.do_decrypt_blocks(from_mut(first))?; + out_blocks = rest; + } + } + + // 2. Bulk path. + let (in_blocks, remainder) = ciphertext.as_chunks::(); + if let Some((last, release)) = in_blocks.split_last() { + // Release the previously held block first (it precedes everything in `in_blocks`). + if let Some(prev) = self.held.replace(*last) + && let Some((first, rest)) = core::mem::take(&mut out_blocks).split_first_mut() + { + *first = prev; + self.inner.do_decrypt_blocks(from_mut(first))?; + out_blocks = rest; + } + // Then every block of this call except the new held one: copied into the output and + // decrypted there, in place. + debug_assert_eq!(release.len(), out_blocks.len()); + out_blocks.copy_from_slice(release); + let (out_groups, out_tail) = out_blocks.as_chunks_mut::(); + for group in out_groups.iter_mut() { + self.inner.do_decrypt_blocks(group)?; + } + for block in out_tail.iter_mut() { + self.inner.do_decrypt_blocks(from_mut(block))?; + } + } + + // 3. Buffer the trailing partial block. + self.buf[..remainder.len()].copy_from_slice(remainder); + self.buf_len = remainder.len(); + Ok(out_len) + } + + /// Decrypts and unpads the held final block. Returns the block and its data length; the rest is + /// padding. `DecryptionFailed` if the ciphertext was not block-aligned, or was empty under a + /// scheme that always pads (a padded message is at least one block); `PaddingError` if the + /// padding is malformed. Under a scheme that adds nothing, an empty ciphertext is the empty + /// message and every held block is entirely data. + fn do_final(self) -> Result<([u8; BLOCK_LEN], usize), SymmetricCipherError> { + let Self { mut inner, buf_len, held, .. } = self; + if buf_len != 0 { + return Err(SymmetricCipherError::DecryptionFailed); + } + let Some(mut block) = held else { + return if P::ALWAYS_PADS { + Err(SymmetricCipherError::DecryptionFailed) + } else { + Ok(([0u8; BLOCK_LEN], 0)) + }; + }; + inner.do_decrypt(&mut block)?; + let data_len = P::unpad(&block)?; + Ok((block, data_len)) + } + + /// `ciphertext_len - 1` for a scheme that always pads (at least one byte of the final block is + /// padding); `ciphertext_len` for one that adds nothing. + fn decrypt_out_max_len(ciphertext_len: usize) -> usize { + if P::ALWAYS_PADS { ciphertext_len.saturating_sub(1) } else { ciphertext_len } + } +} diff --git a/crypto/padding/tests/nopadding_tests.rs b/crypto/padding/tests/nopadding_tests.rs new file mode 100644 index 00000000..148ea93f --- /dev/null +++ b/crypto/padding/tests/nopadding_tests.rs @@ -0,0 +1,55 @@ +//! Tests for `NoPadding`: a `Padding` scheme that adds nothing and refuses to. +//! +//! There is no rule to transcribe; the contract is that `pad` is an error whenever it is called +//! (being called means a partial block existed), `unpad` reports a whole block of data, and the +//! scheme declares that it does not pad aligned data, so the adapters emit no final block. + +use bouncycastle_core::errors::PaddingError; +use bouncycastle_core::traits::Padding; +use bouncycastle_padding::{NoPadding, PKCS7}; + +fn pad_always_refuses() { + for data_len in 0..K { + let mut block: [u8; K] = core::array::from_fn(|i| i as u8 ^ 0xA5); + let original = block; + assert_eq!( + >::pad(&mut block, data_len), + Err(PaddingError::PaddingNotPermitted), + "K={K} data_len={data_len}" + ); + assert_eq!(block, original, "K={K} data_len={data_len}: nothing may be written"); + } + // Beyond the block is the same error every scheme gives. + let mut block = [0u8; K]; + assert_eq!( + >::pad(&mut block, K), + Err(PaddingError::DataLengthTooLong(K - 1)) + ); +} + +#[test] +fn pad_refuses_every_data_length() { + pad_always_refuses::<1>(); + pad_always_refuses::<8>(); + pad_always_refuses::<16>(); + pad_always_refuses::<255>(); +} + +#[test] +fn unpad_reports_the_whole_block_as_data() { + for fill in [0x00u8, 0x01, 0x10, 0x7f, 0xff] { + assert_eq!(>::unpad(&[fill; 16]), Ok(16)); + assert_eq!(>::unpad(&[fill; 8]), Ok(8)); + } + // ...including blocks that would be well-formed PKCS7 padding: there is nothing to strip. + let mut pkcs7 = [0u8; 16]; + >::pad(&mut pkcs7, 5).unwrap(); + assert_eq!(>::unpad(&pkcs7), Ok(16)); +} + +/// The flag the adapters key off: PKCS7 always appends a block to aligned data, NoPadding never. +#[test] +fn always_pads_flags() { + assert!(>::ALWAYS_PADS); + assert!(!>::ALWAYS_PADS); +} diff --git a/crypto/padding/tests/padded_tests.rs b/crypto/padding/tests/padded_tests.rs new file mode 100644 index 00000000..42f7cb60 --- /dev/null +++ b/crypto/padding/tests/padded_tests.rs @@ -0,0 +1,403 @@ +//! Tests for PaddedEncryptor / PaddedDecryptor. +//! +//! No real block cipher exists in the workspace yet, so these tests drive the adapters with a toy +//! CBC-style cipher whose "block permutation" is XOR with the key. It is cryptographically worthless +//! but exercises every code path of the adapters: IV generation, chaining state across calls, and +//! the one-block lag on decryption. + +use bouncycastle_core::errors::{KeyMaterialError, PaddingError, SymmetricCipherError}; +use bouncycastle_core::key_material::{KeyMaterial, KeyMaterialTrait, KeyType}; +use bouncycastle_core::traits::{ + Algorithm, BlockCipherDecryptor, BlockCipherEncryptor, RNG, SecurityStrength, + SymmetricCipherDecryptor, SymmetricCipherEncryptor, +}; +use bouncycastle_core_test_framework::FixedSeedRNG; +use bouncycastle_core_test_framework::symmetric_ciphers::{ + TestFrameworkBlockCipher, TestFrameworkSymmetricCipher, +}; +use bouncycastle_padding::{NoPadding, PKCS7, PaddedDecryptor, PaddedEncryptor}; +use bouncycastle_rng::hash_drbg80090a::{HashDRBG80090A, HashDRBG80090AParams_SHA256}; + +const B: usize = 8; + +/// c_j = p_j ^ c_{j-1} ^ key ; p_j = c_j ^ c_{j-1} ^ key +struct ToyCbc { + key: [u8; B], + chain: [u8; B], +} + +impl ToyCbc { + fn check_key(key: &KeyMaterial) -> Result<[u8; B], SymmetricCipherError> { + if key.key_type() != KeyType::SymmetricCipherKey { + return Err(KeyMaterialError::InvalidKeyType("expected SymmetricCipherKey"))?; + } + if key.security_strength() < Self::MAX_SECURITY_STRENGTH { + return Err(KeyMaterialError::GenericError("key too weak"))?; + } + let mut k = [0u8; B]; + k.copy_from_slice(key.ref_to_bytes()); + Ok(k) + } +} + +impl Algorithm for ToyCbc { + const ALG_NAME: &'static str = "ToyCbc"; + const MAX_SECURITY_STRENGTH: SecurityStrength = SecurityStrength::None; +} + +impl BlockCipherEncryptor for ToyCbc { + fn do_encrypt_init(key: &KeyMaterial) -> Result<(Self, [u8; B]), SymmetricCipherError> { + let mut rng = HashDRBG80090A::::new_from_os(); + Self::do_encrypt_init_rng(key, &mut rng) + } + fn do_encrypt_init_rng( + key: &KeyMaterial, + rng: &mut dyn RNG, + ) -> Result<(Self, [u8; B]), SymmetricCipherError> { + let key = Self::check_key(key)?; + let mut iv = [0u8; B]; + rng.next_bytes_out(&mut iv)?; + Ok((Self { key, chain: iv }, iv)) + } + fn do_encrypt_blocks(&mut self, blocks: &mut [[u8; B]]) -> Result<(), SymmetricCipherError> { + for block in blocks.iter_mut() { + for (b, (c, k)) in block.iter_mut().zip(self.chain.iter().zip(self.key.iter())) { + *b ^= c ^ k; + } + self.chain = *block; + } + Ok(()) + } +} + +impl BlockCipherDecryptor for ToyCbc { + fn do_decrypt_init(key: &KeyMaterial, iv: &[u8; B]) -> Result { + Ok(Self { key: Self::check_key(key)?, chain: *iv }) + } + fn do_decrypt_blocks(&mut self, blocks: &mut [[u8; B]]) -> Result<(), SymmetricCipherError> { + for block in blocks.iter_mut() { + let ct = *block; + for (b, (c, k)) in block.iter_mut().zip(self.chain.iter().zip(self.key.iter())) { + *b ^= c ^ k; + } + self.chain = ct; + } + Ok(()) + } +} + +type Enc = PaddedEncryptor; +type Dec = PaddedDecryptor; +/// The same adapters over `NoPadding`: an alignment check rather than a padding scheme. +type EncNP = PaddedEncryptor; +type DecNP = PaddedDecryptor; + +fn key() -> KeyMaterial { + KeyMaterial::::from_bytes_as_type(&[0x5a; B], KeyType::SymmetricCipherKey).unwrap() +} + +fn msg(len: usize) -> Vec { + (0..len).map(|i| (i * 7 + 3) as u8).collect() +} + +#[test] +fn toy_cipher_passes_core_test_framework() { + TestFrameworkBlockCipher::new().test::(); +} + +/// The padded adapters are the first implementors of `SymmetricCipherEncryptor` / +/// `SymmetricCipherDecryptor`, so this is also what exercises those traits' provided one-shots. +#[test] +fn padded_adapters_pass_the_symmetric_cipher_framework() { + TestFrameworkSymmetricCipher::new().test_encryptor_decryptor::(); +} + +#[test] +fn one_shot_roundtrip_all_lengths() { + let key = key(); + for len in 0..=3 * B + 1 { + let pt = msg(len); + let mut ct = vec![0u8; Enc::encrypt_out_len(len)]; + let (iv, n) = Enc::encrypt_out(&key, &pt, &mut ct).unwrap(); + assert_eq!(n, ct.len()); + assert_eq!(n, (len / B + 1) * B, "always one extra padding block"); + + let mut out = vec![0u8; Dec::decrypt_out_max_len(n)]; + let m = Dec::decrypt_out(&key, &iv, &ct[..n], &mut out).unwrap(); + assert_eq!(&out[..m], &pt[..]); + } +} + +#[test] +fn streaming_matches_one_shot_for_every_chunking() { + let key = key(); + let len = 5 * B + 3; + let pt = msg(len); + + for chunk in [1usize, 2, 3, 7, 8, 9, 15, 16, 17, len] { + // encrypt in chunks + let (mut enc, iv) = Enc::do_encrypt_init(&key).unwrap(); + let mut ct = Vec::new(); + for piece in pt.chunks(chunk) { + let expect = enc.update_out_len(piece.len()); + let mut buf = vec![0u8; expect]; + let n = enc.do_update_out(piece, &mut buf).unwrap(); + assert_eq!(n, expect, "update_out_len must be exact"); + ct.extend_from_slice(&buf[..n]); + } + let (last, last_len) = enc.do_final().unwrap(); + assert_eq!(last_len, B, "PKCS7 always emits a final block"); + ct.extend_from_slice(&last[..last_len]); + assert_eq!(ct.len(), Enc::encrypt_out_len(len)); + + // one-shot decrypt + let mut out = vec![0u8; Dec::decrypt_out_max_len(ct.len())]; + let m = Dec::decrypt_out(&key, &iv, &ct, &mut out).unwrap(); + assert_eq!(&out[..m], &pt[..], "chunk {chunk}"); + + // decrypt in the same chunks + let mut dec = Dec::do_decrypt_init(&key, &iv).unwrap(); + let mut rec = Vec::new(); + for piece in ct.chunks(chunk) { + let expect = dec.update_out_len(piece.len()); + let mut buf = vec![0u8; expect]; + let n = dec.do_update_out(piece, &mut buf).unwrap(); + assert_eq!(n, expect, "update_out_len must be exact (decrypt)"); + rec.extend_from_slice(&buf[..n]); + } + let (block, data_len) = dec.do_final().unwrap(); + rec.extend_from_slice(&block[..data_len]); + assert_eq!(rec, pt, "chunk {chunk}"); + } +} + +#[test] +fn decryptor_lags_by_exactly_one_block() { + let key = key(); + let (iv, ct) = { + let mut ct = vec![0u8; Enc::encrypt_out_len(2 * B)]; + let (iv, _) = Enc::encrypt_out(&key, &msg(2 * B), &mut ct).unwrap(); + (iv, ct) + }; + assert_eq!(ct.len(), 3 * B); + let mut dec = Dec::do_decrypt_init(&key, &iv).unwrap(); + let mut out = [0u8; 3 * B]; + // first block: nothing can be released yet + assert_eq!(dec.update_out_len(B), 0); + assert_eq!(dec.do_update_out(&ct[..B], &mut out).unwrap(), 0); + // second block: releases the first + assert_eq!(dec.update_out_len(B), B); + assert_eq!(dec.do_update_out(&ct[B..2 * B], &mut out).unwrap(), B); + // third block: releases the second + assert_eq!(dec.do_update_out(&ct[2 * B..], &mut out[B..]).unwrap(), B); + let (last, n) = dec.do_final().unwrap(); + assert_eq!(n, 0, "block-aligned plaintext => final block is all padding"); + assert_eq!(&out[..2 * B], &msg(2 * B)[..]); + let _ = last; +} + +#[test] +fn final_out_variants() { + let key = key(); + let (mut enc, iv) = Enc::do_encrypt_init(&key).unwrap(); + let mut ct = [0u8; 2 * B]; + let n = enc.do_update_out(&msg(B + 2), &mut ct).unwrap(); + assert_eq!(n, B); + let mut last = [0u8; B]; + assert_eq!(enc.do_final_out(&mut last).unwrap(), B); + ct[B..].copy_from_slice(&last); + + let mut dec = Dec::do_decrypt_init(&key, &iv).unwrap(); + let mut out = [0u8; B]; + assert_eq!(dec.do_update_out(&ct, &mut out).unwrap(), B); + let mut last_pt = [0u8; B]; + let data_len = dec.do_final_out(&mut last_pt).unwrap(); + assert_eq!(data_len, 2); + let mut rec = out.to_vec(); + rec.extend_from_slice(&last_pt[..data_len]); + assert_eq!(rec, msg(B + 2)); +} + +#[test] +fn tampered_final_block_is_rejected() { + let key = key(); + for len in [0, 1, B - 1, B, B + 5] { + let mut ct = vec![0u8; Enc::encrypt_out_len(len)]; + let (iv, n) = Enc::encrypt_out(&key, &msg(len), &mut ct).unwrap(); + // flipping the low bit of the final byte corrupts the PKCS7 length byte + ct[n - 1] ^= 0x01; + let mut out = vec![0u8; n]; + match Dec::decrypt_out(&key, &iv, &ct, &mut out) { + Err(SymmetricCipherError::PaddingError(PaddingError::InvalidPadding)) => {} + other => panic!("len {len}: expected InvalidPadding, got {other:?}"), + } + } +} + +#[test] +fn malformed_ciphertext_lengths_are_rejected() { + let key = key(); + let iv = [0u8; B]; + let mut out = [0u8; 4 * B]; + + // empty + assert!(matches!( + Dec::decrypt_out(&key, &iv, &[], &mut out), + Err(SymmetricCipherError::DecryptionFailed) + )); + // not a multiple of the block length + assert!(matches!( + Dec::decrypt_out(&key, &iv, &[0u8; B + 1], &mut out), + Err(SymmetricCipherError::DecryptionFailed) + )); + // streaming: partial trailing block at final + let mut dec = Dec::do_decrypt_init(&key, &iv).unwrap(); + dec.do_update_out(&[0u8; B + 3], &mut out).unwrap(); + assert!(matches!(dec.do_final(), Err(SymmetricCipherError::DecryptionFailed))); + // streaming: nothing fed at all + let dec = Dec::do_decrypt_init(&key, &iv).unwrap(); + assert!(matches!(dec.do_final(), Err(SymmetricCipherError::DecryptionFailed))); +} + +#[test] +fn output_buffer_too_small_reports_required_length() { + let key = key(); + let pt = msg(2 * B + 1); + + let mut small = [0u8; 2 * B]; + match Enc::encrypt_out(&key, &pt, &mut small) { + Err(SymmetricCipherError::IncorrectOutputBufferLength(_, need)) => assert_eq!(need, 3 * B), + other => panic!("{other:?}"), + } + + let (mut enc, iv) = Enc::do_encrypt_init(&key).unwrap(); + let mut tiny = [0u8; B - 1]; + match enc.do_update_out(&pt, &mut tiny) { + Err(SymmetricCipherError::IncorrectOutputBufferLength(_, need)) => assert_eq!(need, 2 * B), + other => panic!("{other:?}"), + } + drop(enc); + + let ct = [0u8; 3 * B]; + let mut small = [0u8; 3 * B - 2]; + match Dec::decrypt_out(&key, &iv, &ct, &mut small) { + Err(SymmetricCipherError::IncorrectOutputBufferLength(_, need)) => { + assert_eq!(need, 3 * B - 1) + } + other => panic!("{other:?}"), + } +} + +#[test] +fn wrong_key_type_is_rejected_by_adapters() { + let mac_key = KeyMaterial::::from_bytes_as_type(&[1u8; B], KeyType::MACKey).unwrap(); + assert!(matches!( + Enc::do_encrypt_init(&mac_key), + Err(SymmetricCipherError::KeyMaterialError(_)) + )); + assert!(matches!( + Dec::do_decrypt_init(&mac_key, &[0u8; B]), + Err(SymmetricCipherError::KeyMaterialError(_)) + )); +} + +// ---- NoPadding through the adapters -------------------------------------------------------- + +/// With `NoPadding` the adapters enforce alignment: the framework is told that only multiples of +/// the block length are accepted, and it asserts that every other length is refused with a +/// `PaddingError`, at `encrypt_out` and at a streaming `do_final`. +#[test] +fn no_padding_adapters_pass_the_symmetric_cipher_framework() { + let mut framework = TestFrameworkSymmetricCipher::new(); + framework.required_alignment = B; + framework.test_encryptor_decryptor::(); +} + +/// An aligned message passes through with its length unchanged -- no final block is added -- and the +/// ciphertext is exactly what the bare mode produces: NoPadding is a check, not a transformation. +#[test] +fn no_padding_adds_nothing_to_aligned_data() { + let key = key(); + for blocks in 0..=4usize { + let len = blocks * B; + let pt = msg(len); + assert_eq!(EncNP::encrypt_out_len(len), len); + assert_eq!(DecNP::decrypt_out_max_len(len), len); + + let mut ct = vec![0u8; len]; + let (iv, n) = EncNP::encrypt_out(&key, &pt, &mut ct).unwrap(); + assert_eq!(n, len, "{blocks} blocks: output length equals input length"); + + // Byte for byte the bare cipher's output under the same IV. + let mut bare = pt.clone(); + let (mut enc, _) = + ToyCbc::do_encrypt_init_rng(&key, &mut FixedSeedRNG::::new(iv)).unwrap(); + let (blocks_mut, _) = bare.as_chunks_mut::(); + enc.do_encrypt_blocks(blocks_mut).unwrap(); + assert_eq!(ct, bare, "{blocks} blocks: the adapter must not alter the ciphertext"); + + let mut out = vec![0u8; len]; + let m = DecNP::decrypt_out(&key, &iv, &ct, &mut out).unwrap(); + assert_eq!(&out[..m], &pt[..], "{blocks} blocks: round trip"); + + // Streaming: do_final reports zero output bytes. + let (mut enc, _) = EncNP::do_encrypt_init(&key).unwrap(); + let mut buf = vec![0u8; enc.update_out_len(len)]; + assert_eq!(enc.do_update_out(&pt, &mut buf).unwrap(), len); + let (_, last_len) = enc.do_final().unwrap(); + assert_eq!(last_len, 0, "{blocks} blocks: no final block"); + } +} + +/// An unaligned message is refused with `PaddingNotPermitted`, from the one-shot and from a +/// streaming `do_final`, and nothing is written for the final block. +#[test] +fn no_padding_refuses_unaligned_data() { + let key = key(); + for len in [1usize, B - 1, B + 1, 2 * B + 3, 3 * B - 1] { + let pt = msg(len); + let mut ct = vec![0u8; len + B]; + assert!( + matches!( + EncNP::encrypt_out(&key, &pt, &mut ct), + Err(SymmetricCipherError::PaddingError(PaddingError::PaddingNotPermitted)) + ), + "len {len}: one-shot must refuse an unaligned message" + ); + + let (mut enc, _) = EncNP::do_encrypt_init(&key).unwrap(); + let whole = len / B * B; + let mut buf = vec![0u8; whole]; + assert_eq!(enc.do_update_out(&pt, &mut buf).unwrap(), whole, "whole blocks still stream"); + assert!( + matches!( + enc.do_final(), + Err(SymmetricCipherError::PaddingError(PaddingError::PaddingNotPermitted)) + ), + "len {len}: do_final must refuse the buffered partial block" + ); + } +} + +/// On the decrypt side, an empty ciphertext is the empty message (there is no padding block to +/// demand), and an unaligned ciphertext is still malformed. +#[test] +fn no_padding_decryptor_accepts_empty_and_rejects_unaligned() { + let key = key(); + let iv = [0x11u8; B]; + let mut out = [0u8; 0]; + assert_eq!(DecNP::decrypt_out(&key, &iv, &[], &mut out).unwrap(), 0); + let dec = DecNP::do_decrypt_init(&key, &iv).unwrap(); + assert_eq!(dec.do_final().unwrap().1, 0); + + for len in [1usize, B - 1, B + 1, 2 * B + 5] { + let mut out = vec![0u8; len]; + assert!( + matches!( + DecNP::decrypt_out(&key, &iv, &msg(len), &mut out), + Err(SymmetricCipherError::DecryptionFailed) + ), + "len {len}: an unaligned ciphertext is malformed" + ); + } +} diff --git a/crypto/padding/tests/pkcs7_tests.rs b/crypto/padding/tests/pkcs7_tests.rs new file mode 100644 index 00000000..d68de485 --- /dev/null +++ b/crypto/padding/tests/pkcs7_tests.rs @@ -0,0 +1,121 @@ +//! Tests for PKCS7 against the rule of RFC 5652 §6.3: +//! "the input shall be padded at the trailing end with k-(lth mod k) octets all having value +//! k-(lth mod k)". There are no official test vectors for this scheme; expected values below are +//! computed directly from that rule. + +use bouncycastle_core::errors::PaddingError; +use bouncycastle_core::traits::Padding; +use bouncycastle_padding::PKCS7; + +fn roundtrip_all_lengths() { + for data_len in 0..K { + let mut block = [0xA5u8; K]; + for (i, b) in block.iter_mut().enumerate().take(data_len) { + *b = i as u8; + } + let original = block; + + >::pad(&mut block, data_len).unwrap(); + + // data untouched + assert_eq!(&block[..data_len], &original[..data_len]); + // RFC 5652 §6.3: k - (lth mod k) octets, each of value k - (lth mod k) + let expected_pad = K - data_len; + assert_eq!(block[data_len..].len(), expected_pad); + assert!(block[data_len..].iter().all(|&b| b as usize == expected_pad)); + + assert_eq!(>::unpad(&block), Ok(data_len)); + } +} + +#[test] +fn roundtrip_16() { + roundtrip_all_lengths::<16>(); +} + +#[test] +fn roundtrip_8() { + roundtrip_all_lengths::<8>(); +} + +#[test] +fn roundtrip_boundary_block_lengths() { + roundtrip_all_lengths::<1>(); + roundtrip_all_lengths::<255>(); +} + +#[test] +fn rfc5652_worked_examples() { + // RFC 5652 §6.3 lists the padding strings: "01 -- if lth mod k = k-1", "02 02 -- if lth mod k = k-2", + // ..., "k k ... k k -- if lth mod k = 0". + const K: usize = 16; + let mut b = [0xFFu8; K]; + >::pad(&mut b, K - 1).unwrap(); + assert_eq!(b[K - 1], 0x01); + + let mut b = [0xFFu8; K]; + >::pad(&mut b, K - 2).unwrap(); + assert_eq!(&b[K - 2..], &[0x02, 0x02]); + + let mut b = [0xFFu8; K]; + >::pad(&mut b, 0).unwrap(); + assert_eq!(b, [K as u8; K]); +} + +#[test] +fn pad_rejects_full_block() { + let mut b = [0u8; 16]; + assert_eq!(>::pad(&mut b, 16), Err(PaddingError::DataLengthTooLong(15))); + assert_eq!(>::pad(&mut b, 17), Err(PaddingError::DataLengthTooLong(15))); + // block untouched on error + assert_eq!(b, [0u8; 16]); +} + +#[test] +fn unpad_rejects_malformed() { + const K: usize = 16; + + // last byte zero: no such padding string + let mut b = [0x00u8; K]; + assert_eq!(>::unpad(&b), Err(PaddingError::InvalidPadding)); + + // last byte greater than k + b[K - 1] = (K + 1) as u8; + assert_eq!(>::unpad(&b), Err(PaddingError::InvalidPadding)); + b[K - 1] = 0xFF; + assert_eq!(>::unpad(&b), Err(PaddingError::InvalidPadding)); + + // claims 4 bytes of padding but one of them is wrong, at every possible position + for bad in 0..4 { + let mut b = [0x11u8; K]; + b[K - 4..].copy_from_slice(&[0x04; 4]); + b[K - 4 + bad] ^= 0x01; + if bad == 3 { + // corrupting the length byte itself turns it into 0x05; the preceding bytes are 0x04, so + // still invalid + assert_eq!(b[K - 1], 0x05); + } + assert_eq!( + >::unpad(&b), + Err(PaddingError::InvalidPadding), + "bad position {bad}" + ); + } + + // a full padding block with a single wrong byte anywhere is invalid + for pos in 0..K { + let mut b = [K as u8; K]; + b[pos] ^= 0x80; + assert_eq!(>::unpad(&b), Err(PaddingError::InvalidPadding)); + } +} + +#[test] +fn unpad_ignores_data_bytes_that_happen_to_equal_pad_value() { + // data bytes equal to the pad value must not confuse the length recovery + const K: usize = 16; + let mut b = [0x03u8; K]; // 13 data bytes all 0x03, then 3 bytes of 0x03 padding + >::pad(&mut b, 13).unwrap(); + assert_eq!(b, [0x03u8; K]); + assert_eq!(>::unpad(&b), Ok(13)); +} diff --git a/crypto/rng/src/hash_drbg80090a.rs b/crypto/rng/src/hash_drbg80090a.rs index be70cb8d..a52a3950 100644 --- a/crypto/rng/src/hash_drbg80090a.rs +++ b/crypto/rng/src/hash_drbg80090a.rs @@ -13,7 +13,7 @@ use bouncycastle_core::traits::{Hash, HashAlgParams, RNG, SecurityStrength}; use bouncycastle_sha2::{SHA256, SHA512}; use bouncycastle_utils::{min, secret::Secret}; -use std::fmt::{Display, Formatter}; +use core::fmt::{Display, Formatter}; enum SupportedHash { SHA256, @@ -90,7 +90,7 @@ struct AdministrativeInfo { /// Explicit implementation of Display that prevents auto-generated ones from accidentally leaking secrets. impl Display for WorkingState { - fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result { + fn fmt(&self, f: &mut Formatter<'_>) -> core::fmt::Result { write!(f, "HashDRBG80090A::WorkingState::<{}>", SEED_LEN) } } diff --git a/crypto/sha2/Cargo.toml b/crypto/sha2/Cargo.toml index affcde1b..565ca225 100644 --- a/crypto/sha2/Cargo.toml +++ b/crypto/sha2/Cargo.toml @@ -13,6 +13,7 @@ bouncycastle-utils.workspace = true criterion.workspace = true bouncycastle-core-test-framework.workspace = true bouncycastle-rng.workspace = true +bouncycastle-hex.workspace = true [[bench]] name = "sha2_benches" diff --git a/crypto/sha2/benches/sha2_benches.rs b/crypto/sha2/benches/sha2_benches.rs index 0d12a00a..09771c58 100644 --- a/crypto/sha2/benches/sha2_benches.rs +++ b/crypto/sha2/benches/sha2_benches.rs @@ -5,17 +5,17 @@ use bouncycastle_core::traits::{Hash, RNG}; use bouncycastle_rng as rng; use bouncycastle_sha2::*; -fn bench_sha256(c: &mut Criterion) { +fn bench_hash(c: &mut Criterion, group_name: &str) { let mut data = [0_u8; 1024]; rng::DefaultRNG::default().next_bytes_out(&mut data).unwrap(); - let mut digest = vec![0; SHA256::new().output_len()]; + let mut digest = vec![0; H::default().output_len()]; - let mut group = c.benchmark_group("sha2::sha256"); + let mut group = c.benchmark_group(group_name); group.throughput(Throughput::Bytes(16 * 1024)); group.bench_function("16KiB", |b| { b.iter(|| { - let mut md = SHA256::new(); + let mut md = H::default(); for _ in 0..16 { md.do_update(black_box(&data)); } @@ -26,26 +26,21 @@ fn bench_sha256(c: &mut Criterion) { group.finish(); } +fn bench_sha256(c: &mut Criterion) { + bench_hash::(c, "sha2::sha256"); +} + fn bench_sha512(c: &mut Criterion) { - let mut data = [0_u8; 1024]; - rng::DefaultRNG::default().next_bytes_out(&mut data).unwrap(); + bench_hash::(c, "sha2::sha512"); +} - let mut digest = vec![0; SHA512::new().output_len()]; +fn bench_sha512_224(c: &mut Criterion) { + bench_hash::(c, "sha2::sha512_224"); +} - let mut group = c.benchmark_group("sha2::sha512"); - group.throughput(Throughput::Bytes(16 * 1024)); - group.bench_function("16KiB", |b| { - b.iter(|| { - let mut md = SHA512::new(); - for _ in 0..16 { - md.do_update(black_box(&data)); - } - _ = md.do_final_out(&mut digest); - black_box(&digest); - }) - }); - group.finish(); +fn bench_sha512_256(c: &mut Criterion) { + bench_hash::(c, "sha2::sha512_256"); } -criterion_group!(benches, bench_sha256, bench_sha512); +criterion_group!(benches, bench_sha256, bench_sha512, bench_sha512_224, bench_sha512_256); criterion_main!(benches); diff --git a/crypto/sha2/src/hmac.rs b/crypto/sha2/src/hmac.rs index a94bb19b..03fcec49 100644 --- a/crypto/sha2/src/hmac.rs +++ b/crypto/sha2/src/hmac.rs @@ -244,7 +244,7 @@ //! MAC; see the suspend/resume section above. //! * A key longer than the hash's block length is pre-hashed down to the output length (RFC 2104 //! Section 2), so very long keys add no strength beyond that point. -use crate::{SHA224, SHA256, SHA384, SHA512}; +use crate::{SHA224, SHA256, SHA384, SHA512, SHA512_224, SHA512_256}; use crate::{SUSPENDED_SHA256_STATE_LEN, SUSPENDED_SHA512_STATE_LEN}; use bouncycastle_core::key_material::KeyMaterial; use bouncycastle_core::traits::{HashAlgParams, SecurityStrength}; @@ -267,6 +267,10 @@ pub const HMAC_SHA256_NAME: &str = "HMAC-SHA256"; pub const HMAC_SHA384_NAME: &str = "HMAC-SHA384"; /// pub const HMAC_SHA512_NAME: &str = "HMAC-SHA512"; +/// +pub const HMAC_SHA512_224_NAME: &str = "HMAC-SHA512/224"; +/// +pub const HMAC_SHA512_256_NAME: &str = "HMAC-SHA512/256"; /*** Type aliases ***/ /// Public type for HMAC using SHA224. @@ -321,6 +325,32 @@ impl HMACParams for SHA512 { &[0x06, 0x08, 0x2a, 0x86, 0x48, 0x86, 0xf7, 0x0d, 0x02, 0x0b]; } +/// Public type for HMAC using SHA512/224. +#[allow(non_camel_case_types)] +pub type HMAC_SHA512_224 = HMAC::BLOCK_LEN }>; +impl HMACParams for SHA512_224 { + type MACKey = KeyMaterial<{ ::OUTPUT_LEN }>; + const HMAC_ALG_NAME: &'static str = HMAC_SHA512_224_NAME; + const HMAC_MAX_SECURITY_STRENGTH: SecurityStrength = SecurityStrength::_112bit; + /// Defined in RFC 8018 Appendix B.1.2: id-hmacWithSHA512-224 { digestAlgorithm 12 } + const HMAC_OID: &'static [u32] = &[1, 2, 840, 113549, 2, 12]; + const HMAC_OID_DER: &'static [u8] = + &[0x06, 0x08, 0x2a, 0x86, 0x48, 0x86, 0xf7, 0x0d, 0x02, 0x0c]; +} + +/// Public type for HMAC using SHA512/256. +#[allow(non_camel_case_types)] +pub type HMAC_SHA512_256 = HMAC::BLOCK_LEN }>; +impl HMACParams for SHA512_256 { + type MACKey = KeyMaterial<{ ::OUTPUT_LEN }>; + const HMAC_ALG_NAME: &'static str = HMAC_SHA512_256_NAME; + const HMAC_MAX_SECURITY_STRENGTH: SecurityStrength = SecurityStrength::_128bit; + /// Defined in RFC 8018 Appendix B.1.2: id-hmacWithSHA512-256 { digestAlgorithm 13 } + const HMAC_OID: &'static [u32] = &[1, 2, 840, 113549, 2, 13]; + const HMAC_OID_DER: &'static [u8] = + &[0x06, 0x08, 0x2a, 0x86, 0x48, 0x86, 0xf7, 0x0d, 0x02, 0x0d]; +} + /*** Serialized-state length constants ***/ // HMAC's suspended state is exactly the inner hasher's state -- the key is deliberately excluded and // must be re-supplied on resume -- so each of these is the underlying hash's own state length. @@ -332,3 +362,7 @@ pub const SUSPENDED_HMAC_SHA256_STATE_LEN: usize = SUSPENDED_SHA256_STATE_LEN; pub const SUSPENDED_HMAC_SHA384_STATE_LEN: usize = SUSPENDED_SHA512_STATE_LEN; /// Length in bytes of the serialized state of [`HMAC_SHA512`]. pub const SUSPENDED_HMAC_SHA512_STATE_LEN: usize = SUSPENDED_SHA512_STATE_LEN; +/// Length in bytes of the serialized state of [`HMAC_SHA512_224`]. +pub const SUSPENDED_HMAC_SHA512_224_STATE_LEN: usize = SUSPENDED_SHA512_STATE_LEN; +/// Length in bytes of the serialized state of [`HMAC_SHA512_256`]. +pub const SUSPENDED_HMAC_SHA512_256_STATE_LEN: usize = SUSPENDED_SHA512_STATE_LEN; diff --git a/crypto/sha2/src/lib.rs b/crypto/sha2/src/lib.rs index c53544d7..a54a5faa 100644 --- a/crypto/sha2/src/lib.rs +++ b/crypto/sha2/src/lib.rs @@ -9,7 +9,7 @@ //! # Examples //! ## Hash //! Hash functionality is accessed via the [`bouncycastle_core::traits::Hash`] trait, -//! which is implemented by [`SHA224`], [`SHA256`], [`SHA384`] and [`SHA512`]. +//! which is implemented by all the SHA2 primitives. //! //! The simplest usage is via the static functions. //! ``` @@ -21,7 +21,7 @@ //! ``` //! //! More advanced usage will require creating a SHA2 object to hold state between successive calls, -//! for example if input is received in chunks and not all available at the same time: +//! for example, if input is received in chunks and not all available at the same time: //! //! ``` //! use bouncycastle_sha2 as sha2; @@ -40,6 +40,20 @@ //! let output: Vec = sha2.do_final(); //! ``` //! +//! ## Partial byte +//! It is also possible to provide input where the final byte contains fewer than 8 bits of data +//! (a bit-oriented message, FIPS 180-4 s. 5.1). The partial byte is taken as the most significant bits, +//! leading bit first, and the low "unused" bits are ignored. The following hashes 16 bytes plus the +//! 3 message bits `101`: +//! ``` +//! use bouncycastle_core::traits::Hash; +//! use bouncycastle_sha2 as sha2; +//! +//! let data: &[u8] = b"\x00\x01\x02\x03\x04\x05\x06\x07\x08\x09\x0A\x0B\x0C\x0D\x0E\x0F\xA0"; +//! let mut sha2 = sha2::SHA256::new(); +//! sha2.do_update(&data[..16]); +//! let output: Vec = sha2.do_final_partial_bits(data[16], 3).expect("num_partial_bits is in 0..=7"); +//! ``` //! ## HMAC //! See [hmac]. //! @@ -47,36 +61,6 @@ //! //! See [hkdf] //! -//! # Memory Usage -//! -//! No heap memory is used by the algorithms themselves; the `Vec`-returning convenience methods -//! allocate only the output buffer, and the `*_out` variants allocate nothing. -//! -//! | Object | Size (bytes) | -//! |----------------------------------------------------------|--------------| -//! | `SHA224`, `SHA256` | 112 | -//! | `SHA384`, `SHA512` | 208 | -//! | Suspended `SHA224`/`SHA256` state | 108 | -//! | Suspended `SHA384`/`SHA512` state | 204 | -//! -//! The object holds the 8-word chaining value plus one block of buffered input. The compression -//! function additionally uses a 64-word (SHA-256 family, 256 bytes) or 80-word (SHA-512 family, -//! 640 bytes) message schedule on the stack for the duration of a call. -//! -//! # Security Considerations -//! -//! * SHA-224/256/384/512 offer 112/128/192/256 bits of collision resistance respectively. -//! * SHA-2 is a Merkle–Damgård construction and is therefore subject to length-extension: -//! `H(k || m)` is not a secure MAC. Use HMAC ([`crate::hmac`]) for keyed hashing. -//! * SHA-224 and SHA-384 are truncations of SHA-256 and SHA-512 with distinct initial values, and -//! are not vulnerable to length extension in the same direct way, but should still not be used as -//! `H(k || m)` MACs. -//! * The chaining value and input buffer are held in [`bouncycastle_utils::secret::Secret`] and -//! zeroized on drop. Transient copies (working variables and message schedule) in registers/stack -//! locals during compression are not zeroized. -//! * The implementation contains no data-dependent branches or table lookups. -//! * Messages up to 2^64 bytes are supported (FIPS 180-4 permits 2^64 bits for SHA-224/256 and -//! 2^128 bits for SHA-384/512; the SHA-512 family limit here is 2^67 bits). //! //! # Suspending and resuming execution //! @@ -108,6 +92,31 @@ //! sha2_resumed.do_update(msg_part2); //! let h: Vec = sha2_resumed.do_final(); //! ``` +//! +//! # Memory Usage +//! +//! | Object | Size (bytes) | +//! |----------------------------------------------------------|--------------| +//! | `SHA224`, `SHA256` | 112 | +//! | `SHA384`, `SHA512`, `SHA512_224`, `SHA512_256` | 208 | +//! | Suspended `SHA224`/`SHA256` state | 108 | +//! | Suspended `SHA384`/`SHA512`/`SHA512_224`/`SHA512_256` state | 204 | +//! +//! # Security Considerations +//! +//! * SHA-224/256/384/512 offer 112/128/192/256 bits of collision resistance respectively; +//! SHA-512/224 and SHA-512/256 offer 112 and 128 bits (SP 800-107r1, Table 1 (§4.2)). +//! * SHA-2 is a Merkle–Damgård construction and is therefore subject to length-extension: +//! `H(k || m)` is not a secure MAC. Use HMAC (`bouncycastle-hmac`) for keyed hashing. +//! * SHA-224, SHA-384, SHA-512/224 and SHA-512/256 are truncations of SHA-256 or SHA-512 with +//! distinct initial values, and are not vulnerable to length extension in the same direct way, but +//! should still not be used as `H(k || m)` MACs. +//! * The chaining value and input buffer are held in [`bouncycastle_utils::secret::Secret`] and +//! zeroized on drop. Transient copies (working variables and message schedule) in registers/stack +//! locals during compression are not zeroized. +//! * The implementation contains no data-dependent branches or table lookups. +//! * Messages up to 2^64 bytes are supported (FIPS 180-4 permits 2^64 bits for SHA-224/256 and +//! 2^128 bits for SHA-384/512 and SHA-512/t; the SHA-512 family limit here is 2^67 bits). #![forbid(unsafe_code)] #![forbid(missing_docs)] @@ -120,22 +129,29 @@ pub mod hkdf; pub mod hmac; pub use self::sha256::SHA256Internal; +use self::sha256::{SHA224_H0, SHA256_H0}; pub use self::sha512::SHA512Internal; +use self::sha512::{SHA384_H0, SHA512_H0, sha512t_h0}; use bouncycastle_core::traits::{Algorithm, AlgorithmOID, HashAlgParams, SecurityStrength}; /*** Imports needed for docs ***/ #[allow(unused_imports)] use bouncycastle_core::traits::{Hash, KDF, MAC, Suspendable}; +/*** end of doc-only imports ***/ /*** String constants ***/ -/// +/// Algorithm name string for SHA224, as used by the factories and CLI. pub const SHA224_NAME: &str = "SHA224"; -/// +/// Algorithm name string for SHA256, as used by the factories and CLI. pub const SHA256_NAME: &str = "SHA256"; -/// +/// Algorithm name string for SHA384, as used by the factories and CLI. pub const SHA384_NAME: &str = "SHA384"; -/// +/// Algorithm name string for SHA512, as used by the factories and CLI. pub const SHA512_NAME: &str = "SHA512"; +/// Algorithm name string for SHA512/224, as used by the factories and CLI. +pub const SHA512_224_NAME: &str = "SHA512/224"; +/// Algorithm name string for SHA512/256, as used by the factories and CLI. +pub const SHA512_256_NAME: &str = "SHA512/256"; /*** pub types ***/ /// Public type for SHA224. @@ -146,16 +162,47 @@ pub type SHA256 = SHA256Internal; pub type SHA384 = SHA512Internal; /// Public type for SHA512. pub type SHA512 = SHA512Internal; +/// Public type for the SHA-512/t truncating family (FIPS 180-4 s. 5.3.6): SHA-512 with a t-specific initial +/// hash value, truncated to `T` bits. Only the NIST-approved truncations `T = 224` and `T = 256` +/// can be instantiated, enforced by the sealing trait `SHA512InitValue`; see [`SHA512_224`] and [`SHA512_256`]. +pub type SHA512t = SHA512Internal>; +/// Public type for SHA512/224 (FIPS 180-4 s. 6.6). +pub type SHA512_224 = SHA512t<224>; +/// Public type for SHA512/256 (FIPS 180-4 s. 6.7). +pub type SHA512_256 = SHA512t<256>; /*** Param traits ***/ -/// Private trait on purpose so that only the NIST-approved params can be used. -trait SHA2Params: HashAlgParams {} +/// The SHA-256 family (SHA-224, SHA-256) shares one compression function and differs only in the +/// initial hash value and the output truncation, so each member supplies its H(0) here. +/// +/// Crate-private (aka "sealed") on purpose: it cannot be implemented outside this crate, so the +/// only parameter sets that exist are the NIST-approved ones below. +trait SHA256InitValue: HashAlgParams { + /// The initial hash value H(0), FIPS 180-4 s. 5.3.2 / 5.3.3. + const H0: [u32; 8]; +} -/*** SHA224 ***/ -impl HashAlgParams for SHA224 { - const OUTPUT_LEN: usize = 28; - const BLOCK_LEN: usize = 64; +/// The SHA-512 family (SHA-384, SHA-512, SHA-512/t) shares one compression function and differs +/// only in the initial hash value and the output truncation, so each member supplies its H(0) here. +/// +/// Crate-private for the same reason as [`SHA256InitValue`]. +trait SHA512InitValue: HashAlgParams { + /// The initial hash value H(0), FIPS 180-4 s. 5.3.4 / 5.3.5 / 5.3.6. + const H0: [u64; 8]; +} + +/// The public hash types expose the same parameters as their `*Params` marker, so the constants +/// are defined exactly once (on the params struct) and forwarded here. +impl HashAlgParams for SHA256Internal { + const OUTPUT_LEN: usize = PARAMS::OUTPUT_LEN; + const BLOCK_LEN: usize = PARAMS::BLOCK_LEN; } +impl HashAlgParams for SHA512Internal { + const OUTPUT_LEN: usize = PARAMS::OUTPUT_LEN; + const BLOCK_LEN: usize = PARAMS::BLOCK_LEN; +} + +/*** SHA224 ***/ /// The parameters for SHA224. #[derive(Clone)] pub struct SHA224Params; @@ -173,13 +220,12 @@ impl AlgorithmOID for SHA224 { const OID_DER: &'static [u8] = &[0x06, 0x09, 0x60, 0x86, 0x48, 0x01, 0x65, 0x03, 0x04, 0x02, 0x04]; } -impl SHA2Params for SHA224Params {} +impl SHA256InitValue for SHA224Params { + // FIPS 180-4 s. 6.3 exception 1: H(0) as specified in s. 5.3.2. + const H0: [u32; 8] = SHA224_H0; +} /*** SHA256 ***/ -impl HashAlgParams for SHA256 { - const OUTPUT_LEN: usize = 32; - const BLOCK_LEN: usize = 64; -} /// The parameters for SHA256. #[derive(Clone)] pub struct SHA256Params; @@ -197,13 +243,12 @@ impl HashAlgParams for SHA256Params { const OUTPUT_LEN: usize = 32; const BLOCK_LEN: usize = 64; } -impl SHA2Params for SHA256Params {} +impl SHA256InitValue for SHA256Params { + // FIPS 180-4 s. 6.2.1 step 1: H(0) as specified in s. 5.3.3. + const H0: [u32; 8] = SHA256_H0; +} /*** SHA384 ***/ -impl HashAlgParams for SHA384 { - const OUTPUT_LEN: usize = 48; - const BLOCK_LEN: usize = 128; -} /// The parameters for SHA384. #[derive(Clone)] pub struct SHA384Params; @@ -221,16 +266,15 @@ impl HashAlgParams for SHA384Params { const OUTPUT_LEN: usize = 48; const BLOCK_LEN: usize = 128; } -impl SHA2Params for SHA384Params {} +impl SHA512InitValue for SHA384Params { + // FIPS 180-4 s. 6.5 exception 1: H(0) as specified in s. 5.3.4. + const H0: [u64; 8] = SHA384_H0; +} /*** SHA512 ***/ /// The parameters for SHA512. #[derive(Clone)] pub struct SHA512Params; -impl HashAlgParams for SHA512 { - const OUTPUT_LEN: usize = 64; - const BLOCK_LEN: usize = 128; -} impl Algorithm for SHA512Params { const ALG_NAME: &'static str = SHA512_NAME; const MAX_SECURITY_STRENGTH: SecurityStrength = SecurityStrength::_256bit; @@ -245,7 +289,61 @@ impl AlgorithmOID for SHA512 { const OID_DER: &'static [u8] = &[0x06, 0x09, 0x60, 0x86, 0x48, 0x01, 0x65, 0x03, 0x04, 0x02, 0x03]; } -impl SHA2Params for SHA512Params {} +impl SHA512InitValue for SHA512Params { + // FIPS 180-4 s. 6.4.1 step 1: H(0) as specified in s. 5.3.5. + const H0: [u64; 8] = SHA512_H0; +} + +/*** SHA-512/t ***/ +/// The parameters for SHA-512/t (FIPS 180-4 s. 5.3.6), for a truncation of `T` bits. +/// +/// The parameter traits are implemented only for the NIST-approved truncations `T = 224` and +/// `T = 256` ("Other SHA-512/t hash algorithms with different t values may be specified in +/// [SP 800-107] in the future as the need arises"), so any other `T` is a compile-time error. +#[derive(Clone)] +pub struct SHA512tParams; + +/*** SHA512/224 ***/ +impl Algorithm for SHA512tParams<224> { + const ALG_NAME: &'static str = SHA512_224_NAME; + const MAX_SECURITY_STRENGTH: SecurityStrength = SecurityStrength::_112bit; +} +impl HashAlgParams for SHA512tParams<224> { + const OUTPUT_LEN: usize = 28; // FIPS 180-4 s. 6.6 exception 2: truncated to the left-most 224 bits + const BLOCK_LEN: usize = 128; // FIPS 180-4 Figure 1: block size 1024 bits +} +/// Assigned by NIST in the Computer Security Objects Register: id-sha512-224 { hashAlgs 5 } +impl AlgorithmOID for SHA512_224 { + const OID: &'static [u32] = &[2, 16, 840, 1, 101, 3, 4, 2, 5]; + const OID_DER: &'static [u8] = + &[0x06, 0x09, 0x60, 0x86, 0x48, 0x01, 0x65, 0x03, 0x04, 0x02, 0x05]; +} +impl SHA512InitValue for SHA512tParams<224> { + // FIPS 180-4 s. 6.6 exception 1: H(0) as specified in s. 5.3.6.1 (pinned against the words + // listed there by tests/sha512t_h0_tests.rs). + const H0: [u64; 8] = sha512t_h0(224); +} + +/*** SHA512/256 ***/ +impl Algorithm for SHA512tParams<256> { + const ALG_NAME: &'static str = SHA512_256_NAME; + const MAX_SECURITY_STRENGTH: SecurityStrength = SecurityStrength::_128bit; +} +impl HashAlgParams for SHA512tParams<256> { + const OUTPUT_LEN: usize = 32; // FIPS 180-4 s. 6.7 exception 2: truncated to the left-most 256 bits + const BLOCK_LEN: usize = 128; // FIPS 180-4 Figure 1: block size 1024 bits +} +/// Assigned by NIST in the Computer Security Objects Register: id-sha512-256 { hashAlgs 6 } +impl AlgorithmOID for SHA512_256 { + const OID: &'static [u32] = &[2, 16, 840, 1, 101, 3, 4, 2, 6]; + const OID_DER: &'static [u8] = + &[0x06, 0x09, 0x60, 0x86, 0x48, 0x01, 0x65, 0x03, 0x04, 0x02, 0x06]; +} +impl SHA512InitValue for SHA512tParams<256> { + // FIPS 180-4 s. 6.7 exception 1: H(0) as specified in s. 5.3.6.2 (pinned against the words + // listed there by tests/sha512t_h0_tests.rs). + const H0: [u64; 8] = sha512t_h0(256); +} pub use sha256::SUSPENDED_SHA256_STATE_LEN; pub use sha512::SUSPENDED_SHA512_STATE_LEN; diff --git a/crypto/sha2/src/sha256.rs b/crypto/sha2/src/sha256.rs index 34d09775..4ed7d665 100644 --- a/crypto/sha2/src/sha256.rs +++ b/crypto/sha2/src/sha256.rs @@ -1,10 +1,11 @@ -use crate::SHA2Params; +use crate::SHA256InitValue; use bouncycastle_core::errors::{HashError, SuspendableError}; use bouncycastle_core::suspendable_state::{add_lib_ver, check_lib_ver}; use bouncycastle_core::traits::{Algorithm, Hash, SecurityStrength, Suspendable}; use bouncycastle_utils::{min, secret::Secret}; use core::slice; +/// FIPS 180-4 s. 4.2.2: the sixty-four 32-bit constants K0..K63 shared by SHA-224 and SHA-256. const SHA256_K: [u32; 64] = [ 0x428A2F98, 0x71374491, 0xB5C0FBCF, 0xE9B5DBA5, 0x3956C25B, 0x59F111F1, 0x923F82A4, 0xAB1C5ED5, 0xD807AA98, 0x12835B01, 0x243185BE, 0x550C7DC3, 0x72BE5D74, 0x80DEB1FE, 0x9BDC06A7, 0xC19BF174, @@ -16,126 +17,150 @@ const SHA256_K: [u32; 64] = [ 0x748F82EE, 0x78A5636F, 0x84C87814, 0x8CC70208, 0x90BEFFFA, 0xA4506CEB, 0xBEF9A3F7, 0xC67178F2, ]; +/// FIPS 180-4 Table 1 and s. 6.2: SHA-224 and SHA-256 are defined for a message of l bits where +/// 0 <= l < 2^64, so the longest whole-byte message they cover is 2^61 - 1 bytes. +const MAX_MESSAGE_BYTES: u64 = (1 << 61) - 1; + +/// FIPS 180-4 s. 5.3.2: the initial hash value H(0) for SHA-224. +pub(crate) const SHA224_H0: [u32; 8] = [ + 0xC1059ED8, 0x367CD507, 0x3070DD17, 0xF70E5939, 0xFFC00B31, 0x68581511, 0x64F98FA7, 0xBEFA4FA4, +]; + +/// FIPS 180-4 s. 5.3.3: the initial hash value H(0) for SHA-256. +pub(crate) const SHA256_H0: [u32; 8] = [ + 0x6A09E667, 0xBB67AE85, 0x3C6EF372, 0xA54FF53A, 0x510E527F, 0x9B05688C, 0x1F83D9AB, 0x5BE0CD19, +]; + +/// FIPS 180-4 s. 4.1.2 (4.2) Ch(x, y, z) = (x AND y) XOR (NOT x AND z) +/// Mutants note: the two masks are disjoint, so `^` and `|` give identical results here; a +/// surviving `^`/`|` swap in this function is an equivalent mutant, not a missing test. #[inline] -fn ch(x: u32, y: u32, z: u32) -> u32 { +const fn ch(x: u32, y: u32, z: u32) -> u32 { (x & y) ^ (!x & z) } +/// FIPS 180-4 s. 4.1.2 (4.3) Maj(x, y, z) = (x AND y) XOR (x AND z) XOR (y AND z). +/// Written in the equivalent form (x AND y) OR (z AND (x XOR y)), which saves an operation. +/// Mutants note: the two masks are disjoint, so `^` and `|` give identical results here; a +/// surviving `^`/`|` swap in this function is an equivalent mutant, not a missing test. #[inline] -fn maj(x: u32, y: u32, z: u32) -> u32 { +const fn maj(x: u32, y: u32, z: u32) -> u32 { (x & y) | (z & (x ^ y)) } +/// FIPS 180-4 s. 4.1.2 (4.4) Sigma0(x) = ROTR2(x) XOR ROTR13(x) XOR ROTR22(x) #[inline] -fn sum0(x: u32) -> u32 { +const fn sum0(x: u32) -> u32 { x.rotate_right(2) ^ x.rotate_right(13) ^ x.rotate_right(22) } +/// FIPS 180-4 s. 4.1.2 (4.5) Sigma1(x) = ROTR6(x) XOR ROTR11(x) XOR ROTR25(x) #[inline] -fn sum1(x: u32) -> u32 { +const fn sum1(x: u32) -> u32 { x.rotate_right(6) ^ x.rotate_right(11) ^ x.rotate_right(25) } +/// FIPS 180-4 s. 4.1.2 (4.6) sigma0(x) = ROTR7(x) XOR ROTR18(x) XOR SHR3(x) #[inline] -fn theta0(x: u32) -> u32 { +const fn theta0(x: u32) -> u32 { x.rotate_right(7) ^ x.rotate_right(18) ^ (x >> 3) } +/// FIPS 180-4 s. 4.1.2 (4.7) sigma1(x) = ROTR17(x) XOR ROTR19(x) XOR SHR10(x) #[inline] -fn theta1(x: u32) -> u32 { +const fn theta1(x: u32) -> u32 { x.rotate_right(17) ^ x.rotate_right(19) ^ (x >> 10) } +/// FIPS 180-4 s. 6.2.2, one iteration of the outer loop: absorbs a single 512-bit message block +/// into the hash value `s` (H(i-1) in, H(i) out). +/// +/// Written as a `const fn` (hence `while` rather than `for` loops) to match the SHA-512 side, so the +/// two compression functions can be read side by side against s. 6.2.2 and s. 6.4.2. +#[inline] +const fn compress_block(s: &mut [u32; 8], block: &[u8; 64]) { + // FIPS 180-4 s. 6.2.2 step 1: prepare the message schedule {W_t}. + let mut x = [0u32; 64]; + // FIPS 180-4 s. 6.2.2 step 1: W_t = M_t(i) for 0 <= t <= 15 (s. 5.2.1: sixteen big-endian 32-bit words). + let (words, _remainder) = block.as_chunks::<4>(); + let mut i = 0; + while i < 16 { + x[i] = u32::from_be_bytes(words[i]); + i += 1; + } + // FIPS 180-4 s. 6.2.2 step 1: W_t = sigma1(W_t-2) + W_t-7 + sigma0(W_t-15) + W_t-16 for 16 <= t <= 63. + while i < 64 { + x[i] = theta1(x[i - 2]) + .wrapping_add(x[i - 7]) + .wrapping_add(theta0(x[i - 15])) + .wrapping_add(x[i - 16]); + i += 1; + } + + // FIPS 180-4 s. 6.2.2 step 2: initialize the working variables a..h with H(i-1). + let [mut a, mut b, mut c, mut d, mut e, mut f, mut g, mut h] = *s; + + // FIPS 180-4 s. 6.2.2 step 3: for t = 0 to 63, one round. The spec rotates the working variables + // (h = g, g = f, ...); here the rotation is done by renaming the variables passed to the macro + // instead, eight rounds at a time, which is equivalent and avoids the moves. The spec's T1 lands + // in the "$h" position, "$d" becomes d + T1, and T1 + T2 is then computed in place. + macro_rules! sha256_round { + ($a:ident,$b:ident,$c:ident,$d:ident,$e:ident,$f:ident,$g:ident,$h:ident,$t:ident) => { + // FIPS 180-4 s. 6.2.2 step 3: T1 = h + Sigma1(e) + Ch(e, f, g) + K_t + W_t + $h = $h + .wrapping_add(sum1($e)) + .wrapping_add(ch($e, $f, $g)) + .wrapping_add(SHA256_K[$t]) + .wrapping_add(x[$t]); + // FIPS 180-4 s. 6.2.2 step 3: e = d + T1 + $d = $d.wrapping_add($h); + // FIPS 180-4 s. 6.2.2 step 3: a = T1 + T2, where T2 = Sigma0(a) + Maj(a, b, c) + $h = $h.wrapping_add(sum0($a)).wrapping_add(maj($a, $b, $c)); + $t += 1; + }; + } + + let mut t: usize = 0; + while t < 64 { + sha256_round!(a, b, c, d, e, f, g, h, t); + sha256_round!(h, a, b, c, d, e, f, g, t); + sha256_round!(g, h, a, b, c, d, e, f, t); + sha256_round!(f, g, h, a, b, c, d, e, t); + sha256_round!(e, f, g, h, a, b, c, d, t); + sha256_round!(d, e, f, g, h, a, b, c, t); + sha256_round!(c, d, e, f, g, h, a, b, t); + sha256_round!(b, c, d, e, f, g, h, a, t); + } + + // FIPS 180-4 s. 6.2.2 step 4: H_j(i) = (working variable j) + H_j(i-1). + s[0] = s[0].wrapping_add(a); + s[1] = s[1].wrapping_add(b); + s[2] = s[2].wrapping_add(c); + s[3] = s[3].wrapping_add(d); + s[4] = s[4].wrapping_add(e); + s[5] = s[5].wrapping_add(f); + s[6] = s[6].wrapping_add(g); + s[7] = s[7].wrapping_add(h); +} + #[derive(Clone)] -pub(crate) struct Sha256State { +pub(crate) struct Sha256State { _params: core::marker::PhantomData, h: Secret<[u32; 8]>, } -impl Sha256State { +impl Sha256State { pub(crate) fn new() -> Self { let mut h = Secret::<[u32; 8]>::new(); - match PARAMS::OUTPUT_LEN * 8 { - 224 => { - h.copy_from_slice(&[ - 0xC1059ED8, 0x367CD507, 0x3070DD17, 0xF70E5939, 0xFFC00B31, 0x68581511, - 0x64F98FA7, 0xBEFA4FA4, - ]); - Self { _params: core::marker::PhantomData, h } - } - 256 => { - h.copy_from_slice(&[ - 0x6A09E667, 0xBB67AE85, 0x3C6EF372, 0xA54FF53A, 0x510E527F, 0x9B05688C, - 0x1F83D9AB, 0x5BE0CD19, - ]); - Self { _params: std::marker::PhantomData, h } - } - _ => panic!("Invalid SHA-2 bit size: {}", PARAMS::OUTPUT_LEN), - } + // FIPS 180-4 s. 6.2.1 step 1: set the initial hash value H(0) (s. 5.3.3, or s. 5.3.2 for SHA-224). + h.copy_from_slice(&PARAMS::H0); + Self { _params: core::marker::PhantomData, h } } fn compress(&mut self, blocks: &[[u8; 64]]) { - let mut x = [0u32; 64]; - - // infallible; just unwrapping the [u32; 8] and re-casting to itself. - let s = &mut *self.h; - let &mut [mut a, mut b, mut c, mut d, mut e, mut f, mut g, mut h] = s; - + // FIPS 180-4 s. 6.2.2: each message block M(1), ..., M(N) is processed in order. for block in blocks { - let (chunks, _remainder) = block.as_chunks::<4>(); - for (i, w) in x[..16].iter_mut().zip(chunks) { - *i = u32::from_be_bytes(*w); - } - - for i in 16..64 { - x[i] = theta1(x[i - 2]) - .wrapping_add(x[i - 7]) - .wrapping_add(theta0(x[i - 15])) - .wrapping_add(x[i - 16]); - } - - macro_rules! sha256_round { - ($a:ident,$b:ident,$c:ident,$d:ident,$e:ident,$f:ident,$g:ident,$h:ident,$t:ident,$K:ident,$x:ident) => { - $h = $h - .wrapping_add(sum1($e)) - .wrapping_add(ch($e, $f, $g)) - .wrapping_add($K[$t]) - .wrapping_add($x[$t]); - $d = $d.wrapping_add($h); - $h = $h.wrapping_add(sum0($a)).wrapping_add(maj($a, $b, $c)); - $t += 1; - }; - } - - let mut t: usize = 0; - for _ in 0..8 { - sha256_round!(a, b, c, d, e, f, g, h, t, SHA256_K, x); - sha256_round!(h, a, b, c, d, e, f, g, t, SHA256_K, x); - sha256_round!(g, h, a, b, c, d, e, f, t, SHA256_K, x); - sha256_round!(f, g, h, a, b, c, d, e, t, SHA256_K, x); - sha256_round!(e, f, g, h, a, b, c, d, t, SHA256_K, x); - sha256_round!(d, e, f, g, h, a, b, c, t, SHA256_K, x); - sha256_round!(c, d, e, f, g, h, a, b, t, SHA256_K, x); - sha256_round!(b, c, d, e, f, g, h, a, t, SHA256_K, x); - } - - a = a.wrapping_add(s[0]); - b = b.wrapping_add(s[1]); - c = c.wrapping_add(s[2]); - d = d.wrapping_add(s[3]); - e = e.wrapping_add(s[4]); - f = f.wrapping_add(s[5]); - g = g.wrapping_add(s[6]); - h = h.wrapping_add(s[7]); - - s[0] = a; - s[1] = b; - s[2] = c; - s[3] = d; - s[4] = e; - s[5] = f; - s[6] = g; - s[7] = h; + compress_block(&mut self.h, block); } } } @@ -144,17 +169,15 @@ impl Sha256State { /// This uses a private bound so that you cannot instantiate it directly and have to use the /// provided and NIST-approved parameters. #[derive(Clone)] -pub struct SHA256Internal { +pub struct SHA256Internal { _params: core::marker::PhantomData, state: Sha256State, byte_count: u64, x_buf: Secret<[u8; 64]>, x_buf_off: usize, - // TODO: Investigate whether maximum message size (according to FIPS 180-4) should be added - // (2^64 for SHA256 and 2^128 for SHA512) } -impl SHA256Internal { +impl SHA256Internal { /// Creates a new SHA256 instance, ready for use. pub fn new() -> Self { Self { @@ -167,18 +190,86 @@ impl SHA256Internal { } } -impl Default for SHA256Internal { +impl SHA256Internal { + /// Pads and compresses the final block(s) as per FIPS 180-4 s. 5.1.1, then writes the digest. + /// + /// The `num_partial_bits` (0..=7, validated by the caller) trailing message bits are the most + /// significant bits of `partial_byte`, leading bit first: the ASN.1 BIT STRING order of + /// X.690 s. 8.6.2.1, which is also how FIPS 180-4 s. 3.1 numbers the bits of a message byte. So + /// they are used in place, the low `8 - num_partial_bits` bits are ignored, and the mandatory + /// "1" padding bit follows the message bits immediately in the same byte. + /// + /// Returns the number of bytes written (`min(output.len(), OUTPUT_LEN)`); a shorter output buffer + /// truncates the digest, a longer one is zero-filled past the digest. + fn do_final_internal( + mut self, + partial_byte: u8, + num_partial_bits: usize, + output: &mut [u8], + ) -> usize { + debug_assert!(num_partial_bits <= 7); + output.fill(0); + + let n = *min(&output.len(), &PARAMS::OUTPUT_LEN); + + // FIPS 180-4 s. 5.1.1: append the bit "1" to the end of the message. The message bits are the + // top num_partial_bits bits of partial_byte, so the final message byte is [those bits] [1] [0...]; + // with no partial bits this is the familiar 0x80. The mask is built in u16 so that the 8-bit + // shift for num_partial_bits == 0 cannot overflow (0xFF00 >> 0 truncates to 0x00). + let mask = (0xFF00u16 >> num_partial_bits) as u8; + // Mutants note: the masked message bits and the padding bit occupy disjoint bit positions, so + // `|` and `^` give identical results here; a surviving `|`/`^` swap is an equivalent mutant. + let pad_byte = (partial_byte & mask) | (0x80u8 >> num_partial_bits); + + self.x_buf[self.x_buf_off] = pad_byte; + self.x_buf_off += 1; + + // FIPS 180-4 s. 5.1.1: if fewer than 64 bits remain for l, the k zero bits run into a second block. + if self.x_buf_off > 56 { + self.x_buf[self.x_buf_off..].fill(0x00); + self.state.compress(slice::from_ref(&self.x_buf)); + self.x_buf_off = 0; + } + + // FIPS 180-4 s. 5.1.1: k zero bits so that l + 1 + k = 448 mod 512, then the 64-bit big-endian + // message length l in bits. + self.x_buf[self.x_buf_off..56].fill(0x00); + // byte_count is a byte counter, so l = (byte_count << 3) | num_partial_bits (the low three bits + // of byte_count << 3 are zero). + // Mutants note: the low three bits of byte_count << 3 are zero, so `|` and `^` give identical + // results here; a surviving `|`/`^` swap is an equivalent mutant. + let bit_len: u64 = (self.byte_count << 3) | (num_partial_bits as u64); + self.x_buf[56..64].copy_from_slice(&bit_len.to_be_bytes()); + self.state.compress(slice::from_ref(&self.x_buf)); + + // FIPS 180-4 s. 6.2.2: the digest is H_0(N) || ... || H_7(N) (big-endian words), truncated to the + // left-most OUTPUT_LEN bytes (s. 6.3 exception 2 for SHA-224), and further to the caller's + // buffer if that is shorter. + let h = &self.state.h; + for i in 0..(n / 4) { + output[i * 4..i * 4 + 4].copy_from_slice(&h[i].to_be_bytes()); + } + if !n.is_multiple_of(4) { + output[((n / 4) * 4)..((n / 4) * 4) + (n % 4)] + .copy_from_slice(&h[n / 4].to_be_bytes()[0..(n % 4)]); + } + + n + } +} + +impl Default for SHA256Internal { fn default() -> Self { Self::new() } } -impl Algorithm for SHA256Internal { +impl Algorithm for SHA256Internal { const ALG_NAME: &'static str = PARAMS::ALG_NAME; const MAX_SECURITY_STRENGTH: SecurityStrength = PARAMS::MAX_SECURITY_STRENGTH; } -impl Hash for SHA256Internal { +impl Hash for SHA256Internal { /// As per FIPS 180-4 Figure 1 fn block_bitlen(&self) -> usize { 512 @@ -204,8 +295,13 @@ impl Hash for SHA256Internal { fn do_update(&mut self, block: &[u8]) { let len = block.len(); - // TODO: Check there is enough space left in 'byte_count' to allow this operation, - // TODO: although overflowing a u64 is unlikely to happen in practice, and rust will throw an error anyway. + // FIPS 180-4 s. 5.1.1: do_final_internal encodes l in a 64-bit field as `byte_count << 3`, + // and a left shift discards rather than panics, so past MAX_MESSAGE_BYTES the digest would + // silently be that of a message 2^64 bits shorter. do_update returns (), hence debug-only. + debug_assert!( + self.byte_count.checked_add(len as u64).is_some_and(|total| total <= MAX_MESSAGE_BYTES), + "message exceeds the FIPS 180-4 limit of {MAX_MESSAGE_BYTES} bytes for SHA-224/SHA-256" + ); self.byte_count += len as u64; let available = 64 - self.x_buf_off; @@ -225,6 +321,7 @@ impl Hash for SHA256Internal { self.state.compress(slice::from_ref(&self.x_buf)); } + // FIPS 180-4 s. 5.2.1: the message is parsed into 512-bit blocks; a partial trailing block waits in x_buf. let (chunks, remainder) = block.as_chunks::<64>(); self.state.compress(chunks); @@ -240,63 +337,35 @@ impl Hash for SHA256Internal { output } - fn do_final_out(mut self, output: &mut [u8]) -> usize { - output.fill(0); - - let n = *min(&output.len(), &PARAMS::OUTPUT_LEN); - - let bit_len: u64 = self.byte_count << 3; - - self.x_buf[self.x_buf_off] = 0x80; - self.x_buf_off += 1; - - if self.x_buf_off > 56 { - self.x_buf[self.x_buf_off..].fill(0x00); - self.state.compress(slice::from_ref(&self.x_buf)); - self.x_buf_off = 0; - } - - self.x_buf[self.x_buf_off..56].fill(0x00); - self.x_buf[56..64].copy_from_slice(&bit_len.to_be_bytes()); - self.state.compress(slice::from_ref(&self.x_buf)); - - let h = &self.state.h; - - // let n = output.len(); - for i in 0..(n / 4) { - output[i * 4..i * 4 + 4].copy_from_slice(&h[i].to_be_bytes()); - } - if !n.is_multiple_of(4) { - output[((n / 4) * 4)..((n / 4) * 4) + (n % 4)] - .copy_from_slice(&h[n / 4].to_be_bytes()[0..(n % 4)]); - } - - n + fn do_final_out(self, output: &mut [u8]) -> usize { + // A whole-byte message is the zero-partial-bits case of the general padding. + self.do_final_internal(0, 0, output) } - /// TODO: This is defined in FIPS 180-4 s. 5.1.2 - /// TODO: - /// TODO: It can be implemented if required - #[allow(unused)] fn do_final_partial_bits( self, partial_byte: u8, num_partial_bits: usize, ) -> Result, HashError> { - unimplemented!() + let mut output = vec![0u8; PARAMS::OUTPUT_LEN]; + self.do_final_partial_bits_out(partial_byte, num_partial_bits, &mut output)?; + Ok(output) } - /// TODO: This is defined in FIPS 180-4 s. 5.1.2 - /// TODO: - /// TODO: It can be implemented if required - #[allow(unused)] + /// FIPS 180-4 s. 5.1: bit-oriented messages. The `num_partial_bits` most significant bits of + /// `partial_byte` (ASN.1 BIT STRING order, leading bit first) are appended to the message before + /// padding; the low bits are ignored. `num_partial_bits == 0` behaves exactly like + /// [`Hash::do_final_out`]. fn do_final_partial_bits_out( self, partial_byte: u8, num_partial_bits: usize, output: &mut [u8], ) -> Result { - unimplemented!() + if num_partial_bits > 7 { + return Err(HashError::InvalidLength("num_partial_bits must be in the range [0,7]")); + } + Ok(self.do_final_internal(partial_byte, num_partial_bits, output)) } fn max_security_strength(&self) -> SecurityStrength { @@ -307,7 +376,7 @@ impl Hash for SHA256Internal { /// Length in bytes of the serialized state of SHA224 and SHA256. pub const SUSPENDED_SHA256_STATE_LEN: usize = 108; -impl Suspendable for SHA256Internal { +impl Suspendable for SHA256Internal { fn suspend(self) -> [u8; SUSPENDED_SHA256_STATE_LEN] { debug_assert_eq!(SUSPENDED_SHA256_STATE_LEN, 108); diff --git a/crypto/sha2/src/sha512.rs b/crypto/sha2/src/sha512.rs index c31e3065..8ca2cf8a 100644 --- a/crypto/sha2/src/sha512.rs +++ b/crypto/sha2/src/sha512.rs @@ -1,10 +1,12 @@ -use crate::SHA2Params; +use crate::SHA512InitValue; use bouncycastle_core::errors::{HashError, SuspendableError}; use bouncycastle_core::suspendable_state::{add_lib_ver, check_lib_ver}; use bouncycastle_core::traits::{Algorithm, Hash, SecurityStrength, Suspendable}; use bouncycastle_utils::{min, secret::Secret}; use core::slice; +/// FIPS 180-4 s. 4.2.3: the eighty 64-bit constants K0..K79 shared by SHA-384, SHA-512, +/// SHA-512/224 and SHA-512/256. const SHA512_K: [u64; 80] = [ 0x428A2F98D728AE22, 0x7137449123EF65CD, 0xB5C0FBCFEC4D3B2F, 0xE9B5DBA58189DBBC, 0x3956C25BF348B538, 0x59F111F1B605D019, 0x923F82A4AF194F9B, 0xAB1C5ED5DA6D8118, @@ -28,127 +30,223 @@ const SHA512_K: [u64; 80] = [ 0x4CC5D4BECB3E42B6, 0x597F299CFC657E2A, 0x5FCB6FAB3AD6FAEC, 0x6C44198C4A475817, ]; +/// FIPS 180-4 s. 5.3.4: the initial hash value H(0) for SHA-384. +pub(crate) const SHA384_H0: [u64; 8] = [ + 0xCBBB9D5DC1059ED8, 0x629A292A367CD507, 0x9159015A3070DD17, 0x152FECD8F70E5939, + 0x67332667FFC00B31, 0x8EB44A8768581511, 0xDB0C2E0D64F98FA7, 0x47B5481DBEFA4FA4, +]; + +/// FIPS 180-4 s. 5.3.5: the initial hash value H(0) for SHA-512. +pub(crate) const SHA512_H0: [u64; 8] = [ + 0x6A09E667F3BCC908, 0xBB67AE8584CAA73B, 0x3C6EF372FE94F82B, 0xA54FF53A5F1D36F1, + 0x510E527FADE682D1, 0x9B05688C2B3E6C1F, 0x1F83D9ABFB41BD6B, 0x5BE0CD19137E2179, +]; + +/// FIPS 180-4 s. 5.3.6 "SHA-512/t IV Generation Function": computes the initial hash value H(0) +/// for SHA-512/t. +/// +/// Quoting the procedure: +/// +/// > Denote H(0)' to be the initial hash value of SHA-512 as specified in Section 5.3.5 above. +/// > +/// > Denote H(0)'' to be the initial hash value computed below. +/// > +/// > H(0) is the IV for SHA-512/t. +/// > +/// > For i = 0 to 7 { Hi(0)'' = Hi(0)' xor a5a5a5a5a5a5a5a5(in hex). } +/// > +/// > H(0) = SHA-512 ("SHA-512/t") using H(0)'' as the IV, where t is the specific truncation value. +/// +/// where, per the same section, "t is any positive integer without a leading zero such that t < 512, +/// and t is not 384", and "SHA-512/t" is the ASCII string with t written in decimal (so for t = 256 +/// the message is the 11 bytes `53 48 41 2D 35 31 32 2F 32 35 36`). +/// +/// Deliberate deviation from s. 5.3.6: only a three-digit t is accepted. The crate instantiates +/// only the two truncations FIPS 180-4 approves, t = 224 (s. 5.3.6.1) and t = 256 (s. 5.3.6.2), +/// and both are three digits, so the one- and two-digit cases of the decimal formatting would be +/// branches no caller and no test can reach. +/// +/// This is a `const fn` so that the IV is computed at compile time. +pub(crate) const fn sha512t_h0(t: usize) -> [u64; 8] { + // FIPS 180-4 s. 5.3.6 asks only for "any positive integer without a leading zero such that + // t < 512, and t is not 384"; the t >= 100 is ours, from the three-digit formatting below, so a + // new t under 100 fails the build rather than being written with a leading zero s. 5.3.6 forbids. + assert!( + t >= 100 && t < 512 && t != 384, + "sha512t_h0 formats t as three digits: need 100 <= t < 512 and t != 384" + ); + + // FIPS 180-4 s. 5.3.6: H(0)'' = H(0)', the SHA-512 initial hash value (s. 5.3.5), with each word XOR a5a5a5a5a5a5a5a5. + let mut h = SHA512_H0; + let mut i = 0; + while i < 8 { + h[i] ^= 0xA5A5A5A5A5A5A5A5; + i += 1; + } + + // FIPS 180-4 s. 5.3.6: the message is the ASCII string "SHA-512/t" (11 bytes, so one block). + // It is built directly in its padded form (s. 5.1.2) inside a single 1024-bit block (s. 5.2.2). + let mut block = [0u8; 128]; + let prefix = b"SHA-512/"; + let mut len = 0; + while len < prefix.len() { + block[len] = prefix[len]; + len += 1; + } + // FIPS 180-4 s. 5.3.6: t written in decimal "without a leading zero"; three digits, since + // 100 <= t < 512 (the assertion above), so "SHA-512/t" is the 11 characters of the s. 5.3.6 + // example for t = 256. + block[len] = b'0' + (t / 100) as u8; + block[len + 1] = b'0' + ((t / 10) % 10) as u8; + block[len + 2] = b'0' + (t % 10) as u8; + len += 3; + + // FIPS 180-4 s. 5.1.2: append the bit "1", then k zero bits (the rest of the block is already zero). + block[len] = 0x80; + // FIPS 180-4 s. 5.1.2: the final 128 bits are the message length l in bits; l < 2^64 so bytes 112..120 stay 0. + let bit_len = (len as u64) * 8; + let bit_len_bytes = bit_len.to_be_bytes(); + let mut i = 0; + while i < 8 { + block[120 + i] = bit_len_bytes[i]; + i += 1; + } + + // FIPS 180-4 s. 5.3.6: H(0) = SHA-512("SHA-512/t") using H(0)'' as the IV, i.e. one pass of s. 6.4.2. + compress_block(&mut h, &block); + h +} + +/// FIPS 180-4 s. 4.1.3 (4.8) Ch(x, y, z) = (x AND y) XOR (NOT x AND z) +/// Mutants note: the two masks are disjoint, so `^` and `|` give identical results here; a +/// surviving `^`/`|` swap in this function is an equivalent mutant, not a missing test. #[inline] -fn ch(x: u64, y: u64, z: u64) -> u64 { +const fn ch(x: u64, y: u64, z: u64) -> u64 { (x & y) ^ (!x & z) } +/// FIPS 180-4 s. 4.1.3 (4.9) Maj(x, y, z) = (x AND y) XOR (x AND z) XOR (y AND z). +/// Written in the equivalent form (x AND y) OR (z AND (x XOR y)), which saves an operation. +/// Mutants note: the two masks are disjoint, so `^` and `|` give identical results here; a +/// surviving `^`/`|` swap in this function is an equivalent mutant, not a missing test. #[inline] -fn maj(x: u64, y: u64, z: u64) -> u64 { +const fn maj(x: u64, y: u64, z: u64) -> u64 { (x & y) | (z & (x ^ y)) } +/// FIPS 180-4 s. 4.1.3 (4.10) Sigma0(x) = ROTR28(x) XOR ROTR34(x) XOR ROTR39(x) #[inline] -fn sum0(x: u64) -> u64 { +const fn sum0(x: u64) -> u64 { x.rotate_right(28) ^ x.rotate_right(34) ^ x.rotate_right(39) } +/// FIPS 180-4 s. 4.1.3 (4.11) Sigma1(x) = ROTR14(x) XOR ROTR18(x) XOR ROTR41(x) #[inline] -fn sum1(x: u64) -> u64 { +const fn sum1(x: u64) -> u64 { x.rotate_right(14) ^ x.rotate_right(18) ^ x.rotate_right(41) } +/// FIPS 180-4 s. 4.1.3 (4.12) sigma0(x) = ROTR1(x) XOR ROTR8(x) XOR SHR7(x) #[inline] -fn theta0(x: u64) -> u64 { +const fn theta0(x: u64) -> u64 { x.rotate_right(1) ^ x.rotate_right(8) ^ (x >> 7) } +/// FIPS 180-4 s. 4.1.3 (4.13) sigma1(x) = ROTR19(x) XOR ROTR61(x) XOR SHR6(x) #[inline] -fn theta1(x: u64) -> u64 { +const fn theta1(x: u64) -> u64 { x.rotate_right(19) ^ x.rotate_right(61) ^ (x >> 6) } -// todo -- cleanup -// #[derive(Clone, Copy)] +/// FIPS 180-4 s. 6.4.2, one iteration of the outer loop: absorbs a single 1024-bit message block +/// into the hash value `s` (H(i-1) in, H(i) out). +/// +/// This is a `const fn` (hence `while` rather than `for` loops) so that [`sha512t_h0`] can run it +/// at compile time. At runtime it is ordinary code, and is the hot path of every SHA-512 variant. +#[inline] +const fn compress_block(s: &mut [u64; 8], block: &[u8; 128]) { + // FIPS 180-4 s. 6.4.2 step 1: prepare the message schedule {W_t}. + let mut x = [0u64; 80]; + // FIPS 180-4 s. 6.4.2 step 1: W_t = M_t(i) for 0 <= t <= 15 (s. 5.2.2: sixteen big-endian 64-bit words). + let (words, _remainder) = block.as_chunks::<8>(); + let mut i = 0; + while i < 16 { + x[i] = u64::from_be_bytes(words[i]); + i += 1; + } + // FIPS 180-4 s. 6.4.2 step 1: W_t = sigma1(W_t-2) + W_t-7 + sigma0(W_t-15) + W_t-16 for 16 <= t <= 79. + while i < 80 { + x[i] = theta1(x[i - 2]) + .wrapping_add(x[i - 7]) + .wrapping_add(theta0(x[i - 15])) + .wrapping_add(x[i - 16]); + i += 1; + } + + // FIPS 180-4 s. 6.4.2 step 2: initialize the working variables a..h with H(i-1). + let [mut a, mut b, mut c, mut d, mut e, mut f, mut g, mut h] = *s; + + // FIPS 180-4 s. 6.4.2 step 3: for t = 0 to 79, one round. The spec rotates the working variables + // (h = g, g = f, ...); here the rotation is done by renaming the variables passed to the macro + // instead, eight rounds at a time, which is equivalent and avoids the moves. The spec's T1 lands + // in the "$h" position, "$d" becomes d + T1, and T1 + T2 is then computed in place. + macro_rules! sha512_round { + ($a:ident,$b:ident,$c:ident,$d:ident,$e:ident,$f:ident,$g:ident,$h:ident,$t:ident) => { + // FIPS 180-4 s. 6.4.2 step 3: T1 = h + Sigma1(e) + Ch(e, f, g) + K_t + W_t + $h = $h + .wrapping_add(sum1($e)) + .wrapping_add(ch($e, $f, $g)) + .wrapping_add(SHA512_K[$t]) + .wrapping_add(x[$t]); + // FIPS 180-4 s. 6.4.2 step 3: e = d + T1 + $d = $d.wrapping_add($h); + // FIPS 180-4 s. 6.4.2 step 3: a = T1 + T2, where T2 = Sigma0(a) + Maj(a, b, c) + $h = $h.wrapping_add(sum0($a)).wrapping_add(maj($a, $b, $c)); + $t += 1; + }; + } + + let mut t: usize = 0; + while t < 80 { + sha512_round!(a, b, c, d, e, f, g, h, t); + sha512_round!(h, a, b, c, d, e, f, g, t); + sha512_round!(g, h, a, b, c, d, e, f, t); + sha512_round!(f, g, h, a, b, c, d, e, t); + sha512_round!(e, f, g, h, a, b, c, d, t); + sha512_round!(d, e, f, g, h, a, b, c, t); + sha512_round!(c, d, e, f, g, h, a, b, t); + sha512_round!(b, c, d, e, f, g, h, a, t); + } + + // FIPS 180-4 s. 6.4.2 step 4: H_j(i) = (working variable j) + H_j(i-1). + s[0] = s[0].wrapping_add(a); + s[1] = s[1].wrapping_add(b); + s[2] = s[2].wrapping_add(c); + s[3] = s[3].wrapping_add(d); + s[4] = s[4].wrapping_add(e); + s[5] = s[5].wrapping_add(f); + s[6] = s[6].wrapping_add(g); + s[7] = s[7].wrapping_add(h); +} + #[derive(Clone)] -pub(crate) struct Sha512State { - _params: std::marker::PhantomData, +pub(crate) struct Sha512State { + _params: core::marker::PhantomData, h: Secret<[u64; 8]>, } -impl Sha512State { +impl Sha512State { pub(crate) fn new() -> Self { let mut h = Secret::<[u64; 8]>::new(); - match PARAMS::OUTPUT_LEN * 8 { - 384 => { - h.copy_from_slice(&[ - 0xCBBB9D5DC1059ED8, 0x629A292A367CD507, 0x9159015A3070DD17, 0x152FECD8F70E5939, - 0x67332667FFC00B31, 0x8EB44A8768581511, 0xDB0C2E0D64F98FA7, 0x47B5481DBEFA4FA4, - ]); - Self { _params: std::marker::PhantomData, h } - } - 512 => { - h.copy_from_slice(&[ - 0x6A09E667F3BCC908, 0xBB67AE8584CAA73B, 0x3C6EF372FE94F82B, 0xA54FF53A5F1D36F1, - 0x510E527FADE682D1, 0x9B05688C2B3E6C1F, 0x1F83D9ABFB41BD6B, 0x5BE0CD19137E2179, - ]); - Self { _params: std::marker::PhantomData, h } - } - _ => panic!("Invalid SHA-2 bit size"), - } + // FIPS 180-4 s. 6.4.1 step 1: set the initial hash value H(0) (s. 5.3.4 / 5.3.5 / 5.3.6 per variant). + h.copy_from_slice(&PARAMS::H0); + Self { _params: core::marker::PhantomData, h } } fn compress(&mut self, blocks: &[[u8; 128]]) { - let mut x = [0u64; 80]; - - let s = &mut *self.h; - let &mut [mut a, mut b, mut c, mut d, mut e, mut f, mut g, mut h] = s; - + // FIPS 180-4 s. 6.4.2: each message block M(1), ..., M(N) is processed in order. for block in blocks { - let (chunks, _remainder) = block.as_chunks::<8>(); - for (i, w) in x[..16].iter_mut().zip(chunks) { - *i = u64::from_be_bytes(*w); - } - - for i in 16..80 { - x[i] = theta1(x[i - 2]) - .wrapping_add(x[i - 7]) - .wrapping_add(theta0(x[i - 15])) - .wrapping_add(x[i - 16]); - } - - macro_rules! sha512_round { - ($a:ident,$b:ident,$c:ident,$d:ident,$e:ident,$f:ident,$g:ident,$h:ident,$t:ident,$K:ident,$x:ident) => { - $h = $h - .wrapping_add(sum1($e)) - .wrapping_add(ch($e, $f, $g)) - .wrapping_add($K[$t]) - .wrapping_add($x[$t]); - $d = $d.wrapping_add($h); - $h = $h.wrapping_add(sum0($a)).wrapping_add(maj($a, $b, $c)); - $t += 1; - }; - } - - let mut t: usize = 0; - for _ in 0..10 { - sha512_round!(a, b, c, d, e, f, g, h, t, SHA512_K, x); - sha512_round!(h, a, b, c, d, e, f, g, t, SHA512_K, x); - sha512_round!(g, h, a, b, c, d, e, f, t, SHA512_K, x); - sha512_round!(f, g, h, a, b, c, d, e, t, SHA512_K, x); - sha512_round!(e, f, g, h, a, b, c, d, t, SHA512_K, x); - sha512_round!(d, e, f, g, h, a, b, c, t, SHA512_K, x); - sha512_round!(c, d, e, f, g, h, a, b, t, SHA512_K, x); - sha512_round!(b, c, d, e, f, g, h, a, t, SHA512_K, x); - } - - a = a.wrapping_add(s[0]); - b = b.wrapping_add(s[1]); - c = c.wrapping_add(s[2]); - d = d.wrapping_add(s[3]); - e = e.wrapping_add(s[4]); - f = f.wrapping_add(s[5]); - g = g.wrapping_add(s[6]); - h = h.wrapping_add(s[7]); - - s[0] = a; - s[1] = b; - s[2] = c; - s[3] = d; - s[4] = e; - s[5] = f; - s[6] = g; - s[7] = h; + compress_block(&mut self.h, block); } } } @@ -157,20 +255,20 @@ impl Sha512State { /// This uses a private bound so that you cannot instantiate it directly and have to use the /// provided and NIST-approved parameters. #[derive(Clone)] -pub struct SHA512Internal { - _params: std::marker::PhantomData, +pub struct SHA512Internal { + _params: core::marker::PhantomData, state: Sha512State, - // NOTE The code currently only supports 2^67 bits, not the full 2^128 + // NOTE: FIPS 180-4 allows messages up to 2^128 bits; this counter supports 2^67 bits (2^64 bytes). byte_count: u64, x_buf: Secret<[u8; 128]>, x_buf_off: usize, } -impl SHA512Internal { +impl SHA512Internal { /// Creates a new SHA512 instance, ready for use. pub fn new() -> Self { Self { - _params: std::marker::PhantomData, + _params: core::marker::PhantomData, state: Sha512State::::new(), byte_count: 0, x_buf: Secret::new(), @@ -179,18 +277,88 @@ impl SHA512Internal { } } -impl Default for SHA512Internal { +impl SHA512Internal { + /// Pads and compresses the final block(s) as per FIPS 180-4 s. 5.1.2, then writes the digest. + /// + /// The `num_partial_bits` (0..=7, validated by the caller) trailing message bits are the most + /// significant bits of `partial_byte`, leading bit first: the ASN.1 BIT STRING order of + /// X.690 s. 8.6.2.1, which is also how FIPS 180-4 s. 3.1 numbers the bits of a message byte. So + /// they are used in place, the low `8 - num_partial_bits` bits are ignored, and the mandatory + /// "1" padding bit follows the message bits immediately in the same byte. + /// + /// Returns the number of bytes written (`min(output.len(), OUTPUT_LEN)`); a shorter output buffer + /// truncates the digest, a longer one is zero-filled past the digest. + fn do_final_internal( + mut self, + partial_byte: u8, + num_partial_bits: usize, + output: &mut [u8], + ) -> usize { + debug_assert!(num_partial_bits <= 7); + output.fill(0); + + let n = *min(&output.len(), &PARAMS::OUTPUT_LEN); + + // FIPS 180-4 s. 5.1.2: append the bit "1" to the end of the message. The message bits are the + // top num_partial_bits bits of partial_byte, so the final message byte is [those bits] [1] [0...]; + // with no partial bits this is the familiar 0x80. The mask is built in u16 so that the 8-bit + // shift for num_partial_bits == 0 cannot overflow (0xFF00 >> 0 truncates to 0x00). + let mask = (0xFF00u16 >> num_partial_bits) as u8; + // Mutants note: the masked message bits and the padding bit occupy disjoint bit positions, so + // `|` and `^` give identical results here; a surviving `|`/`^` swap is an equivalent mutant. + let pad_byte = (partial_byte & mask) | (0x80u8 >> num_partial_bits); + + self.x_buf[self.x_buf_off] = pad_byte; + self.x_buf_off += 1; + + // FIPS 180-4 s. 5.1.2: if fewer than 128 bits remain for l, the k zero bits run into a second block. + if self.x_buf_off > 112 { + self.x_buf[self.x_buf_off..].fill(0x00); + self.state.compress(slice::from_ref(&self.x_buf)); + self.x_buf_off = 0; + } + + // FIPS 180-4 s. 5.1.2: k zero bits so that l + 1 + k = 896 mod 1024, then the 128-bit big-endian + // message length l in bits. + self.x_buf[self.x_buf_off..112].fill(0x00); + // byte_count is a byte counter, so the high 64 bits of l are byte_count >> 61 and the low 64 + // bits are (byte_count << 3) | num_partial_bits (the low three bits of byte_count << 3 are zero). + let bit_len_hi: u64 = self.byte_count >> 61; + // Mutants note: the low three bits of byte_count << 3 are zero, so `|` and `^` give identical + // results here; a surviving `|`/`^` swap is an equivalent mutant. + let bit_len_lo: u64 = (self.byte_count << 3) | (num_partial_bits as u64); + self.x_buf[112..120].copy_from_slice(&bit_len_hi.to_be_bytes()); + self.x_buf[120..128].copy_from_slice(&bit_len_lo.to_be_bytes()); + self.state.compress(slice::from_ref(&self.x_buf)); + + // FIPS 180-4 s. 6.4.2: the digest is H_0(N) || ... || H_7(N) (big-endian words), truncated to the + // left-most OUTPUT_LEN bytes (s. 6.5 / 6.6 / 6.7 exception 2 for SHA-384, SHA-512/224 and SHA-512/256), and further to the caller's + // buffer if that is shorter. + let h = &self.state.h; + for i in 0..(n / 8) { + output[i * 8..i * 8 + 8].copy_from_slice(&h[i].to_be_bytes()); + } + if !n.is_multiple_of(8) { + output[((n / 8) * 8)..((n / 8) * 8) + (n % 8)] + .copy_from_slice(&h[n / 8].to_be_bytes()[0..(n % 8)]); + } + + n + } +} + +impl Default for SHA512Internal { fn default() -> Self { Self::new() } } -impl Algorithm for SHA512Internal { +impl Algorithm for SHA512Internal { const ALG_NAME: &'static str = PARAMS::ALG_NAME; const MAX_SECURITY_STRENGTH: SecurityStrength = PARAMS::MAX_SECURITY_STRENGTH; } -impl Hash for SHA512Internal { +impl Hash for SHA512Internal { /// As per FIPS 180-4 Figure 1 fn block_bitlen(&self) -> usize { 1024 @@ -216,8 +384,9 @@ impl Hash for SHA512Internal { fn do_update(&mut self, block: &[u8]) { let len = block.len(); - // TODO: Check there is enough space left in 'byte_count' to allow this operation, - // TODO: although overflowing a u64 is unlikely to happen in practice, and rust will throw an error anyway. + // FIPS 180-4 s. 5.1.2: do_final_internal writes the whole 128-bit field, carrying the top + // three bits of byte_count in bit_len_hi, so unlike SHA-256 nothing is lost to the shift. + // The limit is byte_count itself at 2^64 bytes, far inside the l < 2^128 bits of Table 1. self.byte_count += len as u64; let available = 128 - self.x_buf_off; @@ -236,6 +405,7 @@ impl Hash for SHA512Internal { //self.x_buf_off = 0; } + // FIPS 180-4 s. 5.2.2: the message is parsed into 1024-bit blocks; a partial trailing block waits in x_buf. let (chunks, remainder) = block.as_chunks::<128>(); self.state.compress(chunks); @@ -251,64 +421,35 @@ impl Hash for SHA512Internal { output } - fn do_final_out(mut self, output: &mut [u8]) -> usize { - output.fill(0); - - let n = *min(&output.len(), &PARAMS::OUTPUT_LEN); - - let bit_len_hi: u64 = self.byte_count >> 61; - let bit_len_lo: u64 = self.byte_count << 3; - - self.x_buf[self.x_buf_off] = 0x80; - self.x_buf_off += 1; - - if self.x_buf_off > 112 { - self.x_buf[self.x_buf_off..].fill(0x00); - self.state.compress(slice::from_ref(&self.x_buf)); - self.x_buf_off = 0; - } - - self.x_buf[self.x_buf_off..112].fill(0x00); - self.x_buf[112..120].copy_from_slice(&bit_len_hi.to_be_bytes()); - self.x_buf[120..128].copy_from_slice(&bit_len_lo.to_be_bytes()); - self.state.compress(slice::from_ref(&self.x_buf)); - - let h = &self.state.h; - - for i in 0..(n / 8) { - output[i * 8..i * 8 + 8].copy_from_slice(&h[i].to_be_bytes()); - } - if !n.is_multiple_of(8) { - output[((n / 8) * 8)..((n / 8) * 8) + (n % 8)] - .copy_from_slice(&h[n / 8].to_be_bytes()[0..(n % 8)]); - } - - n + fn do_final_out(self, output: &mut [u8]) -> usize { + // A whole-byte message is the zero-partial-bits case of the general padding. + self.do_final_internal(0, 0, output) } - /// TODO: This is defined in FIPS 180-4 s. 5.1.2 - /// TODO: - /// TODO: It can be implemented if required - #[allow(unused)] fn do_final_partial_bits( self, partial_byte: u8, num_partial_bits: usize, ) -> Result, HashError> { - unimplemented!() + let mut output = vec![0u8; PARAMS::OUTPUT_LEN]; + self.do_final_partial_bits_out(partial_byte, num_partial_bits, &mut output)?; + Ok(output) } - /// TODO: This is defined in FIPS 180-4 s. 5.1.2 - /// TODO: - /// TODO: It can be implemented if required - #[allow(unused)] + /// FIPS 180-4 s. 5.1: bit-oriented messages. The `num_partial_bits` most significant bits of + /// `partial_byte` (ASN.1 BIT STRING order, leading bit first) are appended to the message before + /// padding; the low bits are ignored. `num_partial_bits == 0` behaves exactly like + /// [`Hash::do_final_out`]. fn do_final_partial_bits_out( self, partial_byte: u8, num_partial_bits: usize, output: &mut [u8], ) -> Result { - unimplemented!() + if num_partial_bits > 7 { + return Err(HashError::InvalidLength("num_partial_bits must be in the range [0,7]")); + } + Ok(self.do_final_internal(partial_byte, num_partial_bits, output)) } fn max_security_strength(&self) -> SecurityStrength { @@ -316,10 +457,10 @@ impl Hash for SHA512Internal { } } -/// Length in bytes of the serialized state of SHA384 and SHA512. +/// Length in bytes of the serialized state of SHA384, SHA512, SHA512/224 and SHA512/256. pub const SUSPENDED_SHA512_STATE_LEN: usize = 204; -impl Suspendable for SHA512Internal { +impl Suspendable for SHA512Internal { fn suspend(self) -> [u8; SUSPENDED_SHA512_STATE_LEN] { debug_assert_eq!(SUSPENDED_SHA512_STATE_LEN, 204); diff --git a/crypto/sha2/tests/bc-test-data.rs b/crypto/sha2/tests/bc-test-data.rs new file mode 100644 index 00000000..bdf4b47e --- /dev/null +++ b/crypto/sha2/tests/bc-test-data.rs @@ -0,0 +1,211 @@ +//! NIST CAVP SHAVS test vectors for SHA-224, SHA-256, SHA-384, SHA-512, SHA-512/224 and SHA-512/256. +//! +//! Vectors are read from the bc-test-data repo (https://github.com/bcgit/bc-test-data), which must be +//! cloned alongside this repo at "../bc-test-data" (same convention as the mldsa/mlkem/sha3 crates), +//! under `crypto/sha2/{bit-oriented,byte-oriented}/`. If it is not present, the tests print a warning +//! and pass vacuously. +//! +//! Three SHAVS test types are exercised (SHAVS s. 6): +//! +//! * ShortMsg / LongMsg — `Len` (bits), `Msg`, `MD`. In the bit-oriented files `Len` is not a +//! multiple of 8 for most cases; the trailing bits are packed MSB-first in the final `Msg` byte +//! (SHAVS s. 6.2, "the message is left-justified"), which is exactly the ASN.1 BIT STRING order +//! that [`Hash::do_final_partial_bits`] takes, so the last byte is passed through unchanged. +//! * Monte — SHAVS s. 6.4 pseudo-random message test: `MD0 = MD1 = MD2 = Seed`, +//! `MDi = SHA(MDi-3 || MDi-2 || MDi-1)` for i in 3..=1002, `MD = MD1002`, then reseed with `MD` +//! for the next COUNT. 100 counts per file. (This differs from the SHA-3 Monte test, which hashes +//! only the previous digest.) + +use bouncycastle_core::traits::Hash; +use bouncycastle_hex as hex; +use bouncycastle_sha2::{SHA224, SHA256, SHA384, SHA512, SHA512_224, SHA512_256}; +use std::fs; +use std::path::Path; +use std::sync::Once; + +const TEST_DATA_PATH_RELATIVE: &str = "../../../bc-test-data/crypto/sha2"; +const TEST_DATA_PATH: &str = "../bc-test-data/crypto/sha2"; + +static TEST_DATA_CHECK: Once = Once::new(); + +/// Returns the contents of `/` from bc-test-data, or `None` (after a one-time +/// warning) if the repo is not checked out. +fn get_test_data(orientation: &str, filename: &str) -> Option { + let dir = [TEST_DATA_PATH_RELATIVE, TEST_DATA_PATH].into_iter().find(|d| Path::new(d).exists()); + TEST_DATA_CHECK.call_once(|| match dir { + Some(d) => println!("bc-test-data found at: {d:?}"), + None => println!("WARNING: bc-test-data directory not found; CAVP tests will be skipped"), + }); + let dir = dir?; + Some( + fs::read_to_string(format!("{dir}/{orientation}/{filename}")) + .expect("failed to read CAVP test vector file"), + ) +} + +/// Splits a `Key = value` line from a `.rsp` file. +fn kv(line: &str) -> Option<(&str, &str)> { + let (k, v) = line.split_once('=')?; + Some((k.trim(), v.trim())) +} + +struct MsgCase { + len_bits: usize, + msg: Vec, + md: Vec, +} + +/// Parses a ShortMsg/LongMsg `.rsp` file into `(Len, Msg, MD)` triples. +fn parse_msg_file(content: &str) -> Vec { + let mut cases = vec![]; + let (mut len_bits, mut msg) = (None, None); + for line in content.lines() { + let Some((k, v)) = kv(line) else { continue }; + match k { + "Len" => len_bits = Some(v.parse::().expect("bad Len")), + "Msg" => msg = Some(hex::decode(v).expect("bad Msg hex")), + "MD" => cases.push(MsgCase { + len_bits: len_bits.take().expect("MD without Len"), + msg: msg.take().expect("MD without Msg"), + md: hex::decode(v).expect("bad MD hex"), + }), + _ => {} + } + } + cases +} + +/// Hashes the first `len_bits` bits of `msg` (CAVP MSB-first packing, as the API takes it) with `H`. +fn hash_bits(msg: &[u8], len_bits: usize) -> Vec { + let whole_bytes = len_bits / 8; + let partial_bits = len_bits % 8; + if partial_bits == 0 { + // Note: CAVP writes `Msg = 00` for Len = 0, so always slice rather than using msg directly. + H::default().hash(&msg[..whole_bytes]) + } else { + let mut h = H::default(); + h.do_update(&msg[..whole_bytes]); + // CAVP left-justifies the trailing bits in the last byte, which is the order the API takes. + h.do_final_partial_bits(msg[whole_bytes], partial_bits).expect("partial_bits is in 1..=7") + } +} + +fn run_msg_file(orientation: &str, filename: &str) { + let Some(content) = get_test_data(orientation, filename) else { return }; + let cases = parse_msg_file(&content); + assert!(!cases.is_empty(), "{orientation}/{filename}: no test cases parsed"); + let mut partial_cases = 0; + for c in &cases { + if c.len_bits % 8 != 0 { + partial_cases += 1; + } + assert_eq!( + hash_bits::(&c.msg, c.len_bits), + c.md, + "{orientation}/{filename}: Len = {}", + c.len_bits + ); + // Whole-byte messages are also fed through the streaming API in uneven chunks. + if c.len_bits % 8 == 0 { + let mut h = H::default(); + for chunk in c.msg[..c.len_bits / 8].chunks(37) { + h.do_update(chunk); + } + assert_eq!( + h.do_final(), + c.md, + "{orientation}/{filename}: Len = {} (streamed)", + c.len_bits + ); + } + } + if orientation == "bit-oriented" { + assert!(partial_cases > 0, "{orientation}/{filename}: expected bit-length cases"); + } + println!("{orientation}/{filename}: {} cases ({partial_cases} bit-length)", cases.len()); +} + +struct MonteFile { + seed: Vec, + mds: Vec>, +} + +/// Parses a Monte `.rsp` file into the seed and the per-COUNT expected digests. +fn parse_monte_file(content: &str) -> MonteFile { + let mut seed = None; + let mut mds = vec![]; + for line in content.lines() { + let Some((k, v)) = kv(line) else { continue }; + match k { + "Seed" => seed = Some(hex::decode(v).expect("bad Seed hex")), + "MD" => mds.push(hex::decode(v).expect("bad MD hex")), + _ => {} + } + } + MonteFile { seed: seed.expect("Monte file without Seed"), mds } +} + +/// SHAVS s. 6.4 Monte Carlo test. +fn run_monte_file(orientation: &str, filename: &str) { + let Some(content) = get_test_data(orientation, filename) else { return }; + let MonteFile { mut seed, mds } = parse_monte_file(&content); + assert_eq!(mds.len(), 100, "{orientation}/{filename}: expected 100 COUNTs"); + for (count, expected) in mds.iter().enumerate() { + // MD0 = MD1 = MD2 = Seed + let mut md = [seed.clone(), seed.clone(), seed.clone()]; + // for i = 3 to 1002: Mi = MDi-3 || MDi-2 || MDi-1; MDi = SHA(Mi) + for _ in 3..=1002 { + let mut m = Vec::with_capacity(3 * seed.len()); + m.extend_from_slice(&md[0]); + m.extend_from_slice(&md[1]); + m.extend_from_slice(&md[2]); + let next = H::default().hash(&m); + md.rotate_left(1); + md[2] = next; + } + // MDj = MD1002; Seed = MDj + assert_eq!(&md[2], expected, "{orientation}/{filename}: COUNT = {count}"); + seed = md[2].clone(); + } + println!("{orientation}/{filename}: {} counts", mds.len()); +} + +macro_rules! cavp_tests { + ($mod:ident, $hash:ty, $prefix:literal) => { + mod $mod { + use super::*; + + #[test] + fn bit_oriented_short_msg() { + run_msg_file::<$hash>("bit-oriented", concat!($prefix, "ShortMsg.rsp")); + } + #[test] + fn bit_oriented_long_msg() { + run_msg_file::<$hash>("bit-oriented", concat!($prefix, "LongMsg.rsp")); + } + #[test] + fn bit_oriented_monte() { + run_monte_file::<$hash>("bit-oriented", concat!($prefix, "Monte.rsp")); + } + #[test] + fn byte_oriented_short_msg() { + run_msg_file::<$hash>("byte-oriented", concat!($prefix, "ShortMsg.rsp")); + } + #[test] + fn byte_oriented_long_msg() { + run_msg_file::<$hash>("byte-oriented", concat!($prefix, "LongMsg.rsp")); + } + #[test] + fn byte_oriented_monte() { + run_monte_file::<$hash>("byte-oriented", concat!($prefix, "Monte.rsp")); + } + } + }; +} + +cavp_tests!(sha224, SHA224, "SHA224"); +cavp_tests!(sha256, SHA256, "SHA256"); +cavp_tests!(sha384, SHA384, "SHA384"); +cavp_tests!(sha512, SHA512, "SHA512"); +cavp_tests!(sha512_224, SHA512_224, "SHA512_224"); +cavp_tests!(sha512_256, SHA512_256, "SHA512_256"); diff --git a/crypto/sha2/tests/sha2_tests.rs b/crypto/sha2/tests/sha2_tests.rs index 42c6ba0f..70567a5d 100644 --- a/crypto/sha2/tests/sha2_tests.rs +++ b/crypto/sha2/tests/sha2_tests.rs @@ -1,6 +1,6 @@ #[cfg(test)] mod sha2_tests { - use bouncycastle_core::errors::SuspendableError; + use bouncycastle_core::errors::{HashError, SuspendableError}; use bouncycastle_core::traits::{Algorithm, Hash, HashAlgParams, SecurityStrength}; use bouncycastle_core_test_framework::hash::TestFrameworkHash; use bouncycastle_sha2::*; @@ -12,8 +12,7 @@ mod sha2_tests { #[test] fn sha224() { - let mut test_framework = TestFrameworkHash::new(); - test_framework.enable_partial_byte_tests = false; + let test_framework = TestFrameworkHash::new(); test_framework.test_hash::(b"", b"\xd1\x4a\x02\x8c\x2a\x3a\x2b\xc9\x47\x61\x02\xbb\x28\x82\x34\xc4\x15\xa2\xb0\x1f\x82\x8e\xa6\x2a\xc5\xb3\xe4\x2f"); test_framework.test_hash::(b"a", b"\xab\xd3\x75\x34\xc7\xd9\xa2\xef\xb9\x46\x5d\xe9\x31\xcd\x70\x55\xff\xdb\x88\x79\x56\x3a\xe9\x80\x78\xd6\xd6\xd5"); test_framework.test_hash::(b"abc", b"\x23\x09\x7d\x22\x34\x05\xd8\x22\x86\x42\xa4\x77\xbd\xa2\x55\xb3\x2a\xad\xbc\xe4\xbd\xa0\xb3\xf7\xe3\x6c\x9d\xa7"); @@ -24,8 +23,7 @@ mod sha2_tests { #[test] fn sha256() { - let mut test_framework = TestFrameworkHash::new(); - test_framework.enable_partial_byte_tests = false; + let test_framework = TestFrameworkHash::new(); test_framework.test_hash::(b"", b"\xe3\xb0\xc4\x42\x98\xfc\x1c\x14\x9a\xfb\xf4\xc8\x99\x6f\xb9\x24\x27\xae\x41\xe4\x64\x9b\x93\x4c\xa4\x95\x99\x1b\x78\x52\xb8\x55"); test_framework.test_hash::(b"a", b"\xca\x97\x81\x12\xca\x1b\xbd\xca\xfa\xc2\x31\xb3\x9a\x23\xdc\x4d\xa7\x86\xef\xf8\x14\x7c\x4e\x72\xb9\x80\x77\x85\xaf\xee\x48\xbb"); test_framework.test_hash::(b"abc", b"\xba\x78\x16\xbf\x8f\x01\xcf\xea\x41\x41\x40\xde\x5d\xae\x22\x23\xb0\x03\x61\xa3\x96\x17\x7a\x9c\xb4\x10\xff\x61\xf2\x00\x15\xad"); @@ -35,8 +33,7 @@ mod sha2_tests { #[test] fn sha384() { - let mut test_framework = TestFrameworkHash::new(); - test_framework.enable_partial_byte_tests = false; + let test_framework = TestFrameworkHash::new(); test_framework.test_hash::(b"", b"\x38\xb0\x60\xa7\x51\xac\x96\x38\x4c\xd9\x32\x7e\xb1\xb1\xe3\x6a\x21\xfd\xb7\x11\x14\xbe\x07\x43\x4c\x0c\xc7\xbf\x63\xf6\xe1\xda\x27\x4e\xde\xbf\xe7\x6f\x65\xfb\xd5\x1a\xd2\xf1\x48\x98\xb9\x5b"); test_framework.test_hash::(b"a", b"\x54\xa5\x9b\x9f\x22\xb0\xb8\x08\x80\xd8\x42\x7e\x54\x8b\x7c\x23\xab\xd8\x73\x48\x6e\x1f\x03\x5d\xce\x9c\xd6\x97\xe8\x51\x75\x03\x3c\xaa\x88\xe6\xd5\x7b\xc3\x5e\xfa\xe0\xb5\xaf\xd3\x14\x5f\x31"); test_framework.test_hash::(b"abc", b"\xcb\x00\x75\x3f\x45\xa3\x5e\x8b\xb5\xa0\x3d\x69\x9a\xc6\x50\x07\x27\x2c\x32\xab\x0e\xde\xd1\x63\x1a\x8b\x60\x5a\x43\xff\x5b\xed\x80\x86\x07\x2b\xa1\xe7\xcc\x23\x58\xba\xec\xa1\x34\xc8\x25\xa7"); @@ -46,14 +43,167 @@ mod sha2_tests { #[test] fn sha512() { - let mut test_framework = TestFrameworkHash::new(); - test_framework.enable_partial_byte_tests = false; + let test_framework = TestFrameworkHash::new(); test_framework.test_hash::(b"", b"\xcf\x83\xe1\x35\x7e\xef\xb8\xbd\xf1\x54\x28\x50\xd6\x6d\x80\x07\xd6\x20\xe4\x05\x0b\x57\x15\xdc\x83\xf4\xa9\x21\xd3\x6c\xe9\xce\x47\xd0\xd1\x3c\x5d\x85\xf2\xb0\xff\x83\x18\xd2\x87\x7e\xec\x2f\x63\xb9\x31\xbd\x47\x41\x7a\x81\xa5\x38\x32\x7a\xf9\x27\xda\x3e"); test_framework.test_hash::(b"a", b"\x1f\x40\xfc\x92\xda\x24\x16\x94\x75\x09\x79\xee\x6c\xf5\x82\xf2\xd5\xd7\xd2\x8e\x18\x33\x5d\xe0\x5a\xbc\x54\xd0\x56\x0e\x0f\x53\x02\x86\x0c\x65\x2b\xf0\x8d\x56\x02\x52\xaa\x5e\x74\x21\x05\x46\xf3\x69\xfb\xbb\xce\x8c\x12\xcf\xc7\x95\x7b\x26\x52\xfe\x9a\x75"); test_framework.test_hash::(b"abc", b"\xdd\xaf\x35\xa1\x93\x61\x7a\xba\xcc\x41\x73\x49\xae\x20\x41\x31\x12\xe6\xfa\x4e\x89\xa9\x7e\xa2\x0a\x9e\xee\xe6\x4b\x55\xd3\x9a\x21\x92\x99\x2a\x27\x4f\xc1\xa8\x36\xba\x3c\x23\xa3\xfe\xeb\xbd\x45\x4d\x44\x23\x64\x3c\xe8\x0e\x2a\x9a\xc9\x4f\xa5\x4c\xa4\x9f"); test_framework.test_hash::(b"abcdefghbcdefghicdefghijdefghijkefghijklfghijklmghijklmnhijklmnoijklmnopjklmnopqklmnopqrlmnopqrsmnopqrstnopqrstu", b"\x8e\x95\x9b\x75\xda\xe3\x13\xda\x8c\xf4\xf7\x28\x14\xfc\x14\x3f\x8f\x77\x79\xc6\xeb\x9f\x7f\xa1\x72\x99\xae\xad\xb6\x88\x90\x18\x50\x1d\x28\x9e\x49\x00\xf7\xe4\x33\x1b\x99\xde\xc4\xb5\x43\x3a\xc7\xd3\x29\xee\xb6\xdd\x26\x54\x5e\x96\xe5\x5b\x87\x4b\xe9\x09"); test_framework.test_hash::(&DUMMY_SEED[..512], b"\xed\xb9\xbe\xd7\x21\xaa\x6a\x5f\x6f\xbc\x66\x19\xd3\xa3\xc2\xbe\x3d\x04\x30\x43\xf0\x5a\x9a\xeb\xc7\xb1\x19\x7a\x2a\xa9\xc4\x9a\x57\xd5\xdd\xd4\x67\x4c\x17\x85\x78\x50\x88\xd9\xf1\xff\x42\xc7\x97\xa0\x2a\xdc\x9b\x81\x7a\x13\x9a\x50\x97\x0d\xa6\xc9\x95\x24"); } + + /// Vectors: "" and the one-byte message from NIST CAVP SHA512_224ShortMsg.rsp (Len = 0 and + /// Len = 8); "abc" and the two-block message from the NIST example file SHA512_224.pdf. + #[test] + fn sha512_224() { + let test_framework = TestFrameworkHash::new(); + test_framework.test_hash::(b"", b"\x6e\xd0\xdd\x02\x80\x6f\xa8\x9e\x25\xde\x06\x0c\x19\xd3\xac\x86\xca\xbb\x87\xd6\xa0\xdd\xd0\x5c\x33\x3b\x84\xf4"); + test_framework.test_hash::(b"\xcf", b"\x41\x99\x23\x9e\x87\xd4\x7b\x6f\xed\xa0\x16\x80\x2b\xf3\x67\xfb\x6e\x8b\x56\x55\xef\xf6\x22\x5c\xb2\x66\x8f\x4a"); + test_framework.test_hash::(b"abc", b"\x46\x34\x27\x0f\x70\x7b\x6a\x54\xda\xae\x75\x30\x46\x08\x42\xe2\x0e\x37\xed\x26\x5c\xee\xe9\xa4\x3e\x89\x24\xaa"); + test_framework.test_hash::(b"abcdefghbcdefghicdefghijdefghijkefghijklfghijklmghijklmnhijklmnoijklmnopjklmnopqklmnopqrlmnopqrsmnopqrstnopqrstu", b"\x23\xfe\xc5\xbb\x94\xd6\x0b\x23\x30\x81\x92\x64\x0b\x0c\x45\x33\x35\xd6\x64\x73\x4f\xe4\x0e\x72\x68\x67\x4a\xf9"); + } + + /// Vectors: "" and the one-byte message from NIST CAVP SHA512_256ShortMsg.rsp (Len = 0 and + /// Len = 8); "abc" and the two-block message from the NIST example file SHA512_256.pdf. + #[test] + fn sha512_256() { + let test_framework = TestFrameworkHash::new(); + test_framework.test_hash::(b"", b"\xc6\x72\xb8\xd1\xef\x56\xed\x28\xab\x87\xc3\x62\x2c\x51\x14\x06\x9b\xdd\x3a\xd7\xb8\xf9\x73\x74\x98\xd0\xc0\x1e\xce\xf0\x96\x7a"); + test_framework.test_hash::(b"\xfa", b"\xc4\xef\x36\x92\x3c\x64\xe5\x1e\x87\x57\x20\xe5\x50\x29\x8a\x5a\xb8\xa3\xf2\xf8\x75\xb1\xe1\xa4\xc9\xb9\x5b\xab\xf7\x34\x4f\xef"); + test_framework.test_hash::(b"abc", b"\x53\x04\x8e\x26\x81\x94\x1e\xf9\x9b\x2e\x29\xb7\x6b\x4c\x7d\xab\xe4\xc2\xd0\xc6\x34\xfc\x6d\x46\xe0\xe2\xf1\x31\x07\xe7\xaf\x23"); + test_framework.test_hash::(b"abcdefghbcdefghicdefghijdefghijkefghijklfghijklmghijklmnhijklmnoijklmnopjklmnopqklmnopqrlmnopqrsmnopqrstnopqrstu", b"\x39\x28\xe1\x84\xfb\x86\x90\xf8\x40\xda\x39\x88\x12\x1d\x31\xbe\x65\xcb\x9d\x3e\xf8\x3e\xe6\x14\x6f\xea\xc8\x61\xe1\x9b\x56\x3a"); + } + } + + /// FIPS 180-4 s. 5.1: bit-oriented messages. Zero partial bits must equal the byte-oriented + /// digest; more than 7 partial bits is rejected; only the top bits of the partial byte matter; + /// and the pad byte spilling into a second block must not break. Known answers are in + /// `partial_bits_known_answers`. + #[test] + fn partial_bits() { + fn check() { + // 0 partial bits == do_final + let mut a = H::default(); + a.do_update(b"abc"); + assert_eq!(a.do_final_partial_bits(0xFF, 0).unwrap(), H::default().hash(b"abc")); + + // out of range -> InvalidLength, never a panic + for bad in [8usize, 9, 16, 64, usize::MAX] { + let mut h = H::default(); + h.do_update(b"abc"); + assert!(matches!( + h.do_final_partial_bits(0xFF, bad), + Err(HashError::InvalidLength(_)) + )); + } + + // only the top num_partial_bits bits of partial_byte may influence the result + for n in 1..=7usize { + let mask = (0xFF00u16 >> n) as u8; + let x = H::default().do_final_partial_bits(0xA5, n).unwrap(); + let y = H::default().do_final_partial_bits(0xA5 & mask, n).unwrap(); + let z = H::default().do_final_partial_bits(0xA5 ^ 0x80, n).unwrap(); + assert_eq!(x, y, "n={n}"); + assert_ne!(x, z, "n={n}: the leading bit must change the digest"); + // and a bit-message is distinct from byte-messages of nearby length + assert_ne!(x, H::default().hash(&[]), "n={n}"); + assert_ne!(x, H::default().hash(&[0xA5 & mask]), "n={n}"); + } + + // the partial-bit path must also work when the pad byte spills into a second block + for len in [55usize, 56, 63, 64, 111, 112, 119, 127, 128] { + let msg = vec![0x5Au8; len]; + let mut h = H::default(); + h.do_update(&msg); + let mut out = vec![0u8; 64]; + let written = h.do_final_partial_bits_out(0xC0, 2, &mut out).unwrap(); + assert!(written > 0); + } + } + check::(); + check::(); + check::(); + check::(); + check::(); + check::(); + } + + /// Bit-oriented known answers (FIPS 180-4 s. 5.1). Expected values were produced by an + /// independent pure-Python implementation of FIPS 180-4 with bit-length padding, itself checked + /// against `hashlib` for byte-aligned inputs. `(prefix_len, fill, partial_byte, bits, digest)`, + /// where the `bits` message bits are the top bits of `partial_byte` (ASN.1 BIT STRING order). + #[test] + fn partial_bits_known_answers() { + fn hex(s: &str) -> Vec { + (0..s.len()).step_by(2).map(|i| u8::from_str_radix(&s[i..i + 2], 16).unwrap()).collect() + } + fn check(cases: &[(usize, u8, u8, usize, &str)]) { + for &(prefix_len, fill, partial_byte, bits, expected) in cases { + let mut h = H::default(); + h.do_update(&vec![fill; prefix_len]); + assert_eq!( + h.do_final_partial_bits(partial_byte, bits).unwrap(), + hex(expected), + "{prefix_len}/{bits}" + ); + } + } + check::(&[ + (0, 0, 0x80, 1, "b9debf7d52f36e6468a54817c1fa071166c3a63d384850e1575b42f702dc5aa1"), + (0, 0, 0xA8, 5, "9a6eb6cad1c1017a060c4cc9d1be5c9404397e4d05c8e6c91f6347db8591c1a9"), + (55, 0x5a, 0xC0, 2, "f9f22d1e48f4d6fe0f84db4a04bef65d4be116e4f182845b8a827c897b05723a"), + ( + 111, + 0x5a, + 0xA0, + 3, + "bf63c89e04968fba3fc26ccf8908e0b2d05221834a17f912b48d9816d821be6d", + ), + ]); + let mut h = SHA256::new(); + h.do_update(b"abc"); + assert_eq!( + h.do_final_partial_bits(0xfe, 7).unwrap(), + hex("9f5893e1b85faf8d646489927b5bc22b7394e2a14bbd47da00bbce3a1b27a5ba") + ); + + check::(&[ + ( + 0, + 0, + 0x80, + 1, + "5f72ee8494a425ba13fc8c48ac0a05cbaae7e932e471e948cb524333745aa432c1851c0c43682b0e67d64626f8f45cf165f6b538a94c63be98224e969e75d7ed", + ), + ( + 0, + 0, + 0xA8, + 5, + "dcaab1be5ce172f510ebe2da22f6488bd2f706c8124d6bb16de5cfb3432f0dd6e7262dd35206d500180b70563c419e142c354b6ac155ca8a3f0f0fdb88d567e9", + ), + ( + 55, + 0x5a, + 0xC0, + 2, + "4fe3a857ce5d8abc5dcc7ea0d3f97ff7bb0db06001e1f37c2c2c9d48bd4c609af169b0f5d200d1b9033af31819095a4679b62d87b15673a85ac75c8ecbc2bd57", + ), + ( + 111, + 0x5a, + 0xA0, + 3, + "f0af9c9852d733b024e097ae6aa9e7959c84c05a666b04f3c0df368e2ea93bcccf9136aefa54b0c4db432217742dec7d77365b3f5a6b63fe46c9fc259b8f0101", + ), + ]); + let mut h = SHA512::new(); + h.do_update(b"abc"); + assert_eq!( + h.do_final_partial_bits(0xfe, 7).unwrap(), + hex( + "ec168db3beb4379ddd4dd854461ac533f047f69ebf4770dec59442994a8320a4f240eeb0d808f8b7dc8d23d0428af5f095cc2ded70c516aef86ca68e99f8ffe6" + ) + ); } #[test] @@ -62,16 +212,26 @@ mod sha2_tests { assert_eq!(SHA256::OUTPUT_LEN, 32); assert_eq!(SHA384::OUTPUT_LEN, 48); assert_eq!(SHA512::OUTPUT_LEN, 64); + assert_eq!(SHA512_224::OUTPUT_LEN, 28); + assert_eq!(SHA512_256::OUTPUT_LEN, 32); + assert_eq!(SHA512t::<224>::OUTPUT_LEN, 28); + assert_eq!(SHA512t::<256>::OUTPUT_LEN, 32); assert_eq!(SHA224::BLOCK_LEN, 64); assert_eq!(SHA256::BLOCK_LEN, 64); assert_eq!(SHA384::BLOCK_LEN, 128); assert_eq!(SHA512::BLOCK_LEN, 128); + assert_eq!(SHA512_224::BLOCK_LEN, 128); + assert_eq!(SHA512_256::BLOCK_LEN, 128); assert_eq!(SHA224::new().block_bitlen(), 512); assert_eq!(SHA256::new().block_bitlen(), 512); assert_eq!(SHA384::new().block_bitlen(), 1024); assert_eq!(SHA512::new().block_bitlen(), 1024); + assert_eq!(SHA512_224::new().block_bitlen(), 1024); + assert_eq!(SHA512_256::new().block_bitlen(), 1024); + assert_eq!(SHA512_224::new().output_len(), 28); + assert_eq!(SHA512_256::new().output_len(), 32); } #[test] @@ -80,6 +240,10 @@ mod sha2_tests { assert_eq!(SHA256::ALG_NAME, SHA256_NAME); assert_eq!(SHA384::ALG_NAME, SHA384_NAME); assert_eq!(SHA512::ALG_NAME, SHA512_NAME); + assert_eq!(SHA512_224::ALG_NAME, SHA512_224_NAME); + assert_eq!(SHA512_256::ALG_NAME, SHA512_256_NAME); + assert_eq!(SHA512_224_NAME, "SHA512/224"); + assert_eq!(SHA512_256_NAME, "SHA512/256"); } #[test] @@ -88,6 +252,22 @@ mod sha2_tests { assert_eq!(SHA256::default().max_security_strength(), SecurityStrength::_128bit); assert_eq!(SHA384::default().max_security_strength(), SecurityStrength::_192bit); assert_eq!(SHA512::default().max_security_strength(), SecurityStrength::_256bit); + assert_eq!(SHA512_224::default().max_security_strength(), SecurityStrength::_112bit); + assert_eq!(SHA512_256::default().max_security_strength(), SecurityStrength::_128bit); + assert_eq!(SHA512_224::MAX_SECURITY_STRENGTH, SecurityStrength::_112bit); + assert_eq!(SHA512_256::MAX_SECURITY_STRENGTH, SecurityStrength::_128bit); + } + + /// NIST CSOR: id-sha512-224 { hashAlgs 5 }, id-sha512-256 { hashAlgs 6 }. + #[test] + fn test_oids() { + use bouncycastle_core::traits::AlgorithmOID; + assert_eq!(SHA512_224::OID, &[2, 16, 840, 1, 101, 3, 4, 2, 5]); + assert_eq!(SHA512_256::OID, &[2, 16, 840, 1, 101, 3, 4, 2, 6]); + assert_eq!(SHA512_224::OID_DER.last(), Some(&5)); + assert_eq!(SHA512_256::OID_DER.last(), Some(&6)); + assert_eq!(&SHA512_224::OID_DER[..10], &SHA512::OID_DER[..10]); + assert_eq!(&SHA512_256::OID_DER[..10], &SHA512::OID_DER[..10]); } #[test] @@ -118,7 +298,7 @@ mod sha2_tests { assert_eq!(output, output2); // also, give it a busted x_buf_off, just to satisfy mutants that that's been tested - let mut busted_state = serialized_state.clone(); + let mut busted_state = serialized_state; busted_state[3 + 104] = 65; match SHA256::from_suspended(busted_state) { Err(SuspendableError::InvalidData) => { /* good */ } @@ -146,11 +326,53 @@ mod sha2_tests { assert_eq!(output, output2); // also, give it a busted x_buf_off, just to satisfy mutants that that's been tested - let mut busted_state = serialized_state.clone(); + let mut busted_state = serialized_state; busted_state[3 + 200] = 129; match SHA512::from_suspended(busted_state) { Err(SuspendableError::InvalidData) => { /* good */ } _ => panic!("Expected an error"), } + + // SHA512/224: same state layout as SHA512, but the truncated output must survive the + // round trip too. + let mut sha512_224 = SHA512_224::new(); + sha512_224.do_update(str.as_bytes()); + TestFrameworkSuspendableState::new().test(&sha512_224); + let serialized_state = sha512_224.clone().suspend(); + let output = sha512_224.do_final(); + let output2 = SHA512_224::from_suspended(serialized_state).unwrap().do_final(); + assert_eq!(output, output2); + assert_eq!(output.len(), 28); + } + + /// FIPS 180-4 s. 5.1.2 has SHA-384/512/512-t append the message length l as a *128-bit* field, + /// where s. 5.1.1 gives SHA-224/256 only 64 bits. Since byte_count is a u64 of bytes, l needs + /// `byte_count << 3` for the low word and `byte_count >> 61` for the high one, and it is the + /// high word that separates the two families: drop it and SHA-512 would silently agree with + /// itself across byte counts 2^61 apart, exactly as SHA-256 is obliged to. + /// + /// A message that long cannot be hashed in a test, but suspend()/from_suspended() round-trips + /// byte_count through a byte field, so the state can simply be written by hand. + #[test] + fn sha512_length_field_carries_the_high_word() { + use bouncycastle_core::traits::Suspendable; + + // Suspended layout (see SHA512Internal::suspend): 3 bytes of library version, h[0..8] as + // eight little-endian u64s, then byte_count as a little-endian u64. + const BYTE_COUNT_OFFSET: usize = 3 + 64; + fn with_byte_count(byte_count: u64) -> SHA512 { + let mut state: [u8; SUSPENDED_SHA512_STATE_LEN] = SHA512::new().suspend(); + state[BYTE_COUNT_OFFSET..BYTE_COUNT_OFFSET + 8] + .copy_from_slice(&byte_count.to_le_bytes()); + SHA512::from_suspended(state).unwrap() + } + + // 2^61 bytes is 2^64 bits: the low word of l is identical for these two, so they can only + // differ if the high word is written. + assert_ne!(with_byte_count(0).do_final(), with_byte_count(1 << 61).do_final()); + assert_ne!(with_byte_count(1).do_final(), with_byte_count((1 << 61) + 1).do_final()); + + // and byte_count 0 is still the empty-message digest, i.e. the high word is zero there + assert_eq!(with_byte_count(0).do_final(), SHA512::new().do_final()); } } diff --git a/crypto/sha2/tests/sha512t_h0_tests.rs b/crypto/sha2/tests/sha512t_h0_tests.rs new file mode 100644 index 00000000..5e6290f8 --- /dev/null +++ b/crypto/sha2/tests/sha512t_h0_tests.rs @@ -0,0 +1,63 @@ +//! FIPS 180-4 s. 5.3.6 known-answer tests for the SHA-512/t IV Generation Function. +//! +//! The initial hash value H(0) for SHA-512/224 and SHA-512/256 is not stored as a literal in this +//! crate: it is produced by the IV Generation Function (FIPS 180-4 s. 5.3.6), evaluated at compile +//! time. These tests pin what that function produces against the words the standard lists in +//! s. 5.3.6.1 and s. 5.3.6.2. +//! +//! H(0) is read back through the public suspend API rather than from a crate-private constant. A +//! freshly-constructed hash has processed no message, so the chaining value in its serialized state +//! is still H(0). The layout is a 3-byte library version tag (written by +//! `bouncycastle_core::suspendable_state::add_lib_ver`) followed by the eight 64-bit chaining +//! words, little-endian. +//! +//! Note that a wrong H(0) is also caught end-to-end by the CAVP vectors in `bc-test-data.rs`, since +//! every SHA-512/224 and SHA-512/256 digest would then differ. These tests localize such a failure +//! to the IV Generation Function itself. + +use bouncycastle_core::traits::Suspendable; +use bouncycastle_sha2::{SHA512_224, SHA512_256, SUSPENDED_SHA512_STATE_LEN}; + +/// Bytes occupied by the library version tag at the front of a suspended state. +const LIB_VER_TAG_LEN: usize = 3; + +/// FIPS 180-4 s. 5.3.6.1: the eight 64-bit words H(0) shall consist of for SHA-512/224, "obtained +/// by executing the SHA-512/t IV Generation Function with t = 224". +const SHA512_224_H0: [u64; 8] = [ + 0x8C3D37C819544DA2, 0x73E1996689DCD4D6, 0x1DFAB7AE32FF9C82, 0x679DD514582F9FCF, + 0x0F6D2B697BD44DA8, 0x77E36F7304C48942, 0x3F9D85A86A1D36C8, 0x1112E6AD91D692A1, +]; + +/// FIPS 180-4 s. 5.3.6.2: the eight 64-bit words H(0) shall consist of for SHA-512/256, "obtained +/// by executing the SHA-512/t IV Generation Function with t = 256". +const SHA512_256_H0: [u64; 8] = [ + 0x22312194FC2BF72C, 0x9F555FA3C84C64C2, 0x2393B86B6F53B151, 0x963877195940EABD, + 0x96283EE2A88EFFE3, 0xBE5E1E2553863992, 0x2B0199FC2C85B8AA, 0x0EB72DDC81C52CA2, +]; + +/// Recovers the eight chaining words of a freshly-constructed SHA-512-family hash, which has had no +/// message applied and so still holds H(0). +/// Uses the [`Suspendable`] API to read the internal state. +fn h0_of>() -> [u64; 8] { + let state = H::default().suspend(); + + let mut h0 = [0u64; 8]; + for (i, word) in h0.iter_mut().enumerate() { + let offset = LIB_VER_TAG_LEN + (i * 8); + // infallible: the slice is 8 bytes, and offset + 8 <= 3 + 64 < SUSPENDED_SHA512_STATE_LEN. + *word = u64::from_le_bytes(state[offset..offset + 8].try_into().unwrap()); + } + h0 +} + +/// FIPS 180-4 s. 6.6 exception 1 / s. 5.3.6.1: SHA-512/224 uses the H(0) listed in s. 5.3.6.1. +#[test] +fn sha512_224_h0_matches_the_listed_words() { + assert_eq!(h0_of::(), SHA512_224_H0); +} + +/// FIPS 180-4 s. 6.7 exception 1 / s. 5.3.6.2: SHA-512/256 uses the H(0) listed in s. 5.3.6.2. +#[test] +fn sha512_256_h0_matches_the_listed_words() { + assert_eq!(h0_of::(), SHA512_256_H0); +} diff --git a/crypto/sha3/src/keccak.rs b/crypto/sha3/src/keccak.rs index 6188f826..de32fa97 100644 --- a/crypto/sha3/src/keccak.rs +++ b/crypto/sha3/src/keccak.rs @@ -250,7 +250,8 @@ impl KeccakInternal { } } - /// Absorbs the final `bits` (0..=7, in the least significant bits of `data`) of the message and + /// Absorbs the final `bits` (0..=7, in the least significant bits of `data`, FIPS 202 B.1 order; + /// the public API's MSB-first partial byte is reversed by the callers before reaching here) of the message and /// switches the sponge to the squeezing phase. `bits == 0` means "no further bits": the sponge is /// padded and switched to squeezing without absorbing anything. Callers that have already applied a /// domain-separation suffix rely on this — if the switch did not happen here, a later squeeze would diff --git a/crypto/sha3/src/lib.rs b/crypto/sha3/src/lib.rs index 22c1dc0b..4f276df0 100644 --- a/crypto/sha3/src/lib.rs +++ b/crypto/sha3/src/lib.rs @@ -41,8 +41,11 @@ //! let output: Vec = sha3.do_final(); //! ``` //! -//! It is also possible to provide input where the final byte contains less than 8 bits of data (ie is a partial byte); -//! for example, the following code uses only 3 bits of the final byte: +//! It is also possible to provide input where the final byte contains less than 8 bits of data (ie is a partial byte). +//! The partial byte is taken as it arrives in the final octet of an ASN.1 BIT STRING: the message bits are +//! its most significant bits, leading bit first, and the low "unused" bits are ignored (the reversal into +//! the FIPS 202 Appendix B.1 bit order that Keccak absorbs is done internally). For example, the following +//! code uses only the top 3 bits of the final byte: //! ``` //! use bouncycastle_core::traits::Hash; //! use bouncycastle_sha3 as sha3; diff --git a/crypto/sha3/src/sha3.rs b/crypto/sha3/src/sha3.rs index 4a5bad02..39ff6989 100644 --- a/crypto/sha3/src/sha3.rs +++ b/crypto/sha3/src/sha3.rs @@ -47,8 +47,9 @@ impl SHA3Internal { /// Appends the SHA3 domain-separation suffix and pads as per FIPS 202 s. 6.1, then squeezes the digest. /// /// Private, infallible body shared by [`Hash::do_final_out`] and [`Hash::do_final_partial_bits_out`]. - /// `num_partial_bits` (0..=7, validated by the caller) trailing message bits are taken from the - /// least significant bits of `partial_byte` (FIPS 202 Appendix B.1 bit ordering). FIPS 202 s. 6.1 + /// The `num_partial_bits` (0..=7, validated by the caller) trailing message bits are the most + /// significant bits of `partial_byte`, leading bit first (ASN.1 BIT STRING order); they are reversed + /// below into the FIPS 202 Appendix B.1 bit ordering that Keccak absorbs. FIPS 202 s. 6.1 /// defines SHA3-d(M) = KECCAK[c](M || 01, d), so the two suffix bits are appended directly above /// the message bits; pad10*1 is then applied by the sponge when it switches to squeezing. /// @@ -65,8 +66,12 @@ impl SHA3Internal { // Mutants note: This is just bit-setting into empty space. // It works the same regardless of whether it's OR or XOR. - let mut final_input: u16 = - ((partial_byte as u16) & ((1 << num_partial_bits) - 1)) | (0x02 << num_partial_bits); + // The public convention puts the message bits in the most significant bits of partial_byte, + // leading bit first (ASN.1 BIT STRING order, X.690 s. 8.6.2.1). Keccak absorbs a byte + // LSB-first: FIPS 202 Algorithm 10 (h2b) step 3 sets message bit T[8i + j] = b_ij, the bit + // of weight 2^j in byte i. So reverse the bit order and keep the low num_partial_bits bits. + let message_bits = (partial_byte.reverse_bits() as u16) & ((1 << num_partial_bits) - 1); + let mut final_input: u16 = message_bits | (0x02 << num_partial_bits); let mut final_bits = num_partial_bits + 2; // If message bits + suffix fill a whole byte, absorb it as a normal byte first. diff --git a/crypto/sha3/src/shake.rs b/crypto/sha3/src/shake.rs index 4d1a87a1..263cb0cc 100644 --- a/crypto/sha3/src/shake.rs +++ b/crypto/sha3/src/shake.rs @@ -319,8 +319,12 @@ impl XOF for SHAKEInternal { } // Mutants note: This is just bit-setting into empty space. // It works the same regardless of whether it's OR or XOR. - let mut final_input: u16 = - ((partial_byte as u16) & ((1 << num_partial_bits) - 1)) | (0x0F << num_partial_bits); + // The public convention puts the message bits in the most significant bits of partial_byte, + // leading bit first (ASN.1 BIT STRING order, X.690 s. 8.6.2.1). Keccak absorbs a byte + // LSB-first: FIPS 202 Algorithm 10 (h2b) step 3 sets message bit T[8i + j] = b_ij, the bit + // of weight 2^j in byte i. So reverse the bit order and keep the low num_partial_bits bits. + let message_bits = (partial_byte.reverse_bits() as u16) & ((1 << num_partial_bits) - 1); + let mut final_input: u16 = message_bits | (0x0F << num_partial_bits); let mut final_bits = num_partial_bits + 4; if final_bits >= 8 { @@ -376,7 +380,12 @@ impl XOF for SHAKEInternal { let mut buf = [0u8; 1]; self.squeeze_out(&mut buf); - *output = buf[0] & ((1u8 << num_bits) - 1); + // Keccak emits the bits of an output byte LSB-first (FIPS 202 Algorithm 11, b2h: output bit + // T[8i + j] has weight 2^j), and the public convention returns them as the final octet of an + // ASN.1 BIT STRING (X.690 s. 8.6.2.1): first bit in the MSB, unused low bits zero. So reverse + // the bit order and keep the top num_bits bits. The mask is built in u16 so that num_bits == 0 + // cannot overflow (0xFF00 >> 0 truncates to 0x00). + *output = buf[0].reverse_bits() & ((0xFF00u16 >> num_bits) as u8); Ok(()) } diff --git a/crypto/sha3/tests/cavp_tests.rs b/crypto/sha3/tests/bc-test-data.rs similarity index 92% rename from crypto/sha3/tests/cavp_tests.rs rename to crypto/sha3/tests/bc-test-data.rs index 54069c88..334bb6f9 100644 --- a/crypto/sha3/tests/cavp_tests.rs +++ b/crypto/sha3/tests/bc-test-data.rs @@ -5,12 +5,13 @@ //! under `crypto/sha3/{bit-oriented,byte-oriented}/`. If it is not present the tests print a warning //! and pass vacuously. //! -//! Bit ordering: unlike the SHA-2 CAVP files, SHA-3 CAVP follows FIPS 202 Appendix B.1 — the excess -//! bits of a `Len`-bit message occupy the *least significant* bits of the final `Msg` byte, and the -//! excess bits of an `Outputlen`-bit SHAKE output occupy the least significant bits of the final -//! `Output` byte (verified over every partial case in the files: all high bits are zero). This is -//! exactly the convention of [`Hash::do_final_partial_bits`] / [`XOF::absorb_last_partial_byte`] / -//! [`XOF::squeeze_partial_byte_final`], so no shifting is needed. +//! The SHA3VS files pack bit strings per FIPS 202 Appendix B.1 (Algorithms 10/11, h2b/b2h): the +//! excess bits of a `Len`-bit message occupy the *least significant* bits of the final `Msg` byte, +//! first bit in the LSB, and likewise the excess bits of an `Outputlen`-bit SHAKE output occupy the +//! least significant bits of the final `Output` byte. The API takes and returns partial bytes in +//! ASN.1 BIT STRING order (X.690 s. 8.6.2.1: first bit in the MSB, unused low bits), so the harness +//! bit-reverses the final message byte before absorbing it and the final output byte after squeezing +//! it (`u8::reverse_bits`). //! //! Test types exercised (SHA3VS s. 6): //! @@ -96,7 +97,8 @@ fn parse_msg_file(content: &str) -> Vec { cases } -/// Hashes the first `len_bits` bits of `msg` (FIPS 202 B.1 packing: excess bits in the LSBs). +/// Hashes the first `len_bits` bits of `msg` (FIPS 202 B.1 packing: excess bits in the LSBs, so the +/// final byte is bit-reversed into the API's MSB-first order). fn sha3_bits(msg: &[u8], len_bits: usize) -> Vec { let whole_bytes = len_bits / 8; let partial_bits = len_bits % 8; @@ -106,7 +108,8 @@ fn sha3_bits(msg: &[u8], len_bits: usize) -> Vec { } else { let mut h = H::default(); h.do_update(&msg[..whole_bytes]); - h.do_final_partial_bits(msg[whole_bytes], partial_bits).expect("partial_bits is in 1..=7") + h.do_final_partial_bits(msg[whole_bytes].reverse_bits(), partial_bits) + .expect("partial_bits is in 1..=7") } } @@ -160,18 +163,24 @@ fn run_sha3_monte_file(orientation: &str, filename: &str) { // --------------------------------------------------------------------------------------------- /// SHAKE of the first `len_bits` bits of `msg`, producing `out_bits` bits of output (FIPS 202 B.1 -/// packing on both sides: excess bits in the LSBs of the final byte). +/// packing on both sides: excess bits in the LSBs of the final byte, so the final input byte is +/// bit-reversed into the API's MSB-first order and the final output byte is bit-reversed back). fn shake_bits(msg: &[u8], len_bits: usize, out_bits: usize) -> Vec { let mut x = X::default(); let (whole, partial) = (len_bits / 8, len_bits % 8); x.absorb(&msg[..whole]).expect("absorb before squeeze is infallible"); if partial != 0 { - x.absorb_last_partial_byte(msg[whole], partial).expect("partial is in 1..=7"); + x.absorb_last_partial_byte(msg[whole].reverse_bits(), partial) + .expect("partial is in 1..=7"); } let (out_whole, out_partial) = (out_bits / 8, out_bits % 8); let mut out = x.squeeze(out_whole); if out_partial != 0 { - out.push(x.squeeze_partial_byte_final(out_partial).expect("out_partial is in 1..=7")); + out.push( + x.squeeze_partial_byte_final(out_partial) + .expect("out_partial is in 1..=7") + .reverse_bits(), + ); } out } diff --git a/crypto/sha3/tests/sha3_tests.rs b/crypto/sha3/tests/sha3_tests.rs index 0a3c686f..9a49ba3d 100644 --- a/crypto/sha3/tests/sha3_tests.rs +++ b/crypto/sha3/tests/sha3_tests.rs @@ -621,15 +621,21 @@ pub(crate) mod sha3_test_helpers { let total_bytes = (bits + 7) / 8; let mut result = vec![0u8; total_bytes]; + // Whole bytes are packed per FIPS 202 Appendix B.1 (Algorithm 11, b2h: message bit 8i + j has + // weight 2^j in byte i, i.e. the first bit is the LSB), which is how SHA-3 reads a byte-oriented + // message. for i in 0..full_bytes { let index = i * 8; block[index..(index + 8)].reverse(); result[i] = parse_binary(&block[index..(index + 8)]); } + // The trailing partial byte is packed the way the API takes it: the remaining message bits + // in order from the most significant bit down (ASN.1 BIT STRING order, X.690 s. 8.6.2.1), + // with the unused low bits zero. if total_bytes > full_bytes { - block[(full_bytes * 8)..].reverse(); - result[full_bytes] = parse_binary(&block[(full_bytes * 8)..]); + let partial_bits = bits - full_bytes * 8; + result[full_bytes] = parse_binary(&block[(full_bytes * 8)..]) << (8 - partial_bits); } result diff --git a/crypto/sha3/tests/shake_tests.rs b/crypto/sha3/tests/shake_tests.rs index e10e5c85..3d2f5fba 100644 --- a/crypto/sha3/tests/shake_tests.rs +++ b/crypto/sha3/tests/shake_tests.rs @@ -49,8 +49,9 @@ mod shake_tests { shake.absorb(&[0u8, 1u8, 2u8, 3u8, 4u8]).expect("absorb before squeeze is infallible"); _ = shake.squeeze(3); let out: u8 = shake.squeeze_partial_byte_final(i).expect("Squeeze failed"); - // byte [3] of the stream is 0xFF, so the low `i` bits of it are the low `i` set bits. - assert_eq!(out, ((1u16 << i) - 1) as u8); + // byte [3] of the stream is 0xFF, so its first `i` bits, returned MSB-first, are the top + // `i` set bits. + assert_eq!(out, (0xFF00u16 >> i) as u8); } // success case -- output slice version @@ -59,12 +60,13 @@ mod shake_tests { _ = shake.squeeze(3); let mut out = 0u8; shake.squeeze_partial_byte_final_out(1, &mut out).expect("Squeeze failed"); - assert_eq!(out, 0x01); + assert_eq!(out, 0x80); } /// Regression: squeeze_partial_byte_final() as the *first* squeeze must apply the SHAKE "1111" /// domain suffix (previously it bypassed it and returned raw Keccak output), and must return the - /// low `num_bits` bits of the next output byte (FIPS 202 B.1 bit ordering), zero-extended. + /// first `num_bits` bits of the next output byte (its low bits, FIPS 202 B.1 bit ordering) in the + /// top `num_bits` bits of the result (ASN.1 BIT STRING order), with the unused low bits zero. #[test] fn partial_bit_output_as_first_squeeze_matches_full_output() { let msg = b"abc"; @@ -85,19 +87,25 @@ mod shake_tests { _ = shake.squeeze(skip); } let got = shake.squeeze_partial_byte_final(n).unwrap(); - assert_eq!(got, full & ((1u8 << n) - 1), "skip={skip} n={n}"); - assert_eq!(got >> n, 0, "high bits must be zero"); + assert_eq!( + got, + full.reverse_bits() & ((0xFF00u16 >> n) as u8), + "skip={skip} n={n}" + ); + assert_eq!(got & (0xFFu8 >> n), 0, "unused low bits must be zero"); } } } /// Regression: when the 4 trailing message bits plus the SHAKE "1111" suffix exactly fill a byte, /// the sponge must still switch to squeezing, otherwise the first squeeze appended a second suffix. - /// Vector: NIST CAVP SHA3VS SHAKE128ShortMsg (bit-oriented), Len = 4, Msg = 08. + /// Vector: NIST CAVP SHA3VS SHAKE128ShortMsg (bit-oriented), Len = 4, Msg = 08 (FIPS 202 B.1 + /// packing: message bits 0001 in the low nibble, first bit in the LSB), i.e. 0x10 in the API's + /// MSB-first order. #[test] fn absorb_last_partial_byte_four_bits() { let mut shake = SHAKE128::new(); - shake.absorb_last_partial_byte(0x08, 4).unwrap(); + shake.absorb_last_partial_byte(0x10, 4).unwrap(); assert_eq!( shake.squeeze(16), bouncycastle_hex::decode("d40238024b040a954d9c2c89daf480e5").unwrap(), @@ -129,7 +137,7 @@ mod shake_tests { // actually change the output relative to the byte-aligned message. let mut b = SHAKE128::new(); b.absorb(b"abc").unwrap(); - b.absorb_last_partial_byte(0x7F, 7).unwrap(); + b.absorb_last_partial_byte(0xFE, 7).unwrap(); assert_ne!(b.squeeze(32), SHAKE128::new().hash_xof(b"abc", 32)); } @@ -571,15 +579,21 @@ pub(crate) mod shake_test_helpers { let total_bytes = (bits + 7) / 8; let mut result = vec![0u8; total_bytes]; + // Whole bytes are packed per FIPS 202 Appendix B.1 (Algorithm 11, b2h: message bit 8i + j has + // weight 2^j in byte i, i.e. the first bit is the LSB), which is how SHA-3 reads a byte-oriented + // message. for i in 0..full_bytes { let index = i * 8; block[index..(index + 8)].reverse(); result[i] = parse_binary(&block[index..(index + 8)]); } + // The trailing partial byte is packed the way the API takes it: the remaining message bits + // in order from the most significant bit down (ASN.1 BIT STRING order, X.690 s. 8.6.2.1), + // with the unused low bits zero. if total_bytes > full_bytes { - block[(full_bytes * 8)..].reverse(); - result[full_bytes] = parse_binary(&block[(full_bytes * 8)..]); + let partial_bits = bits - full_bytes * 8; + result[full_bytes] = parse_binary(&block[(full_bytes * 8)..]) << (8 - partial_bits); } result diff --git a/crypto/sm3/Cargo.toml b/crypto/sm3/Cargo.toml new file mode 100644 index 00000000..924fdf7a --- /dev/null +++ b/crypto/sm3/Cargo.toml @@ -0,0 +1,23 @@ +[package] +name = "bouncycastle-sm3" +version.workspace = true +edition.workspace = true + +[dependencies] +bouncycastle-core.workspace = true +bouncycastle-hmac.workspace = true +bouncycastle-utils.workspace = true + +[dev-dependencies] +criterion.workspace = true +bouncycastle-core-test-framework.workspace = true +bouncycastle-hex.workspace = true +bouncycastle-rng.workspace = true + +[[bench]] +name = "sm3_benches" +harness = false + +[[bench]] +name = "hmac_sm3_benches" +harness = false diff --git a/crypto/sm3/benches/hmac_sm3_benches.rs b/crypto/sm3/benches/hmac_sm3_benches.rs new file mode 100644 index 00000000..97cabfbb --- /dev/null +++ b/crypto/sm3/benches/hmac_sm3_benches.rs @@ -0,0 +1,32 @@ +use bouncycastle_core::key_material::{KeyMaterial256, KeyType}; +use bouncycastle_core::traits::{MAC, RNG}; +use bouncycastle_rng as rng; +use bouncycastle_sm3::hmac::HMAC_SM3; +use criterion::{Criterion, Throughput, criterion_group, criterion_main}; +use std::hint::black_box; + +fn bench_hmac_sm3(c: &mut Criterion) { + let mut data_block = [0_u8; 1024]; + rng::DefaultRNG::default().next_bytes_out(&mut data_block).unwrap(); + + let mut big_data: Vec = vec![]; + for _ in 0..16 { + big_data.extend_from_slice(&data_block); + } + + let hmac_key = KeyMaterial256::from_bytes_as_type(&data_block[..32], KeyType::MACKey).unwrap(); + let mut out = [0u8; 32]; + + let mut group = c.benchmark_group("hmac::HMAC_SM3::mac_out() -- 16x1024 one-shot"); + group.throughput(Throughput::Bytes(big_data.len() as u64)); + group.bench_function(format!("{} bytes -- ::hashes()", big_data.len() as u64), |b| { + b.iter(|| { + HMAC_SM3::new(&hmac_key).unwrap().mac_out(black_box(&big_data), &mut out).unwrap(); + black_box(&out); + }) + }); + group.finish(); +} + +criterion_group!(benches, bench_hmac_sm3); +criterion_main!(benches); diff --git a/crypto/sm3/benches/sm3_benches.rs b/crypto/sm3/benches/sm3_benches.rs new file mode 100644 index 00000000..25f407a1 --- /dev/null +++ b/crypto/sm3/benches/sm3_benches.rs @@ -0,0 +1,30 @@ +use criterion::{Criterion, Throughput, criterion_group, criterion_main}; +use std::hint::black_box; + +use bouncycastle_core::traits::{Hash, RNG}; +use bouncycastle_rng as rng; +use bouncycastle_sm3::SM3; + +fn bench_sm3(c: &mut Criterion) { + let mut data = [0_u8; 1024]; + rng::DefaultRNG::default().next_bytes_out(&mut data).unwrap(); + + let mut digest = vec![0; SM3::new().output_len()]; + + let mut group = c.benchmark_group("sm3"); + group.throughput(Throughput::Bytes(16 * 1024)); + group.bench_function("16KiB", |b| { + b.iter(|| { + let mut md = SM3::new(); + for _ in 0..16 { + md.do_update(black_box(&data)); + } + _ = md.do_final_out(&mut digest); + black_box(&digest); + }) + }); + group.finish(); +} + +criterion_group!(benches, bench_sm3); +criterion_main!(benches); diff --git a/crypto/sm3/src/hmac.rs b/crypto/sm3/src/hmac.rs new file mode 100644 index 00000000..96e06dab --- /dev/null +++ b/crypto/sm3/src/hmac.rs @@ -0,0 +1,80 @@ +//! HMAC over SM3, as specified in RFC 2104, taking into account NIST Implementation Guidance in +//! FIPS 140-2 IG A.8 and NIST SP 800-107-r1. +//! +//! Uses [`bouncycastle_hmac`] to provide the HMAC-SM3 instantiation: [`HMAC_SM3`]. +//! +//! HMAC itself is implemented generically in [`bouncycastle_hmac`]; this module supplies the +//! SM3-specific parameters via [`HMACParams`] and publishes the resulting type alias, so that HMAC +//! over SM3 is found in this crate, and [`bouncycastle_hmac`] serves as a utility crate rather than +//! as part of the library's public API. See [`bouncycastle_hmac`] for the full description of the +//! three-phase [`MAC`] lifecycle, key typing and suspend/resume. +//! +//! The key buffer length is the underlying hash's block length: per RFC 2104, a key no longer than +//! the block is used verbatim, and only longer keys are pre-hashed down to the output length, so the +//! buffer must be able to hold a full block. It is taken from [`HashAlgParams::BLOCK_LEN`] -- the +//! 512-bit block GB/T 32905-2016 s. 5.2 pads to -- rather than restated as a literal so the two +//! cannot drift apart. +//! +//! # Usage Examples +//! +//! ``` +//! use bouncycastle_core::key_material::{KeyMaterial256, KeyType}; +//! use bouncycastle_core::traits::MAC; +//! use bouncycastle_sm3::hmac::HMAC_SM3; +//! +//! let key = KeyMaterial256::from_bytes_as_type(&[0x0b; 32], KeyType::MACKey).unwrap(); +//! let tag = HMAC_SM3::new(&key).unwrap().mac(b"Hi There"); +//! assert_eq!(tag.len(), 32); +//! ``` +//! +//! # Security Considerations +//! +//! * Verify with [`MAC::verify`] or [`MAC::do_verify_final`] rather than computing the MAC yourself +//! and comparing: those use a constant-time comparison, while `==` on the byte slices leaks how +//! many leading bytes matched. +//! * Truncating the MAC output below [`MIN_FIPS_DIGEST_LEN`] (4 bytes) is rejected, per FIPS 140-2 +//! IG A.8 / NIST SP 800-107-r1 Section 5.3.3. That is a floor, not a recommendation -- RFC 2104 +//! Section 5 recommends that the output length "be not less than half the length of the hash +//! output ... and not less than 80 bits". +//! * Resuming a suspended HMAC with the wrong key cannot be detected and silently produces a wrong +//! MAC. +//! * SM3 is a Merkle-Damgard construction and so is subject to length extension; `SM3(k || m)` is +//! not a secure MAC and HMAC-SM3 is the right construction for keyed hashing over SM3. + +use crate::{SM3, SUSPENDED_SM3_STATE_LEN}; +use bouncycastle_core::key_material::KeyMaterial; +use bouncycastle_core::traits::{HashAlgParams, SecurityStrength}; +use bouncycastle_hmac::{HMAC, HMACParams}; + +/*** Imports needed for docs ***/ +#[allow(unused_imports)] +use bouncycastle_core::key_material::KeyType; +#[allow(unused_imports)] +use bouncycastle_core::traits::MAC; +#[allow(unused_imports)] +use bouncycastle_hmac::MIN_FIPS_DIGEST_LEN; +/*** end of doc-only imports ***/ + +/*** String constants ***/ +/// Algorithm name string for HMAC-SM3, as used by the factories and CLI. +pub const HMAC_SM3_NAME: &str = "HMAC-SM3"; + +/*** Type aliases ***/ +/// Public type for HMAC using SM3. +#[allow(non_camel_case_types)] +pub type HMAC_SM3 = HMAC::BLOCK_LEN }>; +impl HMACParams for SM3 { + type MACKey = KeyMaterial<{ ::OUTPUT_LEN }>; + const HMAC_ALG_NAME: &'static str = HMAC_SM3_NAME; + const HMAC_MAX_SECURITY_STRENGTH: SecurityStrength = SecurityStrength::_128bit; + /// Assigned by the Chinese OSCCA (GM/T 0006): hmac-sm3 { sm3 2 } = 1.2.156.10197.1.401.2 + const HMAC_OID: &'static [u32] = &[1, 2, 156, 10197, 1, 401, 2]; + const HMAC_OID_DER: &'static [u8] = + &[0x06, 0x09, 0x2A, 0x81, 0x1C, 0xCF, 0x55, 0x01, 0x83, 0x11, 0x02]; +} + +/*** Serialized-state length constants ***/ +// HMAC's suspended state is exactly the inner hasher's state -- the key is deliberately excluded and +// must be re-supplied on resume -- so this is SM3's own state length. +/// Length in bytes of the serialized state of [`HMAC_SM3`]. +pub const SUSPENDED_HMAC_SM3_STATE_LEN: usize = SUSPENDED_SM3_STATE_LEN; diff --git a/crypto/sm3/src/lib.rs b/crypto/sm3/src/lib.rs new file mode 100644 index 00000000..7b114fa1 --- /dev/null +++ b/crypto/sm3/src/lib.rs @@ -0,0 +1,141 @@ +//! Implements the SM3 cryptographic hash function as per GB/T 32905-2016 (also ISO/IEC 10118-3:2018 +//! and IETF draft-shen-sm3-hash-01). +//! +//! SM3 is a 256-bit Merkle–Damgård hash with a 512-bit block, structurally similar to SHA-256 but +//! with different message expansion, round compression functions and constants. +//! +//! # Examples +//! ## Hash +//! Hash functionality is accessed via the [`Hash`] trait, which is implemented by [`SM3`]. +//! +//! The simplest usage is via the one-shot functions. +//! ``` +//! use bouncycastle_core::traits::Hash; +//! use bouncycastle_sm3::SM3; +//! +//! let data: &[u8] = b"abc"; +//! let output: Vec = SM3::new().hash(data); +//! assert_eq!(output[..4], [0x66, 0xc7, 0xf0, 0xf4]); +//! ``` +//! +//! More advanced usage will require creating an SM3 object to hold state between successive calls, +//! for example if input is received in chunks and not all available at the same time: +//! +//! ``` +//! use bouncycastle_core::traits::Hash; +//! use bouncycastle_sm3::SM3; +//! +//! let data: &[u8] = b"\x00\x01\x02\x03\x04\x05\x06\x07\x08\x09\x0A\x0B\x0C\x0D\x0E\x0F +//! \x10\x11\x12\x13\x14\x15\x16\x17\x18\x19\x1A\x1B\x1C\x1D\x1E\x1F"; +//! let mut sm3 = SM3::new(); +//! +//! for chunk in data.chunks(16) { +//! sm3.do_update(chunk); +//! } +//! +//! let output: Vec = sm3.do_final(); +//! ``` +//! +//! It is also possible to provide input where the final byte contains fewer than 8 bits of data +//! (a bit-oriented message, GB/T 32905-2016 s. 5.2). The partial byte is taken as it arrives in the +//! final octet of an ASN.1 BIT STRING: the message bits are its most significant bits, leading bit +//! first, and the low "unused" bits are ignored. The following hashes 16 bytes plus the 3 bits `101`: +//! ``` +//! use bouncycastle_core::traits::Hash; +//! use bouncycastle_sm3::SM3; +//! +//! let data: &[u8] = b"\x00\x01\x02\x03\x04\x05\x06\x07\x08\x09\x0A\x0B\x0C\x0D\x0E\x0F\xA0"; +//! let mut sm3 = SM3::new(); +//! sm3.do_update(&data[..16]); +//! let output: Vec = sm3.do_final_partial_bits(data[16], 3).expect("num_partial_bits is in 0..=7"); +//! ``` +//! +//! ## HMAC +//! See [hmac]. +//! +//! # Memory Usage +//! +//! No heap memory is used by the algorithm itself; the `Vec`-returning convenience methods +//! allocate only the output buffer, and the `*_out` variants allocate nothing. +//! +//! | Object | Size (bytes) | +//! |----------------------------|--------------| +//! | `SM3` | 112 | +//! | Suspended state | 108 | +//! +//! The object holds the 8-word chaining value plus one 64-byte block of buffered input. The +//! compression function additionally uses a 68-word message schedule (272 bytes) on the stack for +//! the duration of a call. +//! +//! # Security Considerations +//! +//! * SM3 offers 128 bits of collision resistance and 256 bits of preimage resistance. +//! * SM3 is a Merkle–Damgård construction and is therefore subject to length-extension: +//! `H(k || m)` is not a secure MAC. Use HMAC ([`crate::hmac`]) for keyed hashing. +//! * The chaining value and input buffer are held in [`bouncycastle_utils::secret::Secret`] and +//! zeroized on drop. Transient copies (working variables and message schedule) in registers/stack +//! locals during compression are not zeroized. +//! * The implementation contains no data-dependent branches or table lookups. +//! * Messages up to 2^64 bytes are supported (the specification allows 2^64 bits). +//! +//! # Suspending and resuming execution +//! +//! When hashing a large message, it can be advantageous to be able to suspend the operation +//! to a cache and resume it later; for example if waiting for the message to stream over a slow network +//! connection. For this reason, [`SM3`] impls [`Suspendable`]. +//! +//! ```rust +//! use bouncycastle_sm3::SM3; +//! use bouncycastle_core::traits::{Hash, Suspendable}; +//! +//! let msg_part1 = b"The quick brown fox"; +//! let msg_part2 = b" jumped over the lazy dog"; +//! +//! let mut sm3 = SM3::new(); +//! sm3.do_update(msg_part1); +//! +//! // suspend the in-progress hash while "waiting" for the second part of the message. +//! let serialized_state = sm3.suspend(); +//! +//! // ... later, possibly on another host: resume from the serialized state. +//! let mut sm3_resumed = SM3::from_suspended(serialized_state).unwrap(); +//! sm3_resumed.do_update(msg_part2); +//! let h: Vec = sm3_resumed.do_final(); +//! ``` + +// todo #![no_std] +// waiting for the no_std refactor that removes the `-> Vec` from core::traits::Hash + +#![forbid(unsafe_code)] +#![forbid(missing_docs)] + +mod sm3; + +pub mod hmac; + +pub use self::sm3::{SM3, SUSPENDED_SM3_STATE_LEN}; +use bouncycastle_core::traits::{Algorithm, AlgorithmOID, HashAlgParams, SecurityStrength}; + +/*** Imports needed for docs ***/ +#[allow(unused_imports)] +use bouncycastle_core::traits::{Hash, Suspendable}; + +/// Algorithm name string for SM3, as used by the factories and CLI. +pub const SM3_NAME: &str = "SM3"; + +impl Algorithm for SM3 { + const ALG_NAME: &'static str = SM3_NAME; + const MAX_SECURITY_STRENGTH: SecurityStrength = SecurityStrength::_128bit; +} + +/// GB/T 32905-2016: 256-bit digest, 512-bit block. +impl HashAlgParams for SM3 { + const OUTPUT_LEN: usize = 32; + const BLOCK_LEN: usize = 64; +} + +/// Assigned by the Chinese OSCCA: sm3 { 1 2 156 10197 1 401 } +impl AlgorithmOID for SM3 { + const OID: &'static [u32] = &[1, 2, 156, 10197, 1, 401]; + const OID_DER: &'static [u8] = &[0x06, 0x08, 0x2A, 0x81, 0x1C, 0xCF, 0x55, 0x01, 0x83, 0x11]; +} diff --git a/crypto/sm3/src/sm3.rs b/crypto/sm3/src/sm3.rs new file mode 100644 index 00000000..a53c9fe7 --- /dev/null +++ b/crypto/sm3/src/sm3.rs @@ -0,0 +1,378 @@ +use bouncycastle_core::errors::{HashError, SuspendableError}; +use bouncycastle_core::suspendable_state::{add_lib_ver, check_lib_ver}; +use bouncycastle_core::traits::{Hash, SecurityStrength, Suspendable}; +use bouncycastle_utils::{min, secret::Secret}; +use core::slice; + +/// GB/T 32905-2016 s. 4.1: initial value IV. +const SM3_IV: [u32; 8] = [ + 0x7380166F, 0x4914B2B9, 0x172442D7, 0xDA8A0600, 0xA96F30BC, 0x163138AA, 0xE38DEE4D, 0xB0FB0E4E, +]; + +/// GB/T 32905-2016 s. 5.1: SM3 takes "a message m of length l (where l < 2^64) in bits", so the +/// longest whole-byte message it covers is 2^61 - 1 bytes. +const MAX_MESSAGE_BYTES: u64 = (1 << 61) - 1; + +/// GB/T 32905-2016 s. 4.2: constants T_j = 79CC4519 for 0 <= j <= 15, 7A879D8A for 16 <= j <= 63. +/// The round function uses (T_j <<< (j mod 32)), which is precomputed here at compile time. +/// Mutants note: `u32::rotate_left` reduces its argument modulo 32 itself, so replacing `j % 32` +/// with `j + 32` is an equivalent mutant; and `+=` -> `*=` on the loop counter is an infinite loop +/// in `const` evaluation, reported as a build timeout. +const SM3_T: [u32; 64] = { + let mut t = [0u32; 64]; + let mut j = 0; + while j < 64 { + let base: u32 = if j < 16 { 0x79CC4519 } else { 0x7A879D8A }; + t[j] = base.rotate_left((j % 32) as u32); + j += 1; + } + t +}; + +/// GB/T 32905-2016 s. 4.3: boolean functions FF_j and GG_j for 0 <= j <= 15. +#[inline] +fn ff0(x: u32, y: u32, z: u32) -> u32 { + x ^ y ^ z +} + +/// GB/T 32905-2016 s. 4.3: FF_j for 16 <= j <= 63 (majority). +/// Mutants note: majority can be written with `|` or `^` between the three terms (FIPS 180-4 writes +/// Maj with XOR), so a surviving `|`/`^` swap in this function is an equivalent mutant. +#[inline] +fn ff1(x: u32, y: u32, z: u32) -> u32 { + (x & y) | (x & z) | (y & z) +} + +/// GB/T 32905-2016 s. 4.3: GG_j for 16 <= j <= 63 (choice). +/// Mutants note: the two masks are disjoint, so `|` and `^` give identical results here; a +/// surviving `|`/`^` swap in this function is an equivalent mutant. +#[inline] +fn gg1(x: u32, y: u32, z: u32) -> u32 { + (x & y) | (!x & z) +} + +/// GB/T 32905-2016 s. 4.4: permutation P0(X) = X ^ (X <<< 9) ^ (X <<< 17). +#[inline] +fn p0(x: u32) -> u32 { + x ^ x.rotate_left(9) ^ x.rotate_left(17) +} + +/// GB/T 32905-2016 s. 4.4: permutation P1(X) = X ^ (X <<< 15) ^ (X <<< 23). +#[inline] +fn p1(x: u32) -> u32 { + x ^ x.rotate_left(15) ^ x.rotate_left(23) +} + +/// The SM3 cryptographic hash function (GB/T 32905-2016). +/// +/// See the [crate-level documentation](crate) for usage. +#[derive(Clone)] +pub struct SM3 { + /// Chaining value V^(i), 8 big-endian words. + v: Secret<[u32; 8]>, + /// Total number of message bytes absorbed so far. Supports messages up to 2^64 bytes. + byte_count: u64, + /// Buffered input that has not yet formed a whole block. + x_buf: Secret<[u8; 64]>, + /// Number of valid bytes in `x_buf` (always < 64). + x_buf_off: usize, +} + +impl SM3 { + /// Creates a new SM3 instance, ready for use. + pub fn new() -> Self { + let mut v = Secret::<[u32; 8]>::new(); + v.copy_from_slice(&SM3_IV); + Self { v, byte_count: 0, x_buf: Secret::new(), x_buf_off: 0 } + } + + /// GB/T 32905-2016 s. 5.3: compression function V^(i+1) = CF(V^(i), B^(i)) for each block. + /// + /// Takes the chaining value rather than `&mut self` so callers can pass `self.x_buf` as the + /// block without a conflicting borrow. + fn compress(v: &mut [u32; 8], blocks: &[[u8; 64]]) { + // s. 5.3.2 message expansion: W_0..W_67. W'_j = W_j ^ W_{j+4} is computed on the fly. + let mut w = [0u32; 68]; + + for block in blocks { + let (chunks, _remainder) = block.as_chunks::<4>(); + for (wj, bytes) in w[..16].iter_mut().zip(chunks) { + *wj = u32::from_be_bytes(*bytes); + } + for j in 16..68 { + // W_j = P1(W_{j-16} ^ W_{j-9} ^ (W_{j-3} <<< 15)) ^ (W_{j-13} <<< 7) ^ W_{j-6} + w[j] = p1(w[j - 16] ^ w[j - 9] ^ w[j - 3].rotate_left(15)) + ^ w[j - 13].rotate_left(7) + ^ w[j - 6]; + } + + // s. 5.3.3 compression: ABCDEFGH <- V^(i) + let [mut a, mut b, mut c, mut d, mut e, mut f, mut g, mut h] = *v; + + // One round of s. 5.3.3. `$ff` / `$gg` select the boolean functions for the round range. + macro_rules! sm3_round { + ($j:expr, $ff:ident, $gg:ident) => { + // SS1 = ((A <<< 12) + E + (T_j <<< (j mod 32))) <<< 7 + let a12 = a.rotate_left(12); + let ss1 = a12.wrapping_add(e).wrapping_add(SM3_T[$j]).rotate_left(7); + // SS2 = SS1 ^ (A <<< 12) + let ss2 = ss1 ^ a12; + // TT1 = FF_j(A,B,C) + D + SS2 + W'_j where W'_j = W_j ^ W_{j+4} + let tt1 = $ff(a, b, c) + .wrapping_add(d) + .wrapping_add(ss2) + .wrapping_add(w[$j] ^ w[$j + 4]); + // TT2 = GG_j(E,F,G) + H + SS1 + W_j + let tt2 = $gg(e, f, g).wrapping_add(h).wrapping_add(ss1).wrapping_add(w[$j]); + // D = C; C = B <<< 9; B = A; A = TT1; H = G; G = F <<< 19; F = E; E = P0(TT2) + d = c; + c = b.rotate_left(9); + b = a; + a = tt1; + h = g; + g = f.rotate_left(19); + f = e; + e = p0(tt2); + }; + } + + // Rounds 0..=15 use FF_0 = GG_0 = XOR (ff0 serves both). + for j in 0..16 { + sm3_round!(j, ff0, ff0); + } + // Rounds 16..=63 use the majority / choice functions. + for j in 16..64 { + sm3_round!(j, ff1, gg1); + } + + // V^(i+1) = ABCDEFGH ^ V^(i) + v[0] ^= a; + v[1] ^= b; + v[2] ^= c; + v[3] ^= d; + v[4] ^= e; + v[5] ^= f; + v[6] ^= g; + v[7] ^= h; + } + } + + /// Pads and compresses the final block(s) as per GB/T 32905-2016 s. 5.2, then writes the digest. + /// + /// The `num_partial_bits` (0..=7, validated by the caller) trailing message bits are the most + /// significant bits of `partial_byte`, leading bit first: the ASN.1 BIT STRING order of + /// X.690 s. 8.6.2.1, which is also how GB/T 32905-2016 (like FIPS 180-4) numbers the bits of a + /// message byte. So they are used in place, the low `8 - num_partial_bits` bits are ignored, and + /// the mandatory "1" padding bit follows the message bits immediately in the same byte. + /// + /// Returns the number of bytes written (`min(output.len(), 32)`); a shorter output buffer + /// truncates the digest, a longer one is zero-filled past the digest. + fn do_final_internal( + mut self, + partial_byte: u8, + num_partial_bits: usize, + output: &mut [u8], + ) -> usize { + debug_assert!(num_partial_bits <= 7); + output.fill(0); + + let n = *min(&output.len(), &32); + + // s. 5.2: final message byte = [the top num_partial_bits bits of partial_byte] [1] [0...]. With + // no partial bits this is 0x80. The mask is built in u16 so that the 8-bit shift for + // num_partial_bits == 0 cannot overflow (0xFF00 >> 0 truncates to 0x00). + let mask = (0xFF00u16 >> num_partial_bits) as u8; + // Mutants note: the masked message bits and the padding bit occupy disjoint bit positions, so + // `|` and `^` give identical results here; a surviving `|`/`^` swap is an equivalent mutant. + let pad_byte = (partial_byte & mask) | (0x80u8 >> num_partial_bits); + + self.x_buf[self.x_buf_off] = pad_byte; + self.x_buf_off += 1; + + // ... then k zero bits so that l + 1 + k = 448 mod 512. If the 64-bit length field no longer + // fits in this block, zero-fill and compress, then start a fresh block. + if self.x_buf_off > 56 { + self.x_buf[self.x_buf_off..].fill(0x00); + Self::compress(&mut self.v, slice::from_ref(&self.x_buf)); + self.x_buf_off = 0; + } + self.x_buf[self.x_buf_off..56].fill(0x00); + + // ... then the 64-bit big-endian message length l in bits. byte_count is a byte counter, so + // l = (byte_count << 3) | num_partial_bits (the low three bits of byte_count << 3 are zero). + // Mutants note: the low three bits of byte_count << 3 are zero, so `|` and `^` give identical + // results here; a surviving `|`/`^` swap is an equivalent mutant. + let bit_len: u64 = (self.byte_count << 3) | (num_partial_bits as u64); + self.x_buf[56..64].copy_from_slice(&bit_len.to_be_bytes()); + Self::compress(&mut self.v, slice::from_ref(&self.x_buf)); + + // s. 5.4: the digest is V^(n) as 8 big-endian words. + let v = &self.v; + for i in 0..(n / 4) { + output[i * 4..i * 4 + 4].copy_from_slice(&v[i].to_be_bytes()); + } + if !n.is_multiple_of(4) { + output[((n / 4) * 4)..((n / 4) * 4) + (n % 4)] + .copy_from_slice(&v[n / 4].to_be_bytes()[0..(n % 4)]); + } + + n + } +} + +impl Default for SM3 { + fn default() -> Self { + Self::new() + } +} + +impl Hash for SM3 { + /// GB/T 32905-2016 s. 5.2: 512-bit blocks. + fn block_bitlen(&self) -> usize { + 512 + } + + fn output_len(&self) -> usize { + 32 + } + + fn hash(self, data: &[u8]) -> Vec { + let mut output = vec![0u8; 32]; + self.hash_out(data, &mut output); + output + } + + fn hash_out(mut self, data: &[u8], output: &mut [u8]) -> usize { + self.do_update(data); + self.do_final_out(output) + } + + fn do_update(&mut self, block: &[u8]) { + let len = block.len(); + + // GB/T 32905-2016 s. 5.2: do_final_internal encodes l in a 64-bit field as + // `byte_count << 3`, and a left shift discards rather than panics, so past + // MAX_MESSAGE_BYTES the digest would silently be that of a message 2^64 bits shorter. + debug_assert!( + self.byte_count.checked_add(len as u64).is_some_and(|total| total <= MAX_MESSAGE_BYTES), + "message exceeds the SM3 limit of {MAX_MESSAGE_BYTES} bytes" + ); + self.byte_count += len as u64; + + let available = 64 - self.x_buf_off; + if len < available { + self.x_buf[self.x_buf_off..self.x_buf_off + len].copy_from_slice(block); + self.x_buf_off += len; + return; + } + + let mut block = block; + if self.x_buf_off != 0 { + self.x_buf[self.x_buf_off..].copy_from_slice(&block[..available]); + block = &block[available..]; + Self::compress(&mut self.v, slice::from_ref(&self.x_buf)); + } + + let (chunks, remainder) = block.as_chunks::<64>(); + Self::compress(&mut self.v, chunks); + + let remaining = remainder.len(); + self.x_buf[..remaining].copy_from_slice(remainder); + self.x_buf_off = remaining; + } + + fn do_final(self) -> Vec { + let mut output = vec![0u8; 32]; + self.do_final_out(&mut output); + output + } + + fn do_final_out(self, output: &mut [u8]) -> usize { + // A whole-byte message is the zero-partial-bits case of the general padding. + self.do_final_internal(0, 0, output) + } + + fn do_final_partial_bits( + self, + partial_byte: u8, + num_partial_bits: usize, + ) -> Result, HashError> { + let mut output = vec![0u8; 32]; + self.do_final_partial_bits_out(partial_byte, num_partial_bits, &mut output)?; + Ok(output) + } + + /// GB/T 32905-2016 s. 5.2: bit-oriented messages. The `num_partial_bits` most significant bits of + /// `partial_byte` (ASN.1 BIT STRING order, leading bit first) are appended to the message before + /// padding; the low bits are ignored. `num_partial_bits == 0` behaves exactly like + /// [`Hash::do_final_out`]. + fn do_final_partial_bits_out( + self, + partial_byte: u8, + num_partial_bits: usize, + output: &mut [u8], + ) -> Result { + if num_partial_bits > 7 { + return Err(HashError::InvalidLength("num_partial_bits must be in the range [0,7]")); + } + Ok(self.do_final_internal(partial_byte, num_partial_bits, output)) + } + + fn max_security_strength(&self) -> SecurityStrength { + SecurityStrength::_128bit + } +} + +/// Length in bytes of the serialized state of SM3. +/// +/// Layout (after the 3-byte library version header; all integers little-endian): +/// [0 .. 32) v [u32; 8] +/// [32 .. 40) byte_count u64 +/// [40 .. 104) x_buf [u8; 64] +/// [104 .. 105) x_buf_off u8 (always < 64) +pub const SUSPENDED_SM3_STATE_LEN: usize = 3 + 105; + +impl Suspendable for SM3 { + fn suspend(self) -> [u8; SUSPENDED_SM3_STATE_LEN] { + let mut out_to_return = [0u8; SUSPENDED_SM3_STATE_LEN]; + + // infallible: add_lib_ver returns a slice of exactly SUSPENDED_SM3_STATE_LEN - 3 = 105 bytes. + let out: &mut [u8; 105] = add_lib_ver(&mut out_to_return).try_into().unwrap(); + + for i in 0..8 { + out[i * 4..(i * 4) + 4].copy_from_slice(&self.v[i].to_le_bytes()); + } + out[32..40].copy_from_slice(&self.byte_count.to_le_bytes()); + out[40..104].copy_from_slice(&*self.x_buf); + debug_assert!(self.x_buf_off < 64); + out[104] = self.x_buf_off as u8; + + out_to_return + } + + fn from_suspended( + serialized_state: [u8; SUSPENDED_SM3_STATE_LEN], + ) -> Result { + // check the version tag. At the moment, we have no not_before version to specify. + // infallible: check_lib_ver returns a slice of exactly SUSPENDED_SM3_STATE_LEN - 3 = 105 bytes. + let input: &[u8; 105] = check_lib_ver(&serialized_state, None)?.try_into().unwrap(); + + let mut v = Secret::<[u32; 8]>::new(); + for i in 0..8 { + // infallible: a 4-byte slice into a [u8; 4] + v[i] = u32::from_le_bytes(input[i * 4..(i * 4) + 4].try_into().unwrap()); + } + // infallible: an 8-byte slice into a [u8; 8] + let byte_count = u64::from_le_bytes(input[32..40].try_into().unwrap()); + + let mut x_buf = Secret::<[u8; 64]>::new(); + x_buf.copy_from_slice(&input[40..104]); + + let x_buf_off = input[104] as usize; + if x_buf_off >= 64 { + return Err(SuspendableError::InvalidData); + } + + Ok(SM3 { v, byte_count, x_buf, x_buf_off }) + } +} diff --git a/crypto/sm3/tests/sm3_tests.rs b/crypto/sm3/tests/sm3_tests.rs new file mode 100644 index 00000000..ead260c5 --- /dev/null +++ b/crypto/sm3/tests/sm3_tests.rs @@ -0,0 +1,240 @@ +#[cfg(test)] +mod sm3_tests { + use bouncycastle_core::errors::{HashError, SuspendableError}; + use bouncycastle_core::traits::{ + Algorithm, AlgorithmOID, Hash, HashAlgParams, SecurityStrength, + }; + use bouncycastle_core_test_framework::DUMMY_SEED; + use bouncycastle_core_test_framework::hash::TestFrameworkHash; + use bouncycastle_hex as hex; + use bouncycastle_sm3::*; + + fn h(s: &str) -> Vec { + hex::decode(s).unwrap() + } + + /// Runs the shared Hash-trait conformance suite against known answers. + /// The first two are the standard vectors from GB/T 32905-2016 Appendix A; the rest are the + /// bc-java SM3DigestTest vectors and digests of DUMMY_SEED generated with openssl and confirmed + /// with bc-java's `SM3Digest`. + #[test] + fn core_test_framework_hash() { + let test_framework = TestFrameworkHash::new(); + + test_framework.test_hash::( + b"abc", + &h("66c7f0f462eeedd9d1f2d46bdc10e4e24167c4875cf2f7a2297da02b8f4ba8e0"), + ); + test_framework.test_hash::( + b"abcdabcdabcdabcdabcdabcdabcdabcdabcdabcdabcdabcdabcdabcdabcdabcd", + &h("debe9ff92275b8a138604889c18e5a4d6fdb70e5387e5765293dcba39c0c5732"), + ); + test_framework.test_hash::( + b"", + &h("1ab21d8355cfa17f8e61194831e81a8f22bec8c728fefb747ed035eb5082aa2b"), + ); + test_framework.test_hash::( + b"a", + &h("623476ac18f65a2909e43c7fec61b49c7e764a91a18ccb82f1917a29c86c5e88"), + ); + test_framework.test_hash::( + b"abcdefghijklmnopqrstuvwxyz", + &h("b80fe97a4da24afc277564f66a359ef440462ad28dcc6d63adb24d5c20a61595"), + ); + test_framework.test_hash::( + &DUMMY_SEED[..512], + &h("b21f830dca06be8b678cf987f26b9a436e1b427963b4450332f01270bd2df75c"), + ); + test_framework.test_hash::( + DUMMY_SEED, + &h("1f00bad6a72e851e0f6e94fd317f97b74d5fbc4c090aefb91e7554e3f9c8c7fb"), + ); + } + + /// bc-java SM3DigestTest "Additional vectors for GMSSL": the SM2 Z_A value from GM/T 0003.5 (also + /// checked against openssl `dgst -sm3`). + #[test] + fn bc_java_vectors() { + let msg = h(concat!( + "0090", + "414C494345313233405941484F4F2E434F4D", + "787968B4FA32C3FD2417842E73BBFEFF2F3C848B6831D7E0EC65228B3937E498", + "63E4C6D3B23B0C849CF84241484BFE48F61D59A5B16BA06E6E12D1DA27C5249A", + "421DEBD61B62EAB6746434EBC3CC315E32220B3BADD50BDC4C4E6C147FEDD43D", + "0680512BCBB42C07D47349D2153B70C4E5D7FDFCBFA36EA1A85841B9E46E09A2", + "0AE4C7798AA0F119471BEE11825BE46202BB79E2A5844495E97C04FF4DF2548A", + "7C0240F88F1CD4E16352A73C17B7F16F07353E53A176D684A9FE0C6BB798E857", + )); + assert_eq!( + SM3::new().hash(&msg), + h("f4a38489e32b45b6f876e3ac2168ca392362dc8f23459c1d1146fc3dbfb7bc9a") + ); + } + + /// Padding boundaries (GB/T 32905-2016 s. 5.2): message lengths around the 56- and 64-byte + /// points where the length field does / does not fit in the current block. Expected values + /// generated with openssl `dgst -sm3` over prefixes of DUMMY_SEED and confirmed with bc-java's + /// `SM3Digest`. + #[test] + fn padding_boundaries() { + for (len, expected) in [ + (55, "a79cf9dcee3404abf7f769698201647fd9d3ff61d629d0f58bb4b5579a427db8"), + (56, "62f7363b15f4de76dd925c493b9d6d00d4ba0ef2a1f334c1d0f13b293aeb40d1"), + (63, "6165e4cbb15cde01c6226e0015a47f710f8f8e1f2c296700033bb34d9212109c"), + (64, "93566f236d157aae078d1ddb5cebdbba1520b5142e22a8915564345ba2ae1d63"), + (65, "c886e6814be748285a10b28ae62ddacd85db830cd2cf3a2bfa2f729c15f63618"), + (119, "8f3ea392a89a7119982d6634660db1a95f35d68267a2235e3255998a857f4fbf"), + (128, "a9e7985473ca09df1510d83b572f72375430756c4a661b00724afeb8b75dd0a5"), + ] { + assert_eq!(SM3::new().hash(&DUMMY_SEED[..len]), h(expected), "len={len}"); + + // and the same via byte-at-a-time streaming, which exercises every x_buf_off value + let mut sm3 = SM3::new(); + for b in &DUMMY_SEED[..len] { + sm3.do_update(core::slice::from_ref(b)); + } + assert_eq!(sm3.do_final(), h(expected), "streaming len={len}"); + } + } + + #[test] + fn test_constants() { + assert_eq!(SM3::OUTPUT_LEN, 32); + assert_eq!(SM3::BLOCK_LEN, 64); + assert_eq!(SM3::new().block_bitlen(), 512); + assert_eq!(SM3::new().output_len(), 32); + } + + #[test] + fn test_algorithm() { + assert_eq!(SM3::ALG_NAME, SM3_NAME); + assert_eq!(SM3_NAME, "SM3"); + assert_eq!(SM3::OID, &[1, 2, 156, 10197, 1, 401]); + assert_eq!(SM3::OID_DER, &[0x06, 0x08, 0x2A, 0x81, 0x1C, 0xCF, 0x55, 0x01, 0x83, 0x11]); + } + + #[test] + fn test_security_strength() { + assert_eq!(SM3::MAX_SECURITY_STRENGTH, SecurityStrength::_128bit); + assert_eq!(SM3::default().max_security_strength(), SecurityStrength::_128bit); + } + + /// GB/T 32905-2016 s. 5.2: bit-oriented messages. Zero partial bits must equal the byte-oriented + /// digest; more than 7 partial bits is rejected; only the top bits of the partial byte matter; + /// and the pad byte spilling into a second block must not break. + #[test] + fn partial_bits() { + let mut a = SM3::new(); + a.do_update(b"abc"); + assert_eq!(a.do_final_partial_bits(0xFF, 0).unwrap(), SM3::new().hash(b"abc")); + + for bad in [8usize, 9, 16, 64, usize::MAX] { + let mut sm3 = SM3::new(); + sm3.do_update(b"abc"); + assert!( + matches!(sm3.do_final_partial_bits(0xFF, bad), Err(HashError::InvalidLength(_))), + "n={bad}" + ); + let mut out = [0u8; 32]; + assert!(matches!( + SM3::new().do_final_partial_bits_out(0xFF, bad, &mut out), + Err(HashError::InvalidLength(_)) + )); + } + + for n in 1..=7usize { + let mask = (0xFF00u16 >> n) as u8; + let x = SM3::new().do_final_partial_bits(0xA5, n).unwrap(); + let y = SM3::new().do_final_partial_bits(0xA5 & mask, n).unwrap(); + let z = SM3::new().do_final_partial_bits(0xA5 ^ 0x80, n).unwrap(); + assert_eq!(x, y, "n={n}"); + assert_ne!(x, z, "n={n}: the leading bit must change the digest"); + assert_ne!(x, SM3::new().hash(&[]), "n={n}"); + assert_ne!(x, SM3::new().hash(&[0xA5 & mask]), "n={n}"); + } + + for len in [55usize, 56, 63, 64, 119, 128] { + let mut sm3 = SM3::new(); + sm3.do_update(&vec![0x5Au8; len]); + let mut out = [0u8; 32]; + assert_eq!(sm3.do_final_partial_bits_out(0xC0, 2, &mut out).unwrap(), 32, "len={len}"); + } + } + + /// Bit-oriented known answers. Neither openssl nor bc-java expose a bit-length SM3 API, so the + /// expected values come from an independent pure-Python implementation of GB/T 32905-2016 with + /// bit-length padding, itself checked against `openssl dgst -sm3` on byte-aligned inputs. + /// `(prefix, partial_byte, bits, digest)`, where the `bits` message bits are the top bits of + /// `partial_byte` (ASN.1 BIT STRING order). + #[test] + fn partial_bits_known_answers() { + let cases: [(&[u8], u8, usize, &str); 6] = [ + (b"", 0x80, 1, "985ffe9568be96328729b1c16631e9328d356432413d7556a646b9eefe479b9e"), + (b"", 0xA8, 5, "469dd7b688a7b98d6362a8e2488a148cb4231bc196b796eee9652cb9044f3dcd"), + (b"abc", 0xfe, 7, "5ad9f5745671e4a49f6704fdadff8cc2ff8a9683d1c7c0810a5dd7db367e9d74"), + ( + &[0x5a; 55], + 0xC0, + 2, + "65985be43230ee70a939d38e34a88198e0d63bb307081459d8d75541d54a382e", + ), + ( + &[0x5a; 111], + 0xA0, + 3, + "8dfb4b90e5f899286782c9b192b67c5ebfbbab5a10d827d2518509307b7877c3", + ), + ( + &DUMMY_SEED[..64], + 0xF0, + 4, + "30e64a364406c1ac354ad17845b4df681de5bad9a1b41e996921a6f5effbf85b", + ), + ]; + for (prefix, partial_byte, bits, expected) in cases { + let mut sm3 = SM3::new(); + sm3.do_update(prefix); + assert_eq!( + sm3.do_final_partial_bits(partial_byte, bits).unwrap(), + h(expected), + "{}/{bits}", + prefix.len() + ); + } + } + + #[test] + fn suspendable_state() { + use bouncycastle_core::traits::Suspendable; + use bouncycastle_core_test_framework::suspendable_state::TestFrameworkSuspendableState; + + let str = "Colorless green ideas sleep furiously"; + + let mut sm3 = SM3::new(); + sm3.do_update(str.as_bytes()); + + // do the default tests + let test_framework = TestFrameworkSuspendableState::new(); + test_framework.test(&sm3); + + // now let's serialize the in-progress state + let serialized_state = sm3.clone().suspend(); + assert_eq!(serialized_state.len(), SUSPENDED_SM3_STATE_LEN); + + // finish the hash + let output = sm3.do_final(); + + // then load from state and finish the hash and make sure we get the same thing + let sm3_from_state = SM3::from_suspended(serialized_state).unwrap(); + let output2 = sm3_from_state.do_final(); + assert_eq!(output, output2); + + // also, give it a busted x_buf_off, just to satisfy mutants that that's been tested + let mut busted_state = serialized_state; + busted_state[3 + 104] = 65; + match SM3::from_suspended(busted_state) { + Err(SuspendableError::InvalidData) => { /* good */ } + _ => panic!("Expected an error"), + } + } +} diff --git a/mem_usage_benches/Cargo.toml b/mem_usage_benches/Cargo.toml index a3623aac..ae00b642 100644 --- a/mem_usage_benches/Cargo.toml +++ b/mem_usage_benches/Cargo.toml @@ -9,12 +9,16 @@ bouncycastle.workspace = true [[bin]] name = "bench_mldsa_mem_usage" -path = "bench_mldsa_mem_usage.rs" +path = "src/bench_mldsa_mem_usage.rs" [[bin]] name = "bench_mlkem_mem_usage" -path = "bench_mlkem_mem_usage.rs" +path = "src/bench_mlkem_mem_usage.rs" [[bin]] name = "bench_sha3_mem_usage" -path = "bench_sha3_mem_usage.rs" +path = "src/bench_sha3_mem_usage.rs" + +[[bin]] +name = "bench_aes_mem_usage" +path = "src/bench_aes_mem_usage.rs" diff --git a/mem_usage_benches/src/bench_aes_mem_usage.rs b/mem_usage_benches/src/bench_aes_mem_usage.rs new file mode 100644 index 00000000..3cf47b5c --- /dev/null +++ b/mem_usage_benches/src/bench_aes_mem_usage.rs @@ -0,0 +1,135 @@ +//! The purpose of this binary is to perform a single run of the primitive under test so that +//! its peak memory usage can be measured with: +//! +//! ```text +//! valgrind --tool=massif --heap=no --stacks=yes -- target/release/bench_aes_mem_usage > /dev/null +//! +//! ms_print massif.out.* +//! ``` +//! +//! or, shoved all into one line: +//! +//! ```text +//! clear; clear; valgrind --tool=massif --heap=no --stacks=yes -- target/release/bench_aes_mem_usage > /dev/null; ms_print massif.out.*; rm massif.out.* +//! ``` +//! +//! Make sure you build in release mode! +//! +//! Note: print!() is used to force the compiler not to optimize away the actual code. +//! The important stuff for benchmarking goes to stderr so the junk can be piped to /dev/null. +//! +//! Main is at the bottom, and controls which of these actually runs -- measure one at a time, +//! because massif reports the peak across the whole process. +//! +//! # What to expect +//! +//! Unlike ML-KEM and ML-DSA, AES has no interesting stack profile: there is no polynomial +//! arithmetic and no sampling, so peak usage is a small constant plus the key schedule. The +//! numbers worth recording in the crate docs are the ones `print_struct_sizes` prints -- the +//! persistent size of each engine -- and the confirmation that per-block work is a fixed, small +//! amount of stack independent of key length. +//! +//! The point of comparison is that a table-driven AES adds 256 B (`AESLightEngine`) to 8 KiB +//! (T-tables) of static data on top of these numbers; this implementation adds zero. + +#![allow(dead_code)] +#![allow(unused_imports)] + +use bouncycastle::aes_lowmemory::{Aes128, Aes192, Aes256}; +use bouncycastle::core::key_material::{KeyMaterial, KeyType}; + +/// This exists so /usr/bin/time can measure the base memory footprint of the harness itself. +fn bench_do_nothing() { + eprintln!("DoNothing"); + + print!("{}", 1 + 1); +} + +/// Prints the in-memory size of each engine, i.e. the persistent cost of holding a key schedule. +fn print_struct_sizes() { + use core::mem::size_of; + + // FIPS 197 Sec 5.2: the schedule is 4 * (Nr + 1) words, so 176 / 208 / 240 bytes. The + // bit-sliced form is stored compressed, so bit-slicing adds nothing to these. + println!("size_of: {}", size_of::()); + println!("size_of: {}", size_of::()); + println!("size_of: {}", size_of::()); +} + +fn key() -> KeyMaterial { + // A fixed non-zero key: an all-zero buffer would be tagged KeyType::Zeroized and rejected. + let mut bytes = [0u8; N]; + for (i, b) in bytes.iter_mut().enumerate() { + *b = (i as u8).wrapping_mul(7).wrapping_add(1); + } + KeyMaterial::::from_bytes_as_type(&bytes, KeyType::SymmetricCipherKey).unwrap() +} + +fn bench_aes128_key_expansion() { + eprintln!("Aes128::new (key expansion)"); + + let aes = Aes128::new(&key::<16>()).unwrap(); + print!("{aes:?}"); +} + +fn bench_aes192_key_expansion() { + eprintln!("Aes192::new (key expansion)"); + + let aes = Aes192::new(&key::<24>()).unwrap(); + print!("{aes:?}"); +} + +fn bench_aes256_key_expansion() { + eprintln!("Aes256::new (key expansion)"); + + let aes = Aes256::new(&key::<32>()).unwrap(); + print!("{aes:?}"); +} + +fn bench_aes128_encrypt_block() { + eprintln!("Aes128::encrypt_block"); + + let aes = Aes128::new(&key::<16>()).unwrap(); + let mut block = [0x11u8; 16]; + aes.encrypt_block(&mut block); + print!("{block:x?}"); +} + +fn bench_aes256_encrypt_block() { + eprintln!("Aes256::encrypt_block"); + + let aes = Aes256::new(&key::<32>()).unwrap(); + let mut block = [0x11u8; 16]; + aes.encrypt_block(&mut block); + print!("{block:x?}"); +} + +fn bench_aes256_decrypt_block() { + eprintln!("Aes256::decrypt_block"); + + let aes = Aes256::new(&key::<32>()).unwrap(); + let mut block = [0x11u8; 16]; + aes.decrypt_block(&mut block); + print!("{block:x?}"); +} + +fn bench_aes256_encrypt_blocks2() { + eprintln!("Aes256::encrypt_blocks2"); + + let aes = Aes256::new(&key::<32>()).unwrap(); + let mut blocks = [[0x11u8; 16], [0x22u8; 16]]; + aes.encrypt_blocks2(&mut blocks); + print!("{blocks:x?}"); +} + +fn main() { + print_struct_sizes() + // bench_do_nothing() + // bench_aes128_key_expansion() + // bench_aes192_key_expansion() + // bench_aes256_key_expansion() + // bench_aes128_encrypt_block() + // bench_aes256_encrypt_block() + // bench_aes256_decrypt_block() + // bench_aes256_encrypt_blocks2() +} diff --git a/mem_usage_benches/bench_mldsa_mem_usage.rs b/mem_usage_benches/src/bench_mldsa_mem_usage.rs similarity index 99% rename from mem_usage_benches/bench_mldsa_mem_usage.rs rename to mem_usage_benches/src/bench_mldsa_mem_usage.rs index a57414e2..ca33d7d9 100644 --- a/mem_usage_benches/bench_mldsa_mem_usage.rs +++ b/mem_usage_benches/src/bench_mldsa_mem_usage.rs @@ -1,13 +1,17 @@ //! The purpose of this binary is to perform a single run of the primitive under test so that //! its peak memory usage can be measured with: //! -//! valgrind --tool=massif --heap=no --stacks=yes -- target/release/bench_mldsa_mem_usage > /dev/null +//! ```text +//! valgrind --tool=massif --heap=no --stacks=yes -- target/release/bench_mldsa_mem_usage > /dev/null //! -//! ms_print massif.out.835000 +//! ms_print massif.out.* +//! ``` //! //! or, shoved all into one line: //! -//! clear; clear; valgrind --tool=massif --heap=no --stacks=yes -- target/release/bench_mldsa_mem_usage > /dev/null; ms_print massif.out.*; rm massif.out.* +//! ```text +//! clear; clear; valgrind --tool=massif --heap=no --stacks=yes -- target/release/bench_mldsa_mem_usage > /dev/null; ms_print massif.out.*; rm massif.out.* +//! ``` //! //! Make sure you build in release mode! //! diff --git a/mem_usage_benches/bench_mlkem_mem_usage.rs b/mem_usage_benches/src/bench_mlkem_mem_usage.rs similarity index 99% rename from mem_usage_benches/bench_mlkem_mem_usage.rs rename to mem_usage_benches/src/bench_mlkem_mem_usage.rs index 8a81b71d..c0743631 100644 --- a/mem_usage_benches/bench_mlkem_mem_usage.rs +++ b/mem_usage_benches/src/bench_mlkem_mem_usage.rs @@ -1,13 +1,17 @@ //! The purpose of this binary is to perform a single run of the primitive under test so that //! its peak memory usage can be measured with: //! -//! valgrind --tool=massif --heap=no --stacks=yes -- target/release/bench_mlkem_mem_usage > /dev/null +//! ```text +//! valgrind --tool=massif --heap=no --stacks=yes -- target/release/bench_mlkem_mem_usage > /dev/null //! -//! ms_print massif.out.835000 +//! ms_print massif.out.* +//! ``` //! //! or, shoved all into one line: //! -//! clear; clear; valgrind --tool=massif --heap=no --stacks=yes -- target/release/bench_mlkem_mem_usage > /dev/null; ms_print massif.out.*; rm massif.out.* +//! ```text +//! clear; clear; valgrind --tool=massif --heap=no --stacks=yes -- target/release/bench_mlkem_mem_usage > /dev/null; ms_print massif.out.*; rm massif.out.* +//! ``` //! //! //! To measure code size, Claude suggests: diff --git a/mem_usage_benches/bench_sha3_mem_usage.rs b/mem_usage_benches/src/bench_sha3_mem_usage.rs similarity index 91% rename from mem_usage_benches/bench_sha3_mem_usage.rs rename to mem_usage_benches/src/bench_sha3_mem_usage.rs index e4155b61..b08e2c3e 100644 --- a/mem_usage_benches/bench_sha3_mem_usage.rs +++ b/mem_usage_benches/src/bench_sha3_mem_usage.rs @@ -1,13 +1,17 @@ //! The purpose of this binary is to perform a single run of the primitive under test so that //! its peak memory usage can be measured with: //! -//! valgrind --tool=massif --heap=no --stacks=yes -- target/release/bench_sha3_mem_usage > /dev/null +//! ```text +//! valgrind --tool=massif --heap=no --stacks=yes -- target/release/bench_sha3_mem_usage > /dev/null //! -//! ms_print massif.out.835000 +//! ms_print massif.out.* +//! ``` //! //! or, shoved all into one line: //! -//! clear; clear; valgrind --tool=massif --heap=no --stacks=yes -- target/release/bench_sha3_mem_usage > /dev/null; ms_print massif.out.*; rm massif.out.* +//! ```text +//! clear; clear; valgrind --tool=massif --heap=no --stacks=yes -- target/release/bench_sha3_mem_usage > /dev/null; ms_print massif.out.*; rm massif.out.* +//! ``` //! //! Make sure you build in release mode! //! diff --git a/mem_usage_benches/lib.rs b/mem_usage_benches/src/lib.rs similarity index 76% rename from mem_usage_benches/lib.rs rename to mem_usage_benches/src/lib.rs index a281a8b2..0445bb89 100644 --- a/mem_usage_benches/lib.rs +++ b/mem_usage_benches/src/lib.rs @@ -1,3 +1,4 @@ +mod bench_aes_mem_usage; mod bench_mldsa_mem_usage; mod bench_mlkem_mem_usage; mod bench_sha3_mem_usage; diff --git a/src/bench_mldsa_mem_usage.rs b/src/bench_mldsa_mem_usage.rs deleted file mode 100644 index 6d1adc14..00000000 --- a/src/bench_mldsa_mem_usage.rs +++ /dev/null @@ -1,471 +0,0 @@ -//! The purpose of this binary is to perform a single run of the primitive under test so that -//! its peak memory usage can be measured with: -//! -//! > valgrind --tool=massif --heap=no --stacks=yes -- target/release/bench_mldsa_mem_usage > /dev/null -//! -//! > ms_print massif.out.835000 -//! -//! alternatively, as a one line command: -//! -//! > clear; clear; valgrind --tool=massif --heap=no --stacks=yes -- target/release/bench_mldsa_mem_usage > /dev/null; ms_print massif.out.*; rm massif.out.* -//! -//! Make sure you build in release mode! -//! -//! Note: -//! The code is using print!() to force the compiler not to optimize away the actual code. -//! It is printing important outputs for benchmarking to stderr so that the rest can be mapped to /dev/null -//! (this is because /usr/bin/time prints useful outputs to stderr as well) -//! -//! Main is at the bottom, controls which this was actually run. - -#![allow(dead_code)] -#![allow(unused_imports)] - -use bouncycastle_core_interface::key_material::{KeyMaterial256, KeyType}; -use bouncycastle_core_interface::traits::{Signature, SignaturePublicKey}; -use bouncycastle_hex as hex; -use bouncycastle_mldsa::MLDSA44PublicKey; - -/// This exists so that /usr/bin/time can be used to measure the base memory footprint of the cargo bench harness -fn bench_do_nothing() { - eprintln!("DoNothing"); - - print!("{}", 1 + 1); -} - -fn bench_mldsa44_keygen() { - use bouncycastle_mldsa::{MLDSATrait, MLDSA44}; - - eprintln!("MLDSA44/KeyGen"); - - let seed = KeyMaterial256::from_bytes_as_type( - &hex::decode("000102030405060708090a0b0c0d0e0f101112131415161718191a1b1c1d1e1f").unwrap(), - KeyType::Seed, - ).unwrap(); - - let (pk, _sk) = MLDSA44::keygen_from_seed(&seed).unwrap(); - println!("{:x?}", pk.encode()); -} - -fn bench_mldsa44_lowmem_keygen() { - use bouncycastle_mldsa_lowmemory::{MLDSATrait, MLDSA44}; - - eprintln!("MLDSA44_lowmemory/KeyGen"); - - let seed = KeyMaterial256::from_bytes_as_type( - &hex::decode("000102030405060708090a0b0c0d0e0f101112131415161718191a1b1c1d1e1f").unwrap(), - KeyType::Seed, - ).unwrap(); - - let (pk, _sk) = MLDSA44::keygen_from_seed(&seed).unwrap(); - println!("{:x?}", pk.encode()); -} - -fn bench_mldsa65_keygen() { - use bouncycastle_mldsa::{MLDSATrait, MLDSA65}; - - eprintln!("MLDSA65/KeyGen"); - - let seed = KeyMaterial256::from_bytes_as_type( - &hex::decode("000102030405060708090a0b0c0d0e0f101112131415161718191a1b1c1d1e1f").unwrap(), - KeyType::Seed, - ).unwrap(); - - let (pk, _sk) = MLDSA65::keygen_from_seed(&seed).unwrap(); - println!("{:x?}", pk.encode()); -} - -fn bench_mldsa65_lowmemory_keygen() { - use bouncycastle_mldsa_lowmemory::{MLDSATrait, MLDSA65}; - - eprintln!("MLDSA65_lowmemory/KeyGen"); - - let seed = KeyMaterial256::from_bytes_as_type( - &hex::decode("000102030405060708090a0b0c0d0e0f101112131415161718191a1b1c1d1e1f").unwrap(), - KeyType::Seed, - ).unwrap(); - - let (pk, _sk) = MLDSA65::keygen_from_seed(&seed).unwrap(); - println!("{:x?}", pk.encode()); -} - -fn bench_mldsa87_keygen() { - use bouncycastle_mldsa::{MLDSATrait, MLDSA87}; - - eprintln!("MLDSA87/KeyGen"); - - let seed = KeyMaterial256::from_bytes_as_type( - &hex::decode("000102030405060708090a0b0c0d0e0f101112131415161718191a1b1c1d1e1f").unwrap(), - KeyType::Seed, - ).unwrap(); - - let (pk, _sk) = MLDSA87::keygen_from_seed(&seed).unwrap(); - println!("{:x?}", pk.encode()); -} - -fn bench_mldsa87_lowmemory_keygen() { - use bouncycastle_mldsa_lowmemory::{MLDSATrait, MLDSA87}; - - eprintln!("MLDSA87_lowmemory/KeyGen"); - - let seed = KeyMaterial256::from_bytes_as_type( - &hex::decode("000102030405060708090a0b0c0d0e0f101112131415161718191a1b1c1d1e1f").unwrap(), - KeyType::Seed, - ).unwrap(); - - let (pk, _sk) = MLDSA87::keygen_from_seed(&seed).unwrap(); - println!("{:x?}", pk.encode()); -} - -fn bench_mldsa44_sign() { - use bouncycastle_mldsa::{MLDSATrait, MLDSA44}; - - eprintln!("MLDSA44/Sign"); - - // set up the seeds outside of the timing loop - // Doing different seeds so that the CPU doesn't cache them or do too much branch prediction - let seed = KeyMaterial256::from_bytes_as_type( - &hex::decode("000102030405060708090a0b0c0d0e0f101112131415161718191a1b1c1d1e1f").unwrap(), - KeyType::Seed, - ).unwrap(); - - let msg = b"The quick brown fox jumped over the lazy dog"; - - /*** ML-DSA-44 ***/ - // since the goal here is to measure peak memory usage; we're here making an assumption that - // mem usage of .sign will be higher than .keygen - let (_mldsa44_pk, mldsa44_sk) = MLDSA44::keygen_from_seed(&seed).unwrap(); - - let mu = MLDSA44::compute_mu_from_sk(&mldsa44_sk, msg, None).unwrap(); - let sig = MLDSA44::sign_mu_deterministic(&mldsa44_sk, &mu, [0u8; 32]).unwrap(); - print!("{:x?}", sig); -} - -fn bench_mldsa44_lowmemory_sign() { - use bouncycastle_mldsa_lowmemory::{MLDSATrait, MLDSA44}; - - eprintln!("MLDSA44_lowmemory/Sign"); - - // set up the seeds outside of the timing loop - // Doing different seeds so that the CPU doesn't cache them or do too much branch prediction - let seed = KeyMaterial256::from_bytes_as_type( - &hex::decode("000102030405060708090a0b0c0d0e0f101112131415161718191a1b1c1d1e1f").unwrap(), - KeyType::Seed, - ).unwrap(); - - let msg = b"The quick brown fox jumped over the lazy dog"; - - /*** ML-DSA-44 ***/ - let (_mldsa44_pk, mldsa44_sk) = MLDSA44::keygen_from_seed(&seed).unwrap(); - - let mu = MLDSA44::compute_mu_from_sk(&mldsa44_sk, msg, None).unwrap(); - let sig = MLDSA44::sign_mu_deterministic(&mldsa44_sk, &mu, [0u8; 32]).unwrap(); - print!("{:x?}", sig); -} - -fn bench_mldsa65_sign() { - use bouncycastle_mldsa::{MLDSATrait, MLDSA65}; - - eprintln!("MLDSA65/Sign"); - - // set up the seeds outside of the timing loop - // Doing different seeds so that the CPU doesn't cache them or do too much branch prediction - let seed = KeyMaterial256::from_bytes_as_type( - &hex::decode("000102030405060708090a0b0c0d0e0f101112131415161718191a1b1c1d1e1f").unwrap(), - KeyType::Seed, - ).unwrap(); - - let msg = b"The quick brown fox jumped over the lazy dog"; - - let (_pk, sk) = MLDSA65::keygen_from_seed(&seed).unwrap(); - - let mu = MLDSA65::compute_mu_from_sk(&sk, msg, None).unwrap(); - let sig = MLDSA65::sign_mu_deterministic(&sk, &mu, [0u8; 32]).unwrap(); - print!("{:x?}", sig); -} - -fn bench_mldsa65_lowmemory_sign() { - use bouncycastle_mldsa_lowmemory::{MLDSATrait, MLDSA65}; - - eprintln!("MLDSA65_lowmemory/Sign"); - - // set up the seeds outside of the timing loop - // Doing different seeds so that the CPU doesn't cache them or do too much branch prediction - let seed = KeyMaterial256::from_bytes_as_type( - &hex::decode("000102030405060708090a0b0c0d0e0f101112131415161718191a1b1c1d1e1f").unwrap(), - KeyType::Seed, - ).unwrap(); - - let msg = b"The quick brown fox jumped over the lazy dog"; - - /*** ML-DSA-44 ***/ - let (_mldsa44_pk, mldsa44_sk) = MLDSA65::keygen_from_seed(&seed).unwrap(); - - let mu = MLDSA65::compute_mu_from_sk(&mldsa44_sk, msg, None).unwrap(); - let sig = MLDSA65::sign_mu_deterministic(&mldsa44_sk, &mu, [0u8; 32]).unwrap(); - print!("{:x?}", sig); -} - -fn bench_mldsa87_sign() { - use bouncycastle_mldsa::{MLDSATrait, MLDSA87}; - - eprintln!("MLDSA87/Sign"); - - // set up the seeds outside of the timing loop - // Doing different seeds so that the CPU doesn't cache them or do too much branch prediction - let seed = KeyMaterial256::from_bytes_as_type( - &hex::decode("000102030405060708090a0b0c0d0e0f101112131415161718191a1b1c1d1e1f").unwrap(), - KeyType::Seed, - ).unwrap(); - - let msg = b"The quick brown fox jumped over the lazy dog"; - - let (_pk, sk) = MLDSA87::keygen_from_seed(&seed).unwrap(); - - let mu = MLDSA87::compute_mu_from_sk(&sk, msg, None).unwrap(); - let sig = MLDSA87::sign_mu_deterministic(&sk, &mu, [0u8; 32]).unwrap(); - print!("{:x?}", sig); -} - -fn bench_mldsa87_lowmemory_sign() { - use bouncycastle_mldsa_lowmemory::{MLDSATrait, MLDSA87}; - - eprintln!("MLDSA87_lowmemory/Sign"); - - // set up the seeds outside of the timing loop - // Doing different seeds so that the CPU doesn't cache them or do too much branch prediction - let seed = KeyMaterial256::from_bytes_as_type( - &hex::decode("000102030405060708090a0b0c0d0e0f101112131415161718191a1b1c1d1e1f").unwrap(), - KeyType::Seed, - ).unwrap(); - - let msg = b"The quick brown fox jumped over the lazy dog"; - - /*** ML-DSA-44 ***/ - let (_mldsa44_pk, mldsa44_sk) = MLDSA87::keygen_from_seed(&seed).unwrap(); - - let mu = MLDSA87::compute_mu_from_sk(&mldsa44_sk, msg, None).unwrap(); - let sig = MLDSA87::sign_mu_deterministic(&mldsa44_sk, &mu, [0u8; 32]).unwrap(); - print!("{:x?}", sig); -} - -fn bench_mldsa44_verify() { - use bouncycastle_mldsa::{MLDSATrait, MLDSA44, MLDSA44_SIG_LEN, MLDSA44PublicKey}; - use bouncycastle_hex as hex; - - eprintln!("MLDSA44/Verify"); - - let msg = b"The quick brown fox jumped over the lazy dog"; - - /* One-time setup of the KAT -- commented out so that keygen is not captured in the bench */ - // let seed = KeyMaterial256::from_bytes_as_type( - // &hex::decode("000102030405060708090a0b0c0d0e0f101112131415161718191a1b1c1d1e1f").unwrap(), - // KeyType::Seed, - // ).unwrap(); - // - // let (mldsa44_pk, _mldsa44_sk) = MLDSA44::keygen_from_seed(&seed).unwrap(); - - // eprintln!("pk:\n{}", &*hex::encode(&mldsa44_pk.encode())); - // let mu = MLDSA44::compute_mu_from_sk(&mldsa44_sk, msg, None).unwrap(); - // let sig = MLDSA44::sign_mu_deterministic(&mldsa44_sk, &mu, [0u8; 32]).unwrap(); - // eprintln!("sig:\n{}", &*hex::encode(sig)); - - let mldsa44_pk = MLDSA44PublicKey::from_bytes(&*hex::decode("d7b2b47254aae0db45e7930d4a98d2c97d8f1397d1789dafa17024b316e9bec94fc9946d42f19b79a7413bbaa33e7149cb42ed5115693ac041facb988adeb5fe0e1d8631184995b592c397d2294e2e14f90aa414ba3826899ac43f4cccacbc26e9a832b95118d5cb433cbef9660b00138e0817f61e762ca274c36ad554eb22aac1162e4ab01acba1e38c4efd8f80b65b333d0f72e55dfe71ce9c1ebb9889e7c56106c0fd73803a2aecfeafded7aa3cb2ceda54d12bd8cd36a78cf975943b47abd25e880ac452e5742ed1e8d1a82afa86e590c758c15ae4d2840d92bca1a5090f40496597fca7d8b9513f1a1bda6e950aaa98de467507d4a4f5a4f0599216582c3572f62eda8905ab3581670c4a02777a33e0ca7295fd8f4ff6d1a0a3a7683d65f5f5f7fc60da023e826c5f92144c02f7d1ba1075987553ea9367fcd76d990b7fa99cd45afdb8836d43e459f5187df058479709a01ea6835935fa70460990cd3dc1ba401ba94bab1dde41ac67ab3319dcaca06048d4c4eef27ee13a9c17d0538f430f2d642dc2415660de78877d8d8abc72523978c042e4285f4319846c44126242976844c10e556ba215b5a719e59d0c6b2a96d39859071fdcc2cde7524a7bedae54e85b318e854e8fe2b2f3edfac9719128270aafd1e5044c3a4fdafd9ff31f90784b8e8e4596144a0daf586511d3d9962b9ea95af197b4e5fc60f2b1ed15de3a5bef5f89bdc79d91051d9b2816e74fa54531efdc1cbe74d448857f476bcd58f21c0b653b3b76a4e076a6559a302718555cc63f74859aabab925f023861ca8cd0f7badb2871f67d55326d7451135ad45f4a1ba69118fbb2c8a30eec9392ef3f977066c9add5c710cc647b1514d217d958c7017c3e90fd20c04e674b90486e9370a31a001d32f473979e4906749e7e477fa0b74508f8a5f2378312b83c25bd388ca0b0fff7478baf42b71667edaac97c46b129643e586e5b055a0c211946d4f36e675bed5860fa042a315d9826164d6a9237c35a5fbf495490a5bd4df248b95c4aae7784b605673166ac4245b5b4b082a09e9323e62f2078c5b76783446defd736ad3a3702d49b089844900a61833397bc4419b30d7a97a0b387c1911474c4d41b53e32a977acb6f0ea75db65bb39e59e701e76957def6f2d44559c31a77122b5204e3b5c219f1688b14ed0bc0b801b3e6e82dcd43e9c0e9f41744cd9815bd1bc8820d8bb123f04facd1b1b685dd5a2b1b8dbbf3ed933670f095a180b4f192d08b10b8fabbdfcc2b24518e32eea0a5e0c904ca844780083f3b0cd2d0b8b6af67bc355b9494025dc7b0a78fa80e3a2dbfeb51328851d6078198e9493651ae787ec0251f922ba30e9f51df62a6d72784cf3dd205393176dfa324a512bd94970a36dd34a514a86791f0eb36f0145b09ab64651b4a0313b299611a2a1c48891627598768a3114060ba4443486df51522a1ce88b30985c216f8e6ed178dd567b304a0d4cafba882a28342f17a9aa26ae58db630083d2c358fdf566c3f5d62a428567bc9ea8ce95caa0f35474b0bfa8f339a250ab4dfcf2083be8eefbc1055e18fe15370eecb260566d83ff06b211aaec43ca29b54ccd00f8815a2465ef0b46515cc7e41f3124f09efff739309ab58b29a1459a00bce5038e938c9678f72eb0e4ee5fdaae66d9f8573fc97fc42b4959f4bf8b61d78433e86b0335d6e9191c4d8bf487b3905c108cfd6ac24b0ceb7dcb7cf51f84d0ed687b95eaeb1c533c06f0d97023d92a70825837b59ba6cb7d4e56b0a87c203862ae8f315ba5925e8edefa679369a2202766151f16a965f9f81ece76cc070b55869e4db9784cf05c830b3242c8312").unwrap()).unwrap(); - let sig = &*hex::decode("5e93b785c5119c3983a291b18420fdbe4bca53d5a3732922faaacd5a5d32a745c78d105ba10bee1ed8069f19e6c537bda16e89d39004c359d1fd381a0291f1c51f1c38edcdb315c8c69570d8f25f1655ba8ea83aff24b8b6be8de762342e347eab2caa6803ed705952dd6450c5185e9d60ce96e8dca423a02f646cea690164a226e4c3d6a515ce16290f19b2c626da9b450ecf665013c5e226b6c0ac5c07ce90e278f1b0134e385d13e74208a0b3ff052a362579f9207ea01f18a039aa1b97ae3452675b620771f8012ee7a4e55c98bfd2019ed8a3b00acea8e8ab28172faa42ca1fda83c5ffe81a45be736bdedd5fb300ce17078b380f620bdeebad693601372c85eacf79bc98e1b48f2ad7e5dce4279a1295bb2ba60a0c5e3726642d2336c5eb1d37c8623c7558241318d89bc783c4f00098077484623c217560a0c7aaf75dcaccb78ee69c207c27c8bf3965ccf58a80c88efcc7e5deb3615d5045a741c4dac0a021dd060d315d4ec2857eb664d728d0af973bea07e1ca563faa0e19996cea3770316c11a5066665662005ace98f6110e883bae060daa7b6d83379e0878796691708a32b85730de8b92d89f90a3660c949165b14612567662e162232296cbd143517a282e22c46b63606d3c14ed4559a5a1c459bab7f355007ad6f7e3b1e07445dfc96bd9b75080b3d4f68998490a26b5e090be2674071ab925bb650590856c59f8ba7488d2b72f840ac3eafe4dd91f0f51c4364112c1a139e3e942a597b93a1e3f4faded129c14b5978b315e2246a93146a79365f0f597a18340cca86bb15ceed39f175eab1e546535afb966f0a65a8f66f737ab02897eddfe92cf7786894843c2691464776c94bd450a1069138b26df83b2d1dd801143a8fdfdc2514cc5b5831ab53a75c55ef29f40e7c63d2c72abe97e2af14853be49be16f4730a159974970951439e55c1589d0f4a162e3517df9d7abc98d8a307216e7f1cb4627c9175c0eef23337e56d5281b83726fff40a148b0c48e8df3496a2118d80219aef8f40b29fba1f2f78786b67ffb7b7d47d406b765bd136610bedeb95cd7321f58f3b836c9258be35d78b498f3efe1db2b243d734fab159baed8807c3cccf83eb2eaf8a9af01a518d48c60e91a96812ad689c2d83cc4e8e9b3650422bed6f13c24adaad91c95b3e3cf354f0f6bc9ee8941a6b15b6975131d95233d8935de367efc6d86a45dac7d0f1ddd9aebd2c59c027fcda448801e93e733aca51874be9ab927a904f96ddb7a46b2da13261d522b23c950c01d5f5e112b76f851ff234f06f8d5e65b1319abcd79a180ae063d65b28c745878c06dbb69ba73293eab34434bf1a92fba691993bd0ff3edac76a12f80c0ada4b1969c7665589d530a67016a625403c537032904f2e104547cd3ea406260dd357fa06ea012a785826c160e99ffd065b0e3f33c7689d3552ab9e2e09fa7e55bbcef042242bcacad8a3da47bcc54a121f1526c8cd4cc5a892a8131cf4eefaf4248ddd6a11ec427ba378aae89aaf582ce1f4e32690a555e740761d358ad4e92bc38418aa782da916524fb09ab2ca6b3d3113d6f2c2a6a9b9d29d4e7489255252af075cbf9feacedae6f3ec0b070824689dd3c78ac143ed6776d95dd8f13d435a290bdca4c11318e5acce04469644e1374a9451b6204f3b3961b7dd239e306fef5f4f4e51b78b0fb9dcee69c3e790b231f2e65fd1ab1c2a75b07067d5c16dde00983a58ffcdaaaee16d2742e133ed737b48064c8a38eca35ab3fa18f6d62f642b12cfdc7980f2ab7db321fec9dcfe499b4fc1ee7eb297954056617c60a6640b92835d165c3c00a951952614488d5657ba0b5e90ae9e0ef7b3b9ecaebd81b8551b6d70e835b2734761639d42e76ffc5b3272b61c896b45b4bd18f30e58c440643ba159221cc6739a19a65f2911fae47b0d4cac4200a6f043b17a03ad393ecb823ed03c8b6cd68167e6c8234f7432557db272079ee899aede73b6b98d6003f45789a141b60d6db40cd2a5974571a4ad3667b889318ba60285d903a2eac01c21608838c40907de6bbabe042cf2ecdd97f549f95ec698d79222c65ba27c30d332a68d057aecdc9388aa34320e0aa74fdbd4d1b643cace216b6d8ad8f07a99955bfdb743a86b40fc61527baca434ac2a7fbeaa77111dc8098b17e800f59dd77ccb0e67707e60123d334e073a2f5a16ffbcd701389add57c3ceccb88b286ac1e6e3e6485af1a12ea241d14a1b5003d7f3bc9e957d4483c0f9f703b3a187d55e505817615fbc4ae0837616184245cfba61ce3b929e33f52b71cdd7b6a0da55c1f997510b1a9002ca4e0678373a3b1ab2897e6b423f15a440a636cc861491ef41ad0aa627d8e198a5ee7bd7b6cb2c9ce2a8cc015f0d206de4c49e2f87f310954a10d86e294f742ee186f4ae9815f699622792206cafba8f5621738160e6c5d611a8252c6f35085b604ef895164d4ea6ddd310c7d8f0c879fb1f884c5741d096b3d2da0ce1151790dda881d18cb6b19a9fed6f5254b7d52d5d92bbbe24c9d6a65604a0b8ed24ad5c197d683f598743c96b5960e8723732b5bd647e9dbeaa851d0e1cf6d2c070d4442762c28098c5cf5a54b2b5e69a99b10815bf0f477bb71f0d5d3a62ba2b3e29bf84d4b4e574707f5f74af704d277bd6ca38da21e2cdac549e5eae1de7a18ee534c8c2291c908caabf159e90e6549db94ba7a3f3d97dd398a75df5b1a7cdfb25410b7efc4ed00d9995b37b58bf91ed7a3510cffea82f9e1c2a3290406004d09057d63b770fa0e53103199544eba662a2c302cf39008f142d2b16963e95ab10be7c2610168608f353a2f2c41c7056dec1a8c7a6bfa0027f9dedacb7786b67ea2c494d43ba851cf9415c1bcc52f027ec02c65534f608e9d166d51dd431cdf5871f5cdd1579cc06079df075a25062ba7e70d9666c4e7fed34cea0ea0f11ade1eb2a9b397bcaaad1061270ecf497803a5fce7f41e6504fbec71a7de7d066b8261868afc49b9e685f0dcce75e2fcb3ba8cf19057e3941576baf58fb821bd4268f7fae3028601da022e9b468646abdb4fa6098a449b4267d509d9a33f4c3ebcc32dac094d48ed600e765787fb92b1974f74f7bb4c66eb2bbd02895e6a381c1c452eaab1ae4731cf632f61ae2c905921174a3bc9bb4cdc89d630264b614988f3abbea1bd617ffa53d71b7d8a371462b773351a2dccaedd7f59cd728fadee059067bd80c94c8c9a1ffca2dc4f848b829c0561385aa82cc98503d0bb66a6aa4fae0703d12e60e1460efbbcdf2412c13e7c684d1b01102026343a414344585f6e7072748baeb5bbc6d1e2effbfe060e2e3e5160797c9ea6bac7f11024404a52575f6c898c97aab2c3cceaf22f3f535f7b818396a1b1bce6000000000000000000000000000018253642").unwrap(); - assert_eq!(sig.len(), MLDSA44_SIG_LEN); - - if MLDSA44::verify(&mldsa44_pk, msg, None, &sig).is_ok() { - eprintln!("Verification succeeded!"); - } else { - panic!("Verification failed! -- figure that out"); - } -} - -fn bench_mldsa44_lowmemory_verify() { - use bouncycastle_mldsa_lowmemory::{MLDSATrait, MLDSA44, MLDSA44_SIG_LEN, MLDSA44PublicKey}; - use bouncycastle_hex as hex; - - eprintln!("MLDSA44_lowmemory/Verify"); - - let msg = b"The quick brown fox jumped over the lazy dog"; - - /* One-time setup of the KAT -- commented out so that keygen is not captured in the bench */ - // let seed = KeyMaterial256::from_bytes_as_type( - // &hex::decode("000102030405060708090a0b0c0d0e0f101112131415161718191a1b1c1d1e1f").unwrap(), - // KeyType::Seed, - // ).unwrap(); - // - // let (mldsa44_pk, _mldsa44_sk) = MLDSA44::keygen_from_seed(&seed).unwrap(); - - // eprintln!("pk:\n{}", &*hex::encode(&mldsa44_pk.encode())); - // let mu = MLDSA44::compute_mu_from_sk(&mldsa44_sk, msg, None).unwrap(); - // let sig = MLDSA44::sign_mu_deterministic(&mldsa44_sk, &mu, [0u8; 32]).unwrap(); - // eprintln!("sig:\n{}", &*hex::encode(sig)); - - let mldsa44_pk = MLDSA44PublicKey::from_bytes(&*hex::decode("d7b2b47254aae0db45e7930d4a98d2c97d8f1397d1789dafa17024b316e9bec94fc9946d42f19b79a7413bbaa33e7149cb42ed5115693ac041facb988adeb5fe0e1d8631184995b592c397d2294e2e14f90aa414ba3826899ac43f4cccacbc26e9a832b95118d5cb433cbef9660b00138e0817f61e762ca274c36ad554eb22aac1162e4ab01acba1e38c4efd8f80b65b333d0f72e55dfe71ce9c1ebb9889e7c56106c0fd73803a2aecfeafded7aa3cb2ceda54d12bd8cd36a78cf975943b47abd25e880ac452e5742ed1e8d1a82afa86e590c758c15ae4d2840d92bca1a5090f40496597fca7d8b9513f1a1bda6e950aaa98de467507d4a4f5a4f0599216582c3572f62eda8905ab3581670c4a02777a33e0ca7295fd8f4ff6d1a0a3a7683d65f5f5f7fc60da023e826c5f92144c02f7d1ba1075987553ea9367fcd76d990b7fa99cd45afdb8836d43e459f5187df058479709a01ea6835935fa70460990cd3dc1ba401ba94bab1dde41ac67ab3319dcaca06048d4c4eef27ee13a9c17d0538f430f2d642dc2415660de78877d8d8abc72523978c042e4285f4319846c44126242976844c10e556ba215b5a719e59d0c6b2a96d39859071fdcc2cde7524a7bedae54e85b318e854e8fe2b2f3edfac9719128270aafd1e5044c3a4fdafd9ff31f90784b8e8e4596144a0daf586511d3d9962b9ea95af197b4e5fc60f2b1ed15de3a5bef5f89bdc79d91051d9b2816e74fa54531efdc1cbe74d448857f476bcd58f21c0b653b3b76a4e076a6559a302718555cc63f74859aabab925f023861ca8cd0f7badb2871f67d55326d7451135ad45f4a1ba69118fbb2c8a30eec9392ef3f977066c9add5c710cc647b1514d217d958c7017c3e90fd20c04e674b90486e9370a31a001d32f473979e4906749e7e477fa0b74508f8a5f2378312b83c25bd388ca0b0fff7478baf42b71667edaac97c46b129643e586e5b055a0c211946d4f36e675bed5860fa042a315d9826164d6a9237c35a5fbf495490a5bd4df248b95c4aae7784b605673166ac4245b5b4b082a09e9323e62f2078c5b76783446defd736ad3a3702d49b089844900a61833397bc4419b30d7a97a0b387c1911474c4d41b53e32a977acb6f0ea75db65bb39e59e701e76957def6f2d44559c31a77122b5204e3b5c219f1688b14ed0bc0b801b3e6e82dcd43e9c0e9f41744cd9815bd1bc8820d8bb123f04facd1b1b685dd5a2b1b8dbbf3ed933670f095a180b4f192d08b10b8fabbdfcc2b24518e32eea0a5e0c904ca844780083f3b0cd2d0b8b6af67bc355b9494025dc7b0a78fa80e3a2dbfeb51328851d6078198e9493651ae787ec0251f922ba30e9f51df62a6d72784cf3dd205393176dfa324a512bd94970a36dd34a514a86791f0eb36f0145b09ab64651b4a0313b299611a2a1c48891627598768a3114060ba4443486df51522a1ce88b30985c216f8e6ed178dd567b304a0d4cafba882a28342f17a9aa26ae58db630083d2c358fdf566c3f5d62a428567bc9ea8ce95caa0f35474b0bfa8f339a250ab4dfcf2083be8eefbc1055e18fe15370eecb260566d83ff06b211aaec43ca29b54ccd00f8815a2465ef0b46515cc7e41f3124f09efff739309ab58b29a1459a00bce5038e938c9678f72eb0e4ee5fdaae66d9f8573fc97fc42b4959f4bf8b61d78433e86b0335d6e9191c4d8bf487b3905c108cfd6ac24b0ceb7dcb7cf51f84d0ed687b95eaeb1c533c06f0d97023d92a70825837b59ba6cb7d4e56b0a87c203862ae8f315ba5925e8edefa679369a2202766151f16a965f9f81ece76cc070b55869e4db9784cf05c830b3242c8312").unwrap()).unwrap(); - let sig = &*hex::decode("5e93b785c5119c3983a291b18420fdbe4bca53d5a3732922faaacd5a5d32a745c78d105ba10bee1ed8069f19e6c537bda16e89d39004c359d1fd381a0291f1c51f1c38edcdb315c8c69570d8f25f1655ba8ea83aff24b8b6be8de762342e347eab2caa6803ed705952dd6450c5185e9d60ce96e8dca423a02f646cea690164a226e4c3d6a515ce16290f19b2c626da9b450ecf665013c5e226b6c0ac5c07ce90e278f1b0134e385d13e74208a0b3ff052a362579f9207ea01f18a039aa1b97ae3452675b620771f8012ee7a4e55c98bfd2019ed8a3b00acea8e8ab28172faa42ca1fda83c5ffe81a45be736bdedd5fb300ce17078b380f620bdeebad693601372c85eacf79bc98e1b48f2ad7e5dce4279a1295bb2ba60a0c5e3726642d2336c5eb1d37c8623c7558241318d89bc783c4f00098077484623c217560a0c7aaf75dcaccb78ee69c207c27c8bf3965ccf58a80c88efcc7e5deb3615d5045a741c4dac0a021dd060d315d4ec2857eb664d728d0af973bea07e1ca563faa0e19996cea3770316c11a5066665662005ace98f6110e883bae060daa7b6d83379e0878796691708a32b85730de8b92d89f90a3660c949165b14612567662e162232296cbd143517a282e22c46b63606d3c14ed4559a5a1c459bab7f355007ad6f7e3b1e07445dfc96bd9b75080b3d4f68998490a26b5e090be2674071ab925bb650590856c59f8ba7488d2b72f840ac3eafe4dd91f0f51c4364112c1a139e3e942a597b93a1e3f4faded129c14b5978b315e2246a93146a79365f0f597a18340cca86bb15ceed39f175eab1e546535afb966f0a65a8f66f737ab02897eddfe92cf7786894843c2691464776c94bd450a1069138b26df83b2d1dd801143a8fdfdc2514cc5b5831ab53a75c55ef29f40e7c63d2c72abe97e2af14853be49be16f4730a159974970951439e55c1589d0f4a162e3517df9d7abc98d8a307216e7f1cb4627c9175c0eef23337e56d5281b83726fff40a148b0c48e8df3496a2118d80219aef8f40b29fba1f2f78786b67ffb7b7d47d406b765bd136610bedeb95cd7321f58f3b836c9258be35d78b498f3efe1db2b243d734fab159baed8807c3cccf83eb2eaf8a9af01a518d48c60e91a96812ad689c2d83cc4e8e9b3650422bed6f13c24adaad91c95b3e3cf354f0f6bc9ee8941a6b15b6975131d95233d8935de367efc6d86a45dac7d0f1ddd9aebd2c59c027fcda448801e93e733aca51874be9ab927a904f96ddb7a46b2da13261d522b23c950c01d5f5e112b76f851ff234f06f8d5e65b1319abcd79a180ae063d65b28c745878c06dbb69ba73293eab34434bf1a92fba691993bd0ff3edac76a12f80c0ada4b1969c7665589d530a67016a625403c537032904f2e104547cd3ea406260dd357fa06ea012a785826c160e99ffd065b0e3f33c7689d3552ab9e2e09fa7e55bbcef042242bcacad8a3da47bcc54a121f1526c8cd4cc5a892a8131cf4eefaf4248ddd6a11ec427ba378aae89aaf582ce1f4e32690a555e740761d358ad4e92bc38418aa782da916524fb09ab2ca6b3d3113d6f2c2a6a9b9d29d4e7489255252af075cbf9feacedae6f3ec0b070824689dd3c78ac143ed6776d95dd8f13d435a290bdca4c11318e5acce04469644e1374a9451b6204f3b3961b7dd239e306fef5f4f4e51b78b0fb9dcee69c3e790b231f2e65fd1ab1c2a75b07067d5c16dde00983a58ffcdaaaee16d2742e133ed737b48064c8a38eca35ab3fa18f6d62f642b12cfdc7980f2ab7db321fec9dcfe499b4fc1ee7eb297954056617c60a6640b92835d165c3c00a951952614488d5657ba0b5e90ae9e0ef7b3b9ecaebd81b8551b6d70e835b2734761639d42e76ffc5b3272b61c896b45b4bd18f30e58c440643ba159221cc6739a19a65f2911fae47b0d4cac4200a6f043b17a03ad393ecb823ed03c8b6cd68167e6c8234f7432557db272079ee899aede73b6b98d6003f45789a141b60d6db40cd2a5974571a4ad3667b889318ba60285d903a2eac01c21608838c40907de6bbabe042cf2ecdd97f549f95ec698d79222c65ba27c30d332a68d057aecdc9388aa34320e0aa74fdbd4d1b643cace216b6d8ad8f07a99955bfdb743a86b40fc61527baca434ac2a7fbeaa77111dc8098b17e800f59dd77ccb0e67707e60123d334e073a2f5a16ffbcd701389add57c3ceccb88b286ac1e6e3e6485af1a12ea241d14a1b5003d7f3bc9e957d4483c0f9f703b3a187d55e505817615fbc4ae0837616184245cfba61ce3b929e33f52b71cdd7b6a0da55c1f997510b1a9002ca4e0678373a3b1ab2897e6b423f15a440a636cc861491ef41ad0aa627d8e198a5ee7bd7b6cb2c9ce2a8cc015f0d206de4c49e2f87f310954a10d86e294f742ee186f4ae9815f699622792206cafba8f5621738160e6c5d611a8252c6f35085b604ef895164d4ea6ddd310c7d8f0c879fb1f884c5741d096b3d2da0ce1151790dda881d18cb6b19a9fed6f5254b7d52d5d92bbbe24c9d6a65604a0b8ed24ad5c197d683f598743c96b5960e8723732b5bd647e9dbeaa851d0e1cf6d2c070d4442762c28098c5cf5a54b2b5e69a99b10815bf0f477bb71f0d5d3a62ba2b3e29bf84d4b4e574707f5f74af704d277bd6ca38da21e2cdac549e5eae1de7a18ee534c8c2291c908caabf159e90e6549db94ba7a3f3d97dd398a75df5b1a7cdfb25410b7efc4ed00d9995b37b58bf91ed7a3510cffea82f9e1c2a3290406004d09057d63b770fa0e53103199544eba662a2c302cf39008f142d2b16963e95ab10be7c2610168608f353a2f2c41c7056dec1a8c7a6bfa0027f9dedacb7786b67ea2c494d43ba851cf9415c1bcc52f027ec02c65534f608e9d166d51dd431cdf5871f5cdd1579cc06079df075a25062ba7e70d9666c4e7fed34cea0ea0f11ade1eb2a9b397bcaaad1061270ecf497803a5fce7f41e6504fbec71a7de7d066b8261868afc49b9e685f0dcce75e2fcb3ba8cf19057e3941576baf58fb821bd4268f7fae3028601da022e9b468646abdb4fa6098a449b4267d509d9a33f4c3ebcc32dac094d48ed600e765787fb92b1974f74f7bb4c66eb2bbd02895e6a381c1c452eaab1ae4731cf632f61ae2c905921174a3bc9bb4cdc89d630264b614988f3abbea1bd617ffa53d71b7d8a371462b773351a2dccaedd7f59cd728fadee059067bd80c94c8c9a1ffca2dc4f848b829c0561385aa82cc98503d0bb66a6aa4fae0703d12e60e1460efbbcdf2412c13e7c684d1b01102026343a414344585f6e7072748baeb5bbc6d1e2effbfe060e2e3e5160797c9ea6bac7f11024404a52575f6c898c97aab2c3cceaf22f3f535f7b818396a1b1bce6000000000000000000000000000018253642").unwrap(); - assert_eq!(sig.len(), MLDSA44_SIG_LEN); - - if MLDSA44::verify(&mldsa44_pk, msg, None, &sig).is_ok() { - eprintln!("Verification succeeded!"); - } else { - panic!("Verification failed! -- figure that out"); - } -} - -fn bench_mldsa65_verify() { - use bouncycastle_mldsa::{MLDSATrait, MLDSA65, MLDSA65_SIG_LEN, MLDSA65PublicKey}; - use bouncycastle_hex as hex; - - eprintln!("MLDSA65/Verify"); - - let msg = b"The quick brown fox jumped over the lazy dog"; - - /* One-time setup of the KAT -- commented out so that keygen is not captured in the bench */ - - - // let seed = KeyMaterial256::from_bytes_as_type( - // &hex::decode("000102030405060708090a0b0c0d0e0f101112131415161718191a1b1c1d1e1f").unwrap(), - // KeyType::Seed, - // ).unwrap(); - // - // let (mldsa65_pk, mldsa65_sk) = MLDSA65::keygen_from_seed(&seed).unwrap(); - // - // eprintln!("pk:\n{}", &*hex::encode(&mldsa65_pk.encode())); - // let mu = MLDSA65::compute_mu_from_sk(&mldsa65_sk, msg, None).unwrap(); - // let sig = MLDSA65::sign_mu_deterministic(&mldsa65_sk, &mu, [0u8; 32]).unwrap(); - // eprintln!("sig:\n{}", &*hex::encode(sig)); - - let mldsa65_pk = MLDSA65PublicKey::from_bytes(&*hex::decode("48683d91978e31eb3dddb8b0473482d2b88a5f625949fd8f58a561e696bd4c27d05b38dbb2edf01e664efd81be1ea893688ce68aa2d51c5958f8bbc6eb4e89ee67d2c0320954d57212cac7229ff1d6eaf03928bd51511f8d88d847736c7de2730d5978e5410713160978867711bf5539a0bfc4c350c2be572baf0ee2e2fb16ccfea08028d99ac49aebb75937ddce111cdab62fff3cea8ba2233d1e56fbc5c5a1e726de63fadd2af016b119177fa3d971a2d9277173fce55b67745af0b7c21d597dbeb93e6a32f341c49a5a8be9e825088d1f2aa45155d6c8ae15367e4eb003b8fdf7851071949739f9fff09023eaf45104d2a84a45906eed4671a44dc28d27987bb55df69e9e8561f61a80a72699503865fed9b7ee72a8e17a19c408144f4b29afef7031c3a6d8571610b42c9f421245a88f197e16812b031159b65b9687e5b3e934c5225ae98a79ba73d2b399d73510effad19e53b8450f0ba8fce1012fd98d260a74aaaa13fae249a006b1c34f5ba0b882f26378222fb36f2283c243f0ffeb5f1bb414a0a70d55e3d40a56b6cbc88ae1f03b7b2882d98deea28e145c9dedfd8eaf1cef2ed94a8b050f8964f46d1ea0d0c2a43e0dda6182adbf4f6ed175b6742257859bf22f3a417ecf1f9d89317b5e539d587af16b9e1313e04514ffa64ba8b3ff2b8321f8811cb3fb022c8f644e70a4b80a2fbfee604abb7379091ea8e6c5c74dfc0283666b40c0793870028204a136bf5da9568eb798d349038bdb0c11e03445e7847cb5069c75cf28ac601c7799d958210ddbcb226e51afef9f1de47b073873d6d3f97456bede085082e74a298b2cd48f4b3093155f366c8fa601c6af858dfa32c08491b2a29887f90335949a5d6edaa679882a3a95d6bf6d970a221f4b9d3d8cbf384af81aac95e2b3294e04789ac83727a5dc04559f96af41d8a053516feeeebc52746eb6ab2819e09108710d835f011fa63065872ad334d5cdffb2b2310507e92fc993ae317da97f4f309cdaf0f67ed99d90215576083849f953b246d7fedb3fdb67679850a5ad404e64147fb7cf4f6aeddd05afb4b834968d1fe88014960dce5d942236526e12a478d69e5fbe6970310b308c06845018cfc7b2ab430a13a6b1ac7bb02cccbb3d911ac2f11068613fbe029bfdce02cf5cd38950ed72c83944edfbc75615af87f864c051f3c55456c5412863a40c06d1dab562bdff0571b8d3c3917bbd300880bba5e998239b95fa91b7d6416d4f398b3adbcd30983ed3592b4d9ef7d4236fd00f50d98aa53a235ac4172720f77d96172672980cfe8ff7a5a702783edc2ba31b2259015a112fc7f468a9c2f9464039002d30ef678b4cb798bc116216bf7a9a7c18ba03b7b58fd07515d3115049d3614be7a07e744300750df1d2c58753389059eafc3d785ccdd31c07648bedc03a5c3b8ad46d064d59c13d57374729fc4e295362e2a5191204530428bc1522afa28ff5fe1655e304ca5bc8c27ad0e0c6a39dd4df28956c14b38cc93682cefe402bbd5e82d29c464e44eb5d37b48fc568dfe0cc6e8e16baea05e5135590f19294e73e8367b0216dbb815030b9de55913f08039c42351c59e5515dd5af8e089a15e625e8f6dee639386c46497d7a263288774de581a7de9629b41b4424141f978fb8331208efdec3c6e0de39bc57063f3dcd6c470373c08891ea29cbc7cc6d6483b8889083ace86aa7b51b1c2cfe6e2ad18d97ce36fbc56ea42fae97e6a7ac114864478c366df1ebb1e7b11a9098504fd5975bdf1f49dc70002b63c1739a9d263fbad4073f6a9f6c2b8af4b4c332a103a0cffa5deeb2d062ca3c215fd360026be7c5164f4a4424ef74948804d66f46487732c8202c795478647b4ea71d627c086024cca354a41f0877b38f19b3774ad2095c8da53b069e21c76ae2d2007e16719ed40080d334f7da52e9f5a5990439caf083a95b833f02ad10a08c1a6d0f260c007285bd4a2f47703a5aef465287d253b18ac22514316210ff566814b10f87a293d6f199d3c3959990d0c1268b4f50d5f9fcefbbf237bd0c28b80182d6659741f14f10bfbb21bba12ab620aa2396f56c0686b4ea9017990224216b2fe8ad76c4a9148eef9a86a3635a6aa77bc1dcfb6fba59a77dfda9b7530dc0ca8648c8d973738e01bab8f08b4905e84aa4641bd602410cd97520265f2f231f2b35e15eb2fa04d2bd94d5a77abaf1e0e161010a990087f5b46ea988b2bc0512fda0fa923dadd6c45c5301d09483673265b5ab2e10f4ba520f6bbad564a5c3d5e27bdb080f7d20e13296a3181954c39c649c943ebe17df5c1f7aae0a8fe126c477585a5d4d648a0d008b6af5e8cd31be69a9296d4f3fd25ed86f221e4b93f65f5929967533624b9235750c30707550b58536d109a7131c5a5bbe4a5715567c12534aec7660761eebb9fae2891c774589b80e566ad557ddef7367196b7227ea9870ef09ddfec79d6b9319a6879b5205d76bf7aba5acf33afb59d17fc54e68383d6be5a08e9b66da53dcde008bb294b8582bd132cdcc49959fdbc21e52721880c8ad0352c79f03a43bbd84c4cdfdc6c529005e1e7cd9a349a7168a35569ba5dea818968d5a91466bd6e64e20bf62417198afc4e81c28dd77ed4028232398b52fbde86bc84f475b9016710ce2aabc11a06b4dbac901ec16cf365ca3f2d53813948a693a0f93e79c46ca5d5a6dca3d28ca50ad18bd13fca55059dd9b185f79f9c47196a4e81b2104bc460a051e02f2e8444f").unwrap()).unwrap(); - let sig = &*hex::decode("9061f15cbf2092f744fbcd799eb02414053c1b0f7412124bedc41cf9a3db0166469e874037d7f081e5f8d3d2033a0307d1c49ed01fe64578c4a6fabd80880cdf1911848f184d4bcf536ca795a0fb1aa19ab7ee3ba6b58bd64bbeac9f58650fff1ef5a97ab6916df962072e20e7c6be96090e3a781a504bc4442bd8889a0aa628907a74299f39fa836031f1bd68355bebe7ae93c1e361a9efbed1325d96227070461fcd6f151b8669d9229b977d9ee51fd2260c3e4a2e820416f9e074958dc3b3e2217e6312b7e0b582a048981cf6579f4bc7715b78c808e4c57e3b8aa38b05c04fcedf209f52c1e331ae83dbdff60ba450a17cc397568e54bc3f16ddf30b92747ce460d925b9be20a1d35e2aed97f124af2616a5361df28ba30e522dd08fa00fd28d1ac484d756a89e3a442fefe8332c56cd2a9fde691bdbda43f1cc54cef57bead96120b50c7d4695bdbb1303cc5ddda898e4eeb83083176e40e0232cdd1c3150371df05d6fdad7e1164d90393cf308e99edfeb31fed263e2866ee3b7f3937b399c974d87ba7b489efe3c9b80371d2928446adc31991ab0cefaaa080575b9ec81cfa133a9911c035a8058d0d3f2e34de4a9fb009bb4ccdb16de7b908574a7496725ff857556c1b33917e986c80f1014a9e3083add2fb35f345c5d06159e443329d0da099987b996c3731592b460c2ffd2955f7546f4216100ba43188803ff9b36969685f909fa2539323b8c8ec1c095a5085e554dd450e0e67ab670b6a11ebf6c25520fc13e364060f91f9b7f3d5cb48ff28b8fc83d4293f1f35ad6ff6ae4574ad7a1c6005fc0389a7b21386b0850a05d832fe6a14bb2b1db1f8e20bd09174946cd098b81c8f797e95f2143a949770cf1219bfef039db51a80fc247f65f41554c7173dd805ba82fdf47ab6d4bfd37dfe46fc47904421ae00dc005a22f9c4784b0ea9e665392a412245016d5c6d7673a6a180d228d4255a538e451ffd8b414d40304c0c888992e0ab6de1602109527417bc1c7eb782ae77a8c3cdfc1d13a1e874207898264e38080243109c5969649ac8383417e922ba115331142d0ed35440b15d40bee0cf58af37c0f0524ffac1c71ceed3bb82f76ab108a8ad1a0c8b78d9341148c642369be7bef59d46f49d70c83560607f140848ec9a7607d4a08f8b6e4447f5523f416981888a8de9647ffef79389e4983e5c9387698d0cc2d429322365ce7e7b5fd6d6eb921c813fcf06199fe1ca41e9cfe03b539f321671a2acad0963f876f9db7a1c4371b9f101005217995b5b6a40976246d245da603dba8dac812a5480c3476a99d0ffdf0ef943d72d912543148b2fe78e8b0159324fe9bcd4ced33cd212fe4f3dfd6d4c5e1958beb95ac6b533ace3e78015e3880b52bf45299263a4c0096f8ba5fe3a6298cab675cb7f382e7ef49720eb4cf47376e2d2574122ccf91129c858e948904fecefb91226ed42403ba12dd3258909a87dfcbf65cc3adc3d98d277fdcec7664e2292b7d27afbb5aafb405c20a34b2fe2c0849ee280bb891dfdf59f19b89b0246358db54cf3fdc66eaaaa750c8903f1d42678f3edf0b7530410aa881bc617f94346379854af4532e61f65aae7576c35faf55e155bd6787b4634d54191907e155c239e68480cdfa0c87054bfb62855f409a20d5335fb123e681e64ec847cd985b6062059f436aebac623c038b6c3405ac325191a8d1126a5ef8f38cccbf144a5c324c1e093cf99efbe10ca03d439bcfb8ba5e293b7d318837f7bc42a99964392369da76e79d71d1a2c248a11324a87ae1e3cbeab6fb0d0bcae1ef55e43dfb6f1b4cfb82c7a778fb828a3727ef07685fe38a74b3dd25d015322c2d9f245c08d8c2b43865694233782eb734436c4eddef5406208d6c4572c7371262fe02319cfbbcf2e23bed8aa969d1ae6f5f25ff6b8ebcf0925066f761a39bbff49f0c8dbc3be84f0c442b044ea01b669747e3c8293cfe9ccdf2ef063ae3d28d10720c279a2691616abd23b055cfc6c562125df4ad0fa6631304972ddc3674b1aaa7665bf621320d83eac8d5b371d7d719829f58b23458182558710de31d81ef9a47d8839c79640b2025d1965a418bc90e4115f1423311a8b64fcde0f2d2145ee535b0931b84bc8110445f2ff68d136ed709ddb7ea9ff75f3b4e8b4f836230ca9e81069477f634e07270af60ef96f72557a081d664abcf35548f699484653da645483ff2bf5998617ae8bfa62d56e714f3c0136e5035a3f78e06c2f470df7fd3380d14033f81e2aae6b4d90487dab76b9b3b8761fb56c36f5429da3d4346cb22e641ad8d7d2d80fa240d4e0154e6b3d2f1b3ef6cf174c08d062f575c83a4078174f874364df36a6328beeef69ba7f90e1df9fdcec9a2f15ebf04fa7d6756da2e5a59c9cbbcbc397d6fb28d0fc9a60534dff0752716ed079ad1ab19a224d1c8ae8a53242fd164989ff997489b6520eb3c0e97f4bcc1a9c3cbd44f008c03ef52cf7e626881d246925e0336c0ac668867f853da7820f914115a7c77ac31b66f46fbf97f66fa26416fc4581d459a4f2462d52cf0c79b278955aa73e8fa56e3c320f516bcc54c97e587199c15ab953cc37189b81c70cabb2559e445bcc9d8174ad7574e9acb02f43e0c34ff5e6746ee730ad41ff8eef93c2071c2649063dd92f343c06ef6abaf98f28d98d968071c12cc10a90c22d8b3b3480c76f7a51b7ec594b3435d2e3d779c1a15037697f3a058650472e47eecd5f32eb3243a516f0e703f9888c84690750648d6a9a876bf1f353db6891dc6d317d6e87ac088f42b5f6f20d799ece4fa7aaa928d2ac795e8de83d1e1c7fa2f9a4106693e981c21c63b3221c4fa2649f45f0c6e05dbf24011af16ab2e5fe94a640b485988037ebe1e8ad0b2623d95e9947f0726121d7828614e3b2d77a7a1f9a938bea9a1a7a2627b7d2e358c42ccc6c0b80a15a1c2f6e9aaf0495bdb7bb8d4b0e28a1ab5ab93ca0ff3e3f910c490c13486852534d5e12160835ec5916c5c68349c4e2d8fa956c643277edd3b6c81c88c010421705fd317ff9e3c94df0ed5305f530acbccf8dd0e87140cd38152664a572c168cd72595b7fac243c03f3fb33ef74a28c0e4469f94587c13704e9efe8010b2125aca78c22c33c82366e1a7c4028c2ae2e8d26e1a57e4297fac987f84a0a27f42b4c93a4f4d14569824b0880fb67407ed58f267ac403aa0b1f93784b4b4c67036037e60d58072611b0e90ca316976ef4e0b302cdad1b6dcca92efb8e1f6be2397967508be2c02a25ed0380ba1f7955f857c8fb043297780d136b2b064040c8e55143d715ea997e134ed973c98ef82786f0ccf66c17d863542180c66d54d08e116f2e35d995e214489ad0fad7a55fe9ebc1a777fe34141147c080b98d13463a3bbc6fc82f2fc95f4de7b3591d9c8cd4416917a4338095d5620104b7be13f5a131dd3f7aad5b559d11e8171dfb91e2bb1e47ac3810b1cdc1a1e370c867b7b7b50c4688dce545763157e02f47e1cc661d5bf2fbc336cfae080ab15728b1ab9dd199f2779d451e6178977fb658c17344cffb7aa3af5791a28fc8a089c85187753e5e313c8d1f0fe7755e28be444426a189e8bce2d2f79db31d4c3ca911a83455525355f95d159351cd731a88e55403851236ee2128f279d5be644c042453ae65d9e9f3b40d6c82bdeb002acdee061ecca3f2dceabef9a900e6e063d56ab39cb82dbc77a4677572d7616cd72c0f6d5b9b941dfda1fe7c896b8cc24d65a4322d712a84e94adfc8ed0cc56cc1ae97f775bd3cea5b20b524d9a7a916056e19af095d30171e5e14c7c998f78dc44845edf307363eab7913f680a5e5a1540a6f945507ffa67591f8d1a2920ab3b6e754e35379dd67870c242335e2717903ff3c687e5c33dc953416865d5f23bd752e55492b9d5d888d7b37ef33b0a6774d052b0987c066a2e01767207aa7fbfc393ca62874613dde3794f74fadb5d55b877b877a605918c812610fbcafad72ee245e6dd8721138d6bd3f4eedad853aed1ec437ad02ac937c80dae26fa5f70083bd346779b779387f7b3d2aae57770d8177928833281ccb7a38da24834fd9726fd17eb603cba9041e82bfeed0e33942dde1d48c271f5b39aa7230f41afb89d36f7976eee4f51a036743031c534f64685b94c990a93a5737fe628ee9cda8ed9c08b11d3836f833835c445b317a77ead7599d1a0c08873014510d36bb7ff5fb961277589ea48c32a60c87ec40681be067b17785ec44825bd89faa25249e735a628b6eebcc6cce4e0314c627588118c40b2e0d460d8d5ce358c56458f36914ca203f5a5381c6deb5a76bbc08c40a87437da0d0b571788a05e9f96d9bb770de8a0b1b960ff2a44a964c9b7939853742e83ce8deb79191b2d82454655f227079dd8c5b0216c8470b8e1ac70526301bbfa2bc4adca68a766ccb2a6e0ebf2e99905bf5242590b01703868b3faf841c11c383be145a40fea6375e18a01468e459603b5efdf8a4e9abd179280ae8b5947d78d2f0c4d37715eaa42bc37cf8730e41ffbf9826d46424f2922a96033cefaa8b4bbe4c8b89d43501fd5211d5392ca19a98ba127d9025b5c6e86ba024471940549a2b5d8e14961c9dc19696da1a5bffd01030d5e6100000000000000000000000000000000000000000000000005090f131a1f").unwrap(); - assert_eq!(sig.len(), MLDSA65_SIG_LEN); - - if MLDSA65::verify(&mldsa65_pk, msg, None, &sig).is_ok() { - eprintln!("Verification succeeded!"); - } else { - panic!("Verification failed! -- figure that out"); - } -} - -fn bench_mldsa65_lowmemory_verify() { - use bouncycastle_mldsa_lowmemory::{MLDSATrait, MLDSA65, MLDSA65_SIG_LEN, MLDSA65PublicKey}; - use bouncycastle_hex as hex; - - eprintln!("MLDSA65_lowmemory/Verify"); - - let msg = b"The quick brown fox jumped over the lazy dog"; - - /* One-time setup of the KAT -- commented out so that keygen is not captured in the bench */ - - // let seed = KeyMaterial256::from_bytes_as_type( - // &hex::decode("000102030405060708090a0b0c0d0e0f101112131415161718191a1b1c1d1e1f").unwrap(), - // KeyType::Seed, - // ).unwrap(); - // - // let (mldsa65_pk, mldsa65_sk) = MLDSA65::keygen_from_seed(&seed).unwrap(); - // - // eprintln!("pk:\n{}", &*hex::encode(&mldsa65_pk.encode())); - // let mu = MLDSA65::compute_mu_from_sk(&mldsa65_sk, msg, None).unwrap(); - // let sig = MLDSA65::sign_mu_deterministic(&mldsa65_sk, &mu, [0u8; 32]).unwrap(); - // eprintln!("sig:\n{}", &*hex::encode(sig)); - - let mldsa65_pk = MLDSA65PublicKey::from_bytes(&*hex::decode("48683d91978e31eb3dddb8b0473482d2b88a5f625949fd8f58a561e696bd4c27d05b38dbb2edf01e664efd81be1ea893688ce68aa2d51c5958f8bbc6eb4e89ee67d2c0320954d57212cac7229ff1d6eaf03928bd51511f8d88d847736c7de2730d5978e5410713160978867711bf5539a0bfc4c350c2be572baf0ee2e2fb16ccfea08028d99ac49aebb75937ddce111cdab62fff3cea8ba2233d1e56fbc5c5a1e726de63fadd2af016b119177fa3d971a2d9277173fce55b67745af0b7c21d597dbeb93e6a32f341c49a5a8be9e825088d1f2aa45155d6c8ae15367e4eb003b8fdf7851071949739f9fff09023eaf45104d2a84a45906eed4671a44dc28d27987bb55df69e9e8561f61a80a72699503865fed9b7ee72a8e17a19c408144f4b29afef7031c3a6d8571610b42c9f421245a88f197e16812b031159b65b9687e5b3e934c5225ae98a79ba73d2b399d73510effad19e53b8450f0ba8fce1012fd98d260a74aaaa13fae249a006b1c34f5ba0b882f26378222fb36f2283c243f0ffeb5f1bb414a0a70d55e3d40a56b6cbc88ae1f03b7b2882d98deea28e145c9dedfd8eaf1cef2ed94a8b050f8964f46d1ea0d0c2a43e0dda6182adbf4f6ed175b6742257859bf22f3a417ecf1f9d89317b5e539d587af16b9e1313e04514ffa64ba8b3ff2b8321f8811cb3fb022c8f644e70a4b80a2fbfee604abb7379091ea8e6c5c74dfc0283666b40c0793870028204a136bf5da9568eb798d349038bdb0c11e03445e7847cb5069c75cf28ac601c7799d958210ddbcb226e51afef9f1de47b073873d6d3f97456bede085082e74a298b2cd48f4b3093155f366c8fa601c6af858dfa32c08491b2a29887f90335949a5d6edaa679882a3a95d6bf6d970a221f4b9d3d8cbf384af81aac95e2b3294e04789ac83727a5dc04559f96af41d8a053516feeeebc52746eb6ab2819e09108710d835f011fa63065872ad334d5cdffb2b2310507e92fc993ae317da97f4f309cdaf0f67ed99d90215576083849f953b246d7fedb3fdb67679850a5ad404e64147fb7cf4f6aeddd05afb4b834968d1fe88014960dce5d942236526e12a478d69e5fbe6970310b308c06845018cfc7b2ab430a13a6b1ac7bb02cccbb3d911ac2f11068613fbe029bfdce02cf5cd38950ed72c83944edfbc75615af87f864c051f3c55456c5412863a40c06d1dab562bdff0571b8d3c3917bbd300880bba5e998239b95fa91b7d6416d4f398b3adbcd30983ed3592b4d9ef7d4236fd00f50d98aa53a235ac4172720f77d96172672980cfe8ff7a5a702783edc2ba31b2259015a112fc7f468a9c2f9464039002d30ef678b4cb798bc116216bf7a9a7c18ba03b7b58fd07515d3115049d3614be7a07e744300750df1d2c58753389059eafc3d785ccdd31c07648bedc03a5c3b8ad46d064d59c13d57374729fc4e295362e2a5191204530428bc1522afa28ff5fe1655e304ca5bc8c27ad0e0c6a39dd4df28956c14b38cc93682cefe402bbd5e82d29c464e44eb5d37b48fc568dfe0cc6e8e16baea05e5135590f19294e73e8367b0216dbb815030b9de55913f08039c42351c59e5515dd5af8e089a15e625e8f6dee639386c46497d7a263288774de581a7de9629b41b4424141f978fb8331208efdec3c6e0de39bc57063f3dcd6c470373c08891ea29cbc7cc6d6483b8889083ace86aa7b51b1c2cfe6e2ad18d97ce36fbc56ea42fae97e6a7ac114864478c366df1ebb1e7b11a9098504fd5975bdf1f49dc70002b63c1739a9d263fbad4073f6a9f6c2b8af4b4c332a103a0cffa5deeb2d062ca3c215fd360026be7c5164f4a4424ef74948804d66f46487732c8202c795478647b4ea71d627c086024cca354a41f0877b38f19b3774ad2095c8da53b069e21c76ae2d2007e16719ed40080d334f7da52e9f5a5990439caf083a95b833f02ad10a08c1a6d0f260c007285bd4a2f47703a5aef465287d253b18ac22514316210ff566814b10f87a293d6f199d3c3959990d0c1268b4f50d5f9fcefbbf237bd0c28b80182d6659741f14f10bfbb21bba12ab620aa2396f56c0686b4ea9017990224216b2fe8ad76c4a9148eef9a86a3635a6aa77bc1dcfb6fba59a77dfda9b7530dc0ca8648c8d973738e01bab8f08b4905e84aa4641bd602410cd97520265f2f231f2b35e15eb2fa04d2bd94d5a77abaf1e0e161010a990087f5b46ea988b2bc0512fda0fa923dadd6c45c5301d09483673265b5ab2e10f4ba520f6bbad564a5c3d5e27bdb080f7d20e13296a3181954c39c649c943ebe17df5c1f7aae0a8fe126c477585a5d4d648a0d008b6af5e8cd31be69a9296d4f3fd25ed86f221e4b93f65f5929967533624b9235750c30707550b58536d109a7131c5a5bbe4a5715567c12534aec7660761eebb9fae2891c774589b80e566ad557ddef7367196b7227ea9870ef09ddfec79d6b9319a6879b5205d76bf7aba5acf33afb59d17fc54e68383d6be5a08e9b66da53dcde008bb294b8582bd132cdcc49959fdbc21e52721880c8ad0352c79f03a43bbd84c4cdfdc6c529005e1e7cd9a349a7168a35569ba5dea818968d5a91466bd6e64e20bf62417198afc4e81c28dd77ed4028232398b52fbde86bc84f475b9016710ce2aabc11a06b4dbac901ec16cf365ca3f2d53813948a693a0f93e79c46ca5d5a6dca3d28ca50ad18bd13fca55059dd9b185f79f9c47196a4e81b2104bc460a051e02f2e8444f").unwrap()).unwrap(); - let sig = &*hex::decode("9061f15cbf2092f744fbcd799eb02414053c1b0f7412124bedc41cf9a3db0166469e874037d7f081e5f8d3d2033a0307d1c49ed01fe64578c4a6fabd80880cdf1911848f184d4bcf536ca795a0fb1aa19ab7ee3ba6b58bd64bbeac9f58650fff1ef5a97ab6916df962072e20e7c6be96090e3a781a504bc4442bd8889a0aa628907a74299f39fa836031f1bd68355bebe7ae93c1e361a9efbed1325d96227070461fcd6f151b8669d9229b977d9ee51fd2260c3e4a2e820416f9e074958dc3b3e2217e6312b7e0b582a048981cf6579f4bc7715b78c808e4c57e3b8aa38b05c04fcedf209f52c1e331ae83dbdff60ba450a17cc397568e54bc3f16ddf30b92747ce460d925b9be20a1d35e2aed97f124af2616a5361df28ba30e522dd08fa00fd28d1ac484d756a89e3a442fefe8332c56cd2a9fde691bdbda43f1cc54cef57bead96120b50c7d4695bdbb1303cc5ddda898e4eeb83083176e40e0232cdd1c3150371df05d6fdad7e1164d90393cf308e99edfeb31fed263e2866ee3b7f3937b399c974d87ba7b489efe3c9b80371d2928446adc31991ab0cefaaa080575b9ec81cfa133a9911c035a8058d0d3f2e34de4a9fb009bb4ccdb16de7b908574a7496725ff857556c1b33917e986c80f1014a9e3083add2fb35f345c5d06159e443329d0da099987b996c3731592b460c2ffd2955f7546f4216100ba43188803ff9b36969685f909fa2539323b8c8ec1c095a5085e554dd450e0e67ab670b6a11ebf6c25520fc13e364060f91f9b7f3d5cb48ff28b8fc83d4293f1f35ad6ff6ae4574ad7a1c6005fc0389a7b21386b0850a05d832fe6a14bb2b1db1f8e20bd09174946cd098b81c8f797e95f2143a949770cf1219bfef039db51a80fc247f65f41554c7173dd805ba82fdf47ab6d4bfd37dfe46fc47904421ae00dc005a22f9c4784b0ea9e665392a412245016d5c6d7673a6a180d228d4255a538e451ffd8b414d40304c0c888992e0ab6de1602109527417bc1c7eb782ae77a8c3cdfc1d13a1e874207898264e38080243109c5969649ac8383417e922ba115331142d0ed35440b15d40bee0cf58af37c0f0524ffac1c71ceed3bb82f76ab108a8ad1a0c8b78d9341148c642369be7bef59d46f49d70c83560607f140848ec9a7607d4a08f8b6e4447f5523f416981888a8de9647ffef79389e4983e5c9387698d0cc2d429322365ce7e7b5fd6d6eb921c813fcf06199fe1ca41e9cfe03b539f321671a2acad0963f876f9db7a1c4371b9f101005217995b5b6a40976246d245da603dba8dac812a5480c3476a99d0ffdf0ef943d72d912543148b2fe78e8b0159324fe9bcd4ced33cd212fe4f3dfd6d4c5e1958beb95ac6b533ace3e78015e3880b52bf45299263a4c0096f8ba5fe3a6298cab675cb7f382e7ef49720eb4cf47376e2d2574122ccf91129c858e948904fecefb91226ed42403ba12dd3258909a87dfcbf65cc3adc3d98d277fdcec7664e2292b7d27afbb5aafb405c20a34b2fe2c0849ee280bb891dfdf59f19b89b0246358db54cf3fdc66eaaaa750c8903f1d42678f3edf0b7530410aa881bc617f94346379854af4532e61f65aae7576c35faf55e155bd6787b4634d54191907e155c239e68480cdfa0c87054bfb62855f409a20d5335fb123e681e64ec847cd985b6062059f436aebac623c038b6c3405ac325191a8d1126a5ef8f38cccbf144a5c324c1e093cf99efbe10ca03d439bcfb8ba5e293b7d318837f7bc42a99964392369da76e79d71d1a2c248a11324a87ae1e3cbeab6fb0d0bcae1ef55e43dfb6f1b4cfb82c7a778fb828a3727ef07685fe38a74b3dd25d015322c2d9f245c08d8c2b43865694233782eb734436c4eddef5406208d6c4572c7371262fe02319cfbbcf2e23bed8aa969d1ae6f5f25ff6b8ebcf0925066f761a39bbff49f0c8dbc3be84f0c442b044ea01b669747e3c8293cfe9ccdf2ef063ae3d28d10720c279a2691616abd23b055cfc6c562125df4ad0fa6631304972ddc3674b1aaa7665bf621320d83eac8d5b371d7d719829f58b23458182558710de31d81ef9a47d8839c79640b2025d1965a418bc90e4115f1423311a8b64fcde0f2d2145ee535b0931b84bc8110445f2ff68d136ed709ddb7ea9ff75f3b4e8b4f836230ca9e81069477f634e07270af60ef96f72557a081d664abcf35548f699484653da645483ff2bf5998617ae8bfa62d56e714f3c0136e5035a3f78e06c2f470df7fd3380d14033f81e2aae6b4d90487dab76b9b3b8761fb56c36f5429da3d4346cb22e641ad8d7d2d80fa240d4e0154e6b3d2f1b3ef6cf174c08d062f575c83a4078174f874364df36a6328beeef69ba7f90e1df9fdcec9a2f15ebf04fa7d6756da2e5a59c9cbbcbc397d6fb28d0fc9a60534dff0752716ed079ad1ab19a224d1c8ae8a53242fd164989ff997489b6520eb3c0e97f4bcc1a9c3cbd44f008c03ef52cf7e626881d246925e0336c0ac668867f853da7820f914115a7c77ac31b66f46fbf97f66fa26416fc4581d459a4f2462d52cf0c79b278955aa73e8fa56e3c320f516bcc54c97e587199c15ab953cc37189b81c70cabb2559e445bcc9d8174ad7574e9acb02f43e0c34ff5e6746ee730ad41ff8eef93c2071c2649063dd92f343c06ef6abaf98f28d98d968071c12cc10a90c22d8b3b3480c76f7a51b7ec594b3435d2e3d779c1a15037697f3a058650472e47eecd5f32eb3243a516f0e703f9888c84690750648d6a9a876bf1f353db6891dc6d317d6e87ac088f42b5f6f20d799ece4fa7aaa928d2ac795e8de83d1e1c7fa2f9a4106693e981c21c63b3221c4fa2649f45f0c6e05dbf24011af16ab2e5fe94a640b485988037ebe1e8ad0b2623d95e9947f0726121d7828614e3b2d77a7a1f9a938bea9a1a7a2627b7d2e358c42ccc6c0b80a15a1c2f6e9aaf0495bdb7bb8d4b0e28a1ab5ab93ca0ff3e3f910c490c13486852534d5e12160835ec5916c5c68349c4e2d8fa956c643277edd3b6c81c88c010421705fd317ff9e3c94df0ed5305f530acbccf8dd0e87140cd38152664a572c168cd72595b7fac243c03f3fb33ef74a28c0e4469f94587c13704e9efe8010b2125aca78c22c33c82366e1a7c4028c2ae2e8d26e1a57e4297fac987f84a0a27f42b4c93a4f4d14569824b0880fb67407ed58f267ac403aa0b1f93784b4b4c67036037e60d58072611b0e90ca316976ef4e0b302cdad1b6dcca92efb8e1f6be2397967508be2c02a25ed0380ba1f7955f857c8fb043297780d136b2b064040c8e55143d715ea997e134ed973c98ef82786f0ccf66c17d863542180c66d54d08e116f2e35d995e214489ad0fad7a55fe9ebc1a777fe34141147c080b98d13463a3bbc6fc82f2fc95f4de7b3591d9c8cd4416917a4338095d5620104b7be13f5a131dd3f7aad5b559d11e8171dfb91e2bb1e47ac3810b1cdc1a1e370c867b7b7b50c4688dce545763157e02f47e1cc661d5bf2fbc336cfae080ab15728b1ab9dd199f2779d451e6178977fb658c17344cffb7aa3af5791a28fc8a089c85187753e5e313c8d1f0fe7755e28be444426a189e8bce2d2f79db31d4c3ca911a83455525355f95d159351cd731a88e55403851236ee2128f279d5be644c042453ae65d9e9f3b40d6c82bdeb002acdee061ecca3f2dceabef9a900e6e063d56ab39cb82dbc77a4677572d7616cd72c0f6d5b9b941dfda1fe7c896b8cc24d65a4322d712a84e94adfc8ed0cc56cc1ae97f775bd3cea5b20b524d9a7a916056e19af095d30171e5e14c7c998f78dc44845edf307363eab7913f680a5e5a1540a6f945507ffa67591f8d1a2920ab3b6e754e35379dd67870c242335e2717903ff3c687e5c33dc953416865d5f23bd752e55492b9d5d888d7b37ef33b0a6774d052b0987c066a2e01767207aa7fbfc393ca62874613dde3794f74fadb5d55b877b877a605918c812610fbcafad72ee245e6dd8721138d6bd3f4eedad853aed1ec437ad02ac937c80dae26fa5f70083bd346779b779387f7b3d2aae57770d8177928833281ccb7a38da24834fd9726fd17eb603cba9041e82bfeed0e33942dde1d48c271f5b39aa7230f41afb89d36f7976eee4f51a036743031c534f64685b94c990a93a5737fe628ee9cda8ed9c08b11d3836f833835c445b317a77ead7599d1a0c08873014510d36bb7ff5fb961277589ea48c32a60c87ec40681be067b17785ec44825bd89faa25249e735a628b6eebcc6cce4e0314c627588118c40b2e0d460d8d5ce358c56458f36914ca203f5a5381c6deb5a76bbc08c40a87437da0d0b571788a05e9f96d9bb770de8a0b1b960ff2a44a964c9b7939853742e83ce8deb79191b2d82454655f227079dd8c5b0216c8470b8e1ac70526301bbfa2bc4adca68a766ccb2a6e0ebf2e99905bf5242590b01703868b3faf841c11c383be145a40fea6375e18a01468e459603b5efdf8a4e9abd179280ae8b5947d78d2f0c4d37715eaa42bc37cf8730e41ffbf9826d46424f2922a96033cefaa8b4bbe4c8b89d43501fd5211d5392ca19a98ba127d9025b5c6e86ba024471940549a2b5d8e14961c9dc19696da1a5bffd01030d5e6100000000000000000000000000000000000000000000000005090f131a1f").unwrap(); - assert_eq!(sig.len(), MLDSA65_SIG_LEN); - - if MLDSA65::verify(&mldsa65_pk, msg, None, &sig).is_ok() { - eprintln!("Verification succeeded!"); - } else { - panic!("Verification failed! -- figure that out"); - } -} - -fn bench_mldsa87_verify() { - use bouncycastle_mldsa::{MLDSATrait, MLDSA87, MLDSA87_SIG_LEN, MLDSA87PublicKey}; - use bouncycastle_hex as hex; - - eprintln!("MLDSA87/Verify"); - - let msg = b"The quick brown fox jumped over the lazy dog"; - - /* One-time setup of the KAT -- commented out so that keygen is not captured in the bench */ - - // let seed = KeyMaterial256::from_bytes_as_type( - // &hex::decode("000102030405060708090a0b0c0d0e0f101112131415161718191a1b1c1d1e1f").unwrap(), - // KeyType::Seed, - // ).unwrap(); - // - // let (mldsa65_pk, mldsa65_sk) = MLDSA87::keygen_from_seed(&seed).unwrap(); - // - // eprintln!("pk:\n{}", &*hex::encode(&mldsa65_pk.encode())); - // let mu = MLDSA87::compute_mu_from_sk(&mldsa65_sk, msg, None).unwrap(); - // let sig = MLDSA87::sign_mu_deterministic(&mldsa65_sk, &mu, [0u8; 32]).unwrap(); - // eprintln!("sig:\n{}", &*hex::encode(sig)); - - let mldsa87_pk = MLDSA87PublicKey::from_bytes(&*hex::decode("9792bcec2f2430686a82fccf3c2f5ff665e771d7ab41b90258cfa7e90ec97124a73b323b9ba21ab64d767c433f5a521effe18f86e46a188952c4467e048b729e7fc4d115e7e48da1896d5fe119b10dcddef62cb307954074b42336e52836de61da941f8d37ea68ac8106fabe19070679af6008537120f70793b8ea9cc0e6e7b7b4c9a5c7421c60f24451ba1e933db1a2ee16c79559f21b3d1b8305850aa42afbb13f1f4d5b9f4835f9d87dfceb162d0ef4a7fdc4cba1743cd1c87bb4967da16cc8764b6569df8ee5bdcbffe9a4e05748e6fdf225af9e4eeb7773b62e8f85f9b56b548945551844fbd89806a4ac369bed2d256100f688a6ad5e0a709826dc4449e91e23c5506e642361ef5a313712f79bc4b3186861ca85a4bab17e7f943d1b8a333aa3ae7ce16b440d6018f9e04daf5725c7f1a93fad1a5a27b67895bd249aa91685de20af32c8b7e268c7f96877d0c85001135a4f0a8f1b8264fa6ebe5a349d8aecad1a16299ccf2fd9c7b85bace2ced3aa1276ba61ee78ed7e5ca5b67cdd458a9354030e6abbbabf56a0a2316fec9dba83b51d42fd3167f1e0f90855d5c66509b210265dc1e54ec44b43ba7cf9aef118b44d80912ce75166a6651e116cebe49229a7062c09931f71abd2293f76f7efc3215ba97800037e58e470bdbbb43c1b0439eaf79c54d93b44aac9efe9fbe151874cfb2a64cbee28cc4c0fe7775e5d870f1c02e5b2e3c5004c995f24c9b779cb753a277d0e71fd425eb6bc2ca56ce129db51f70740f31e63976b50c7312e9797d78c5b1ac24a5fa347cc916e0a83f5c3b675cd30b81e3fa10b93444e07397571cce98b28da51db9056bc728c5b0b1181e2fbd387b4c79ab1a5fefece37167af772ddad14eb4c3982da5a59d0e9eb173ec6315091170027a3ab5ef6aa129cb8585727b9358a28501d713a72f3f1db31714286f9b6408013af06045d75592fc0b7dd47c73ed9c75b11e9d7c69f7cadfc3280a9062c5273c43be1c34f87448864cea7b5c97d6d32f59bd5f25384653bb5c4faa45bea8b89402843e645b6b9269e2bd988ddacb033328ffb060450f7df080053e6969b251e875ecec32cfc592840d69ab69a75e06b379c535d95266b082f4f09c93162b33b0d9f7307a4eaaa52104437fed66f8ee3eabbd45d67b25a8133f496468b52baffdbfad93eef1a9818b5e42ec722788a3d8d3529fc777d2ba570801dfae01ec88302837c1fb9e0355727645ee1046c3f915f6ae82dad4fb6b0356a46518ffc834155c3b4fe6dafa6cc8a5ccf53c73a0849d8d44f7dcf72754e70e1b7dfb447bb4ef49d1a718f6171bbce200950e0ce926106b151a3e871d5ce49731bd6650a9b0ca972da1c5f136d44820ea6383c08f3b384cf2338e789c513f618cc5694a6f0cee104511e1ed7c5f23a1ebfd8a0db8424553240156dbf622831b0c643d1c551b6f3f7a98d29b85c2de05a65fa615eee16495bd90737672115b53e91c5d90028cf3f1a93953a153de53b44084e9ccff6b736693926daefebb2d77aa5ad689b92f31686669df16d1715cc58f7a2cfb72dd1a51e92f825993a74022be7e9eb6054654457094d14928f20215e7b222ac56b51adbec8d8bdb6983979a7e3a21b44b5d1518ca97d0b5195f51ed6a24350c89747e1edea51b448e3e9147054ce927873c90db394d86888e07dff177593d6f79e152302204aeb03be2386af3e24078bd028b1689f5e147c9f452c8ceb02ec59cc9db63a03576ceeafe98239023897da0236630a53c0de7f435a19869792fab36e7b9e635760f09069e6432e700035ac2a02879fff0a1e1bec522047193d94eb5df1efd53eea1144ca78940852f5ec9727904b366ede4f5e2d331fad5fc282ea2c47e923142771c3dd75a87357487def99e5f18e9d9ed623c175d02888c51f82c07a80d54716b3c3c2bdbe2e9f0a9bbaaebeb4d52936876406f5c00e8e4bbd0a5ec05797e6207c5ab6c88f1a688421bd05a114f4d7de2ac241fa0e8bedff47f762ddcbeaa91004f8d31e85095c81054994ad3826e344ba96040810fc0b2ad1de48cfade002c62e5a49a0731ab38344bc1636df16bf607d56855e56d684003c718e4bad9e5a099979fcddeeb1c4a7776cd37a3417cb0e184e29ef9bc0e87475ba663be09e00ab562eb7c0f7165f969a9b42414198ccf1bff2a2c8d689a414ece7662927665689e94db961ebaec5615cbc1a7895c6851ac961432ff1118d4607d32ef9dc732d51333be4b4d0e30ddea784eca8be47e741be9c19631dc470a52ef4dc13a4f3633fd434d787c170977b417df598e1d0dde506bb71d6f0bc17ec70e3b03cdc1965cb36993f633b0472e50d0923ac6c66fdf1d3e6459cc121f0f5f94d09e9dbcf5d690e23233838a0bacb7c638d1b2650a4308cd171b6855126d1da672a6ed85a8d78c286fb56f4ab3d21497528045c63262c8a42af2f9802c53b7bb8be28e78fe0b5ce45fbb7a1af1a3b28a8d94b7890e3c882e39bc98e9f0ad76025bf0dd2f00298e7141a226b3d7cee414f604d1e0ba54d11d5fe58bccea6ad77ad2e8c1caacf32459014b7b91001b1efa8ad172a523fb8e365b577121bf9fd88a2c60c21e821d7b6acb47a5a995e40caced5c223b8fe6de5e18e9d2e5893aefebb7aae7ff1a146260e2f110e939528213a0025a38ec79aabc861b25ebc509a4674c132aaacb7e0146f14efd11cfcaf4caa4f775a716ce325e0a435a4d349d720bcf137450afc45046fc1a1f83a9d329777a7084e4aadae7122ce97005930528eb3c7f7f1129b372887a371155a3ba201a25cbf1dcb64e7cdee092c3141fb5550fe3d0dd82e870e578b2b46500818113b8f6569773c677385b69a42b77dcba7acffd95fd4452e23aaa1d37e1da2151ea658d40a3596b27ac9f8129dc6cf0643772624b59f4f461230df471ca26087c3942d5c6687df6082835935a3f87cb762b0c3b1d0dda4a6533965bef1b7b8292e254c014d090fed857c44c1839c694c0a64e3fad90a11f534722b6ee1574f2e149d55d744de4887024e08511431c062750e16c74ab9f3242f2db3ffb12a8d6107faa229d6f6373b07f36d3932b3bdb04c19dd64eadd7f93c3c564c358a1c81dcf1c9c31e5b06568f97544c17dc15698c5cb38983a9afc42783faa773a52c9d8260690be9e3156aa5bc1509dea3f69587695cd6ff172ba83e6a6d8a7d6bbebbbcda3672731983f89bc5831dc37c3f3c5c56facc697f3cb20bd5dbadbd702e54844ac2f626901fe159db93dfd4773d8fe73562b846c1fc856d1802762840ebc72d7988bde75cbca70d319d32ce0cc0253bb2ad455723ee0c7f4736ce6e6665c5aca32a481c53839bc259167b013d0423395eeb9aaaee3206149a7d550d67fc5fdfe4a8a5c35d2510b664379ab8f72855a2af47abce2a632048eaf89e5cb4a88debc53a595103acce4f1cff18acff07afe1eb5716aa1e40b63134c3a3ae9579fa87f515be093c2d29db6d6b65c93661e00636b592704d093cc6716c2342eb1853d48c85c63ac8a2854462c7b77e7e3bd1eac5bca28ffaa00b5d349f8a547ad875b96a8c2b2910c9301309a3f9138a5693111f55b3c009ca947c39dfc82d98eb1caa4a9cbe885f786fa86e55be062222f8ba90a974073326b31212aece0a34a60").unwrap()).unwrap(); - let sig = &*hex::decode("781368e64dba542a7eacbd2257335cc943a03241009b797093c615f76a671a7591430441d80bb582304b33b9fce295e0dd57fe169355ddf4453a2aca62d8eb8109ef0d9cf3f5b0a94e04ad81b3e786014243ecde816551aa7fe01c639054256a491756bef59f5034f717ff4f85e70ba7731a49971415b6a7e7d816ab434b9f17a3095ede6fd432be2bfa82724045dda0dfff7a0281e9000939ccba3d8ab3245139c441648c76a6536127e4d1ef0df1531883ab78c8b41323617ad8db03d9908c9e08a9f7321c45051b3c94213347b11c4a84491de7a7be68701e47d7f0e0b33e767bef17694e4d33244ed92ebd74c85ab6c84441cddc14331e6ae8bd23674bda27f09c050d88f7d430feee7f15a72a24d653bb6bec54491b98362ce131d37c7d78a3f9a893db5abdccd6663593b88bc6c97f07f8eafccfd25e8180d918efbcd95bbf3da29f081e3e1932095939198e2a155b2d803a3e84ca4f34569df695c259faf3c0d8f0cd217ebd2dbad542b32fbb54e44aaf0b5dc739fafef2e46db8d68bfc35f44f038cb1f5231a1b5b134ae683e7f3297cc7a95bd191b310f68201450797fe3293cde1672dfeca4b493f53c768ea048a972a4cd84d39ef682957b8f28ba29487b4689b43fec2655823d9bb99ffcf31490366a9860a5d5b8e32a3b8bfeb6f55f88fb80c8c0142086f220e1f6f2862dabda58c3b6f5faa805b39cfac4b6d7ea7acdf1b0690063b0c1ea38c7c4755189966dc631055f153f71b77b114fa5c309316ba512330ea5cdb0bb176001e57461563d17259f35d0c30ef5ac838c0325402bab52c531469526ae3ee6293f7b5769d27e69fa81cd25a31cd095b126e70c57ac3169a5f585a11f1748d9d22f2564911c26a24b2153a78f3a06822f5f1963f237abeb48efd9a9cd478de579c5a0ba84d00e96fbde36d8ce20e7e948547fb6850834ff79d211830f6ee973359781d9d5008fb43a89354782fde4158177f5206ce1d38c889e99e4bb5b4ab34d6a05c42f5d719ea03dbc54adba75a3bb44a3c08c7556462f8c5b7c568a69242cf5be6098eba0a2249c1ca5b2109b6404a962abc1c159c6b48a79fb97e4a3337d99323746221297423f9bd1b12e78489e01e6a10f0fd6bba1cfd6ae1b75dbe69f8b8ee51a4e7f68ba2c407c9c0bad3892b29b0170ab75836fdd49a7ee3c2bb30f2c3d226bcec49140952170b0d160f97b30b7b7b096719538677ebb06922f26925227c8852acc107a8f173b38d96697584bd3dfe169b4073aa58a7bf371d5c4bb0eed30f08212defb3aec902d4546084176bf0f86d93cf36a4689a5e874b32d6b7d3c1e3fbcfd988c35dbc9a8d0a019ad6d7e15ec3ac97125db6abfe00beffe35a81666699a91e15945c62d646690b5b52de8b835ee9be53588fde5d63023b52b2b1f4610c237a829f5901a46042963cce7b85aa040adde02985e14e23c4eadb75221c607d24672e244c66c9c24c3cb7fd90bb23295c9d3d9da516bce3dd462d6660f9f91ef0618a4d4d3d6668c5d1e2e8ed433ebfe0762beb743324e11608f8b14b69ce4c221c1654ba4992a5af2d949c2939f95d1c8fb767af2a843cc7c78f57259d5c0c6ca83fca41ef5ecc4eeeea93e4518c24d3040f2cd90df3e535e989e606fa109e2c453ed7353db1cdb27137f005f9dd8d2aebfb7255a6098b690215e100cfe44ca0f2745fced48322bc9667ab16d2e1c0ff491b96a17b833d4fd44d31c2230ac835796e063ab03000f04f15c70560033763a48552cceaacade9ca5c8055f3745e179068a287183f2bc3ef6327dec5ac7cf7b052ef5a8873e697efde089688f43be464827c2fa83eb531b3674145e95c699c82990e684967dad319d9f64ab16cd9fe9b6c41232ac4ae3795fd8a76aa9b02e970242061c6da45a2af74ad9cb2a79935c92625e242f4bc7fce54d5c10a9e61f875162fa651b66057ba036f062d6d39d0502b93a5640b78c6c2fd20b02ff83676a87a94945d476c349803ea4fe60cdcea65bb2629e2bc09d4472ec63422dee2052f098deaf5531e6c9bed6672a8b699802efe0cded80c8455f585d1ba633d281f1a21adab48e63b44e0c2a4d7608cf98aabf8adc86bcb8f61e8b06cd2385f82e0a3cdd03cab152d5951859c4532f9168e78f17ba2a5772780327dcf4e62b4d26e443762fc488ae4cd4d1156dbd5782595cfd7697a514abc9b160c9ccf08edc86134a755b90e9bb543511e888e3157721a52d1bc5db33029fb335ea2114e21c03368c8d7f4d827960641772a4a32a738df60d19ec77ab09d22f57cc2523b9503b3f5b1cebc5ae15f885f159842db7359a1c89d3d82d3407068f15b6739626eb8c521fc8c5c7491f945d49f14e6989da340bdf49e7f8a792747aa658bc114143ba93f26022d001735b744639bbf22aab2a1851cfc934f9c69d3764fdea3d23db17998e6138cfd7cd9e9a47cb74193bd71aaf28cdd9d1eb595125546a4f4357ebbd1f410e3bf8557892de68509b5b98c5c229e942c910fdd3e54cb6ad54d8dd886cb97ecc06d1e401b8395d0bcb0db9a031dc66c9294f9053c68fc42042b1fa1671fc7d510b70916c0139cfebe3a91244527ce9439860cedb30908197be851cbd1d3b18ca541358449fb34fb5cd569630ed5f67b8795e87828f2ce3becfe457579d82333b0bbab094de391e1f8157bd431e365ca864630932bbebb48f45f8134424e18ab455029b54b19e2f3bfec5e44ad0ea5c03f53d8f925b635838aa7015a7c9e325bdfaff966ea9512dd50f87c8995cea7561c23f4fb06d964ab8f1913a6ca17e4ca60d6bc078e1784f89c673c91d955bcf45f58ca9709579d5e3831df12cfdb7516fd21878cb54243579b9346d2de4be25f508e84b1adc78cb91c03da3c4fd59e4529189838f74f6312820620a5996b791ffcb332f847094613f2148b862034fa89d0d0ff1808d902c5d1af64d5522492d61ecde4c73be89a33782cef1acc1dc327fb2eb9d17642209b85aa8b1dc57cbf067c7aa29da6b7e157d23e171d3ae6f3855834071791402c851ff2dd67109979f7ee5e09e64b4eefdee7112b55ce200bb8c8051e3428c305fa1d576bffbb25a70eb571168fc60dadd928b10cfd07de80a85b8df3edc372d488c21f0d5787611cc6fb73aeeb6f920a109294b49d3870f90de3b360d14df77ef95640bcac7a4dbca901a31db83e83f5c59ce327207ea9b27c3b978d30d53865c1b84764f025e8732d5007554ce5c9cc410b2eefd7e4d990c538557606a6bc47577a43768d30aa3e8598fd6f4fe7ac439f3931c58fd69d90765ac9f456ac7de085e14a0898c4557f5d3baaae07edc607de6900146b97b35aae570153dc107815ef9febdd4fd567d637fee8f8bfb4b3413ea6aead4846ab733a04f1e4bc32a3bbb1c16baf8d0bdb9ccb82fe46479ccfd040b5e64064e539b39c66e4501dc822873ac6119a4a112a1f7cd6df0e5f84356ce853ced34ce69a9e7383534983c51c50269bf8b9586a0e5ba905fd3bce080b00e7f7d48e55f489479b5771e995fb020e58feb74af65c3ee76aa4e69b5ba8bda249a1b2d62c08d418c3635d061846040843991ab475473da85d94981fb84425e7ad951ce0a42be642fe658b7aaae72b147cdc086c24b1571eb2272e2a72b15660d854ebe19ec7d9ab7ea17800d0b6ae727b39217467c662ba08e6f19193951eeff02806a7843eb5c71b2f04dcb605ecedc5128cd67703038c44bf20fe06f3ed8c1368fe38e72944d5c52fca46a45fd48d8fe5da64183d4d62ec01aa3d9d672ec67a01c17f21e02525f0513cce030c664fc8784763086608bc8099c204c255ffed1daf432ceb45fbd135e21e8190c5bfee192171faa77520481e69e87b7f76790bef76cb8d3c88f5c6e32fc59e7bd45351d66696b61d9f40726fb9a98000b68738cf7e34b98b6a4aaa2ac1d7b1407db89783f8077103ea9c9e89247eae078adfb36e21474c3bb1fe0c87687c6233a533a01e1081b93a3521d339f39c075609bace531994988ae314f77fc6034113a138c67eb7e03750cbec8d28bd21afedfefa8f091619ae500b4ca4599d019dc8ca4bf118d70b8676dfc796a4f6d986adba4c8574ed4abaea5465466220e5e53dc8fcb395d1e59d278673cbc4e3f40658df98ac2fd126a94922879e1a3be91c1acc20803c35fa764abbadab07bde85ff4bd9e0fb6f06baf5bf42b8a2cbf6c2f62606becc361552921a12d6c8236fde84db4bddac77e8872478cffc4e148c1c7acfedf6b17d98731c2de36f3cbef1f6f781a940e0874d5b74535bbe066b53064d43b13926570a9e1c4e6da206c8bd252caf2b62e7d223f7ac12939137f330be59374d7295a6c2dff92e07c727510e48d970593e47229fc8bc3bd5b8ea780dacff4d23063df65feda5f8f65b17a333e532acad7916780c74d6a70d38b367f3f6f4e947b85fc15235bbe46b26495d2780098db853a931377cfbedea620f2355ca21e81ce9e0078b0dd6cb70f23ed558682be3b3d594eefe85344e1f275428b316cc088995939298f2a2d15ac9b676ac3e9cb92f2a64dec7732a91fc761aa1b126ea575e3953177da6e1cd78faea824665330a81d9e24572b9860bf0aba4df8bd5d4e3e2c72bbfbb2a985c7ae2f077951fe8401e1d156ecada1e353817b20f41e0b2460a0caaf2b36d6a7f1b35125d797dcc714421027d14171765a646071ed952b6a5294eecf6a3a71c104c843a4a8b3efcc27467b20cb0a94abf5802229ea4d8312783e78791a50b3c0a88fe6497198cd4bf470dac46f34e50019fdee2040cfe99124b312b1122b83e51d878877cec0855f1158c445cfdc2253f4389d5e3a8ba1669abb5976a4617e85f543da9f5e30b10ca7481c8185392782b46fb0a0e5ab408b2945e3c79a1cc49fb7c27254a9b540e7397a5b655bf7e4f83184db32a128aa2e00a624d7dcd6b77efd151f1e5cba8890af9170fa06c555715dc1787e995ad19270973ae95b88dcafdaf62c28843d3f8b9c78dc8e37d911dab3f7ee9d4c7389c654bdcfc05056b360020140e57e31473258a4081e2a708f7caba90c356d0847098fc0762484086aba898a60b023d6a3060402406240748785d51caff52a0ef3dc2a45dadf80ac18502d24422a8cbb10192b88f4e9160206b2ed3e04114f2a339df269e2c36b8613ce37087471701755330cb559575366ee0fa2d3afcda32eede6dd906345daaa04812198e96c42239c242edb90059709f497da5b87705384aef2af22dc2edfef3c00d8c9156d8b3163fe7a7779e04f04911a8b934fb3072eee844484fede5e2ee96d338eefe2da986067ffe0218ada7de1d0e42d823d6b033918278888ba0608ab8f7be997bdf263689a36f5204c802ad836363779b4b0d6ce5083df0b98a2e2c700062a4fa5e57bc73bd45357e01d90c7954bc6904d1ce8166a9168da39a60c5cae8119bb6b9ab074fb2d0aee384fc2c0e4806811d6002b4e2401e7430b50cb0e8075f33d5386aecde256e169d95e2f9c6556c08ba042e68a53ce8aca9cc02818f7382f150dc04de0019b19c7a3ab0d72d6ed013d7a115d74b279f71fd6effef34049877e0b11e0659be938a5de684eaf23513095eb4a1bdf536c3c01a4655c4b4a0673214cef29a481d06a02cc9a5bfc7b8d846c33484cd67b1de98f60b69918f177b64558ca567a6237d35ff01771a42320ce02bb98f3e4ad4ac7db75611bd9961eac662a38b1f785970c99f3dd105ff586f61301c48d66708cbf7d53a733e357b6c256e8b73f0e1305a0bc137989e521100c2ee6259e607fe12198e8bcb988b0854668e40d7cae6adc3ba40ba121b7319d06d988a073d03097b9f5c1c07284b6473ae57bf154811b77baceb0412b8a6983bdd0ccd9e3bf014e520009cb26d5780eabef1bbafa5e25d41098a54c47fce8b68d395291d54284d33aa50b9664d1510b467c8a539361ca9a4448bc01fcb4c4e3ef475e8afb46a494ae13ee9ea8a1266825fba7f32b9712fde252698a68359b50141d90f5c4a06283ddb54ad7e1412ac5ebb12501f7a82b2a7f27b2dbab626c3db4074523b3211d3182ea261397a6f7b187cf2b8a356ded10812f1d305169aedf79b5ff1cf7c2d6e86ee11f28e96aa63b5a03f59fc960ac7d0572e91dda61905c0711a9b26344a2a10aa2041f2b13cb1a9a9a27774b6d0deddc9d81ea1b142ad7b72be47991f2c9261d6708156e38d00b074020766eb0c494392d65b82ca65f7c3352f9bb78325ecb6df596c8ae57826b08ccd6f1d529d2e25925c1ac972425bedeb88a5d0e3138ddc434da3462ebdf6b1239a21f141ec62cbe4bb993ba253b55a76d30fac19c2c1384ef6b9746c07787aa1fe913a1348390bd8c1f386a08c77cf7106c927ce24dffc9d6ee1b32354d95ed2923482531de6b390bf0f5eb80276e90e7ed11131c848bbabec4d317236269a0a3a7cbe0f1272f93949ca6d23ea2a7ee3f697791aab71533423066d400000000000000000000000000000000000000000000000000000000050e181f23292c2f").unwrap(); - assert_eq!(sig.len(), MLDSA87_SIG_LEN); - - if MLDSA87::verify(&mldsa87_pk, msg, None, &sig).is_ok() { - eprintln!("Verification succeeded!"); - } else { - panic!("Verification failed! -- figure that out"); - } -} - -fn bench_mldsa87_lowmemory_verify() { - use bouncycastle_mldsa_lowmemory::{MLDSATrait, MLDSA87, MLDSA87_SIG_LEN, MLDSA87PublicKey}; - use bouncycastle_hex as hex; - - eprintln!("MLDSA87/Verify"); - - let msg = b"The quick brown fox jumped over the lazy dog"; - - /* One-time setup of the KAT -- commented out so that keygen is not captured in the bench */ - - // let seed = KeyMaterial256::from_bytes_as_type( - // &hex::decode("000102030405060708090a0b0c0d0e0f101112131415161718191a1b1c1d1e1f").unwrap(), - // KeyType::Seed, - // ).unwrap(); - // - // let (mldsa65_pk, mldsa65_sk) = MLDSA87::keygen_from_seed(&seed).unwrap(); - // - // eprintln!("pk:\n{}", &*hex::encode(&mldsa65_pk.encode())); - // let mu = MLDSA87::compute_mu_from_sk(&mldsa65_sk, msg, None).unwrap(); - // let sig = MLDSA87::sign_mu_deterministic(&mldsa65_sk, &mu, [0u8; 32]).unwrap(); - // eprintln!("sig:\n{}", &*hex::encode(sig)); - - let mldsa87_pk = MLDSA87PublicKey::from_bytes(&*hex::decode("9792bcec2f2430686a82fccf3c2f5ff665e771d7ab41b90258cfa7e90ec97124a73b323b9ba21ab64d767c433f5a521effe18f86e46a188952c4467e048b729e7fc4d115e7e48da1896d5fe119b10dcddef62cb307954074b42336e52836de61da941f8d37ea68ac8106fabe19070679af6008537120f70793b8ea9cc0e6e7b7b4c9a5c7421c60f24451ba1e933db1a2ee16c79559f21b3d1b8305850aa42afbb13f1f4d5b9f4835f9d87dfceb162d0ef4a7fdc4cba1743cd1c87bb4967da16cc8764b6569df8ee5bdcbffe9a4e05748e6fdf225af9e4eeb7773b62e8f85f9b56b548945551844fbd89806a4ac369bed2d256100f688a6ad5e0a709826dc4449e91e23c5506e642361ef5a313712f79bc4b3186861ca85a4bab17e7f943d1b8a333aa3ae7ce16b440d6018f9e04daf5725c7f1a93fad1a5a27b67895bd249aa91685de20af32c8b7e268c7f96877d0c85001135a4f0a8f1b8264fa6ebe5a349d8aecad1a16299ccf2fd9c7b85bace2ced3aa1276ba61ee78ed7e5ca5b67cdd458a9354030e6abbbabf56a0a2316fec9dba83b51d42fd3167f1e0f90855d5c66509b210265dc1e54ec44b43ba7cf9aef118b44d80912ce75166a6651e116cebe49229a7062c09931f71abd2293f76f7efc3215ba97800037e58e470bdbbb43c1b0439eaf79c54d93b44aac9efe9fbe151874cfb2a64cbee28cc4c0fe7775e5d870f1c02e5b2e3c5004c995f24c9b779cb753a277d0e71fd425eb6bc2ca56ce129db51f70740f31e63976b50c7312e9797d78c5b1ac24a5fa347cc916e0a83f5c3b675cd30b81e3fa10b93444e07397571cce98b28da51db9056bc728c5b0b1181e2fbd387b4c79ab1a5fefece37167af772ddad14eb4c3982da5a59d0e9eb173ec6315091170027a3ab5ef6aa129cb8585727b9358a28501d713a72f3f1db31714286f9b6408013af06045d75592fc0b7dd47c73ed9c75b11e9d7c69f7cadfc3280a9062c5273c43be1c34f87448864cea7b5c97d6d32f59bd5f25384653bb5c4faa45bea8b89402843e645b6b9269e2bd988ddacb033328ffb060450f7df080053e6969b251e875ecec32cfc592840d69ab69a75e06b379c535d95266b082f4f09c93162b33b0d9f7307a4eaaa52104437fed66f8ee3eabbd45d67b25a8133f496468b52baffdbfad93eef1a9818b5e42ec722788a3d8d3529fc777d2ba570801dfae01ec88302837c1fb9e0355727645ee1046c3f915f6ae82dad4fb6b0356a46518ffc834155c3b4fe6dafa6cc8a5ccf53c73a0849d8d44f7dcf72754e70e1b7dfb447bb4ef49d1a718f6171bbce200950e0ce926106b151a3e871d5ce49731bd6650a9b0ca972da1c5f136d44820ea6383c08f3b384cf2338e789c513f618cc5694a6f0cee104511e1ed7c5f23a1ebfd8a0db8424553240156dbf622831b0c643d1c551b6f3f7a98d29b85c2de05a65fa615eee16495bd90737672115b53e91c5d90028cf3f1a93953a153de53b44084e9ccff6b736693926daefebb2d77aa5ad689b92f31686669df16d1715cc58f7a2cfb72dd1a51e92f825993a74022be7e9eb6054654457094d14928f20215e7b222ac56b51adbec8d8bdb6983979a7e3a21b44b5d1518ca97d0b5195f51ed6a24350c89747e1edea51b448e3e9147054ce927873c90db394d86888e07dff177593d6f79e152302204aeb03be2386af3e24078bd028b1689f5e147c9f452c8ceb02ec59cc9db63a03576ceeafe98239023897da0236630a53c0de7f435a19869792fab36e7b9e635760f09069e6432e700035ac2a02879fff0a1e1bec522047193d94eb5df1efd53eea1144ca78940852f5ec9727904b366ede4f5e2d331fad5fc282ea2c47e923142771c3dd75a87357487def99e5f18e9d9ed623c175d02888c51f82c07a80d54716b3c3c2bdbe2e9f0a9bbaaebeb4d52936876406f5c00e8e4bbd0a5ec05797e6207c5ab6c88f1a688421bd05a114f4d7de2ac241fa0e8bedff47f762ddcbeaa91004f8d31e85095c81054994ad3826e344ba96040810fc0b2ad1de48cfade002c62e5a49a0731ab38344bc1636df16bf607d56855e56d684003c718e4bad9e5a099979fcddeeb1c4a7776cd37a3417cb0e184e29ef9bc0e87475ba663be09e00ab562eb7c0f7165f969a9b42414198ccf1bff2a2c8d689a414ece7662927665689e94db961ebaec5615cbc1a7895c6851ac961432ff1118d4607d32ef9dc732d51333be4b4d0e30ddea784eca8be47e741be9c19631dc470a52ef4dc13a4f3633fd434d787c170977b417df598e1d0dde506bb71d6f0bc17ec70e3b03cdc1965cb36993f633b0472e50d0923ac6c66fdf1d3e6459cc121f0f5f94d09e9dbcf5d690e23233838a0bacb7c638d1b2650a4308cd171b6855126d1da672a6ed85a8d78c286fb56f4ab3d21497528045c63262c8a42af2f9802c53b7bb8be28e78fe0b5ce45fbb7a1af1a3b28a8d94b7890e3c882e39bc98e9f0ad76025bf0dd2f00298e7141a226b3d7cee414f604d1e0ba54d11d5fe58bccea6ad77ad2e8c1caacf32459014b7b91001b1efa8ad172a523fb8e365b577121bf9fd88a2c60c21e821d7b6acb47a5a995e40caced5c223b8fe6de5e18e9d2e5893aefebb7aae7ff1a146260e2f110e939528213a0025a38ec79aabc861b25ebc509a4674c132aaacb7e0146f14efd11cfcaf4caa4f775a716ce325e0a435a4d349d720bcf137450afc45046fc1a1f83a9d329777a7084e4aadae7122ce97005930528eb3c7f7f1129b372887a371155a3ba201a25cbf1dcb64e7cdee092c3141fb5550fe3d0dd82e870e578b2b46500818113b8f6569773c677385b69a42b77dcba7acffd95fd4452e23aaa1d37e1da2151ea658d40a3596b27ac9f8129dc6cf0643772624b59f4f461230df471ca26087c3942d5c6687df6082835935a3f87cb762b0c3b1d0dda4a6533965bef1b7b8292e254c014d090fed857c44c1839c694c0a64e3fad90a11f534722b6ee1574f2e149d55d744de4887024e08511431c062750e16c74ab9f3242f2db3ffb12a8d6107faa229d6f6373b07f36d3932b3bdb04c19dd64eadd7f93c3c564c358a1c81dcf1c9c31e5b06568f97544c17dc15698c5cb38983a9afc42783faa773a52c9d8260690be9e3156aa5bc1509dea3f69587695cd6ff172ba83e6a6d8a7d6bbebbbcda3672731983f89bc5831dc37c3f3c5c56facc697f3cb20bd5dbadbd702e54844ac2f626901fe159db93dfd4773d8fe73562b846c1fc856d1802762840ebc72d7988bde75cbca70d319d32ce0cc0253bb2ad455723ee0c7f4736ce6e6665c5aca32a481c53839bc259167b013d0423395eeb9aaaee3206149a7d550d67fc5fdfe4a8a5c35d2510b664379ab8f72855a2af47abce2a632048eaf89e5cb4a88debc53a595103acce4f1cff18acff07afe1eb5716aa1e40b63134c3a3ae9579fa87f515be093c2d29db6d6b65c93661e00636b592704d093cc6716c2342eb1853d48c85c63ac8a2854462c7b77e7e3bd1eac5bca28ffaa00b5d349f8a547ad875b96a8c2b2910c9301309a3f9138a5693111f55b3c009ca947c39dfc82d98eb1caa4a9cbe885f786fa86e55be062222f8ba90a974073326b31212aece0a34a60").unwrap()).unwrap(); - let sig = &*hex::decode("781368e64dba542a7eacbd2257335cc943a03241009b797093c615f76a671a7591430441d80bb582304b33b9fce295e0dd57fe169355ddf4453a2aca62d8eb8109ef0d9cf3f5b0a94e04ad81b3e786014243ecde816551aa7fe01c639054256a491756bef59f5034f717ff4f85e70ba7731a49971415b6a7e7d816ab434b9f17a3095ede6fd432be2bfa82724045dda0dfff7a0281e9000939ccba3d8ab3245139c441648c76a6536127e4d1ef0df1531883ab78c8b41323617ad8db03d9908c9e08a9f7321c45051b3c94213347b11c4a84491de7a7be68701e47d7f0e0b33e767bef17694e4d33244ed92ebd74c85ab6c84441cddc14331e6ae8bd23674bda27f09c050d88f7d430feee7f15a72a24d653bb6bec54491b98362ce131d37c7d78a3f9a893db5abdccd6663593b88bc6c97f07f8eafccfd25e8180d918efbcd95bbf3da29f081e3e1932095939198e2a155b2d803a3e84ca4f34569df695c259faf3c0d8f0cd217ebd2dbad542b32fbb54e44aaf0b5dc739fafef2e46db8d68bfc35f44f038cb1f5231a1b5b134ae683e7f3297cc7a95bd191b310f68201450797fe3293cde1672dfeca4b493f53c768ea048a972a4cd84d39ef682957b8f28ba29487b4689b43fec2655823d9bb99ffcf31490366a9860a5d5b8e32a3b8bfeb6f55f88fb80c8c0142086f220e1f6f2862dabda58c3b6f5faa805b39cfac4b6d7ea7acdf1b0690063b0c1ea38c7c4755189966dc631055f153f71b77b114fa5c309316ba512330ea5cdb0bb176001e57461563d17259f35d0c30ef5ac838c0325402bab52c531469526ae3ee6293f7b5769d27e69fa81cd25a31cd095b126e70c57ac3169a5f585a11f1748d9d22f2564911c26a24b2153a78f3a06822f5f1963f237abeb48efd9a9cd478de579c5a0ba84d00e96fbde36d8ce20e7e948547fb6850834ff79d211830f6ee973359781d9d5008fb43a89354782fde4158177f5206ce1d38c889e99e4bb5b4ab34d6a05c42f5d719ea03dbc54adba75a3bb44a3c08c7556462f8c5b7c568a69242cf5be6098eba0a2249c1ca5b2109b6404a962abc1c159c6b48a79fb97e4a3337d99323746221297423f9bd1b12e78489e01e6a10f0fd6bba1cfd6ae1b75dbe69f8b8ee51a4e7f68ba2c407c9c0bad3892b29b0170ab75836fdd49a7ee3c2bb30f2c3d226bcec49140952170b0d160f97b30b7b7b096719538677ebb06922f26925227c8852acc107a8f173b38d96697584bd3dfe169b4073aa58a7bf371d5c4bb0eed30f08212defb3aec902d4546084176bf0f86d93cf36a4689a5e874b32d6b7d3c1e3fbcfd988c35dbc9a8d0a019ad6d7e15ec3ac97125db6abfe00beffe35a81666699a91e15945c62d646690b5b52de8b835ee9be53588fde5d63023b52b2b1f4610c237a829f5901a46042963cce7b85aa040adde02985e14e23c4eadb75221c607d24672e244c66c9c24c3cb7fd90bb23295c9d3d9da516bce3dd462d6660f9f91ef0618a4d4d3d6668c5d1e2e8ed433ebfe0762beb743324e11608f8b14b69ce4c221c1654ba4992a5af2d949c2939f95d1c8fb767af2a843cc7c78f57259d5c0c6ca83fca41ef5ecc4eeeea93e4518c24d3040f2cd90df3e535e989e606fa109e2c453ed7353db1cdb27137f005f9dd8d2aebfb7255a6098b690215e100cfe44ca0f2745fced48322bc9667ab16d2e1c0ff491b96a17b833d4fd44d31c2230ac835796e063ab03000f04f15c70560033763a48552cceaacade9ca5c8055f3745e179068a287183f2bc3ef6327dec5ac7cf7b052ef5a8873e697efde089688f43be464827c2fa83eb531b3674145e95c699c82990e684967dad319d9f64ab16cd9fe9b6c41232ac4ae3795fd8a76aa9b02e970242061c6da45a2af74ad9cb2a79935c92625e242f4bc7fce54d5c10a9e61f875162fa651b66057ba036f062d6d39d0502b93a5640b78c6c2fd20b02ff83676a87a94945d476c349803ea4fe60cdcea65bb2629e2bc09d4472ec63422dee2052f098deaf5531e6c9bed6672a8b699802efe0cded80c8455f585d1ba633d281f1a21adab48e63b44e0c2a4d7608cf98aabf8adc86bcb8f61e8b06cd2385f82e0a3cdd03cab152d5951859c4532f9168e78f17ba2a5772780327dcf4e62b4d26e443762fc488ae4cd4d1156dbd5782595cfd7697a514abc9b160c9ccf08edc86134a755b90e9bb543511e888e3157721a52d1bc5db33029fb335ea2114e21c03368c8d7f4d827960641772a4a32a738df60d19ec77ab09d22f57cc2523b9503b3f5b1cebc5ae15f885f159842db7359a1c89d3d82d3407068f15b6739626eb8c521fc8c5c7491f945d49f14e6989da340bdf49e7f8a792747aa658bc114143ba93f26022d001735b744639bbf22aab2a1851cfc934f9c69d3764fdea3d23db17998e6138cfd7cd9e9a47cb74193bd71aaf28cdd9d1eb595125546a4f4357ebbd1f410e3bf8557892de68509b5b98c5c229e942c910fdd3e54cb6ad54d8dd886cb97ecc06d1e401b8395d0bcb0db9a031dc66c9294f9053c68fc42042b1fa1671fc7d510b70916c0139cfebe3a91244527ce9439860cedb30908197be851cbd1d3b18ca541358449fb34fb5cd569630ed5f67b8795e87828f2ce3becfe457579d82333b0bbab094de391e1f8157bd431e365ca864630932bbebb48f45f8134424e18ab455029b54b19e2f3bfec5e44ad0ea5c03f53d8f925b635838aa7015a7c9e325bdfaff966ea9512dd50f87c8995cea7561c23f4fb06d964ab8f1913a6ca17e4ca60d6bc078e1784f89c673c91d955bcf45f58ca9709579d5e3831df12cfdb7516fd21878cb54243579b9346d2de4be25f508e84b1adc78cb91c03da3c4fd59e4529189838f74f6312820620a5996b791ffcb332f847094613f2148b862034fa89d0d0ff1808d902c5d1af64d5522492d61ecde4c73be89a33782cef1acc1dc327fb2eb9d17642209b85aa8b1dc57cbf067c7aa29da6b7e157d23e171d3ae6f3855834071791402c851ff2dd67109979f7ee5e09e64b4eefdee7112b55ce200bb8c8051e3428c305fa1d576bffbb25a70eb571168fc60dadd928b10cfd07de80a85b8df3edc372d488c21f0d5787611cc6fb73aeeb6f920a109294b49d3870f90de3b360d14df77ef95640bcac7a4dbca901a31db83e83f5c59ce327207ea9b27c3b978d30d53865c1b84764f025e8732d5007554ce5c9cc410b2eefd7e4d990c538557606a6bc47577a43768d30aa3e8598fd6f4fe7ac439f3931c58fd69d90765ac9f456ac7de085e14a0898c4557f5d3baaae07edc607de6900146b97b35aae570153dc107815ef9febdd4fd567d637fee8f8bfb4b3413ea6aead4846ab733a04f1e4bc32a3bbb1c16baf8d0bdb9ccb82fe46479ccfd040b5e64064e539b39c66e4501dc822873ac6119a4a112a1f7cd6df0e5f84356ce853ced34ce69a9e7383534983c51c50269bf8b9586a0e5ba905fd3bce080b00e7f7d48e55f489479b5771e995fb020e58feb74af65c3ee76aa4e69b5ba8bda249a1b2d62c08d418c3635d061846040843991ab475473da85d94981fb84425e7ad951ce0a42be642fe658b7aaae72b147cdc086c24b1571eb2272e2a72b15660d854ebe19ec7d9ab7ea17800d0b6ae727b39217467c662ba08e6f19193951eeff02806a7843eb5c71b2f04dcb605ecedc5128cd67703038c44bf20fe06f3ed8c1368fe38e72944d5c52fca46a45fd48d8fe5da64183d4d62ec01aa3d9d672ec67a01c17f21e02525f0513cce030c664fc8784763086608bc8099c204c255ffed1daf432ceb45fbd135e21e8190c5bfee192171faa77520481e69e87b7f76790bef76cb8d3c88f5c6e32fc59e7bd45351d66696b61d9f40726fb9a98000b68738cf7e34b98b6a4aaa2ac1d7b1407db89783f8077103ea9c9e89247eae078adfb36e21474c3bb1fe0c87687c6233a533a01e1081b93a3521d339f39c075609bace531994988ae314f77fc6034113a138c67eb7e03750cbec8d28bd21afedfefa8f091619ae500b4ca4599d019dc8ca4bf118d70b8676dfc796a4f6d986adba4c8574ed4abaea5465466220e5e53dc8fcb395d1e59d278673cbc4e3f40658df98ac2fd126a94922879e1a3be91c1acc20803c35fa764abbadab07bde85ff4bd9e0fb6f06baf5bf42b8a2cbf6c2f62606becc361552921a12d6c8236fde84db4bddac77e8872478cffc4e148c1c7acfedf6b17d98731c2de36f3cbef1f6f781a940e0874d5b74535bbe066b53064d43b13926570a9e1c4e6da206c8bd252caf2b62e7d223f7ac12939137f330be59374d7295a6c2dff92e07c727510e48d970593e47229fc8bc3bd5b8ea780dacff4d23063df65feda5f8f65b17a333e532acad7916780c74d6a70d38b367f3f6f4e947b85fc15235bbe46b26495d2780098db853a931377cfbedea620f2355ca21e81ce9e0078b0dd6cb70f23ed558682be3b3d594eefe85344e1f275428b316cc088995939298f2a2d15ac9b676ac3e9cb92f2a64dec7732a91fc761aa1b126ea575e3953177da6e1cd78faea824665330a81d9e24572b9860bf0aba4df8bd5d4e3e2c72bbfbb2a985c7ae2f077951fe8401e1d156ecada1e353817b20f41e0b2460a0caaf2b36d6a7f1b35125d797dcc714421027d14171765a646071ed952b6a5294eecf6a3a71c104c843a4a8b3efcc27467b20cb0a94abf5802229ea4d8312783e78791a50b3c0a88fe6497198cd4bf470dac46f34e50019fdee2040cfe99124b312b1122b83e51d878877cec0855f1158c445cfdc2253f4389d5e3a8ba1669abb5976a4617e85f543da9f5e30b10ca7481c8185392782b46fb0a0e5ab408b2945e3c79a1cc49fb7c27254a9b540e7397a5b655bf7e4f83184db32a128aa2e00a624d7dcd6b77efd151f1e5cba8890af9170fa06c555715dc1787e995ad19270973ae95b88dcafdaf62c28843d3f8b9c78dc8e37d911dab3f7ee9d4c7389c654bdcfc05056b360020140e57e31473258a4081e2a708f7caba90c356d0847098fc0762484086aba898a60b023d6a3060402406240748785d51caff52a0ef3dc2a45dadf80ac18502d24422a8cbb10192b88f4e9160206b2ed3e04114f2a339df269e2c36b8613ce37087471701755330cb559575366ee0fa2d3afcda32eede6dd906345daaa04812198e96c42239c242edb90059709f497da5b87705384aef2af22dc2edfef3c00d8c9156d8b3163fe7a7779e04f04911a8b934fb3072eee844484fede5e2ee96d338eefe2da986067ffe0218ada7de1d0e42d823d6b033918278888ba0608ab8f7be997bdf263689a36f5204c802ad836363779b4b0d6ce5083df0b98a2e2c700062a4fa5e57bc73bd45357e01d90c7954bc6904d1ce8166a9168da39a60c5cae8119bb6b9ab074fb2d0aee384fc2c0e4806811d6002b4e2401e7430b50cb0e8075f33d5386aecde256e169d95e2f9c6556c08ba042e68a53ce8aca9cc02818f7382f150dc04de0019b19c7a3ab0d72d6ed013d7a115d74b279f71fd6effef34049877e0b11e0659be938a5de684eaf23513095eb4a1bdf536c3c01a4655c4b4a0673214cef29a481d06a02cc9a5bfc7b8d846c33484cd67b1de98f60b69918f177b64558ca567a6237d35ff01771a42320ce02bb98f3e4ad4ac7db75611bd9961eac662a38b1f785970c99f3dd105ff586f61301c48d66708cbf7d53a733e357b6c256e8b73f0e1305a0bc137989e521100c2ee6259e607fe12198e8bcb988b0854668e40d7cae6adc3ba40ba121b7319d06d988a073d03097b9f5c1c07284b6473ae57bf154811b77baceb0412b8a6983bdd0ccd9e3bf014e520009cb26d5780eabef1bbafa5e25d41098a54c47fce8b68d395291d54284d33aa50b9664d1510b467c8a539361ca9a4448bc01fcb4c4e3ef475e8afb46a494ae13ee9ea8a1266825fba7f32b9712fde252698a68359b50141d90f5c4a06283ddb54ad7e1412ac5ebb12501f7a82b2a7f27b2dbab626c3db4074523b3211d3182ea261397a6f7b187cf2b8a356ded10812f1d305169aedf79b5ff1cf7c2d6e86ee11f28e96aa63b5a03f59fc960ac7d0572e91dda61905c0711a9b26344a2a10aa2041f2b13cb1a9a9a27774b6d0deddc9d81ea1b142ad7b72be47991f2c9261d6708156e38d00b074020766eb0c494392d65b82ca65f7c3352f9bb78325ecb6df596c8ae57826b08ccd6f1d529d2e25925c1ac972425bedeb88a5d0e3138ddc434da3462ebdf6b1239a21f141ec62cbe4bb993ba253b55a76d30fac19c2c1384ef6b9746c07787aa1fe913a1348390bd8c1f386a08c77cf7106c927ce24dffc9d6ee1b32354d95ed2923482531de6b390bf0f5eb80276e90e7ed11131c848bbabec4d317236269a0a3a7cbe0f1272f93949ca6d23ea2a7ee3f697791aab71533423066d400000000000000000000000000000000000000000000000000000000050e181f23292c2f").unwrap(); - assert_eq!(sig.len(), MLDSA87_SIG_LEN); - - if MLDSA87::verify(&mldsa87_pk, msg, None, &sig).is_ok() { - eprintln!("Verification succeeded!"); - } else { - panic!("Verification failed! -- figure that out"); - } -} - - - -fn main() { - // bench_do_nothing(); - // bench_mldsa44_keygen(); - // bench_mldsa44_lowmem_keygen(); - // bench_mldsa65_keygen(); - // bench_mldsa65_lowmemory_keygen() - // bench_mldsa87_keygen(); - // bench_mldsa87_lowmemory_keygen() - // bench_mldsa44_sign(); - // bench_mldsa44_lowmemory_sign(); - // bench_mldsa65_sign(); - // bench_mldsa65_lowmemory_sign(); - // bench_mldsa87_sign(); - // bench_mldsa87_lowmemory_sign(); - // bench_mldsa44_verify(); - // bench_mldsa44_lowmemory_verify(); - // bench_mldsa65_verify(); - // bench_mldsa65_lowmemory_verify(); - // bench_mldsa87_verify(); - bench_mldsa87_lowmemory_verify(); -} \ No newline at end of file diff --git a/src/lib.rs b/src/lib.rs index b46df8cd..afe7659c 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -1,3 +1,4 @@ +pub use bouncycastle_aes_lowmemory as aes_lowmemory; pub use bouncycastle_base64 as base64; pub use bouncycastle_core as core; pub use bouncycastle_factory as factory; @@ -8,6 +9,9 @@ pub use bouncycastle_mldsa as mldsa; pub use bouncycastle_mldsa_lowmemory as mldsa_lowmemory; pub use bouncycastle_mlkem as mlkem; pub use bouncycastle_mlkem_lowmemory as mlkem_lowmemory; +pub use bouncycastle_modes as modes; +pub use bouncycastle_padding as padding; pub use bouncycastle_rng as rng; pub use bouncycastle_sha2 as sha2; pub use bouncycastle_sha3 as sha3; +pub use bouncycastle_sm3 as sm3;