Compare commits

...

67 Commits
trunk ... dev

Author SHA1 Message Date
JohnE d0485e1531 awslc: say what FIPS mode does and does not claim
Refs: D-47
2026-11-16 21:33:40 -05:00
JohnE 4fa2651fe4 deps: pair bindgen 0.73 with prettyplease 0.3
The lock paired it with prettyplease 0.2 (syn 2), so the AWS-LC-FIPS
build failed to compile bindgen.

Refs: R3
2026-11-16 21:33:14 -05:00
JohnE 424f7607bd wolfssl: add SHA-256 and SHA-512 known-answer tests
The engine now refuses any directly used algorithm without a passing KAT,
and wolfSSL had none for its hashes.

Refs: R3
2026-11-16 21:15:29 -05:00
JohnE 4b79e83063 boring: report FIPS mode only for a validated module
A fips build from source is not a certified module; only fips-validated,
which needs a prebuilt validated BoringCrypto, may report FIPS. Also wipes
plaintext on a failed seal and the expected tag after verify.

Refs: R3
2026-11-16 21:04:42 -05:00
JohnE a3b33ae10c cascade: compare lineages and refuse provider aliases
Release policy now requires distinct adjacent lineages, and no provider can
be registered under another provider's name or a slot name.

Refs: R3
2026-11-16 21:03:11 -05:00
JohnE 598203b475 core: add a provider lineage for diversity rules
AWS-LC forks BoringSSL, so the two report one lineage and count as one
library when suites demand distinct providers.

Refs: R3
2026-11-16 21:03:10 -05:00
JohnE d0111ac521 workspace: leave wolfSSL out of default builds
wolfSSL is GPLv3 or commercial; it builds only when asked, in its own CI job.
CI also builds and self-tests AWS-LC-FIPS.

Refs: R3
2026-11-16 20:55:55 -05:00
JohnE 2861b9926a conformance: make the wolfSSL cross-check opt-in
The wolfssl feature adds wolfSSL and the pinned-file check; without it every
vector is still checked against the providers that are built.

Refs: R3
2026-11-16 20:55:55 -05:00
JohnE cdb600225f cascade: test against AWS-LC instead of wolfSSL
AWS-LC is the default vetted provider now; wolfSSL is opt-in.

Refs: R3
2026-11-16 20:55:55 -05:00
JohnE d2d2224c1e conformance: run the CCC v2 cascade vectors on awslc
Moving the AES-GCM anchor (and so the HKDF key schedule) or every layer
awslc offers onto it must reproduce cascade_v2.json byte for byte.

Refs: R3
2026-11-16 20:34:06 -05:00
JohnE 7de21de817 conformance: cross-check the awslc provider
awslc must reproduce the pinned vectors byte for byte and interoperate on
KEMs; regenerating only added it to provider lists, no output changed.

Refs: R3
2026-11-16 20:34:06 -05:00
JohnE 9310fe1262 awslc: add AwsLcProvider and registry init
Wires the primitives into CryptoProvider/KemProvider with cached
self-test, benchmark, capabilities and FIPS status.

Refs: R3
2026-11-16 20:33:07 -05:00
JohnE 59ae2bfa04 awslc: add capability probes and the AEAD benchmark
An algorithm is available only when its live probe works and its KAT
passed, so the engine's gate never admits an unverified algorithm.

Refs: R3
2026-11-16 20:33:07 -05:00
JohnE feaecad922 awslc: report FIPS mode only for a FIPS build
fips_mode() is true only with the fips feature (AWS-LC-FIPS) and when
aws_lc_rs::try_fips_mode() succeeds; an open-source build never asks.

Refs: R3
2026-11-16 20:33:07 -05:00
JohnE aba0763b3f awslc: add X25519 and ML-KEM known-answer tests
aws-lc-rs has no deterministic ML-KEM encapsulation, so the KAT decapsulates
an OpenSSL-made seed-00 vector pinned to the RustCrypto provider's values.

Refs: R3
2026-11-16 20:33:07 -05:00
JohnE 3099de4097 awslc: add symmetric known-answer self-tests
Every AEAD, hash, HMAC and HKDF the provider offers gets a published
vector, so the engine's KAT gate can admit it.

Refs: R3
2026-11-16 20:33:07 -05:00
JohnE 732eb8dd29 awslc: add X25519 and ML-KEM-768/1024
Public keys and ciphertexts use the standard encodings; ML-KEM private
keys are the expanded FIPS 203 dk since aws-lc-rs has no seed keygen API.

Refs: R3
2026-11-16 20:33:07 -05:00
JohnE 92e3eaf22f awslc: add HKDF-SHA-256/384/512
An empty salt is passed as the explicit zero salt of hash length: same
bytes as RFC 5869 and the other providers, and the form AWS-LC-FIPS approves.

Refs: R3
2026-11-16 20:33:07 -05:00
JohnE 72c24def82 awslc: add SHA-2, SHA-3 and HMAC-SHA-2
HMAC verification uses aws-lc-rs's constant-time hmac::verify; BLAKE2b
and Poly1305 are not in aws-lc-rs and report FeatureNotCompiled.

Refs: R3
2026-11-16 20:33:07 -05:00
JohnE 0631c1c637 awslc: add the aws-lc-rs provider crate with AEADs
aws-lc-rs (Apache-2.0/ISC) replaces wolfSSL as the vetted provider and
FIPS anchor; start with AES-256-GCM, AES-256-GCM-SIV and ChaCha20-Poly1305.

Refs: R3
2026-11-16 20:33:07 -05:00
JohnE bb6a09bd06 conformance: cross-check the boring provider
BoringProvider must reproduce every shared vector byte for byte; the
regenerated file only adds "boring" to the provider lists.

Refs: R3
2026-11-16 20:26:52 -05:00
JohnE 19ac46f165 boring: add BoringProvider with cached KATs and fips mode
Capabilities are computed once; fips_mode needs both the fips feature and
FIPS_mode() at run time.

Refs: R3
2026-11-16 20:26:52 -05:00
JohnE 5702935fc7 boring: add capability probes and AEAD benchmark
An algorithm is available only when its live probe and its KAT pass, so
the engine gate never sees an untested BoringSSL algorithm.

Refs: R3
2026-11-16 20:26:52 -05:00
JohnE 789b77fd7a boring: add known-answer self-test for every algorithm
The engine gate offers only algorithms with a passing KAT; the vectors are
the ones the RustCrypto and wolfSSL providers already pin.

Refs: R3
2026-11-16 20:26:52 -05:00
JohnE 4051bd6ccd boring: add X25519 and ML-KEM-768/1024 KEMs
Same key, ciphertext and secret formats as the other providers, so keys
and ciphertexts interoperate across libraries.

Refs: R3
2026-11-16 20:26:52 -05:00
JohnE 944b335454 boring: add AES-GCM and ChaCha20-Poly1305 AEADs
AES-256-GCM, ChaCha20-Poly1305 and XChaCha20-Poly1305 via EVP_AEAD, in the
ciphertext||tag format the other providers use.

Refs: R3
2026-11-16 20:26:52 -05:00
JohnE da2ed16c8d boring: add HKDF-SHA-2 key derivation
Uses BoringSSL's native HKDF; empty salt and length cap match the other
providers so the CCC key schedule derives the same keys.

Refs: R3
2026-11-16 20:26:52 -05:00
JohnE 01fb73fb4c boring: add HMAC-SHA-2 with constant-time verify
HMAC-SHA-256/384/512 from BoringSSL; tags are compared with CRYPTO_memcmp.

Refs: R3
2026-11-16 20:26:52 -05:00
JohnE 0ed4d9bb19 boring: add BoringSSL provider crate with SHA-2
Second native provider after the move off wolfSSL, backed by boring 5.5.0.
Starts with the crate skeleton and SHA-256/384/512.

Refs: R3
2026-11-16 20:26:52 -05:00
JohnE f8bca636b5 cascade: bind the vetted layer through a provider slot
Built-in suites name a 'vetted' slot that AWS-LC, BoringSSL or wolfSSL can
fill; the ciphertext does not depend on which one.

Refs: R3
2026-11-16 20:20:13 -05:00
JohnE 04643dbe97 workspace: refresh Cargo.lock for 0.2.0
The new crates were locked at 0.1.0 before the rebase onto the bump.

Refs: R3
2026-11-16 20:04:21 -05:00
JohnE 44a10149ce cascade: add HPKE PSK mode
LGP's Ultra U2 layer passes the McEliece secret as the HPKE PSK (spec
§8.5); interop with the hpke crate is tested both ways.
Refs: R4-10
2026-11-16 19:56:43 -05:00
JohnE 09553945af ci: add Gitea CI with a liboqs interop job
ccc_rust had only ci.sh; the McEliece cross-check against liboqs ran
nowhere (R3 review).
Refs: R3-6
2026-11-16 19:56:43 -05:00
JohnE 2fad139f73 cascade: pin CCC v2 and STREAM vectors across providers
Cascade output is pinned per built-in suite, and moving a layer to the
other provider must give identical bytes (R3 exit).
Refs: R3-6
2026-11-16 19:56:43 -05:00
JohnE 61e135f48d cascade: anchor the key schedule in the FIPS AES-GCM layer
Release suites need AES-256-GCM from a FIPS provider, whose HKDF keys
every layer; untested algorithms are refused; suite and rounds join the
HKDF info; STREAM gets a consuming finish().
Refs: R3-3, R3-6, R3-7
2026-11-16 19:56:43 -05:00
JohnE 3aec1a8460 wolfssl: add XChaCha, HKDF and HMAC self-test vectors
The cascade and HPKE key schedules use HKDF and HMAC, which had no
known-answer test, so a broken KDF passed the self-test gate.
Refs: R3-6
2026-11-16 19:56:43 -05:00
JohnE 9b11fb0c43 wolfssl: document the FIPS 140-3 build
Explains the bundle variables, configure options and the in-core
hash workflow for release builds.

Refs: R3-7
2026-11-16 19:56:43 -05:00
JohnE d92de9e60b wolfssl: report fips_mode from the FIPS self-test status
fips_mode must mean a validated module whose POST passed, not just a
build flag, so the policy can trust it.

Refs: R3-7
2026-11-16 19:56:43 -05:00
JohnE e68c3f5d46 wolfssl: build against the wolfCrypt FIPS bundle with fips
Release builds need the validated module (D-26); the build fails
when WOLFSSL_FIPS_SOURCE_DIR is missing instead of falling back.

Refs: R3-7
2026-11-16 19:56:43 -05:00
JohnE 64082b98a8 oqs: cross-check McEliece against the rustcrypto provider
Keys and ciphertexts from either implementation must work in the
other, including implicit rejection.

Refs: R3-9
2026-11-16 19:56:43 -05:00
JohnE 99c0324195 oqs: add seeded self-test that gates capabilities
liboqs reproduces the RustCrypto McEliece KAT bit for bit; HQC and
Frodo values pin the liboqs 0.13 build.

Refs: R3-5
2026-11-16 19:56:43 -05:00
JohnE b39272228f oqs: add McEliece 460896f, HQC-192 and FrodoKEM-976 KEMs
Code-based and LWE KEMs that wolfCrypt and RustCrypto lack; every
randomised call holds one lock so the self-test can seed liboqs.

Refs: R3-5
2026-11-16 19:56:43 -05:00
JohnE 355bfe3c2e oqs: add experimental liboqs provider crate as a stub
Without the liboqs feature it offers nothing, so default builds need
no cmake. The feature builds once the KEM and self-test land.

Refs: R3-5
2026-11-16 19:56:43 -05:00
JohnE 6e8f51d23f core: add HQC-192 and FrodoKEM-976 IDs and KEM tiers
The oqs provider needs IDs for them, and the policy checks need a
tier per KEM like the AEADs have.

Refs: R3-5
2026-11-16 19:56:43 -05:00
JohnE ec3db2efac rustcrypto: add McEliece 460896f self-test, mark it available
A seeded KAT pins keygen, encapsulation and decapsulation, so a
broken build fails closed instead of offering the KEM.

Refs: R3-9
2026-11-16 19:56:43 -05:00
JohnE 7ba9f6c996 rustcrypto: add Classic McEliece 460896f behind a feature
Ultra U2 needs a conservative KEM; work runs on an 8 MiB worker stack
so small caller threads cannot overflow. Not yet marked available.

Refs: R3-9
2026-11-16 19:56:43 -05:00
JohnE 3e0481901c core: add Classic McEliece 460896f KEM ID
Ultra U2 uses the f variant for steady keygen; ID 54 stays as is.
Providers report it as not compiled until they implement it.

Refs: R3-9
2026-11-16 19:56:43 -05:00
JohnE 92c75616ef cascade: add Argon2id with explicit parameters
Keyslots record their own Argon2id costs per profile; the providers'
Argon2id has one fixed set. Cross-checked against both providers.
Refs: R5-3
2026-11-16 19:56:43 -05:00
JohnE 9a39f9e1b8 docs: record CCC v2 benchmark results
Ultra's 3x16 cascade costs under 1 ms per 4 KiB message on M3.
Refs: R3
2026-11-16 19:56:43 -05:00
JohnE 66438b7049 cascade: add the 3-, 9- and 48-layer benchmark
The R3 exit asks for recorded seal and open costs of long suites.
Refs: R3-2
2026-11-16 19:56:43 -05:00
JohnE 71d07bd495 cascade: add RFC 9180 HPKE base mode over the providers
Inbox seals and LGP hand-outs use X-Wing HPKE with the vetted AEAD and
KDF; interop is checked against the independent hpke crate.
Refs: R3-9
2026-11-16 19:56:43 -05:00
JohnE 9ee740497b cascade: test built-in suites with both real providers
Each suite resolves and round-trips at 1, 3 and 16 rounds, and release
policy refuses this non-FIPS build (fail closed, D-26).
Refs: R3-3, R3-7
2026-11-16 19:56:43 -05:00
JohnE ba0cda4d26 conformance: pin cross-provider vectors for wolfssl and rustcrypto
Every algorithm both providers offer must give byte-identical output;
the vectors are checked in so CI catches drift in either provider.
Refs: R3-6
2026-11-16 19:56:43 -05:00
JohnE 5184dbd6ef rustcrypto: add provider, capabilities and benchmark
Registers as "rustcrypto" (fips_mode false); an algorithm is available
only if its live probe and its self-test both pass (fail closed, D-28).
Refs: R3-4
2026-11-16 19:56:43 -05:00
JohnE af11468d97 rustcrypto: add HKDF-SHA-384 self-test vector
Every offered algorithm needs a KAT before it is marked available;
the value is the RFC 5869 TC1 inputs checked against OpenSSL.
Refs: R3-4
2026-11-16 19:56:43 -05:00
JohnE 66ec0f0685 rustcrypto: add KDF and KEM self-test vectors
HKDF, Argon2id (RFC 9106), X25519 and X-Wing use published vectors;
ML-KEM seed keys are pinned against OpenSSL 3.6 deterministic encaps.
Refs: R3-4
2026-11-16 19:56:43 -05:00
JohnE 6a321e3efc rustcrypto: add AEAD, hash and MAC self-test vectors
Startup self-tests must fail closed (D-28); each symmetric algorithm
gets an RFC or NIST known-answer vector, including tag rejection.
Refs: R3-4
2026-11-16 19:56:43 -05:00
JohnE 2f1248e447 rustcrypto: add X25519, ML-KEM and X-Wing KEMs
Pure-Rust KEMs for the hybrid key agreement; ML-KEM keys are 64-byte
FIPS 203 seeds and X25519 keeps the wolfSSL ephemeral-DH convention.
Refs: R3-4
2026-11-16 19:56:43 -05:00
JohnE 2a8dbdcd6b rustcrypto: add HKDF, BLAKE2b KDF and Argon2id
Same semantics as the wolfSSL provider (zero salt, 255*HashLen cap,
64 MiB/3/4 Argon2id) so either provider derives identical keys.
Refs: R3-4
2026-11-16 19:56:43 -05:00
JohnE bb5473eeca rustcrypto: add hash and MAC primitives
SHA-2, SHA-3 and BLAKE2b digests plus HMAC, keyed BLAKE2b and Poly1305,
matching the wolfSSL provider's key and tag conventions.
Refs: R3-4
2026-11-16 19:56:43 -05:00
JohnE bc589960c8 rustcrypto: add pure-Rust provider crate with AEADs
Second, independent AEAD implementation for cascade layers (provider
diversity): AES-256-GCM, AES-256-GCM-SIV, (X)ChaCha20-Poly1305, Ascon-AEAD128.
Refs: R3-4
2026-11-16 19:56:43 -05:00
JohnE 743e9ee00e cascade: add STREAM mode for blobs
64 KiB segments with counter and last-flag nonces, so blobs cannot be
reordered or truncated, with memory bounded by one segment.
Refs: R3-2
2026-11-16 19:56:43 -05:00
JohnE 7058c5ffa4 cascade: add CCC v2 seal and open with suite policy
Independent HKDF-SHA-512 key and nonce per layer per round, AAD bound to
suite and layout, at most 16 rounds, fail closed on policy or self-test.
Refs: R3-2, R3-3, R3-6
2026-11-16 19:56:43 -05:00
JohnE 7776380a93 cascade: add secret types and bucket padding
Secrets never print and are wiped on drop (S8); padding hides sizes
behind buckets and unpads strictly.
Refs: R3-2, R3-8
2026-11-16 19:56:43 -05:00
JohnE f8c64390e3 wolfssl: fix HKDF-SHA-512 extract
wc_Tls13_HKDF_Extract rejects SHA-512 here, so every HKDF-SHA-512 call
failed; extract is now HMAC(salt, ikm), pinned by reference vectors.
Refs: R3-2
2026-11-16 19:56:43 -05:00
JohnE 7a10b28f2d core: add GCM-SIV, Ascon-AEAD128, X-Wing and tiers
The Rust registry becomes the single source of algorithm IDs and tiers
for CCC v2 (G-8); existing IDs keep their Dart values until R10.
Refs: R3-1
2026-11-16 19:56:43 -05:00
JohnE 110d33443f workspace: bump version to 0.2.0 and set authors
Owner's pending version bump, committed before merging the v2 work.

Refs: R3
2026-11-16 19:56:34 -05:00
84 changed files with 12359 additions and 78 deletions

View File

@ -0,0 +1,48 @@
# ccc_rust CI (R3-6). Gitea Actions (GitHub Actions syntax).
# The default job runs every default provider's self-test (wolfSSL is opt-in
# and has its own job), the cross-provider
# conformance and CCC v2 vector tests; the liboqs job builds the experimental
# provider and runs the McEliece interop check against the pure-Rust one.
name: ccc-ci
on:
push:
branches: [dev, trunk]
pull_request:
workflow_dispatch:
jobs:
test:
runs-on: ubuntu-latest
timeout-minutes: 45
steps:
- uses: actions/checkout@v4
with:
submodules: recursive
- name: Tests (default features)
run: ./ci.sh test
- name: Release-mode tests (cascade vectors, Argon2id, McEliece)
run: cargo test --release
- name: AWS-LC-FIPS build and self-test (the release anchor)
run: cargo test -p ccc-crypto-awslc --no-default-features --features fips --release
wolfssl:
# Opt-in provider (GPLv3 or commercial): self-test and cross-check only.
runs-on: ubuntu-latest
timeout-minutes: 45
steps:
- uses: actions/checkout@v4
with:
submodules: recursive
- name: wolfSSL self-test, conformance and pinned vectors
run: cargo test -p ccc-crypto-wolfssl -p ccc-conformance-tests --features ccc-conformance-tests/wolfssl --release
liboqs:
runs-on: ubuntu-latest
timeout-minutes: 60
steps:
- uses: actions/checkout@v4
with:
submodules: recursive
- name: Build liboqs provider and run its interop tests
run: cargo test -p ccc-crypto-oqs --features liboqs --release

1024
Cargo.lock generated

File diff suppressed because it is too large Load Diff

View File

@ -2,14 +2,31 @@
resolver = "2"
members = [
"crates/ccc-crypto-core",
"crates/ccc-cascade",
"crates/ccc-crypto-wolfssl",
"crates/ccc-crypto-rustcrypto",
"crates/ccc-crypto-oqs",
"crates/ccc-crypto-boring",
"crates/ccc-crypto-awslc",
"tests/conformance",
]
# Plain `cargo build` / `cargo test` leave out wolfSSL (GPLv3 or commercial).
# Build it explicitly: `cargo test -p ccc-crypto-wolfssl` and
# `cargo test -p ccc-conformance-tests --features wolfssl`.
default-members = [
"crates/ccc-crypto-core",
"crates/ccc-cascade",
"crates/ccc-crypto-rustcrypto",
"crates/ccc-crypto-oqs",
"crates/ccc-crypto-boring",
"crates/ccc-crypto-awslc",
"tests/conformance",
]
[workspace.package]
version = "0.1.0"
version = "0.2.0"
edition = "2021"
authors = ["LetUsMsg Engineering"]
authors = ["Malloc LLC"]
license = "MIT"
repository = "https://github.com/letusmsg/ccc_rust"
@ -26,4 +43,11 @@ env_logger = "0.11"
# ccc-crypto-core is referenced by every crate in the workspace.
ccc-crypto-core = { path = "crates/ccc-crypto-core" }
ccc-cascade = { path = "crates/ccc-cascade" }
ccc-crypto-rustcrypto = { path = "crates/ccc-crypto-rustcrypto" }
# Classic McEliece key generation is about 100x slower unoptimised; keep
# debug builds and the provider self-test usable.
[profile.dev.package.classic-mceliece-rust]
opt-level = 3

10
ci.sh
View File

@ -47,29 +47,29 @@ do_lint() {
pass "Format OK"
step "Clippy"
cargo clippy --workspace -- -D warnings || fail "clippy failed"
cargo clippy --all-targets -- -D warnings || fail "clippy failed"
pass "Clippy OK"
}
do_test() {
step "Unit tests"
cargo test --workspace || fail "cargo test failed"
cargo test || fail "cargo test failed"
pass "Unit tests passed"
step "Conformance vectors"
cargo run -p ccc-conformance-tests || fail "conformance tests failed"
cargo run -p ccc-conformance-tests --features wolfssl || fail "conformance tests failed"
pass "Conformance tests passed"
}
do_build() {
step "Build (debug)"
cargo build --workspace || fail "debug build failed"
cargo build || fail "debug build failed"
pass "Debug build OK"
}
do_release() {
step "Build (release)"
cargo build --workspace --release || fail "release build failed"
cargo build --release || fail "release build failed"
pass "Release build OK"
}

View File

@ -0,0 +1,20 @@
[package]
name = "ccc-cascade"
version.workspace = true
edition.workspace = true
authors.workspace = true
license.workspace = true
description = "CCC v2 cascade: per-layer HKDF keys, rounds, salt, AAD binding, padding, STREAM mode, suites and policy."
[dependencies]
ccc-crypto-core.workspace = true
zeroize.workspace = true
thiserror.workspace = true
argon2 = { version = "0.5", default-features = false, features = ["alloc", "zeroize"] }
[dev-dependencies]
ccc-crypto-awslc = { path = "../ccc-crypto-awslc" }
ccc-crypto-rustcrypto = { path = "../ccc-crypto-rustcrypto" }
# Independent RFC 9180 implementation, used only as an interop oracle.
hpke = { version = "0.15", default-features = false, features = ["alloc", "mlkem", "x25519", "aes", "hkdfsha2", "getrandom"] }
serde_json.workspace = true

View File

@ -0,0 +1,51 @@
//! R3 exit benchmark: seal and open time for 3-, 9- and 48-layer suites at 1
//! and 16 rounds, with layers alternating between wolfSSL and RustCrypto.
//! cargo run --release -p ccc-cascade --example bench_cascade
use std::sync::Arc;
use std::time::Instant;
use ccc_cascade::{open, seal, Context, Layer, Policy, ProviderSet, Suite};
use ccc_crypto_core::AeadAlgorithm::*;
use ccc_crypto_awslc::AwsLcProvider;
use ccc_crypto_rustcrypto::RustCryptoProvider;
fn suite(n: usize) -> Suite {
let cycle = [
Layer { aead: AesGcm256, provider: "awslc" },
Layer { aead: XChaCha20Poly1305, provider: "rustcrypto" },
Layer { aead: ChaCha20Poly1305, provider: "awslc" },
Layer { aead: AesGcmSiv256, provider: "rustcrypto" },
Layer { aead: AesGcmSiv256, provider: "awslc" },
Layer { aead: AsconAead128, provider: "rustcrypto" },
];
Suite { id: 1000 + n as u16, name: "bench", layers: (0..n).map(|i| cycle[i % cycle.len()].clone()).collect() }
}
fn main() {
let mut p = ProviderSet::new();
p.add(Arc::new(AwsLcProvider::new()));
p.add(Arc::new(RustCryptoProvider::new()));
let ctx = Context { domain: b"bench", aad: b"aad" };
println!("| layers | rounds | message | seal µs | open µs | overhead B |");
for layers in [3usize, 9, 48] {
let s = p.resolve(&suite(layers), &Policy::development()).unwrap();
for rounds in [1u8, 16] {
for size in [1024usize, 4096] {
let pt = vec![0x5a; size];
let iters = if layers * rounds as usize > 100 { 50 } else { 500 };
let t = Instant::now();
let mut ct = vec![];
for _ in 0..iters {
ct = seal(&s, rounds, &[1; 32], &[2; 32], ctx, &pt).unwrap();
}
let seal_us = t.elapsed().as_secs_f64() * 1e6 / iters as f64;
let t = Instant::now();
for _ in 0..iters {
open(&s, rounds, &[1; 32], &[2; 32], ctx, &ct).unwrap();
}
let open_us = t.elapsed().as_secs_f64() * 1e6 / iters as f64;
println!("| {layers} | {rounds} | {size} | {seal_us:.0} | {open_us:.0} | {} |", ct.len() - size);
}
}
}
}

View File

@ -0,0 +1,162 @@
//! The CCC v2 cascade (R3-2, D-8).
//!
//! For round `r` (0-based, up to [`MAX_ROUNDS`]) and layer `i` of a suite:
//!
//! ```text
//! okm(r,i) = HKDF-SHA-512(ikm = root key,
//! salt = per-message or per-record salt (32 bytes),
//! info = u16be(len(domain)) || domain || "ccc2"
//! || u16be(suite_id) || u8(rounds)
//! || u8(r) || u8(i) || u32be(alg_id(i)))
//! key(r,i) || nonce(r,i) = okm(r,i)
//! aad(r,i) = u16be(len(aad)) || aad || u16be(suite_id) || u8(rounds) || u8(r) || u8(i)
//! ```
//!
//! Sealing runs round 0 layer 0 first and the last layer of the last round
//! last; opening runs the reverse. Every layer of every round has an
//! independent key and nonce (S4). Nonces are derived, never random, and the
//! salt is fresh per message or record, so nonce reuse cannot happen. The AAD
//! binds the caller's context (S5) plus the suite, the round count and the
//! layer position, so a ciphertext cannot be opened under another suite or
//! layout. Any failure while opening is reported as one
//! [`CascadeError::AuthenticationFailed`]: the caller never learns which layer
//! failed.
use ccc_crypto_core::{AeadAlgorithm, KdfAlgorithm};
use zeroize::Zeroizing;
use crate::suite::{ResolvedSuite, MAX_ROUNDS};
use crate::CascadeError;
/// Salt length for every message and record.
pub const SALT_LEN: usize = 32;
/// Shortest accepted root key.
pub const MIN_ROOT_KEY_LEN: usize = 32;
/// What a cascade seal or open is about: the caller's domain label and AAD.
#[derive(Debug, Clone, Copy)]
pub struct Context<'a> {
/// Domain label, e.g. `b"lum/v1/rec"` or `b"lum/lgp/msg"`.
pub domain: &'a [u8],
/// Associated data binding the ciphertext to its place.
pub aad: &'a [u8],
}
pub(crate) fn layer_info(domain: &[u8], suite: u16, rounds: u8, round: u8, layer: u8, alg: AeadAlgorithm) -> Vec<u8> {
let mut info = Vec::with_capacity(domain.len() + 15);
info.extend_from_slice(&(domain.len() as u16).to_be_bytes());
info.extend_from_slice(domain);
info.extend_from_slice(b"ccc2");
info.extend_from_slice(&suite.to_be_bytes());
info.push(rounds);
info.push(round);
info.push(layer);
info.extend_from_slice(&(alg as u32).to_be_bytes());
info
}
pub(crate) fn layer_aad(aad: &[u8], suite: u16, rounds: u8, round: u8, layer: u8) -> Vec<u8> {
let mut out = Vec::with_capacity(aad.len() + 7);
out.extend_from_slice(&(aad.len() as u16).to_be_bytes());
out.extend_from_slice(aad);
out.extend_from_slice(&suite.to_be_bytes());
out.push(rounds);
out.push(round);
out.push(layer);
out
}
pub(crate) fn check_inputs(root_key: &[u8], salt: &[u8], ctx: &Context<'_>) -> Result<(), CascadeError> {
if root_key.len() < MIN_ROOT_KEY_LEN {
return Err(CascadeError::InvalidInput("root key shorter than 32 bytes"));
}
if salt.len() != SALT_LEN {
return Err(CascadeError::InvalidInput("salt must be 32 bytes"));
}
if ctx.domain.len() > u16::MAX as usize || ctx.aad.len() > u16::MAX as usize {
return Err(CascadeError::InvalidInput("domain or aad too long"));
}
Ok(())
}
/// Wiped-on-drop bytes.
pub(crate) type SecretVec = Zeroizing<Vec<u8>>;
/// Derive `(key, nonce)` for one layer.
pub(crate) fn layer_key(
suite: &ResolvedSuite,
root_key: &[u8],
salt: &[u8],
info: &[u8],
alg: AeadAlgorithm,
) -> Result<(SecretVec, SecretVec), CascadeError> {
let okm = suite.kdf.derive_key(KdfAlgorithm::Sha512, root_key, salt, info, alg.key_len() + alg.nonce_len())?;
let key = Zeroizing::new(okm[..alg.key_len()].to_vec());
let nonce = Zeroizing::new(okm[alg.key_len()..].to_vec());
Ok((key, nonce))
}
fn check_rounds(rounds: u8) -> Result<(), CascadeError> {
if rounds == 0 || rounds > MAX_ROUNDS {
return Err(CascadeError::Policy(format!("rounds must be 1..={MAX_ROUNDS}, got {rounds}")));
}
Ok(())
}
/// Seal `plaintext` with `rounds` passes of `suite`.
///
/// The output is the bare cascade ciphertext (plaintext length plus one tag
/// per layer per round); the caller frames it (version, suite, salt).
pub fn seal(
suite: &ResolvedSuite,
rounds: u8,
root_key: &[u8],
salt: &[u8],
ctx: Context<'_>,
plaintext: &[u8],
) -> Result<Vec<u8>, CascadeError> {
check_rounds(rounds)?;
check_inputs(root_key, salt, &ctx)?;
let mut data = Zeroizing::new(plaintext.to_vec());
for r in 0..rounds {
for (i, (alg, provider)) in suite.layers.iter().enumerate() {
let i = i as u8;
let (key, nonce) =
layer_key(suite, root_key, salt, &layer_info(ctx.domain, suite.id, rounds, r, i, *alg), *alg)?;
let aad = layer_aad(ctx.aad, suite.id, rounds, r, i);
data = Zeroizing::new(provider.encrypt_aead(*alg, &key, &nonce, &data, &aad)?);
}
}
Ok(data.to_vec())
}
/// Open a cascade ciphertext sealed by [`seal`] with the same inputs.
pub fn open(
suite: &ResolvedSuite,
rounds: u8,
root_key: &[u8],
salt: &[u8],
ctx: Context<'_>,
ciphertext: &[u8],
) -> Result<Zeroizing<Vec<u8>>, CascadeError> {
check_rounds(rounds)?;
check_inputs(root_key, salt, &ctx)?;
if ciphertext.len() < suite.overhead_per_round() * rounds as usize {
return Err(CascadeError::AuthenticationFailed);
}
let mut data = Zeroizing::new(ciphertext.to_vec());
for r in (0..rounds).rev() {
for (i, (alg, provider)) in suite.layers.iter().enumerate().rev() {
let i = i as u8;
let (key, nonce) =
layer_key(suite, root_key, salt, &layer_info(ctx.domain, suite.id, rounds, r, i, *alg), *alg)?;
let aad = layer_aad(ctx.aad, suite.id, rounds, r, i);
data = Zeroizing::new(
provider
.decrypt_aead(*alg, &key, &nonce, &data, &aad)
.map_err(|_| CascadeError::AuthenticationFailed)?,
);
}
}
Ok(data)
}

View File

@ -0,0 +1,286 @@
//! HPKE base and PSK modes, single shot (RFC 9180 §5.1, §6.1), over the provider
//! traits (R3-9). Used for the inbox seal to the channel ingest key (CIK) and
//! for LGP key hand-outs to receive keys, with the X-Wing KEM.
//!
//! The KEM, the KDF (HKDF via the provider's HMAC) and the AEAD each come from
//! a provider, so in release builds the AEAD and KDF are the FIPS module's.
//! Extract and Expand are built on HMAC so the labelled key schedule is exactly
//! RFC 9180's; interop is checked against the independent `hpke` crate.
//!
//! Output of [`seal`]: `enc || ciphertext`, where `enc` is the KEM ciphertext.
//! Base mode and PSK mode (`seal_psk` / `open_psk`) are supported.
use ccc_crypto_core::{AeadAlgorithm, AeadProvider, KemAlgorithm, KemProvider, MacAlgorithm, MacProvider};
use zeroize::Zeroizing;
use crate::CascadeError;
/// An HPKE ciphersuite: KEM, KDF and AEAD with their RFC 9180 / IANA IDs.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct HpkeSuite {
/// The KEM.
pub kem: KemAlgorithm,
/// IANA HPKE KEM ID (X-Wing: 0x647a).
pub kem_id: u16,
/// Length of `enc` (the KEM ciphertext) in bytes.
pub enc_len: usize,
/// HMAC for HKDF: `HmacSha256` (KDF ID 1) or `HmacSha512` (KDF ID 3).
pub kdf: MacAlgorithm,
/// The AEAD (AES-256-GCM: ID 2, ChaCha20-Poly1305: ID 3).
pub aead: AeadAlgorithm,
}
impl HpkeSuite {
/// X-Wing, HKDF-SHA256, AES-256-GCM: the LGP and inbox suite.
pub const XWING_SHA256_AES256GCM: HpkeSuite = HpkeSuite {
kem: KemAlgorithm::XWing,
kem_id: 0x647a,
enc_len: 1120,
kdf: MacAlgorithm::HmacSha256,
aead: AeadAlgorithm::AesGcm256,
};
fn kdf_id(&self) -> Result<u16, CascadeError> {
match self.kdf {
MacAlgorithm::HmacSha256 => Ok(1),
MacAlgorithm::HmacSha384 => Ok(2),
MacAlgorithm::HmacSha512 => Ok(3),
_ => Err(CascadeError::InvalidInput("HPKE KDF must be HMAC-SHA-2")),
}
}
fn hash_len(&self) -> usize {
match self.kdf {
MacAlgorithm::HmacSha384 => 48,
MacAlgorithm::HmacSha512 => 64,
_ => 32,
}
}
fn aead_id(&self) -> Result<u16, CascadeError> {
match self.aead {
AeadAlgorithm::AesGcm256 => Ok(2),
AeadAlgorithm::ChaCha20Poly1305 => Ok(3),
_ => Err(CascadeError::InvalidInput("HPKE AEAD must be AES-256-GCM or ChaCha20-Poly1305")),
}
}
fn suite_id(&self) -> Result<Vec<u8>, CascadeError> {
let mut id = b"HPKE".to_vec();
id.extend_from_slice(&self.kem_id.to_be_bytes());
id.extend_from_slice(&self.kdf_id()?.to_be_bytes());
id.extend_from_slice(&self.aead_id()?.to_be_bytes());
Ok(id)
}
}
/// The providers one HPKE operation uses.
pub struct HpkeProviders<'a> {
/// Provider of the KEM.
pub kem: &'a dyn KemProvider,
/// Provider of HMAC (the KDF).
pub mac: &'a dyn MacProvider,
/// Provider of the AEAD.
pub aead: &'a dyn AeadProvider,
}
type Secret = Zeroizing<Vec<u8>>;
struct Schedule<'a> {
suite: HpkeSuite,
suite_id: Vec<u8>,
mac: &'a dyn MacProvider,
}
impl Schedule<'_> {
// RFC 9180 §4: LabeledExtract(salt, label, ikm) = Extract(salt, "HPKE-v1" || suite_id || label || ikm)
fn labeled_extract(&self, salt: &[u8], label: &[u8], ikm: &[u8]) -> Result<Secret, CascadeError> {
let mut input = Zeroizing::new(Vec::with_capacity(7 + self.suite_id.len() + label.len() + ikm.len()));
input.extend_from_slice(b"HPKE-v1");
input.extend_from_slice(&self.suite_id);
input.extend_from_slice(label);
input.extend_from_slice(ikm);
// HKDF-Extract: an empty salt means HashLen zero bytes (RFC 5869 §2.2).
let zero = vec![0u8; self.suite.hash_len()];
let salt = if salt.is_empty() { &zero[..] } else { salt };
Ok(Zeroizing::new(self.mac.compute_mac(self.suite.kdf, salt, &input)?))
}
// LabeledExpand(prk, label, info, L) = Expand(prk, I2OSP(L, 2) || "HPKE-v1" || suite_id || label || info, L)
fn labeled_expand(&self, prk: &[u8], label: &[u8], info: &[u8], len: usize) -> Result<Secret, CascadeError> {
let mut labeled = Vec::with_capacity(9 + self.suite_id.len() + label.len() + info.len());
labeled.extend_from_slice(&(len as u16).to_be_bytes());
labeled.extend_from_slice(b"HPKE-v1");
labeled.extend_from_slice(&self.suite_id);
labeled.extend_from_slice(label);
labeled.extend_from_slice(info);
let hash_len = self.suite.hash_len();
if len > 255 * hash_len {
return Err(CascadeError::InvalidInput("HKDF output too long"));
}
let mut okm = Zeroizing::new(Vec::with_capacity(len));
let mut t: Secret = Zeroizing::new(Vec::new());
let mut counter = 1u8;
while okm.len() < len {
let mut input = Zeroizing::new(t.to_vec());
input.extend_from_slice(&labeled);
input.push(counter);
t = Zeroizing::new(self.mac.compute_mac(self.suite.kdf, prk, &input)?);
let take = (len - okm.len()).min(hash_len);
okm.extend_from_slice(&t[..take]);
counter = counter.wrapping_add(1);
}
Ok(okm)
}
// RFC 9180 §5.1 KeySchedule for mode_base (psk = None) or mode_psk.
// Returns (key, base_nonce).
fn key_schedule(
&self,
shared_secret: &[u8],
info: &[u8],
psk: Option<&Psk<'_>>,
) -> Result<(Secret, Secret), CascadeError> {
let (mode, psk_bytes, psk_id): (u8, &[u8], &[u8]) = match psk {
None => (0, b"", b""),
Some(p) => (1, p.psk, p.psk_id),
};
let psk_id_hash = self.labeled_extract(b"", b"psk_id_hash", psk_id)?;
let info_hash = self.labeled_extract(b"", b"info_hash", info)?;
let mut context = vec![mode];
context.extend_from_slice(&psk_id_hash);
context.extend_from_slice(&info_hash);
let secret = self.labeled_extract(shared_secret, b"secret", psk_bytes)?;
let key = self.labeled_expand(&secret, b"key", &context, self.suite.aead.key_len())?;
let nonce = self.labeled_expand(&secret, b"base_nonce", &context, self.suite.aead.nonce_len())?;
Ok((key, nonce))
}
}
fn schedule<'a>(suite: HpkeSuite, mac: &'a dyn MacProvider) -> Result<Schedule<'a>, CascadeError> {
Ok(Schedule { suite, suite_id: suite.suite_id()?, mac })
}
/// Key schedule only, from a known shared secret (for test vectors).
pub fn key_schedule_for_tests(
suite: HpkeSuite,
mac: &dyn MacProvider,
shared_secret: &[u8],
info: &[u8],
) -> Result<(Vec<u8>, Vec<u8>), CascadeError> {
let (k, n) = schedule(suite, mac)?.key_schedule(shared_secret, info, None)?;
Ok((k.to_vec(), n.to_vec()))
}
/// A pre-shared key for HPKE mode_psk (RFC 9180 §5.1.2). LGP's Ultra U2 layer
/// passes the Classic McEliece shared secret as the PSK, so the hand-out key
/// depends on both KEMs (the spec, §8.5).
pub struct Psk<'a> {
/// The pre-shared key (at least 32 bytes).
pub psk: &'a [u8],
/// Its identifier (non-empty).
pub psk_id: &'a [u8],
}
fn check_psk(psk: Option<&Psk<'_>>) -> Result<(), CascadeError> {
match psk {
Some(p) if p.psk.len() < 32 || p.psk_id.is_empty() => {
Err(CascadeError::InvalidInput("HPKE psk must be >= 32 bytes with a non-empty psk_id"))
}
_ => Ok(()),
}
}
/// Seal `plaintext` to `recipient_pk` (RFC 9180 SealBase, one message, so the
/// nonce is `base_nonce`). Returns `enc || ciphertext`.
pub fn seal(
suite: HpkeSuite,
p: &HpkeProviders<'_>,
recipient_pk: &[u8],
info: &[u8],
aad: &[u8],
plaintext: &[u8],
) -> Result<Vec<u8>, CascadeError> {
seal_with(suite, p, recipient_pk, info, aad, plaintext, None)
}
/// [`seal`] in mode_psk (RFC 9180 SealPSK).
pub fn seal_psk(
suite: HpkeSuite,
p: &HpkeProviders<'_>,
recipient_pk: &[u8],
psk: &Psk<'_>,
info: &[u8],
aad: &[u8],
plaintext: &[u8],
) -> Result<Vec<u8>, CascadeError> {
seal_with(suite, p, recipient_pk, info, aad, plaintext, Some(psk))
}
fn seal_with(
suite: HpkeSuite,
p: &HpkeProviders<'_>,
recipient_pk: &[u8],
info: &[u8],
aad: &[u8],
plaintext: &[u8],
psk: Option<&Psk<'_>>,
) -> Result<Vec<u8>, CascadeError> {
check_psk(psk)?;
let encap = p.kem.encapsulate(suite.kem, recipient_pk)?;
if encap.ciphertext.len() != suite.enc_len {
return Err(CascadeError::Crypto("KEM returned an unexpected enc length".into()));
}
let (key, nonce) = schedule(suite, p.mac)?.key_schedule(&encap.shared_secret, info, psk)?;
let ct = p.aead.encrypt_aead(suite.aead, &key, &nonce, plaintext, aad)?;
let mut out = Vec::with_capacity(encap.ciphertext.len() + ct.len());
out.extend_from_slice(&encap.ciphertext);
out.extend_from_slice(&ct);
Ok(out)
}
/// Open `enc || ciphertext` with the recipient's private key. Any failure is
/// [`CascadeError::AuthenticationFailed`].
pub fn open(
suite: HpkeSuite,
p: &HpkeProviders<'_>,
recipient_sk: &[u8],
info: &[u8],
aad: &[u8],
sealed: &[u8],
) -> Result<Zeroizing<Vec<u8>>, CascadeError> {
open_with(suite, p, recipient_sk, info, aad, sealed, None)
}
/// [`open`] in mode_psk (RFC 9180 OpenPSK).
pub fn open_psk(
suite: HpkeSuite,
p: &HpkeProviders<'_>,
recipient_sk: &[u8],
psk: &Psk<'_>,
info: &[u8],
aad: &[u8],
sealed: &[u8],
) -> Result<Zeroizing<Vec<u8>>, CascadeError> {
open_with(suite, p, recipient_sk, info, aad, sealed, Some(psk))
}
fn open_with(
suite: HpkeSuite,
p: &HpkeProviders<'_>,
recipient_sk: &[u8],
info: &[u8],
aad: &[u8],
sealed: &[u8],
psk: Option<&Psk<'_>>,
) -> Result<Zeroizing<Vec<u8>>, CascadeError> {
check_psk(psk)?;
if sealed.len() < suite.enc_len + suite.aead.tag_len() {
return Err(CascadeError::AuthenticationFailed);
}
let (enc, ct) = sealed.split_at(suite.enc_len);
let ss = p.kem.decapsulate(suite.kem, recipient_sk, enc).map_err(|_| CascadeError::AuthenticationFailed)?;
let (key, nonce) = schedule(suite, p.mac)?.key_schedule(&ss, info, psk)?;
let pt = p.aead.decrypt_aead(suite.aead, &key, &nonce, ct, aad).map_err(|_| CascadeError::AuthenticationFailed)?;
Ok(Zeroizing::new(pt))
}

View File

@ -0,0 +1,61 @@
//! # ccc-cascade
//!
//! CCC v2 (design: "Cascade encryption: CCC v2", D-8, D-25): a cascade of
//! AEAD layers from several providers, with an independent HKDF-SHA-512 key
//! and nonce for every layer of every round, a random 32-byte salt per message
//! or record, AAD binding, bucket padding and a STREAM mode for blobs. Plus the
//! suite registry and the policy checks (at least one vetted layer, FIPS vetted
//! layer in release builds, adjacent provider diversity, self-tests passed).
//!
//! Nothing here is specific to LetUsMsg and nothing does I/O.
#![forbid(unsafe_code)]
#![warn(missing_docs)]
pub mod cascade;
pub mod hpke;
pub mod padding;
pub mod password;
pub mod secret;
pub mod stream;
pub mod suite;
pub mod suites;
pub use cascade::{open, seal, Context, SALT_LEN};
pub use padding::{pad, unpad, Bucketing};
pub use secret::{Key32, SecretBytes};
pub use stream::{StreamOpener, StreamSealer, SEGMENT_LEN};
pub use suite::{Layer, Policy, ProviderSet, ResolvedSuite, Suite, MAX_ROUNDS};
use ccc_crypto_core::CryptoError;
/// Errors from the cascade.
#[derive(Debug, Clone, thiserror::Error)]
pub enum CascadeError {
/// A suite, round count or layout breaks the policy (fail closed).
#[error("policy: {0}")]
Policy(String),
/// An algorithm failed its provider's self-test; no fallback (D-28).
#[error("self-test failed: {0}")]
SelfTestFailed(String),
/// Opening failed. Never says which layer.
#[error("authentication failed")]
AuthenticationFailed,
/// Malformed input.
#[error("invalid input: {0}")]
InvalidInput(&'static str),
/// A provider error while sealing or deriving keys.
#[error("crypto: {0}")]
Crypto(String),
}
impl From<CryptoError> for CascadeError {
fn from(e: CryptoError) -> Self {
match e {
CryptoError::AuthenticationFailed => Self::AuthenticationFailed,
other => Self::Crypto(other.to_string()),
}
}
}
#[cfg(test)]
mod tests;

View File

@ -0,0 +1,96 @@
//! Bucket padding (design: "Record envelope" and the profile padding rows).
//!
//! Padded form: `u32be(len) || data || zeros`, with the total rounded up to a
//! bucket so sizes leak less. Unpadding is strict: the fill must be all zeros.
use crate::CascadeError;
/// How sizes are rounded.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct Bucketing {
/// Bucket step in bytes below `linear_limit`.
pub step: usize,
/// Up to this size, buckets are multiples of `step`; above it, powers of two.
pub linear_limit: usize,
}
impl Bucketing {
/// Records at rest: 256-byte steps up to 4 KiB, then powers of two.
pub const RECORDS: Bucketing = Bucketing { step: 256, linear_limit: 4096 };
/// Standard and the floor: 256-byte buckets.
pub const WIRE_256: Bucketing = Bucketing { step: 256, linear_limit: 4096 };
/// High: 1 KiB buckets.
pub const WIRE_1K: Bucketing = Bucketing { step: 1024, linear_limit: 4096 };
/// Ultra: one 4 KiB bucket for every message (plus random extra steps).
pub const WIRE_4K: Bucketing = Bucketing { step: 4096, linear_limit: 4096 };
/// The bucket size for `n` bytes (including the 4-byte length prefix).
pub fn bucket(&self, n: usize) -> usize {
let step = self.step.max(1);
if n <= self.linear_limit {
n.div_ceil(step).max(1) * step
} else {
n.next_power_of_two()
}
}
}
/// Pad `data`. `extra_steps` adds that many more `step`s (Ultra's random
/// extra; the caller draws it from its RNG port).
pub fn pad(data: &[u8], b: Bucketing, extra_steps: usize) -> Result<Vec<u8>, CascadeError> {
let len = u32::try_from(data.len()).map_err(|_| CascadeError::InvalidInput("too large to pad"))?;
let total = b.bucket(data.len() + 4) + extra_steps * b.step;
let mut out = Vec::with_capacity(total);
out.extend_from_slice(&len.to_be_bytes());
out.extend_from_slice(data);
out.resize(total, 0);
Ok(out)
}
/// Undo [`pad`]. Fails if the length prefix or the zero fill is wrong.
pub fn unpad(padded: &[u8]) -> Result<&[u8], CascadeError> {
let bad = CascadeError::InvalidInput("bad padding");
let prefix: [u8; 4] = padded.get(..4).and_then(|p| p.try_into().ok()).ok_or(bad.clone())?;
let len = u32::from_be_bytes(prefix) as usize;
let end = 4usize.checked_add(len).filter(|e| *e <= padded.len()).ok_or(bad.clone())?;
if padded[end..].iter().any(|b| *b != 0) {
return Err(bad);
}
Ok(&padded[4..end])
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn buckets() {
let r = Bucketing::RECORDS;
assert_eq!(r.bucket(1), 256);
assert_eq!(r.bucket(256), 256);
assert_eq!(r.bucket(257), 512);
assert_eq!(r.bucket(4096), 4096);
assert_eq!(r.bucket(4097), 8192);
assert_eq!(Bucketing::WIRE_4K.bucket(10), 4096);
assert_eq!(Bucketing::WIRE_1K.bucket(1500), 2048);
}
#[test]
fn round_trip_and_strict_unpad() {
for n in [0usize, 1, 251, 252, 253, 4092, 4093, 10_000] {
let data: Vec<u8> = (0..n).map(|i| i as u8).collect();
let p = pad(&data, Bucketing::RECORDS, 0).unwrap();
assert_eq!(p.len(), Bucketing::RECORDS.bucket(n + 4));
assert_eq!(unpad(&p).unwrap(), data.as_slice());
}
let p = pad(b"hi", Bucketing::WIRE_256, 2).unwrap();
assert_eq!(p.len(), 256 * 3);
let mut bad = p.clone();
*bad.last_mut().unwrap() = 1;
assert!(unpad(&bad).is_err(), "non-zero fill");
let mut bad = p.clone();
bad[..4].copy_from_slice(&10_000u32.to_be_bytes());
assert!(unpad(&bad).is_err(), "length past end");
assert!(unpad(&[0, 0]).is_err());
}
}

View File

@ -0,0 +1,59 @@
//! Password hashing with explicit parameters (Argon2id, RFC 9106).
//!
//! The providers' `KdfAlgorithm::Argon2id` uses one fixed parameter set; the
//! keyslots need the parameters each slot records (per profile, D-28: never
//! reduced per device), so this module takes them explicitly.
use zeroize::Zeroizing;
use crate::CascadeError;
/// Argon2id cost parameters.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct Argon2Params {
/// Memory in KiB.
pub memory_kib: u32,
/// Passes over memory.
pub iterations: u32,
/// Lanes.
pub parallelism: u32,
}
/// Fewest bytes of salt accepted.
pub const MIN_SALT_LEN: usize = 16;
/// Argon2id(`secret`, `salt`) with `params`, producing `out_len` bytes.
pub fn argon2id(
secret: &[u8],
salt: &[u8],
params: Argon2Params,
out_len: usize,
) -> Result<Zeroizing<Vec<u8>>, CascadeError> {
if salt.len() < MIN_SALT_LEN {
return Err(CascadeError::InvalidInput("Argon2id salt shorter than 16 bytes"));
}
let p = argon2::Params::new(params.memory_kib, params.iterations, params.parallelism, Some(out_len))
.map_err(|_| CascadeError::InvalidInput("bad Argon2id parameters"))?;
let a = argon2::Argon2::new(argon2::Algorithm::Argon2id, argon2::Version::V0x13, p);
let mut out = Zeroizing::new(vec![0u8; out_len]);
a.hash_password_into(secret, salt, &mut out).map_err(|_| CascadeError::InvalidInput("Argon2id failed"))?;
Ok(out)
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn deterministic_and_parameter_sensitive() {
// Known-answer agreement with both providers is in
// tests/password_cross_check.rs.
let p = Argon2Params { memory_kib: 64, iterations: 3, parallelism: 1 };
let a = argon2id(b"password", &[1; 16], p, 32).unwrap();
assert_eq!(a, argon2id(b"password", &[1; 16], p, 32).unwrap());
assert_ne!(a, argon2id(b"password", &[2; 16], p, 32).unwrap());
assert_ne!(a, argon2id(b"passwore", &[1; 16], p, 32).unwrap());
assert_ne!(a, argon2id(b"password", &[1; 16], Argon2Params { iterations: 4, ..p }, 32).unwrap());
assert!(argon2id(b"password", &[1; 8], p, 32).is_err());
}
}

View File

@ -0,0 +1,89 @@
//! Secret byte types (R3-8, S8): zeroized on drop and never printed.
use std::fmt;
use zeroize::{Zeroize, Zeroizing};
/// Secret bytes. `Debug` prints only the length; the bytes are wiped on drop.
#[derive(Clone, Default)]
pub struct SecretBytes(Zeroizing<Vec<u8>>);
impl SecretBytes {
/// Take ownership of `bytes`.
pub fn new(bytes: Vec<u8>) -> Self {
Self(Zeroizing::new(bytes))
}
/// Copy `bytes` in; the caller should wipe its own copy.
pub fn from_slice(bytes: &[u8]) -> Self {
Self(Zeroizing::new(bytes.to_vec()))
}
/// The secret bytes.
pub fn expose(&self) -> &[u8] {
&self.0
}
/// Length in bytes.
pub fn len(&self) -> usize {
self.0.len()
}
/// Whether it is empty.
pub fn is_empty(&self) -> bool {
self.0.is_empty()
}
}
impl From<Zeroizing<Vec<u8>>> for SecretBytes {
fn from(z: Zeroizing<Vec<u8>>) -> Self {
Self(z)
}
}
impl fmt::Debug for SecretBytes {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "SecretBytes([REDACTED; {}])", self.0.len())
}
}
/// A 32-byte secret key.
#[derive(Clone)]
pub struct Key32([u8; 32]);
impl Key32 {
/// Wrap `bytes`.
pub fn new(bytes: [u8; 32]) -> Self {
Self(bytes)
}
/// The key bytes.
pub fn expose(&self) -> &[u8; 32] {
&self.0
}
}
impl Drop for Key32 {
fn drop(&mut self) {
self.0.zeroize();
}
}
impl fmt::Debug for Key32 {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str("Key32([REDACTED])")
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn debug_never_prints_secrets() {
let s = SecretBytes::from_slice(b"top secret value");
assert_eq!(format!("{s:?}"), "SecretBytes([REDACTED; 16])");
let k = Key32::new([0x41; 32]);
assert_eq!(format!("{k:?}"), "Key32([REDACTED])");
}
}

View File

@ -0,0 +1,138 @@
//! STREAM mode for blobs (R3-2, attachments): 64 KiB segments, one cascade
//! round, per-segment nonces and a final-segment flag (the STREAM construction
//! of Hoang, Reyhanitabar, Rogaway and Vizár).
//!
//! Per layer `i` the key and a nonce prefix come from the same schedule as
//! [`crate::cascade`] (round 0, domain suffixed `/stream`). Segment `n`'s
//! nonce is `prefix || u32be(n) || u8(last)`, so segments cannot be reordered,
//! dropped, duplicated or truncated without failing authentication. Memory is
//! bounded by one segment.
use zeroize::Zeroizing;
use crate::cascade::{check_inputs, layer_aad, layer_info, layer_key, Context};
use crate::suite::ResolvedSuite;
use crate::CascadeError;
/// Plaintext bytes per segment (the last may be shorter, even empty).
pub const SEGMENT_LEN: usize = 64 * 1024;
struct LayerState {
key: Zeroizing<Vec<u8>>,
prefix: Zeroizing<Vec<u8>>,
}
/// Shared state of a sealer or opener.
struct Stream {
suite: ResolvedSuite,
aad: Vec<u8>,
layers: Vec<LayerState>,
next: u32,
finished: bool,
}
impl Stream {
fn new(suite: &ResolvedSuite, root_key: &[u8], salt: &[u8], ctx: Context<'_>) -> Result<Self, CascadeError> {
check_inputs(root_key, salt, &ctx)?;
let mut domain = ctx.domain.to_vec();
domain.extend_from_slice(b"/stream");
let mut layers = Vec::with_capacity(suite.layers.len());
for (i, (alg, _)) in suite.layers.iter().enumerate() {
if alg.nonce_len() < 12 {
return Err(CascadeError::InvalidInput("STREAM needs nonces of at least 12 bytes"));
}
let (key, nonce) =
layer_key(suite, root_key, salt, &layer_info(&domain, suite.id, 1, 0, i as u8, *alg), *alg)?;
let prefix = Zeroizing::new(nonce[..alg.nonce_len() - 5].to_vec());
layers.push(LayerState { key, prefix });
}
Ok(Self { suite: suite.clone(), aad: ctx.aad.to_vec(), layers, next: 0, finished: false })
}
fn nonce(&self, layer: usize, last: bool) -> Vec<u8> {
let mut n = self.layers[layer].prefix.to_vec();
n.extend_from_slice(&self.next.to_be_bytes());
n.push(u8::from(last));
n
}
fn advance(&mut self, last: bool) -> Result<(), CascadeError> {
self.finished = last;
self.next = self.next.checked_add(1).ok_or(CascadeError::InvalidInput("too many segments"))?;
Ok(())
}
}
/// Seals a blob segment by segment.
pub struct StreamSealer(Stream);
impl StreamSealer {
/// Start sealing under `root_key` and a fresh 32-byte `salt`.
pub fn new(suite: &ResolvedSuite, root_key: &[u8], salt: &[u8], ctx: Context<'_>) -> Result<Self, CascadeError> {
Ok(Self(Stream::new(suite, root_key, salt, ctx)?))
}
/// Seal the next segment (at most [`SEGMENT_LEN`] bytes). Mark the final
/// one with `last`; nothing can be sealed after it.
pub fn seal_segment(&mut self, segment: &[u8], last: bool) -> Result<Vec<u8>, CascadeError> {
let s = &mut self.0;
if s.finished {
return Err(CascadeError::InvalidInput("stream already finished"));
}
if segment.len() > SEGMENT_LEN || (!last && segment.len() != SEGMENT_LEN) {
return Err(CascadeError::InvalidInput("segments are SEGMENT_LEN bytes, except the last"));
}
let mut data = Zeroizing::new(segment.to_vec());
for (i, (alg, provider)) in s.suite.layers.iter().enumerate() {
let aad = layer_aad(&s.aad, s.suite.id, 1, 0, i as u8);
data = Zeroizing::new(provider.encrypt_aead(*alg, &s.layers[i].key, &s.nonce(i, last), &data, &aad)?);
}
s.advance(last)?;
Ok(data.to_vec())
}
}
/// Opens a blob segment by segment.
pub struct StreamOpener(Stream);
impl StreamOpener {
/// Start opening a blob sealed with these inputs.
pub fn new(suite: &ResolvedSuite, root_key: &[u8], salt: &[u8], ctx: Context<'_>) -> Result<Self, CascadeError> {
Ok(Self(Stream::new(suite, root_key, salt, ctx)?))
}
/// Open the next sealed segment. `last` must say whether it is the final
/// one; a wrong claim fails authentication.
pub fn open_segment(&mut self, sealed: &[u8], last: bool) -> Result<Zeroizing<Vec<u8>>, CascadeError> {
let s = &mut self.0;
if s.finished || sealed.len() > SEGMENT_LEN + s.suite.overhead_per_round() {
return Err(CascadeError::AuthenticationFailed);
}
let mut data = Zeroizing::new(sealed.to_vec());
for (i, (alg, provider)) in s.suite.layers.iter().enumerate().rev() {
let aad = layer_aad(&s.aad, s.suite.id, 1, 0, i as u8);
data = Zeroizing::new(
provider
.decrypt_aead(*alg, &s.layers[i].key, &s.nonce(i, last), &data, &aad)
.map_err(|_| CascadeError::AuthenticationFailed)?,
);
}
s.advance(last)?;
Ok(data)
}
/// Whether the final segment has been opened.
pub fn is_finished(&self) -> bool {
self.0.finished
}
/// End of input: succeeds only if the final segment was opened, so a
/// truncated blob is always rejected.
pub fn finish(self) -> Result<(), CascadeError> {
if self.0.finished {
Ok(())
} else {
Err(CascadeError::AuthenticationFailed)
}
}
}

View File

@ -0,0 +1,237 @@
//! Cascade suites, providers and policy (R3-3, R3-6, R3-7).
//!
//! A suite is an ordered list of layers, each an AEAD from a named provider.
//! Before a suite is used it is *resolved* against the providers this build
//! has, and checked against a [`Policy`]:
//!
//! - at least one vetted layer (S4);
//! - in release builds, a vetted layer from a FIPS-mode provider (D-26);
//! - optionally, adjacent layers from different providers;
//! - experimental layers only when the policy allows them;
//! - every layer's algorithm passed its provider's self-test (fail closed, S6,
//! D-28): there is no fallback suite.
use std::collections::{HashMap, HashSet};
use std::sync::Arc;
use ccc_crypto_core::{AeadAlgorithm, CryptoProvider, KdfAlgorithm, Tier};
use crate::CascadeError;
/// Most rounds any suite may use (D-25).
pub const MAX_ROUNDS: u8 = 16;
/// One layer of a suite.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Layer {
/// The AEAD.
pub aead: AeadAlgorithm,
/// The provider slot that runs it: a provider name (`"rustcrypto"`), or
/// a slot such as [`crate::suites::VETTED`] that the build binds to one of
/// several interchangeable providers with [`ProviderSet::bind`].
pub provider: &'static str,
}
/// A named, versioned suite.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Suite {
/// Stable suite ID; part of every envelope and of the AAD.
pub id: u16,
/// Name for logs and diagnostics.
pub name: &'static str,
/// Layers, applied first to last when sealing.
pub layers: Vec<Layer>,
}
/// The rules a suite must meet.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Policy {
/// The vetted layer must come from a FIPS-mode provider (release builds).
pub require_fips_vetted_layer: bool,
/// Adjacent layers must come from different library lineages
/// ([`CryptoProvider::lineage`]).
pub require_distinct_adjacent_providers: bool,
/// Experimental-tier layers are allowed.
pub allow_experimental: bool,
/// Fewest layers allowed.
pub min_layers: usize,
}
impl Policy {
/// Development builds: everything but the FIPS requirement.
pub fn development() -> Self {
Self {
require_fips_vetted_layer: false,
require_distinct_adjacent_providers: false,
allow_experimental: false,
min_layers: 1,
}
}
/// Release builds (D-26): the vetted layer must come from a provider in
/// FIPS mode (AWS-LC-FIPS by default), and adjacent layers from different
/// library lineages. A build without a FIPS module cannot resolve any
/// suite.
pub fn release() -> Self {
Self { require_fips_vetted_layer: true, require_distinct_adjacent_providers: true, ..Self::development() }
}
}
/// Slot names a suite may use besides provider names; see [`ProviderSet::bind`].
const SLOTS: &[&str] = &[crate::suites::VETTED];
/// The providers this build has, with the algorithms that passed their
/// known-answer self-test. An algorithm without a passing vector is treated as
/// failed: the gate fails closed (S6).
#[derive(Clone, Default)]
pub struct ProviderSet {
providers: HashMap<&'static str, Arc<dyn CryptoProvider>>,
passed: HashSet<(&'static str, u32)>,
}
impl ProviderSet {
/// An empty set.
pub fn new() -> Self {
Self::default()
}
/// Add `provider` after running its self-test. Algorithms that fail are
/// recorded and every suite using them refuses to resolve.
///
/// # Panics
/// If the provider's name is a reserved slot name (a build error).
pub fn add(&mut self, provider: Arc<dyn CryptoProvider>) -> &mut Self {
let name = provider.provider_name();
assert!(!SLOTS.contains(&name), "provider name {name:?} is a reserved slot");
self.bind_unchecked(name, provider)
}
/// Add `provider` under the slot `slot` (for example
/// [`crate::suites::VETTED`]) after running its self-test. Providers that
/// implement an algorithm produce the same bytes, so the binding can change
/// between builds without changing any ciphertext.
///
/// # Panics
/// If `slot` is neither a reserved slot nor the provider's own name, so
/// one library can never pose as another (a build error).
pub fn bind(&mut self, slot: &'static str, provider: Arc<dyn CryptoProvider>) -> &mut Self {
assert!(
SLOTS.contains(&slot) || slot == provider.provider_name(),
"cannot bind {:?} under the name {slot:?}",
provider.provider_name()
);
self.bind_unchecked(slot, provider)
}
fn bind_unchecked(&mut self, slot: &'static str, provider: Arc<dyn CryptoProvider>) -> &mut Self {
let name = slot;
self.passed.retain(|(p, _)| *p != name);
let report = provider.self_test();
// Any failing vector for an algorithm disqualifies it, even if another
// vector for it passed.
let failed: HashSet<u32> = report.results.iter().filter(|r| !r.passed).map(|r| r.algo_id).collect();
for r in report.results.iter().filter(|r| r.passed && !failed.contains(&r.algo_id)) {
self.passed.insert((name, r.algo_id));
}
self.providers.insert(name, provider);
self
}
/// The provider bound to `name` (a provider name or a slot).
pub fn get(&self, name: &str) -> Option<&Arc<dyn CryptoProvider>> {
self.providers.get(name)
}
/// Whether `(provider, algorithm)` failed its self-test or has none.
pub fn failed_self_test(&self, provider: &str, algo_id: u32) -> bool {
!self.passed.iter().any(|(p, a)| *p == provider && *a == algo_id)
}
/// Resolve `suite` under `policy`.
pub fn resolve(&self, suite: &Suite, policy: &Policy) -> Result<ResolvedSuite, CascadeError> {
let deny = |m: String| Err(CascadeError::Policy(format!("suite {}: {m}", suite.name)));
if suite.layers.len() < policy.min_layers.max(1) {
return deny(format!("needs at least {} layers", policy.min_layers.max(1)));
}
let mut layers = Vec::with_capacity(suite.layers.len());
for (i, l) in suite.layers.iter().enumerate() {
let Some(p) = self.providers.get(l.provider) else {
return deny(format!("layer {i}: provider {} is not in this build", l.provider));
};
if self.failed_self_test(l.provider, l.aead as u32) {
return Err(CascadeError::SelfTestFailed(format!("{} in {}", l.aead.name(), l.provider)));
}
let caps = p.capabilities();
if !caps.aead.get(&l.aead).is_some_and(|c| c.available) {
return deny(format!("layer {i}: {} not available in {}", l.aead.name(), l.provider));
}
if l.aead.tier() == Tier::Experimental && !policy.allow_experimental {
return deny(format!("layer {i}: experimental {} not allowed", l.aead.name()));
}
layers.push((l.aead, p.clone()));
}
if !suite.layers.iter().any(|l| l.aead.tier() == Tier::Vetted) {
return deny("no vetted layer".into());
}
// The anchor layer supplies the key schedule's HKDF. In release builds
// it must be an approved AEAD (AES-256-GCM) from a FIPS-mode provider
// (D-26); otherwise prefer an approved AEAD, then any vetted layer.
let fips_anchor =
suite.layers.iter().find(|l| l.aead.fips_approved() && self.providers[l.provider].fips_mode());
let anchor = if policy.require_fips_vetted_layer {
match fips_anchor {
Some(l) => l,
None => return deny("no AES-256-GCM layer from a FIPS-mode provider".into()),
}
} else {
suite
.layers
.iter()
.find(|l| l.aead.fips_approved())
.or_else(|| suite.layers.iter().find(|l| l.aead.tier() == Tier::Vetted))
.expect("a vetted layer exists")
};
if self.failed_self_test(anchor.provider, KdfAlgorithm::Sha512 as u32) {
return Err(CascadeError::SelfTestFailed(format!("HKDF-SHA-512 in {}", anchor.provider)));
}
// Distinct means distinct code bases, so compare the lineage of what
// the slots are bound to, not the slot names.
let implementation = |slot: &str| self.providers[slot].lineage();
if policy.require_distinct_adjacent_providers
&& suite.layers.windows(2).any(|w| implementation(w[0].provider) == implementation(w[1].provider))
{
return deny("adjacent layers share a provider".into());
}
let kdf = self.providers[anchor.provider].clone();
Ok(ResolvedSuite { id: suite.id, name: suite.name, layers, kdf })
}
}
/// A suite checked against a policy, with its providers attached.
#[derive(Clone)]
pub struct ResolvedSuite {
/// Suite ID.
pub id: u16,
/// Suite name.
pub name: &'static str,
pub(crate) layers: Vec<(AeadAlgorithm, Arc<dyn CryptoProvider>)>,
pub(crate) kdf: Arc<dyn CryptoProvider>,
}
impl ResolvedSuite {
/// Number of layers.
pub fn layer_count(&self) -> usize {
self.layers.len()
}
/// Bytes one round adds (one tag per layer).
pub fn overhead_per_round(&self) -> usize {
self.layers.iter().map(|(a, _)| a.tag_len()).sum()
}
}
impl std::fmt::Debug for ResolvedSuite {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("ResolvedSuite").field("id", &self.id).field("name", &self.name).finish()
}
}

View File

@ -0,0 +1,72 @@
//! Built-in suites (R3-1): the registry's named, versioned suites. IDs are
//! stable: they are part of every envelope and of the AAD.
//!
//! LetUsMsg's profiles pick from these in `lum-crypto` (R3-10).
use ccc_crypto_core::AeadAlgorithm::{AesGcm256, AesGcmSiv256, AsconAead128, XChaCha20Poly1305};
use crate::suite::{Layer, Suite};
/// The slot for the vetted, FIPS-capable layer. Builds bind it to AWS-LC
/// (default), BoringSSL or wolfSSL with [`crate::ProviderSet::bind`].
pub const VETTED: &str = "vetted";
const fn layer(aead: ccc_crypto_core::AeadAlgorithm, provider: &'static str) -> Layer {
Layer { aead, provider }
}
/// Floor: one vetted layer (AES-256-GCM from the vetted provider).
pub fn floor_aes() -> Suite {
Suite { id: 1, name: "floor-aes", layers: vec![layer(AesGcm256, VETTED)] }
}
/// Standard+: two layers, two providers, two design families.
pub fn standard_2() -> Suite {
Suite {
id: 2,
name: "standard-2",
layers: vec![layer(AesGcm256, VETTED), layer(XChaCha20Poly1305, "rustcrypto")],
}
}
/// High: three layers alternating providers.
pub fn high_3() -> Suite {
Suite {
id: 3,
name: "high-3",
layers: vec![
layer(XChaCha20Poly1305, "rustcrypto"),
layer(AesGcm256, VETTED),
layer(AesGcmSiv256, "rustcrypto"),
],
}
}
/// Ultra: three layers from two providers including a conservative
/// alternative (Ascon-AEAD128), with adjacent layers from different providers.
pub fn ultra_3() -> Suite {
Suite {
id: 4,
name: "ultra-3",
layers: vec![
layer(XChaCha20Poly1305, "rustcrypto"),
layer(AesGcm256, VETTED),
layer(AsconAead128, "rustcrypto"),
],
}
}
/// Storage at rest for Standard: two layers (design: storage cascade row).
pub fn storage_2() -> Suite {
Suite { id: 5, name: "storage-2", layers: vec![layer(AesGcm256, VETTED), layer(AesGcmSiv256, "rustcrypto")] }
}
/// Every built-in suite.
pub fn all() -> Vec<Suite> {
vec![floor_aes(), standard_2(), high_3(), ultra_3(), storage_2()]
}
/// The built-in suite with `id`.
pub fn by_id(id: u16) -> Option<Suite> {
all().into_iter().find(|s| s.id == id)
}

View File

@ -0,0 +1,339 @@
//! Cascade tests over the wolfSSL provider, plus a delegating test provider
//! that lets the policy checks see other provider names, FIPS mode and
//! self-test failures.
use std::sync::Arc;
use ccc_crypto_core::{
AeadAlgorithm::{self, AesGcm256, ChaCha20Poly1305, XChaCha20Poly1305},
AeadProvider, AlgoTestResult, BenchmarkReport, CryptoError, CryptoProvider, HashAlgorithm, HashProvider,
KdfAlgorithm, KdfProvider, MacAlgorithm, MacProvider, ProviderCapabilities, SelfTestReport,
};
use ccc_crypto_awslc::AwsLcProvider;
use ccc_crypto_rustcrypto::RustCryptoProvider;
use zeroize::Zeroizing;
use super::*;
/// Delegates to RustCrypto under another name, with a chosen FIPS flag and
/// optionally one algorithm failing its self-test.
struct TestProvider {
name: &'static str,
fips: bool,
fail: Option<AeadAlgorithm>,
inner: RustCryptoProvider,
}
impl TestProvider {
fn arc(name: &'static str, fips: bool, fail: Option<AeadAlgorithm>) -> Arc<dyn CryptoProvider> {
Arc::new(Self { name, fips, fail, inner: RustCryptoProvider::new() })
}
}
impl AeadProvider for TestProvider {
fn encrypt_aead(&self, a: AeadAlgorithm, k: &[u8], n: &[u8], p: &[u8], aad: &[u8]) -> Result<Vec<u8>, CryptoError> {
self.inner.encrypt_aead(a, k, n, p, aad)
}
fn decrypt_aead(&self, a: AeadAlgorithm, k: &[u8], n: &[u8], c: &[u8], aad: &[u8]) -> Result<Vec<u8>, CryptoError> {
self.inner.decrypt_aead(a, k, n, c, aad)
}
}
impl KdfProvider for TestProvider {
fn derive_key(
&self,
a: KdfAlgorithm,
ikm: &[u8],
salt: &[u8],
info: &[u8],
len: usize,
) -> Result<Zeroizing<Vec<u8>>, CryptoError> {
self.inner.derive_key(a, ikm, salt, info, len)
}
}
impl MacProvider for TestProvider {
fn compute_mac(&self, a: MacAlgorithm, k: &[u8], d: &[u8]) -> Result<Vec<u8>, CryptoError> {
self.inner.compute_mac(a, k, d)
}
fn verify_mac(&self, a: MacAlgorithm, k: &[u8], d: &[u8], m: &[u8]) -> Result<bool, CryptoError> {
self.inner.verify_mac(a, k, d, m)
}
}
impl HashProvider for TestProvider {
fn hash(&self, a: HashAlgorithm, d: &[u8]) -> Result<Vec<u8>, CryptoError> {
self.inner.hash(a, d)
}
}
impl CryptoProvider for TestProvider {
fn provider_name(&self) -> &'static str {
self.name
}
fn lineage(&self) -> &'static str {
// Test providers named "bssl-*" claim AWS-LC's lineage.
if self.name.starts_with("bssl-") {
"boringssl"
} else {
self.name
}
}
fn fips_mode(&self) -> bool {
self.fips
}
fn capabilities(&self) -> ProviderCapabilities {
self.inner.capabilities()
}
fn self_test(&self) -> SelfTestReport {
let mut r = self.inner.self_test();
// "novec" has no vector at all for AES-256-GCM-SIV.
if self.name == "novec" {
r.results.retain(|t| t.algo_id != AeadAlgorithm::AesGcmSiv256 as u32);
}
if let Some(a) = self.fail {
r.results.push(AlgoTestResult {
algo_id: a as u32,
algo_name: a.name().into(),
passed: false,
error_message: Some("injected".into()),
});
}
r
}
fn benchmark(&self) -> BenchmarkReport {
self.inner.benchmark()
}
}
fn providers() -> ProviderSet {
let mut set = ProviderSet::new();
set.add(Arc::new(AwsLcProvider::new()));
set.add(TestProvider::arc("other", false, None));
set.add(TestProvider::arc("fips", true, None));
set
}
fn suite(id: u16, layers: &[(AeadAlgorithm, &'static str)]) -> Suite {
Suite { id, name: "test", layers: layers.iter().map(|(aead, provider)| Layer { aead: *aead, provider }).collect() }
}
fn three() -> ResolvedSuite {
let s = suite(9, &[(XChaCha20Poly1305, "other"), (AesGcm256, "awslc"), (ChaCha20Poly1305, "other")]);
providers().resolve(&s, &Policy::development()).unwrap()
}
const KEY: [u8; 32] = [7; 32];
const SALT: [u8; 32] = [3; 32];
fn ctx(aad: &[u8]) -> Context<'_> {
Context { domain: b"test/v1", aad }
}
#[test]
fn round_trip_across_rounds() {
let s = three();
for rounds in [1u8, 3, 16] {
let ct = seal(&s, rounds, &KEY, &SALT, ctx(b"a"), b"hello cascade").unwrap();
assert_eq!(ct.len(), 13 + 16 * 3 * rounds as usize, "one tag per layer per round");
assert_eq!(open(&s, rounds, &KEY, &SALT, ctx(b"a"), &ct).unwrap().as_slice(), b"hello cascade");
}
// Ultra's 16 rounds of 3 layers add 768 bytes (design figure).
assert_eq!(seal(&s, 16, &KEY, &SALT, ctx(b""), b"").unwrap().len(), 768);
}
#[test]
fn any_change_fails_closed_with_one_error() {
let s = three();
let ct = seal(&s, 3, &KEY, &SALT, ctx(b"vault|table|key"), b"secret").unwrap();
let auth = |r: Result<Zeroizing<Vec<u8>>, CascadeError>| matches!(r, Err(CascadeError::AuthenticationFailed));
for i in [0, ct.len() / 2, ct.len() - 1] {
let mut t = ct.clone();
t[i] ^= 1;
assert!(auth(open(&s, 3, &KEY, &SALT, ctx(b"vault|table|key"), &t)), "byte {i}");
}
assert!(auth(open(&s, 3, &KEY, &SALT, ctx(b"vault|table|other"), &ct)), "aad");
assert!(auth(open(&s, 3, &KEY, &[4; 32], ctx(b"vault|table|key"), &ct)), "salt");
assert!(auth(open(&s, 3, &[8; 32], &SALT, ctx(b"vault|table|key"), &ct)), "key");
assert!(auth(open(&s, 2, &KEY, &SALT, ctx(b"vault|table|key"), &ct)), "rounds");
assert!(auth(open(&s, 3, &KEY, &SALT, ctx(b"vault|table|key"), &ct[..10])), "truncated");
let other_domain = Context { domain: b"test/v2", aad: b"vault|table|key" };
assert!(auth(open(&s, 3, &KEY, &SALT, other_domain, &ct)), "domain");
// Same layers under another suite ID do not open (AAD binds the suite).
let same_layers = suite(10, &[(XChaCha20Poly1305, "other"), (AesGcm256, "awslc"), (ChaCha20Poly1305, "other")]);
let s10 = providers().resolve(&same_layers, &Policy::development()).unwrap();
assert!(auth(open(&s10, 3, &KEY, &SALT, ctx(b"vault|table|key"), &ct)), "suite id");
}
#[test]
fn salt_makes_identical_messages_differ() {
let s = three();
let a = seal(&s, 1, &KEY, &[1; 32], ctx(b""), b"same").unwrap();
let b = seal(&s, 1, &KEY, &[2; 32], ctx(b""), b"same").unwrap();
assert_ne!(a, b);
}
#[test]
fn layer_keys_and_nonces_are_all_distinct() {
let s = three();
let mut seen = std::collections::HashSet::new();
for r in 0..16u8 {
for (i, (alg, _)) in s.layers.iter().enumerate() {
let (k, n) =
cascade::layer_key(&s, &KEY, &SALT, &cascade::layer_info(b"d", s.id, 16, r, i as u8, *alg), *alg)
.unwrap();
assert!(seen.insert(k.to_vec()), "key reuse at round {r} layer {i}");
assert!(seen.insert(n.to_vec()), "nonce reuse at round {r} layer {i}");
}
}
}
#[test]
fn rounds_are_capped_at_16() {
let s = three();
assert!(matches!(seal(&s, 0, &KEY, &SALT, ctx(b""), b"x"), Err(CascadeError::Policy(_))));
assert!(matches!(seal(&s, 17, &KEY, &SALT, ctx(b""), b"x"), Err(CascadeError::Policy(_))));
assert!(matches!(seal(&s, 1, &[0; 16], &SALT, ctx(b""), b"x"), Err(CascadeError::InvalidInput(_))));
assert!(matches!(seal(&s, 1, &KEY, &[0; 16], ctx(b""), b"x"), Err(CascadeError::InvalidInput(_))));
}
#[test]
fn policy_checks() {
let p = providers();
let dev = Policy::development();
let missing = suite(1, &[(AesGcm256, "absent")]);
assert!(matches!(p.resolve(&missing, &dev), Err(CascadeError::Policy(_))));
let empty = suite(1, &[]);
assert!(matches!(p.resolve(&empty, &dev), Err(CascadeError::Policy(_))));
// AWS-LC here is the default (non-FIPS) build, so release refuses it.
let vetted = suite(1, &[(AesGcm256, "awslc")]);
assert!(p.resolve(&vetted, &dev).is_ok());
assert!(matches!(p.resolve(&vetted, &Policy::release()), Err(CascadeError::Policy(_))));
let fips = suite(1, &[(AesGcm256, "fips"), (XChaCha20Poly1305, "other")]);
assert!(p.resolve(&fips, &Policy::release()).is_ok());
let distinct = Policy { require_distinct_adjacent_providers: true, ..dev.clone() };
let same = suite(1, &[(AesGcm256, "awslc"), (ChaCha20Poly1305, "awslc")]);
assert!(matches!(p.resolve(&same, &distinct), Err(CascadeError::Policy(_))));
assert!(p.resolve(&fips, &distinct).is_ok());
// Unavailable algorithm in the provider: refused, not substituted.
let ascon = suite(1, &[(AesGcm256, "awslc"), (AeadAlgorithm::AsconAead128, "awslc")]);
// (Refused: AWS-LC has no Ascon.)
assert!(matches!(p.resolve(&ascon, &dev), Err(CascadeError::Policy(_) | CascadeError::SelfTestFailed(_))));
}
#[test]
fn release_needs_aes_gcm_from_the_fips_provider_and_uses_its_kdf() {
let p = providers();
// ChaCha20 from a FIPS-mode provider is not an approved service.
let chacha_fips = suite(1, &[(ChaCha20Poly1305, "fips"), (XChaCha20Poly1305, "other")]);
assert!(matches!(p.resolve(&chacha_fips, &Policy::release()), Err(CascadeError::Policy(_))));
let ok = suite(1, &[(XChaCha20Poly1305, "other"), (AesGcm256, "fips")]);
let r = p.resolve(&ok, &Policy::release()).unwrap();
assert_eq!(r.kdf.provider_name(), "fips", "key schedule runs in the FIPS module");
}
#[test]
fn an_algorithm_without_a_passing_vector_is_refused() {
let mut p = ProviderSet::new();
p.add(TestProvider::arc("novec", false, None));
// AES-256-GCM-SIV has no vector in this provider's self-test.
let siv = suite(1, &[(AesGcm256, "novec"), (ccc_crypto_core::AeadAlgorithm::AesGcmSiv256, "novec")]);
assert!(p.resolve(&siv, &Policy::development()).is_err());
}
#[test]
fn self_test_failure_blocks_every_suite_using_it() {
let mut p = providers();
p.add(TestProvider::arc("broken", false, Some(ChaCha20Poly1305)));
let uses = suite(1, &[(AesGcm256, "awslc"), (ChaCha20Poly1305, "broken")]);
assert!(matches!(p.resolve(&uses, &Policy::development()), Err(CascadeError::SelfTestFailed(_))));
// Other algorithms of that provider still work: the failure is per algorithm.
let other = suite(1, &[(AesGcm256, "broken")]);
assert!(p.resolve(&other, &Policy::development()).is_ok());
}
#[test]
fn stream_round_trip_and_tamper() {
let s = three();
let blob: Vec<u8> = (0..(SEGMENT_LEN * 2 + 100)).map(|i| (i % 251) as u8).collect();
let mut sealer = StreamSealer::new(&s, &KEY, &SALT, ctx(b"blob-1")).unwrap();
let chunks: Vec<&[u8]> = blob.chunks(SEGMENT_LEN).collect();
let sealed: Vec<Vec<u8>> =
chunks.iter().enumerate().map(|(i, c)| sealer.seal_segment(c, i == chunks.len() - 1).unwrap()).collect();
assert!(sealer.seal_segment(b"", true).is_err(), "nothing after the last segment");
let open_all = |segs: &[Vec<u8>], lasts: &[bool]| -> Result<Vec<u8>, CascadeError> {
let mut o = StreamOpener::new(&s, &KEY, &SALT, ctx(b"blob-1"))?;
let mut out = vec![];
for (seg, last) in segs.iter().zip(lasts) {
out.extend_from_slice(&o.open_segment(seg, *last)?);
}
o.finish()?;
Ok(out)
};
assert_eq!(open_all(&sealed, &[false, false, true]).unwrap(), blob);
let swapped = vec![sealed[1].clone(), sealed[0].clone(), sealed[2].clone()];
assert!(open_all(&swapped, &[false, false, true]).is_err(), "reordered");
assert!(open_all(&sealed[..2], &[false, false]).is_err(), "truncated");
assert!(open_all(&sealed[..2], &[false, true]).is_err(), "early end claimed");
let mut flipped = sealed.clone();
flipped[2][0] ^= 1;
assert!(open_all(&flipped, &[false, false, true]).is_err(), "tampered");
let mut o = StreamOpener::new(&s, &KEY, &SALT, ctx(b"blob-2")).unwrap();
assert!(o.open_segment(&sealed[0], false).is_err(), "other blob's AAD");
}
#[test]
fn builtin_suites_have_unique_ids_and_a_vetted_layer() {
let all = suites::all();
let ids: std::collections::HashSet<_> = all.iter().map(|s| s.id).collect();
assert_eq!(ids.len(), all.len());
for s in &all {
assert!(s.layers.iter().any(|l| l.aead.tier() == ccc_crypto_core::Tier::Vetted), "{}", s.name);
assert_eq!(suites::by_id(s.id).as_ref(), Some(s));
}
}
#[test]
fn slots_bind_providers_and_distinct_compares_implementations() {
let mut p = providers();
let wolf: Arc<dyn CryptoProvider> = Arc::new(AwsLcProvider::new());
p.bind(crate::suites::VETTED, wolf.clone());
let s = suite(1, &[(AesGcm256, crate::suites::VETTED), (XChaCha20Poly1305, "other")]);
let dev = Policy::development();
let r = p.resolve(&s, &dev).unwrap();
assert_eq!(r.kdf.provider_name(), "awslc", "the slot runs the bound provider");
// The same implementation behind two names is not two providers.
let distinct = Policy { require_distinct_adjacent_providers: true, ..dev.clone() };
let same = suite(1, &[(AesGcm256, crate::suites::VETTED), (ChaCha20Poly1305, "awslc")]);
assert!(matches!(p.resolve(&same, &distinct), Err(CascadeError::Policy(_))));
// Rebinding replaces the slot's self-test results.
p.bind(crate::suites::VETTED, TestProvider::arc("broken2", false, Some(AesGcm256)));
assert!(matches!(p.resolve(&s, &dev), Err(CascadeError::SelfTestFailed(_))));
// An unbound slot is refused.
let unbound = suite(1, &[(AesGcm256, "unbound-slot")]);
assert!(matches!(ProviderSet::new().resolve(&unbound, &dev), Err(CascadeError::Policy(_))));
}
#[test]
fn distinct_rule_compares_lineages_and_release_turns_it_on() {
let mut p = providers();
p.add(TestProvider::arc("bssl-fork", false, None));
assert!(Policy::release().require_distinct_adjacent_providers);
let distinct = Policy { require_distinct_adjacent_providers: true, ..Policy::development() };
// AWS-LC next to another BoringSSL fork is one lineage, not two.
let forks = suite(1, &[(AesGcm256, "awslc"), (ChaCha20Poly1305, "bssl-fork")]);
assert!(matches!(p.resolve(&forks, &distinct), Err(CascadeError::Policy(_))));
let mixed = suite(1, &[(AesGcm256, "awslc"), (XChaCha20Poly1305, "other")]);
assert!(p.resolve(&mixed, &distinct).is_ok());
}
#[test]
#[should_panic(expected = "cannot bind")]
fn a_provider_cannot_pose_under_another_name() {
let mut p = ProviderSet::new();
p.bind("rustcrypto", Arc::new(AwsLcProvider::new()));
}
#[test]
#[should_panic(expected = "reserved slot")]
fn a_provider_named_like_a_slot_is_refused() {
let mut p = ProviderSet::new();
p.add(TestProvider::arc("vetted", false, None));
}

View File

@ -0,0 +1,54 @@
//! Every built-in suite resolves with the real providers (wolfSSL and
//! RustCrypto) and round-trips at every allowed round count, and Ultra meets
//! its policy: two providers, a conservative alternative, distinct adjacent
//! providers.
use std::sync::Arc;
use ccc_cascade::{open, seal, suites, Context, Policy, ProviderSet};
use ccc_crypto_core::Tier;
use ccc_crypto_rustcrypto::RustCryptoProvider;
use ccc_crypto_awslc::AwsLcProvider;
fn providers() -> ProviderSet {
let mut p = ProviderSet::new();
p.bind(ccc_cascade::suites::VETTED, Arc::new(AwsLcProvider::new()));
p.add(Arc::new(RustCryptoProvider::new()));
p
}
#[test]
fn every_builtin_suite_round_trips() {
let p = providers();
let ctx = Context { domain: b"lum/test", aad: b"aad" };
for suite in suites::all() {
let r = p.resolve(&suite, &Policy::development()).unwrap_or_else(|e| panic!("{}: {e}", suite.name));
for rounds in [1u8, 3, 16] {
let ct = seal(&r, rounds, &[5; 32], &[6; 32], ctx, b"payload").unwrap();
assert_eq!(
open(&r, rounds, &[5; 32], &[6; 32], ctx, &ct).unwrap().as_slice(),
b"payload",
"{}",
suite.name
);
}
}
}
#[test]
fn ultra_meets_its_diversity_rules() {
let ultra = suites::ultra_3();
let strict = Policy { require_distinct_adjacent_providers: true, min_layers: 3, ..Policy::development() };
providers().resolve(&ultra, &strict).unwrap();
let names: std::collections::HashSet<_> = ultra.layers.iter().map(|l| l.provider).collect();
assert!(names.len() >= 2);
assert!(ultra.layers.iter().any(|l| l.aead.tier() == Tier::Conservative));
}
#[test]
fn release_policy_refuses_this_non_fips_build() {
// Fail closed: without the commercial FIPS module no suite resolves (D-26).
for suite in suites::all() {
assert!(providers().resolve(&suite, &Policy::release()).is_err(), "{}", suite.name);
}
}

View File

@ -0,0 +1,133 @@
//! CCC v2 known-answer vectors (vectors/cascade_v2.json) and the
//! cross-provider check at cascade level: the same suite with a layer moved to
//! the other provider gives byte-identical ciphertext.
//!
//! Regenerate (only when the format deliberately changes, with a version bump):
//! cargo test -p ccc-cascade --test cascade_vectors -- --ignored regenerate
use std::sync::Arc;
use ccc_cascade::{open, seal, suites, Context, Layer, Policy, ProviderSet, StreamOpener, StreamSealer, Suite};
use ccc_crypto_core::AeadAlgorithm::{self, *};
use serde_json::{json, Value};
const PATH: &str = concat!(env!("CARGO_MANIFEST_DIR"), "/../../vectors/cascade_v2.json");
fn providers() -> ProviderSet {
let mut p = ProviderSet::new();
let vetted = Arc::new(ccc_crypto_awslc::AwsLcProvider::new());
p.add(vetted.clone());
p.bind(ccc_cascade::suites::VETTED, vetted);
p.add(Arc::new(ccc_crypto_rustcrypto::RustCryptoProvider::new()));
p
}
fn hex(b: &[u8]) -> String {
b.iter().map(|x| format!("{x:02x}")).collect()
}
fn unhex(s: &str) -> Vec<u8> {
(0..s.len()).step_by(2).map(|i| u8::from_str_radix(&s[i..i + 2], 16).unwrap()).collect()
}
fn pattern(n: usize, seed: u8) -> Vec<u8> {
(0..n).map(|i| (i as u8).wrapping_mul(31).wrapping_add(seed)).collect()
}
fn cases() -> Vec<(Suite, u8, usize)> {
vec![
(suites::floor_aes(), 1, 0),
(suites::floor_aes(), 1, 37),
(suites::standard_2(), 1, 300),
(suites::high_3(), 3, 1024),
(suites::ultra_3(), 16, 4096),
(suites::storage_2(), 1, 255),
]
}
fn generate() -> Value {
let p = providers();
let mut out = vec![];
for (suite, rounds, len) in cases() {
let r = p.resolve(&suite, &Policy::development()).unwrap();
let (key, salt, pt, aad) = (pattern(32, 1), pattern(32, 2), pattern(len, 3), pattern(19, 4));
let ct = seal(&r, rounds, &key, &salt, Context { domain: b"ccc/v2/kat", aad: &aad }, &pt).unwrap();
out.push(json!({"suite": suite.id, "rounds": rounds, "key": hex(&key), "salt": hex(&salt),
"aad": hex(&aad), "pt": hex(&pt), "ct": hex(&ct)}));
}
let r = p.resolve(&suites::standard_2(), &Policy::development()).unwrap();
let blob = pattern(64 * 1024 + 100, 5);
let mut s =
StreamSealer::new(&r, &pattern(32, 6), &pattern(32, 7), Context { domain: b"ccc/v2/kat", aad: b"b" }).unwrap();
let segs: Vec<String> =
blob.chunks(64 * 1024).enumerate().map(|(i, c)| hex(&s.seal_segment(c, i == 1).unwrap())).collect();
json!({"version": 2, "domain": "ccc/v2/kat", "cascade": out,
"stream": {"suite": 2, "key": hex(&pattern(32, 6)), "salt": hex(&pattern(32, 7)), "aad": "62",
"blob_len": blob.len(), "segments": segs}})
}
#[test]
#[ignore]
fn regenerate() {
std::fs::write(PATH, serde_json::to_string_pretty(&generate()).unwrap() + "\n").unwrap();
}
#[test]
fn pinned_vectors_still_hold() {
let pinned: Value = serde_json::from_str(&std::fs::read_to_string(PATH).unwrap()).unwrap();
assert_eq!(pinned, generate(), "CCC v2 output changed; a format change needs a version bump");
// And the pinned ciphertexts open.
let p = providers();
for v in pinned["cascade"].as_array().unwrap() {
let suite = suites::by_id(v["suite"].as_u64().unwrap() as u16).unwrap();
let r = p.resolve(&suite, &Policy::development()).unwrap();
let aad = unhex(v["aad"].as_str().unwrap());
let pt = open(
&r,
v["rounds"].as_u64().unwrap() as u8,
&unhex(v["key"].as_str().unwrap()),
&unhex(v["salt"].as_str().unwrap()),
Context { domain: b"ccc/v2/kat", aad: &aad },
&unhex(v["ct"].as_str().unwrap()),
)
.unwrap();
assert_eq!(hex(&pt), v["pt"].as_str().unwrap());
}
let st = &pinned["stream"];
let r = p.resolve(&suites::standard_2(), &Policy::development()).unwrap();
let mut o = StreamOpener::new(
&r,
&unhex(st["key"].as_str().unwrap()),
&unhex(st["salt"].as_str().unwrap()),
Context { domain: b"ccc/v2/kat", aad: b"b" },
)
.unwrap();
let segs = st["segments"].as_array().unwrap();
let mut n = 0;
for (i, seg) in segs.iter().enumerate() {
n += o.open_segment(&unhex(seg.as_str().unwrap()), i == segs.len() - 1).unwrap().len();
}
o.finish().unwrap();
assert_eq!(n as u64, st["blob_len"].as_u64().unwrap());
}
#[test]
fn moving_a_layer_to_the_other_provider_gives_identical_bytes() {
let p = providers();
let both: [AeadAlgorithm; 3] = [AesGcm256, ChaCha20Poly1305, AeadAlgorithm::AesGcmSiv256];
for alg in both {
let mk = |prov: &'static str| Suite {
id: 77,
name: "swap",
// The anchor (and so the KDF) stays AWS-LC AES-GCM; only the
// tested layer moves.
layers: vec![Layer { aead: AesGcm256, provider: "awslc" }, Layer { aead: alg, provider: prov }],
};
let a = p.resolve(&mk("awslc"), &Policy::development()).unwrap();
let b = p.resolve(&mk("rustcrypto"), &Policy::development()).unwrap();
let ctx = Context { domain: b"swap", aad: b"aad" };
let ca = seal(&a, 3, &[9; 32], &[8; 32], ctx, b"same bytes either way").unwrap();
let cb = seal(&b, 3, &[9; 32], &[8; 32], ctx, b"same bytes either way").unwrap();
assert_eq!(ca, cb, "{alg:?}");
assert_eq!(open(&b, 3, &[9; 32], &[8; 32], ctx, &ca).unwrap().as_slice(), b"same bytes either way");
}
}

View File

@ -0,0 +1,98 @@
//! HPKE (X-Wing, HKDF-SHA256, AES-256-GCM) interop with the independent
//! `hpke` crate, both directions, plus tamper and context checks.
//! KEM from the RustCrypto provider; HMAC and AEAD from AWS-LC (the vetted
//! provider), as in production.
use ::hpke::{Deserializable, Kem as _, OpModeR, OpModeS, PskBundle, Serializable};
use ccc_cascade::hpke::{self as ours, HpkeProviders, HpkeSuite, Psk};
use ccc_cascade::CascadeError;
use ccc_crypto_core::{KemAlgorithm, KemProvider};
use ccc_crypto_rustcrypto::RustCryptoProvider;
use ccc_crypto_awslc::AwsLcProvider;
type Kem = ::hpke::kem::XWing;
type Kdf = ::hpke::kdf::HkdfSha256;
type Aead = ::hpke::aead::AesGcm256;
const SUITE: HpkeSuite = HpkeSuite::XWING_SHA256_AES256GCM;
#[test]
fn our_seal_opens_with_the_hpke_crate() {
let rc = RustCryptoProvider::new();
let vetted = AwsLcProvider::new();
let p = HpkeProviders { kem: &rc, mac: &vetted, aead: &vetted };
let (sk, pk) = Kem::derive_keypair(b"interop test seed for x-wing hpke");
let sealed = ours::seal(SUITE, &p, &pk.to_bytes(), b"lum/inbox", b"aad", b"inbox envelope").unwrap();
let (enc, ct) = sealed.split_at(SUITE.enc_len);
let enc = <Kem as ::hpke::Kem>::EncappedKey::from_bytes(enc).unwrap();
let pt = ::hpke::single_shot_open::<Aead, Kdf, Kem>(&OpModeR::Base, &sk, &enc, b"lum/inbox", ct, b"aad").unwrap();
assert_eq!(pt, b"inbox envelope");
}
#[test]
fn hpke_crate_seal_opens_with_ours() {
let rc = RustCryptoProvider::new();
let vetted = AwsLcProvider::new();
let p = HpkeProviders { kem: &rc, mac: &vetted, aead: &vetted };
let kp = rc.generate_keypair(KemAlgorithm::XWing).unwrap();
let pk = <Kem as ::hpke::Kem>::PublicKey::from_bytes(&kp.public_key).unwrap();
let (enc, ct) =
::hpke::single_shot_seal::<Aead, Kdf, Kem>(&OpModeS::Base, &pk, b"lum/lgp/handout", b"seed", b"a").unwrap();
let mut sealed = enc.to_bytes().to_vec();
sealed.extend_from_slice(&ct);
let pt = ours::open(SUITE, &p, &kp.private_key, b"lum/lgp/handout", b"a", &sealed).unwrap();
assert_eq!(pt.as_slice(), b"seed");
}
#[test]
fn wrong_context_or_tamper_fails_closed() {
let rc = RustCryptoProvider::new();
let vetted = AwsLcProvider::new();
let p = HpkeProviders { kem: &rc, mac: &vetted, aead: &vetted };
let kp = rc.generate_keypair(KemAlgorithm::XWing).unwrap();
let other = rc.generate_keypair(KemAlgorithm::XWing).unwrap();
let sealed = ours::seal(SUITE, &p, &kp.public_key, b"info", b"aad", b"msg").unwrap();
assert_eq!(sealed.len(), SUITE.enc_len + 3 + 16);
let fails =
|r: Result<zeroize::Zeroizing<Vec<u8>>, CascadeError>| matches!(r, Err(CascadeError::AuthenticationFailed));
assert!(fails(ours::open(SUITE, &p, &kp.private_key, b"other", b"aad", &sealed)), "info");
assert!(fails(ours::open(SUITE, &p, &kp.private_key, b"info", b"x", &sealed)), "aad");
assert!(fails(ours::open(SUITE, &p, &other.private_key, b"info", b"aad", &sealed)), "key");
for i in [0, SUITE.enc_len, sealed.len() - 1] {
let mut t = sealed.clone();
t[i] ^= 1;
assert!(fails(ours::open(SUITE, &p, &kp.private_key, b"info", b"aad", &t)), "byte {i}");
}
assert!(fails(ours::open(SUITE, &p, &kp.private_key, b"info", b"aad", &sealed[..100])), "short");
}
#[test]
fn psk_mode_interops_both_ways_and_needs_the_psk() {
let rc = RustCryptoProvider::new();
let vetted = AwsLcProvider::new();
let p = HpkeProviders { kem: &rc, mac: &vetted, aead: &vetted };
let psk_bytes = [0x42u8; 32];
let psk = Psk { psk: &psk_bytes, psk_id: b"lum/lgp/u2" };
let bundle = PskBundle::new(&psk_bytes, b"lum/lgp/u2").unwrap();
// Ours -> hpke crate.
let (sk, pk) = Kem::derive_keypair(b"psk interop seed for x-wing hpke");
let sealed = ours::seal_psk(SUITE, &p, &pk.to_bytes(), &psk, b"info", b"aad", b"seed").unwrap();
let (enc, ct) = sealed.split_at(SUITE.enc_len);
let enc = <Kem as ::hpke::Kem>::EncappedKey::from_bytes(enc).unwrap();
let pt = ::hpke::single_shot_open::<Aead, Kdf, Kem>(&OpModeR::Psk(bundle), &sk, &enc, b"info", ct, b"aad")
.unwrap();
assert_eq!(pt, b"seed");
// hpke crate -> ours.
let kp = rc.generate_keypair(KemAlgorithm::XWing).unwrap();
let pk2 = <Kem as ::hpke::Kem>::PublicKey::from_bytes(&kp.public_key).unwrap();
let (enc, ct) =
::hpke::single_shot_seal::<Aead, Kdf, Kem>(&OpModeS::Psk(bundle), &pk2, b"info", b"msg", b"aad").unwrap();
let mut sealed = enc.to_bytes().to_vec();
sealed.extend_from_slice(&ct);
assert_eq!(ours::open_psk(SUITE, &p, &kp.private_key, &psk, b"info", b"aad", &sealed).unwrap().as_slice(), b"msg");
// Without the PSK, or with another one, it does not open.
assert!(ours::open(SUITE, &p, &kp.private_key, b"info", b"aad", &sealed).is_err());
let other = Psk { psk: &[0x43; 32], psk_id: b"lum/lgp/u2" };
assert!(ours::open_psk(SUITE, &p, &kp.private_key, &other, b"info", b"aad", &sealed).is_err());
assert!(ours::seal_psk(SUITE, &p, &kp.public_key, &Psk { psk: &[1; 16], psk_id: b"x" }, b"", b"", b"").is_err());
}

View File

@ -0,0 +1,15 @@
//! Argon2id with explicit parameters matches the RustCrypto provider's
//! fixed-parameter Argon2id (64 MiB, t=3, 4 lanes), and it agrees with the pinned conformance vectors.
use ccc_cascade::password::{argon2id, Argon2Params};
use ccc_crypto_core::{KdfAlgorithm, KdfProvider};
#[test]
fn matches_both_providers() {
let p = Argon2Params { memory_kib: 64 * 1024, iterations: 3, parallelism: 4 };
let salt = [0x24u8; 16];
let ours = argon2id(b"correct horse battery staple", &salt, p, 32).unwrap();
let rc = ccc_crypto_rustcrypto::RustCryptoProvider::new()
.derive_key(KdfAlgorithm::Argon2id, b"correct horse battery staple", &salt, b"", 32)
.unwrap();
assert_eq!(ours.as_slice(), rc.as_slice());
}

View File

@ -0,0 +1,27 @@
[package]
name = "ccc-crypto-awslc"
version.workspace = true
edition.workspace = true
authors.workspace = true
license.workspace = true
description = "AWS-LC (aws-lc-rs) provider for the CCC crypto system; FIPS 140-3 with the `fips` feature."
[dependencies]
ccc-crypto-core.workspace = true
zeroize.workspace = true
log.workspace = true
# Apache-2.0 OR ISC. The backend (`aws-lc-sys` or `aws-lc-fips-sys`) is
# chosen by this crate's features below.
aws-lc-rs = { version = "1.19", default-features = false, features = ["alloc"] }
[features]
default = ["non-fips"]
# The open-source AWS-LC build (`aws-lc-sys`).
non-fips = ["aws-lc-rs/aws-lc-sys"]
# AWS-LC-FIPS (`aws-lc-fips-sys`), the FIPS 140-3 validated module. aws-lc-rs
# uses it whenever this feature is on; for a build without the unused
# open-source backend, use `--no-default-features --features fips`.
fips = ["aws-lc-rs/fips"]
[dev-dependencies]
hex = "0.4"

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

View File

@ -0,0 +1,217 @@
//! AEADs from `aws_lc_rs::aead`.
//!
//! Wire format matches the other providers: `ciphertext || 16-byte tag`.
//!
//! | Algorithm | aws-lc-rs | FIPS 140-3 approved |
//! |-------------------|---------------------|---------------------|
//! | AES-256-GCM | `AES_256_GCM` | yes |
//! | AES-256-GCM-SIV | `AES_256_GCM_SIV` | no |
//! | ChaCha20-Poly1305 | `CHACHA20_POLY1305` | no |
//!
//! XChaCha20-Poly1305 and the Ascon AEADs are not in AWS-LC and return
//! [`CryptoError::FeatureNotCompiled`].
//!
//! The caller supplies the nonce, so AES-256-GCM here is the "external IV"
//! mode; a FIPS deployment relies on the cascade's nonce construction for
//! uniqueness, as with the wolfSSL provider.
use aws_lc_rs::aead::{
self, Aad, LessSafeKey, Nonce, UnboundKey, AES_256_GCM, AES_256_GCM_SIV, CHACHA20_POLY1305,
};
use zeroize::Zeroizing;
use ccc_crypto_core::{algorithms::AeadAlgorithm, error::CryptoError};
const TAG_LEN: usize = 16;
/// Encrypt `plaintext`; returns `ciphertext || tag`.
pub fn encrypt(
algo: AeadAlgorithm,
key: &[u8],
nonce: &[u8],
plaintext: &[u8],
aad: &[u8],
) -> Result<Vec<u8>, CryptoError> {
let (key, nonce) = prepare(algo, key, nonce)?;
let mut in_out = Vec::with_capacity(plaintext.len() + TAG_LEN);
in_out.extend_from_slice(plaintext);
key.seal_in_place_append_tag(nonce, Aad::from(aad), &mut in_out)
.map_err(|_| CryptoError::InvalidInput(format!("{}: input too long", algo.name())))?;
Ok(in_out)
}
/// Authenticate and decrypt `ciphertext || tag`.
///
/// Returns [`CryptoError::AuthenticationFailed`] if the tag does not verify.
pub fn decrypt(
algo: AeadAlgorithm,
key: &[u8],
nonce: &[u8],
ciphertext_and_tag: &[u8],
aad: &[u8],
) -> Result<Vec<u8>, CryptoError> {
let (key, nonce) = prepare(algo, key, nonce)?;
if ciphertext_and_tag.len() < TAG_LEN {
return Err(CryptoError::InvalidInput(format!(
"{}: ciphertext too short (no room for tag)",
algo.name()
)));
}
// Wiped on every path, so a rejected message leaves no unauthenticated
// plaintext behind.
let mut in_out = Zeroizing::new(ciphertext_and_tag.to_vec());
let pt_len = key
.open_in_place(nonce, Aad::from(aad), &mut in_out)
.map_err(|_| CryptoError::AuthenticationFailed)?
.len();
Ok(in_out[..pt_len].to_vec())
}
fn algorithm(algo: AeadAlgorithm) -> Result<&'static aead::Algorithm, CryptoError> {
match algo {
AeadAlgorithm::AesGcm256 => Ok(&AES_256_GCM),
AeadAlgorithm::AesGcmSiv256 => Ok(&AES_256_GCM_SIV),
AeadAlgorithm::ChaCha20Poly1305 => Ok(&CHACHA20_POLY1305),
AeadAlgorithm::XChaCha20Poly1305
| AeadAlgorithm::Ascon128a
| AeadAlgorithm::AsconAead128 => Err(CryptoError::FeatureNotCompiled(format!(
"{} is not offered by the awslc provider",
algo.name()
))),
}
}
/// Check lengths and build the key (aws-lc keeps its own copy and cleanses
/// it on drop) and nonce.
fn prepare(
algo: AeadAlgorithm,
key: &[u8],
nonce: &[u8],
) -> Result<(LessSafeKey, Nonce), CryptoError> {
let alg = algorithm(algo)?;
if key.len() != algo.key_len() {
return Err(CryptoError::InvalidKey(format!(
"{}: expected {}-byte key, got {}",
algo.name(),
algo.key_len(),
key.len()
)));
}
if nonce.len() != algo.nonce_len() {
return Err(CryptoError::InvalidNonce(format!(
"{}: expected {}-byte nonce, got {}",
algo.name(),
algo.nonce_len(),
nonce.len()
)));
}
let key = UnboundKey::new(alg, key).map_err(|_| CryptoError::InvalidKey(algo.name().into()))?;
let nonce = Nonce::try_assume_unique_for_key(nonce)
.map_err(|_| CryptoError::InvalidNonce(algo.name().into()))?;
Ok((LessSafeKey::new(key), nonce))
}
#[cfg(test)]
mod tests {
use super::*;
const OFFERED: [AeadAlgorithm; 3] = [
AeadAlgorithm::AesGcm256,
AeadAlgorithm::AesGcmSiv256,
AeadAlgorithm::ChaCha20Poly1305,
];
fn inputs(algo: AeadAlgorithm) -> (Vec<u8>, Vec<u8>) {
let key = (0..algo.key_len() as u8).collect();
let nonce = (0..algo.nonce_len() as u8).map(|b| b ^ 0x5a).collect();
(key, nonce)
}
#[test]
fn roundtrip_all_offered() {
for algo in OFFERED {
let (key, nonce) = inputs(algo);
for (pt, aad) in [
(&b"hello cascade"[..], &b"hdr"[..]),
(b"", b""),
(b"x", b""),
(b"", b"aad only"),
] {
let ct = encrypt(algo, &key, &nonce, pt, aad).unwrap();
assert_eq!(ct.len(), pt.len() + TAG_LEN, "{}", algo.name());
assert_eq!(decrypt(algo, &key, &nonce, &ct, aad).unwrap(), pt);
}
}
}
#[test]
fn tampering_is_rejected() {
for algo in OFFERED {
let (key, nonce) = inputs(algo);
let ct = encrypt(algo, &key, &nonce, b"payload", b"aad").unwrap();
for i in [0, ct.len() - 1] {
let mut bad = ct.clone();
bad[i] ^= 0x01;
assert!(matches!(
decrypt(algo, &key, &nonce, &bad, b"aad"),
Err(CryptoError::AuthenticationFailed)
));
}
assert!(matches!(
decrypt(algo, &key, &nonce, &ct, b"aaD"),
Err(CryptoError::AuthenticationFailed)
));
}
}
#[test]
fn bad_lengths_are_rejected() {
for algo in OFFERED {
let (key, nonce) = inputs(algo);
assert!(matches!(
encrypt(algo, &key[1..], &nonce, b"", b""),
Err(CryptoError::InvalidKey(_))
));
assert!(matches!(
encrypt(algo, &key, &nonce[1..], b"", b""),
Err(CryptoError::InvalidNonce(_))
));
assert!(matches!(
decrypt(algo, &key, &nonce, &[0u8; 15], b""),
Err(CryptoError::InvalidInput(_))
));
}
}
#[test]
fn unoffered_aeads_are_not_compiled() {
for algo in [
AeadAlgorithm::XChaCha20Poly1305,
AeadAlgorithm::Ascon128a,
AeadAlgorithm::AsconAead128,
] {
let key = vec![0u8; algo.key_len()];
let nonce = vec![0u8; algo.nonce_len()];
assert!(matches!(
encrypt(algo, &key, &nonce, b"", b""),
Err(CryptoError::FeatureNotCompiled(_))
));
assert!(matches!(
decrypt(algo, &key, &nonce, &[0u8; 16], b""),
Err(CryptoError::FeatureNotCompiled(_))
));
}
}
#[test]
fn algorithms_are_not_interchangeable() {
let key = [7u8; 32];
let nonce = [9u8; 12];
let gcm = encrypt(AeadAlgorithm::AesGcm256, &key, &nonce, b"same", b"").unwrap();
let siv = encrypt(AeadAlgorithm::AesGcmSiv256, &key, &nonce, b"same", b"").unwrap();
let cha = encrypt(AeadAlgorithm::ChaCha20Poly1305, &key, &nonce, b"same", b"").unwrap();
assert_ne!(gcm, siv);
assert_ne!(gcm, cha);
assert!(decrypt(AeadAlgorithm::AesGcmSiv256, &key, &nonce, &gcm, b"").is_err());
}
}

View File

@ -0,0 +1,273 @@
//! Live capability probes and the AEAD throughput benchmark.
//!
//! An algorithm is `available` only when a live probe succeeds **and** its
//! known-answer self-test passed, so a failing KAT removes the algorithm
//! (fail closed, D-28) instead of leaving a silently wrong implementation in
//! the catalog.
use std::time::Instant;
use ccc_crypto_core::{
algorithms::{AeadAlgorithm, HashAlgorithm, KdfAlgorithm, KemAlgorithm, MacAlgorithm},
capabilities::{AlgorithmCapability, ProviderCapabilities},
types::{AlgoBenchResult, BenchmarkReport, SelfTestReport},
};
use crate::{aead, hash, kdf, kem, mac, PROVIDER_NAME};
/// AEADs this provider implements, in benchmark order.
pub const AEADS: [AeadAlgorithm; 3] = [
AeadAlgorithm::AesGcm256,
AeadAlgorithm::AesGcmSiv256,
AeadAlgorithm::ChaCha20Poly1305,
];
/// KDFs this provider implements.
pub const KDFS: [KdfAlgorithm; 3] = [
KdfAlgorithm::Sha256,
KdfAlgorithm::Sha384,
KdfAlgorithm::Sha512,
];
/// MACs this provider implements.
pub const MACS: [MacAlgorithm; 3] = [
MacAlgorithm::HmacSha256,
MacAlgorithm::HmacSha384,
MacAlgorithm::HmacSha512,
];
/// Hashes this provider implements.
pub const HASHES: [HashAlgorithm; 5] = [
HashAlgorithm::Sha256,
HashAlgorithm::Sha384,
HashAlgorithm::Sha512,
HashAlgorithm::Sha3_256,
HashAlgorithm::Sha3_512,
];
/// KEMs this provider implements.
pub const KEMS: [KemAlgorithm; 3] = [
KemAlgorithm::X25519,
KemAlgorithm::MlKem768,
KemAlgorithm::MlKem1024,
];
fn kat_passed(report: &SelfTestReport, id: u32) -> bool {
let mut results = report.results.iter().filter(|r| r.algo_id == id).peekable();
// An algorithm without a KAT is never marked available.
results.peek().is_some() && results.all(|r| r.passed)
}
fn cap(available: bool, deterministic_io: bool, efficiency_score: u8) -> AlgorithmCapability {
if !available {
return AlgorithmCapability::unavailable();
}
AlgorithmCapability {
available,
deterministic_io,
efficiency_score,
reliability_score: 100,
}
}
fn aead_probe(algo: AeadAlgorithm) -> bool {
let key = vec![0u8; algo.key_len()];
let nonce = vec![0u8; algo.nonce_len()];
aead::encrypt(algo, &key, &nonce, b"x", b"")
.and_then(|ct| aead::decrypt(algo, &key, &nonce, &ct, b""))
.is_ok_and(|pt| pt == b"x")
}
fn kem_probe(algo: KemAlgorithm) -> bool {
let Ok(kp) = kem::generate_keypair(algo) else {
return false;
};
let Ok(enc) = kem::encapsulate(algo, &kp.public_key) else {
return false;
};
kem::decapsulate(algo, &kp.private_key, &enc.ciphertext)
.is_ok_and(|ss| *ss == enc.shared_secret)
}
/// Build the capability matrix from live probes, the self-test report and
/// (optionally) benchmark scores.
pub fn probe_capabilities(
self_test: &SelfTestReport,
benchmarks: Option<&BenchmarkReport>,
) -> ProviderCapabilities {
let mut caps = ProviderCapabilities::empty(PROVIDER_NAME);
let score = |id: u32| {
benchmarks
.and_then(|b| b.results.iter().find(|r| r.algo_id == id))
.map(|r| r.efficiency_score)
.unwrap_or(0)
};
for algo in AeadAlgorithm::ALL {
let ok = AEADS.contains(&algo) && aead_probe(algo) && kat_passed(self_test, algo as u32);
caps = caps.with_aead(algo, cap(ok, true, score(algo as u32)));
}
for algo in KDFS {
let ok = kdf::derive_key(algo, b"key", b"salt", b"info", 32).is_ok()
&& kat_passed(self_test, algo as u32);
caps = caps.with_kdf(algo, cap(ok, true, 80));
}
for algo in [
KdfAlgorithm::Blake2b512,
KdfAlgorithm::Argon2id,
KdfAlgorithm::Kmac256,
] {
caps = caps.with_kdf(algo, AlgorithmCapability::unavailable());
}
for algo in MACS {
let ok = mac::compute_mac(algo, &[0x42; 32], b"data").is_ok()
&& kat_passed(self_test, algo as u32);
caps = caps.with_mac(algo, cap(ok, true, 85));
}
for algo in [MacAlgorithm::Blake2bMac, MacAlgorithm::Poly1305] {
caps = caps.with_mac(algo, AlgorithmCapability::unavailable());
}
for algo in HASHES {
let ok = hash::hash(algo, b"probe").is_ok() && kat_passed(self_test, algo as u32);
caps = caps.with_hash(algo, cap(ok, true, 90));
}
caps = caps.with_hash(
HashAlgorithm::Blake2b512,
AlgorithmCapability::unavailable(),
);
for algo in KemAlgorithm::ALL {
let ok = KEMS.contains(&algo) && kem_probe(algo) && kat_passed(self_test, algo as u32);
// Key generation and encapsulation are randomised.
caps = caps.with_kem(algo, cap(ok, false, 80));
}
caps
}
/// The provider benchmark: 100 × 1 MiB per AEAD, as in the other providers.
pub fn run_benchmark() -> BenchmarkReport {
run_benchmark_with(1024 * 1024, 100)
}
/// Encrypt `iters` × `size` bytes per AEAD and score each relative to the
/// fastest (0–100).
pub fn run_benchmark_with(size: usize, iters: u32) -> BenchmarkReport {
let plaintext = vec![0xABu8; size];
let mut raw: Vec<(AeadAlgorithm, f64)> = Vec::new();
for algo in AEADS {
if !aead_probe(algo) {
continue;
}
let key = vec![0u8; algo.key_len()];
let nonce = vec![0u8; algo.nonce_len()];
let start = Instant::now();
for _ in 0..iters {
let _ = aead::encrypt(algo, &key, &nonce, &plaintext, b"");
}
let secs = start.elapsed().as_secs_f64().max(1e-9);
raw.push((
algo,
(size as f64 * iters as f64) / (1024.0 * 1024.0 * secs),
));
}
let max = raw.iter().map(|(_, t)| *t).fold(0.0, f64::max);
let results = raw
.into_iter()
.map(|(algo, throughput)| AlgoBenchResult {
algo_id: algo as u32,
algo_name: algo.name().into(),
throughput_mbps: throughput,
efficiency_score: if max > 0.0 {
((throughput / max) * 100.0).round() as u8
} else {
0
},
})
.collect();
BenchmarkReport {
provider_name: PROVIDER_NAME.into(),
results,
}
}
#[cfg(test)]
mod tests {
use super::*;
use ccc_crypto_core::types::AlgoTestResult;
#[test]
fn offered_algorithms_are_available() {
let caps = probe_capabilities(&crate::self_test::run(), None);
assert_eq!(caps.provider_name, "awslc");
for algo in AeadAlgorithm::ALL {
assert_eq!(
caps.aead[&algo].available,
AEADS.contains(&algo),
"{}",
algo.name()
);
}
assert!(KDFS.iter().all(|a| caps.kdf[a].available));
assert_eq!(
caps.kdf.values().filter(|c| c.available).count(),
KDFS.len()
);
assert!(MACS.iter().all(|a| caps.mac[a].available));
assert_eq!(
caps.mac.values().filter(|c| c.available).count(),
MACS.len()
);
assert!(HASHES.iter().all(|a| caps.hash[a].available));
assert!(!caps.hash[&HashAlgorithm::Blake2b512].available);
for algo in KemAlgorithm::ALL {
assert_eq!(
caps.kem[&algo].available,
KEMS.contains(&algo),
"{}",
algo.name()
);
}
}
#[test]
fn every_offered_algorithm_has_a_passing_kat() {
let report = crate::self_test::run();
let ids = AEADS
.iter()
.map(|a| *a as u32)
.chain(KDFS.iter().map(|a| *a as u32))
.chain(MACS.iter().map(|a| *a as u32))
.chain(HASHES.iter().map(|a| *a as u32))
.chain(KEMS.iter().map(|a| *a as u32));
for id in ids {
assert!(kat_passed(&report, id), "algorithm {id}");
}
}
#[test]
fn failed_kat_makes_algorithm_unavailable() {
let mut report = crate::self_test::run();
for id in [
AeadAlgorithm::AesGcm256 as u32,
KemAlgorithm::MlKem768 as u32,
] {
report.results.push(AlgoTestResult {
algo_id: id,
algo_name: "forced failure".into(),
passed: false,
error_message: Some("test".into()),
});
}
let caps = probe_capabilities(&report, None);
assert!(!caps.aead[&AeadAlgorithm::AesGcm256].available);
assert!(caps.aead[&AeadAlgorithm::ChaCha20Poly1305].available);
assert!(!caps.kem[&KemAlgorithm::MlKem768].available);
assert!(caps.kem[&KemAlgorithm::MlKem1024].available);
}
#[test]
fn small_benchmark_scores_every_aead() {
let report = run_benchmark_with(4096, 2);
assert_eq!(report.results.len(), AEADS.len());
assert!(report.results.iter().any(|r| r.efficiency_score == 100));
}
}

View File

@ -0,0 +1,56 @@
//! FIPS 140-3 status of the linked AWS-LC.
//!
//! Only a build with the `fips` feature links AWS-LC-FIPS; every other build
//! reports `false` without asking the library, so an open-source AWS-LC can
//! never claim FIPS mode.
//!
//! "FIPS mode" means the validated module's code is running with its
//! self-tests passed. It does not say the platform is one of the certificate's
//! operating environments, nor that every service is approved: AES-GCM
//! encryption with a caller-supplied IV is not (design D-47). Those claims are
//! made per platform in the release documentation, not by this flag.
/// `Some(Ok(()))` when built with `fips` and AWS-LC reports FIPS mode,
/// `Some(Err(reason))` when built with `fips` but the module is not in FIPS
/// mode, `None` without the `fips` feature.
pub fn fips_status() -> Option<Result<(), &'static str>> {
if cfg!(feature = "fips") {
Some(aws_lc_rs::try_fips_mode())
} else {
None
}
}
/// `true` only when built with the `fips` feature and AWS-LC-FIPS reports
/// FIPS mode at runtime.
pub fn fips_mode() -> bool {
matches!(fips_status(), Some(Ok(())))
}
/// The linked AWS-LC version, for logs and diagnostics.
pub fn awslc_version() -> &'static str {
aws_lc_rs::awslc_version()
}
#[cfg(test)]
mod tests {
use super::*;
#[cfg(not(feature = "fips"))]
#[test]
fn open_source_build_is_not_fips() {
assert_eq!(fips_status(), None);
assert!(!fips_mode());
}
#[cfg(feature = "fips")]
#[test]
fn fips_build_is_in_fips_mode() {
assert!(fips_mode(), "status {:?}", fips_status());
}
#[test]
fn version_is_reported() {
assert!(!awslc_version().is_empty());
}
}

View File

@ -0,0 +1,60 @@
//! Hash functions from `aws_lc_rs::digest`: SHA-2 and SHA-3.
//!
//! BLAKE2b-512 is not in AWS-LC and returns
//! [`CryptoError::FeatureNotCompiled`].
use aws_lc_rs::digest::{self, SHA256, SHA384, SHA3_256, SHA3_512, SHA512};
use ccc_crypto_core::{algorithms::HashAlgorithm, error::CryptoError};
/// Compute the digest of `data`.
pub fn hash(algo: HashAlgorithm, data: &[u8]) -> Result<Vec<u8>, CryptoError> {
let alg = match algo {
HashAlgorithm::Sha256 => &SHA256,
HashAlgorithm::Sha384 => &SHA384,
HashAlgorithm::Sha512 => &SHA512,
HashAlgorithm::Sha3_256 => &SHA3_256,
HashAlgorithm::Sha3_512 => &SHA3_512,
HashAlgorithm::Blake2b512 => {
return Err(CryptoError::FeatureNotCompiled(format!(
"{} is not offered by the awslc provider",
algo.name()
)))
}
};
Ok(digest::digest(alg, data).as_ref().to_vec())
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn digest_lengths_match_registry() {
for algo in [
HashAlgorithm::Sha256,
HashAlgorithm::Sha384,
HashAlgorithm::Sha512,
HashAlgorithm::Sha3_256,
HashAlgorithm::Sha3_512,
] {
assert_eq!(hash(algo, b"abc").unwrap().len(), algo.digest_len());
}
}
#[test]
fn sha256_abc() {
assert_eq!(
hex::encode(hash(HashAlgorithm::Sha256, b"abc").unwrap()),
"ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad"
);
}
#[test]
fn blake2b_is_not_compiled() {
assert!(matches!(
hash(HashAlgorithm::Blake2b512, b"abc"),
Err(CryptoError::FeatureNotCompiled(_))
));
}
}

View File

@ -0,0 +1,156 @@
//! HKDF-SHA-2 (RFC 5869) from `aws_lc_rs::hkdf`.
//!
//! Semantics match the wolfSSL and RustCrypto providers byte for byte:
//!
//! - An empty salt means the all-zero salt of hash length (RFC 5869 §2.2).
//! It is passed to AWS-LC explicitly as that zero string: HMAC pads a short
//! key with zeros, so the output is identical, and AWS-LC-FIPS approves
//! HKDF only with a non-empty salt.
//! - The output is capped at 255 × hash length.
//!
//! The BLAKE2b-512 KDF, Argon2id and KMAC256 are not in aws-lc-rs and return
//! [`CryptoError::FeatureNotCompiled`].
use aws_lc_rs::hkdf::{KeyType, Salt, HKDF_SHA256, HKDF_SHA384, HKDF_SHA512};
use zeroize::Zeroizing;
use ccc_crypto_core::{algorithms::KdfAlgorithm, error::CryptoError};
/// Derive `length` bytes from `ikm`.
pub fn derive_key(
algo: KdfAlgorithm,
ikm: &[u8],
salt: &[u8],
info: &[u8],
length: usize,
) -> Result<Zeroizing<Vec<u8>>, CryptoError> {
let (alg, hash_len) = match algo {
KdfAlgorithm::Sha256 => (HKDF_SHA256, 32),
KdfAlgorithm::Sha384 => (HKDF_SHA384, 48),
KdfAlgorithm::Sha512 => (HKDF_SHA512, 64),
KdfAlgorithm::Blake2b512 | KdfAlgorithm::Argon2id | KdfAlgorithm::Kmac256 => {
return Err(CryptoError::FeatureNotCompiled(format!(
"{} is not offered by the awslc provider",
algo.name()
)))
}
};
let max_len = 255 * hash_len;
if length > max_len {
return Err(CryptoError::InvalidInput(format!(
"HKDF: requested length {length} exceeds maximum {max_len}"
)));
}
let zero_salt = [0u8; 64];
let salt = if salt.is_empty() {
&zero_salt[..hash_len]
} else {
salt
};
// aws-lc-rs keeps its copy of the IKM in a zeroising buffer.
let prk = Salt::new(alg, salt).extract(ikm);
let mut okm = Zeroizing::new(vec![0u8; length]);
prk.expand(&[info], OkmLen(length))
.and_then(|o| o.fill(&mut okm))
.map_err(|_| CryptoError::InternalError("HKDF expand failed".into()))?;
Ok(okm)
}
/// The requested output length, as aws-lc-rs wants it.
struct OkmLen(usize);
impl KeyType for OkmLen {
fn len(&self) -> usize {
self.0
}
}
#[cfg(test)]
mod tests {
use super::*;
fn h(s: &str) -> Vec<u8> {
hex::decode(s).unwrap()
}
fn tc1(algo: KdfAlgorithm) -> String {
let okm = derive_key(
algo,
&h("0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b"),
&h("000102030405060708090a0b0c"),
&h("f0f1f2f3f4f5f6f7f8f9"),
42,
)
.unwrap();
hex::encode(&*okm)
}
#[test]
fn hkdf_sha256_rfc5869_tc1() {
assert_eq!(
tc1(KdfAlgorithm::Sha256),
"3cb25f25faacd57a90434f64d0362f2a2d2d0a90cf1a5a4c5db02d56ecc4c5bf34007208d5b887185865"
);
}
#[test]
fn hkdf_sha512_matches_the_other_providers() {
assert_eq!(
tc1(KdfAlgorithm::Sha512),
"832390086cda71fb47625bb5ceb168e4c8e26a1a16ed34d9fc7fe92c1481579338da362cb8d9f925d7cb"
);
}
#[test]
fn hkdf_sha256_rfc5869_tc3_empty_salt_and_info() {
let okm = derive_key(
KdfAlgorithm::Sha256,
&h("0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b"),
b"",
b"",
42,
)
.unwrap();
assert_eq!(
hex::encode(&*okm),
"8da4e775a563c18f715f802a063c5a31b8a11f5c5ee1879ec3454e5f3c738d2d9d201395faa4b61a96c8"
);
}
#[test]
fn hkdf_empty_salt_is_zero_salt() {
for (algo, n) in [
(KdfAlgorithm::Sha256, 32),
(KdfAlgorithm::Sha384, 48),
(KdfAlgorithm::Sha512, 64),
] {
let a = derive_key(algo, b"ikm", b"", b"info", 32).unwrap();
let b = derive_key(algo, b"ikm", &vec![0u8; n], b"info", 32).unwrap();
assert_eq!(*a, *b);
}
}
#[test]
fn hkdf_length_limit() {
assert!(derive_key(KdfAlgorithm::Sha256, b"k", b"", b"", 0).is_ok());
assert!(derive_key(KdfAlgorithm::Sha256, b"k", b"", b"", 255 * 32).is_ok());
assert!(matches!(
derive_key(KdfAlgorithm::Sha256, b"k", b"", b"", 255 * 32 + 1),
Err(CryptoError::InvalidInput(_))
));
}
#[test]
fn unoffered_kdfs_are_not_compiled() {
for algo in [
KdfAlgorithm::Blake2b512,
KdfAlgorithm::Argon2id,
KdfAlgorithm::Kmac256,
] {
assert!(matches!(
derive_key(algo, b"k", b"saltsalt", b"", 32),
Err(CryptoError::FeatureNotCompiled(_))
));
}
}
}

View File

@ -0,0 +1,367 @@
//! KEMs: X25519 (`aws_lc_rs::agreement`) and ML-KEM-768/1024 (FIPS 203,
//! `aws_lc_rs::kem`).
//!
//! Key and ciphertext formats:
//!
//! | Algorithm | Private key | Public key | Ciphertext | Secret |
//! |-------------|---------------------------------|------------|-----------------------|--------|
//! | X25519 | 32-byte scalar (LE) | 32 | 32 (ephemeral public) | 32 |
//! | ML-KEM-768 | 2400-byte FIPS 203 `dk` | 1184 | 1088 | 32 |
//! | ML-KEM-1024 | 3168-byte FIPS 203 `dk` | 1568 | 1568 | 32 |
//!
//! X25519 follows the other providers' KEM convention: encapsulation makes an
//! ephemeral key pair, the ciphertext is its public key and the secret is the
//! raw RFC 7748 shared value. An all-zero shared value (a low-order peer
//! point) is rejected.
//!
//! Public keys and ciphertexts are the standard encodings, so they
//! interoperate with every provider. The ML-KEM private key is the expanded
//! FIPS 203 decapsulation key, because aws-lc-rs has no stable API for seed
//! key generation; the RustCrypto provider stores the 64-byte seed instead,
//! so ML-KEM private keys are not portable between those two providers.
//!
//! X448, X-Wing, Classic McEliece, HQC and FrodoKEM are not offered.
use aws_lc_rs::agreement::{self, PrivateKey, UnparsedPublicKey, X25519};
use aws_lc_rs::encoding::{AsBigEndian, Curve25519SeedBin};
use aws_lc_rs::kem::{self, Ciphertext, DecapsulationKey, EncapsulationKey};
use zeroize::Zeroizing;
use ccc_crypto_core::{
algorithms::KemAlgorithm,
error::CryptoError,
types::{KemEncapResult, KemKeyPair},
};
/// Generate a key pair.
pub fn generate_keypair(algo: KemAlgorithm) -> Result<KemKeyPair, CryptoError> {
match algo {
KemAlgorithm::X25519 => {
let sk = PrivateKey::generate(&X25519).map_err(internal("X25519 keygen"))?;
Ok(KemKeyPair {
public_key: x25519_public(&sk)?,
private_key: x25519_private_bytes(&sk)?,
})
}
KemAlgorithm::MlKem768 | KemAlgorithm::MlKem1024 => {
let (p, name) = mlkem(algo)?;
let dk = DecapsulationKey::generate(p.alg).map_err(internal(name))?;
let ek = dk.encapsulation_key().map_err(internal(name))?;
Ok(KemKeyPair {
public_key: ek.key_bytes().map_err(internal(name))?.as_ref().to_vec(),
private_key: dk.key_bytes().map_err(internal(name))?.as_ref().to_vec(),
})
}
_ => not_compiled(algo),
}
}
/// Encapsulate a fresh shared secret to `public_key`.
pub fn encapsulate(algo: KemAlgorithm, public_key: &[u8]) -> Result<KemEncapResult, CryptoError> {
match algo {
KemAlgorithm::X25519 => {
let eph = PrivateKey::generate(&X25519).map_err(internal("X25519 keygen"))?;
x25519_encapsulate_with(&eph, public_key)
}
KemAlgorithm::MlKem768 | KemAlgorithm::MlKem1024 => {
let (p, name) = mlkem(algo)?;
mlkem_encapsulate(p, name, public_key)
}
_ => not_compiled(algo),
}
}
/// Recover the shared secret from `ciphertext` with `private_key`.
pub fn decapsulate(
algo: KemAlgorithm,
private_key: &[u8],
ciphertext: &[u8],
) -> Result<Zeroizing<Vec<u8>>, CryptoError> {
match algo {
KemAlgorithm::X25519 => x25519_dh(private_key, ciphertext),
KemAlgorithm::MlKem768 | KemAlgorithm::MlKem1024 => {
let (p, name) = mlkem(algo)?;
mlkem_decapsulate(p, name, private_key, ciphertext)
}
_ => not_compiled(algo),
}
}
fn not_compiled<T>(algo: KemAlgorithm) -> Result<T, CryptoError> {
Err(CryptoError::FeatureNotCompiled(format!(
"{} is not offered by the awslc provider",
algo.name()
)))
}
fn internal<E>(what: &'static str) -> impl Fn(E) -> CryptoError {
move |_| CryptoError::InternalError(format!("{what} failed"))
}
// ── X25519 ───────────────────────────────────────────────────────────────────
fn x25519_public(sk: &PrivateKey) -> Result<Vec<u8>, CryptoError> {
Ok(sk
.compute_public_key()
.map_err(internal("X25519 public key"))?
.as_ref()
.to_vec())
}
fn x25519_private_bytes(sk: &PrivateKey) -> Result<Vec<u8>, CryptoError> {
let bin: Curve25519SeedBin = sk
.as_be_bytes()
.map_err(internal("X25519 private key export"))?;
Ok(bin.as_ref().to_vec())
}
fn x25519_private(bytes: &[u8]) -> Result<PrivateKey, CryptoError> {
if bytes.len() != 32 {
return Err(CryptoError::InvalidKey(
"X25519: private key must be 32 bytes".into(),
));
}
PrivateKey::from_private_key(&X25519, bytes)
.map_err(|_| CryptoError::InvalidKey("X25519: invalid private key".into()))
}
/// X25519 encapsulation with a caller-chosen ephemeral scalar (for KATs).
pub fn x25519_encapsulate_deterministic(
ephemeral_private: &[u8],
public_key: &[u8],
) -> Result<KemEncapResult, CryptoError> {
x25519_encapsulate_with(&x25519_private(ephemeral_private)?, public_key)
}
fn x25519_encapsulate_with(
eph: &PrivateKey,
public_key: &[u8],
) -> Result<KemEncapResult, CryptoError> {
let ss = x25519_agree(eph, public_key)?;
Ok(KemEncapResult {
ciphertext: x25519_public(eph)?,
shared_secret: ss.to_vec(),
})
}
fn x25519_dh(private_key: &[u8], public_key: &[u8]) -> Result<Zeroizing<Vec<u8>>, CryptoError> {
x25519_agree(&x25519_private(private_key)?, public_key)
}
fn x25519_agree(sk: &PrivateKey, public_key: &[u8]) -> Result<Zeroizing<Vec<u8>>, CryptoError> {
if public_key.len() != 32 {
return Err(CryptoError::InvalidKey(
"X25519: public key must be 32 bytes".into(),
));
}
let low_order = || CryptoError::InvalidKey("X25519: low-order public key".into());
let ss = agreement::agree(sk, UnparsedPublicKey::new(&X25519, public_key), (), |s| {
Ok(Zeroizing::new(s.to_vec()))
})
.map_err(|()| low_order())?;
// AWS-LC already refuses an all-zero result; checked here as well so the
// rule does not depend on the backend version.
if ss.iter().fold(0u8, |acc, b| acc | b) == 0 {
return Err(low_order());
}
Ok(ss)
}
// ── ML-KEM ───────────────────────────────────────────────────────────────────
/// FIPS 203 sizes for one parameter set.
#[derive(Clone, Copy)]
pub(crate) struct MlKemParams {
pub(crate) alg: &'static kem::Algorithm,
pub(crate) dk_len: usize,
pub(crate) ek_len: usize,
pub(crate) ct_len: usize,
}
pub(crate) const MLKEM768: MlKemParams = MlKemParams {
alg: &kem::ML_KEM_768,
dk_len: 2400,
ek_len: 1184,
ct_len: 1088,
};
pub(crate) const MLKEM1024: MlKemParams = MlKemParams {
alg: &kem::ML_KEM_1024,
dk_len: 3168,
ek_len: 1568,
ct_len: 1568,
};
fn mlkem(algo: KemAlgorithm) -> Result<(MlKemParams, &'static str), CryptoError> {
match algo {
KemAlgorithm::MlKem768 => Ok((MLKEM768, "ML-KEM-768")),
KemAlgorithm::MlKem1024 => Ok((MLKEM1024, "ML-KEM-1024")),
_ => not_compiled(algo),
}
}
pub(crate) fn mlkem_encapsulate(
p: MlKemParams,
name: &'static str,
public_key: &[u8],
) -> Result<KemEncapResult, CryptoError> {
if public_key.len() != p.ek_len {
return Err(CryptoError::InvalidKey(format!(
"{name}: public key must be {} bytes",
p.ek_len
)));
}
let ek = EncapsulationKey::new(p.alg, public_key)
.map_err(|_| CryptoError::InvalidKey(format!("{name}: invalid public key")))?;
let (ct, ss) = ek.encapsulate().map_err(internal(name))?;
Ok(KemEncapResult {
ciphertext: ct.as_ref().to_vec(),
shared_secret: ss.as_ref().to_vec(),
})
}
pub(crate) fn mlkem_decapsulate(
p: MlKemParams,
name: &'static str,
private_key: &[u8],
ciphertext: &[u8],
) -> Result<Zeroizing<Vec<u8>>, CryptoError> {
if private_key.len() != p.dk_len {
return Err(CryptoError::InvalidKey(format!(
"{name}: private key must be {} bytes",
p.dk_len
)));
}
if ciphertext.len() != p.ct_len {
return Err(CryptoError::InvalidInput(format!(
"{name}: wrong ciphertext length"
)));
}
let dk = DecapsulationKey::new(p.alg, private_key)
.map_err(|_| CryptoError::InvalidKey(format!("{name}: invalid private key")))?;
// A malformed ciphertext of the right length gets FIPS 203 implicit
// rejection (a pseudo-random secret), not an error.
let ss = dk
.decapsulate(Ciphertext::from(ciphertext))
.map_err(|_| CryptoError::InvalidKey(format!("{name}: decapsulation failed")))?;
Ok(Zeroizing::new(ss.as_ref().to_vec()))
}
#[cfg(test)]
mod tests {
use super::*;
const OFFERED: [KemAlgorithm; 3] = [
KemAlgorithm::X25519,
KemAlgorithm::MlKem768,
KemAlgorithm::MlKem1024,
];
#[test]
fn roundtrip_all_offered() {
for algo in OFFERED {
let kp = generate_keypair(algo).unwrap();
let enc = encapsulate(algo, &kp.public_key).unwrap();
let ss = decapsulate(algo, &kp.private_key, &enc.ciphertext).unwrap();
assert_eq!(*ss, enc.shared_secret, "{}", algo.name());
assert_eq!(ss.len(), 32);
}
}
#[test]
fn sizes() {
for (algo, sk, pk, ct) in [
(KemAlgorithm::X25519, 32, 32, 32),
(KemAlgorithm::MlKem768, 2400, 1184, 1088),
(KemAlgorithm::MlKem1024, 3168, 1568, 1568),
] {
let kp = generate_keypair(algo).unwrap();
assert_eq!(kp.private_key.len(), sk);
assert_eq!(kp.public_key.len(), pk);
assert_eq!(
encapsulate(algo, &kp.public_key).unwrap().ciphertext.len(),
ct
);
}
}
#[test]
fn x25519_rfc7748() {
let alice = hex::decode("77076d0a7318a57d3c16c17251b26645df4c2f87ebc0992ab177fba51db92c2a")
.unwrap();
let bob_pub =
hex::decode("de9edb7d7b7dc1b4d35b61c2ece435373f8343c85b78674dadfc7e146f882b4f")
.unwrap();
let ss = decapsulate(KemAlgorithm::X25519, &alice, &bob_pub).unwrap();
assert_eq!(
hex::encode(&*ss),
"4a5d9d5ba4ce2de1728e3bf480350f25e07e21c947d19e3376f09b3c1e161742"
);
}
#[test]
fn x25519_private_key_round_trips() {
let kp = generate_keypair(KemAlgorithm::X25519).unwrap();
let mut base = [0u8; 32];
base[0] = 9;
let pk = decapsulate(KemAlgorithm::X25519, &kp.private_key, &base).unwrap();
assert_eq!(*pk, kp.public_key);
}
#[test]
fn x25519_low_order_point_rejected() {
let sk = [0x11u8; 32];
assert!(matches!(
decapsulate(KemAlgorithm::X25519, &sk, &[0u8; 32]),
Err(CryptoError::InvalidKey(_))
));
}
#[test]
fn wrong_lengths_rejected() {
for algo in OFFERED {
let kp = generate_keypair(algo).unwrap();
let enc = encapsulate(algo, &kp.public_key).unwrap();
assert!(encapsulate(algo, &kp.public_key[1..]).is_err());
assert!(decapsulate(algo, &kp.private_key[1..], &enc.ciphertext).is_err());
assert!(decapsulate(algo, &kp.private_key, &enc.ciphertext[1..]).is_err());
}
}
#[test]
fn mlkem_implicit_rejection() {
for algo in [KemAlgorithm::MlKem768, KemAlgorithm::MlKem1024] {
let kp = generate_keypair(algo).unwrap();
let enc = encapsulate(algo, &kp.public_key).unwrap();
let mut ct = enc.ciphertext.clone();
ct[0] ^= 1;
let ss = decapsulate(algo, &kp.private_key, &ct).unwrap();
assert_ne!(*ss, enc.shared_secret);
}
}
#[test]
fn unsupported_kems() {
for algo in [
KemAlgorithm::X448,
KemAlgorithm::XWing,
KemAlgorithm::ClassicMcEliece460896,
KemAlgorithm::ClassicMcEliece460896f,
KemAlgorithm::Hqc192,
KemAlgorithm::FrodoKem976Shake,
] {
assert!(matches!(
generate_keypair(algo),
Err(CryptoError::FeatureNotCompiled(_))
));
assert!(matches!(
encapsulate(algo, &[0u8; 32]),
Err(CryptoError::FeatureNotCompiled(_))
));
assert!(matches!(
decapsulate(algo, &[0u8; 32], &[0u8; 32]),
Err(CryptoError::FeatureNotCompiled(_))
));
}
}
}

View File

@ -0,0 +1,39 @@
//! # ccc-crypto-awslc
//!
//! AWS-LC implementation of the CCC provider traits, built on `aws-lc-rs`
//! (Apache-2.0 OR ISC). It is the default vetted provider and the FIPS
//! anchor: built with the `fips` feature it links AWS-LC-FIPS, a FIPS 140-3
//! validated module, and [`AwsLcProvider`] reports `fips_mode()` only when
//! that module says it is in FIPS mode.
//!
//! Offered: AES-256-GCM, AES-256-GCM-SIV, ChaCha20-Poly1305, HKDF-SHA-256/
//! 384/512, HMAC-SHA-256/384/512, SHA-256/384/512, SHA3-256/512, X25519 and
//! ML-KEM-768/1024. Each one is listed as available only after its
//! known-answer test passed.
//!
//! Call [`init()`] once at start-up to register it in the global
//! [`ProviderRegistry`][ccc_crypto_core::registry::ProviderRegistry].
#![forbid(unsafe_code)]
pub mod aead;
pub mod capabilities;
pub mod fips;
pub mod hash;
pub mod kdf;
pub mod kem;
pub mod mac;
pub mod provider;
pub mod self_test;
pub use provider::AwsLcProvider;
/// The provider's registry name.
pub const PROVIDER_NAME: &str = "awslc";
/// Register an [`AwsLcProvider`] in the global registry.
pub fn init() {
ccc_crypto_core::ProviderRegistry::global()
.register(PROVIDER_NAME, Box::new(AwsLcProvider::new()));
log::info!("[ccc-crypto-awslc] provider registered");
}

View File

@ -0,0 +1,97 @@
//! HMAC-SHA-2 from `aws_lc_rs::hmac`.
//!
//! Keyed BLAKE2b and one-time Poly1305 are not exposed by aws-lc-rs and
//! return [`CryptoError::FeatureNotCompiled`].
use aws_lc_rs::hmac::{self, HMAC_SHA256, HMAC_SHA384, HMAC_SHA512};
use ccc_crypto_core::{algorithms::MacAlgorithm, error::CryptoError};
fn algorithm(algo: MacAlgorithm) -> Result<hmac::Algorithm, CryptoError> {
match algo {
MacAlgorithm::HmacSha256 => Ok(HMAC_SHA256),
MacAlgorithm::HmacSha384 => Ok(HMAC_SHA384),
MacAlgorithm::HmacSha512 => Ok(HMAC_SHA512),
MacAlgorithm::Blake2bMac | MacAlgorithm::Poly1305 => Err(CryptoError::FeatureNotCompiled(
format!("{} is not offered by the awslc provider", algo.name()),
)),
}
}
/// Compute a MAC tag over `data`. Any key length is accepted (RFC 2104).
pub fn compute_mac(algo: MacAlgorithm, key: &[u8], data: &[u8]) -> Result<Vec<u8>, CryptoError> {
let key = hmac::Key::new(algorithm(algo)?, key);
Ok(hmac::sign(&key, data).as_ref().to_vec())
}
/// Verify a MAC tag in constant time (`hmac::verify`). A mismatch,
/// including a wrong-length tag, is `Ok(false)`.
pub fn verify_mac(
algo: MacAlgorithm,
key: &[u8],
data: &[u8],
mac: &[u8],
) -> Result<bool, CryptoError> {
let key = hmac::Key::new(algorithm(algo)?, key);
Ok(hmac::verify(&key, data, mac).is_ok())
}
#[cfg(test)]
mod tests {
use super::*;
const OFFERED: [MacAlgorithm; 3] = [
MacAlgorithm::HmacSha256,
MacAlgorithm::HmacSha384,
MacAlgorithm::HmacSha512,
];
#[test]
fn tag_lengths_and_verify() {
let key = [0x42u8; 32];
for algo in OFFERED {
let tag = compute_mac(algo, &key, b"data").unwrap();
assert_eq!(tag.len(), algo.tag_len(), "{}", algo.name());
assert!(verify_mac(algo, &key, b"data", &tag).unwrap());
let mut bad = tag.clone();
bad[0] ^= 1;
assert!(!verify_mac(algo, &key, b"data", &bad).unwrap());
assert!(!verify_mac(algo, &key, b"data", &tag[1..]).unwrap());
assert!(!verify_mac(algo, &key, b"Data", &tag).unwrap());
}
}
#[test]
fn hmac_sha256_rfc4231_tc2() {
let tag = compute_mac(
MacAlgorithm::HmacSha256,
b"Jefe",
b"what do ya want for nothing?",
)
.unwrap();
assert_eq!(
hex::encode(tag),
"5bdcc146bf60754e6a042426089575c75a003f089d2739839dec58b964ec3843"
);
}
#[test]
fn empty_and_long_keys_work() {
assert!(compute_mac(MacAlgorithm::HmacSha512, b"", b"x").is_ok());
assert!(compute_mac(MacAlgorithm::HmacSha256, &[1u8; 200], b"x").is_ok());
}
#[test]
fn unoffered_macs_are_not_compiled() {
for algo in [MacAlgorithm::Blake2bMac, MacAlgorithm::Poly1305] {
assert!(matches!(
compute_mac(algo, &[1u8; 32], b"x"),
Err(CryptoError::FeatureNotCompiled(_))
));
assert!(matches!(
verify_mac(algo, &[1u8; 32], b"x", &[0u8; 16]),
Err(CryptoError::FeatureNotCompiled(_))
));
}
}
}

View File

@ -0,0 +1,195 @@
//! [`AwsLcProvider`]: the [`CryptoProvider`] implementation.
use std::sync::OnceLock;
use zeroize::Zeroizing;
use ccc_crypto_core::{
algorithms::{AeadAlgorithm, HashAlgorithm, KdfAlgorithm, KemAlgorithm, MacAlgorithm},
capabilities::ProviderCapabilities,
error::CryptoError,
provider::{AeadProvider, CryptoProvider, HashProvider, KdfProvider, KemProvider, MacProvider},
types::{BenchmarkReport, KemEncapResult, KemKeyPair, SelfTestReport},
};
use crate::{aead, capabilities, fips, hash, kdf, kem, mac, self_test, PROVIDER_NAME};
/// The AWS-LC provider. Self-test, benchmark, capabilities and the FIPS
/// status are computed lazily on first use and cached.
#[derive(Default)]
pub struct AwsLcProvider {
caps: OnceLock<ProviderCapabilities>,
bench: OnceLock<BenchmarkReport>,
kats: OnceLock<SelfTestReport>,
fips: OnceLock<bool>,
}
impl AwsLcProvider {
/// Create a provider; no work is done until it is queried.
pub fn new() -> Self {
Self::default()
}
fn kats(&self) -> &SelfTestReport {
self.kats.get_or_init(self_test::run)
}
fn bench(&self) -> &BenchmarkReport {
self.bench.get_or_init(|| {
log::info!("[ccc-crypto-awslc] running throughput benchmark…");
capabilities::run_benchmark()
})
}
}
impl AeadProvider for AwsLcProvider {
fn encrypt_aead(
&self,
algo: AeadAlgorithm,
key: &[u8],
nonce: &[u8],
plaintext: &[u8],
aad: &[u8],
) -> Result<Vec<u8>, CryptoError> {
aead::encrypt(algo, key, nonce, plaintext, aad)
}
fn decrypt_aead(
&self,
algo: AeadAlgorithm,
key: &[u8],
nonce: &[u8],
ciphertext_and_tag: &[u8],
aad: &[u8],
) -> Result<Vec<u8>, CryptoError> {
aead::decrypt(algo, key, nonce, ciphertext_and_tag, aad)
}
}
impl KdfProvider for AwsLcProvider {
fn derive_key(
&self,
algo: KdfAlgorithm,
ikm: &[u8],
salt: &[u8],
info: &[u8],
length: usize,
) -> Result<Zeroizing<Vec<u8>>, CryptoError> {
kdf::derive_key(algo, ikm, salt, info, length)
}
}
impl MacProvider for AwsLcProvider {
fn compute_mac(
&self,
algo: MacAlgorithm,
key: &[u8],
data: &[u8],
) -> Result<Vec<u8>, CryptoError> {
mac::compute_mac(algo, key, data)
}
fn verify_mac(
&self,
algo: MacAlgorithm,
key: &[u8],
data: &[u8],
mac_bytes: &[u8],
) -> Result<bool, CryptoError> {
mac::verify_mac(algo, key, data, mac_bytes)
}
}
impl HashProvider for AwsLcProvider {
fn hash(&self, algo: HashAlgorithm, data: &[u8]) -> Result<Vec<u8>, CryptoError> {
hash::hash(algo, data)
}
}
impl KemProvider for AwsLcProvider {
fn generate_keypair(&self, algo: KemAlgorithm) -> Result<KemKeyPair, CryptoError> {
kem::generate_keypair(algo)
}
fn encapsulate(
&self,
algo: KemAlgorithm,
public_key: &[u8],
) -> Result<KemEncapResult, CryptoError> {
kem::encapsulate(algo, public_key)
}
fn decapsulate(
&self,
algo: KemAlgorithm,
private_key: &[u8],
ciphertext: &[u8],
) -> Result<Zeroizing<Vec<u8>>, CryptoError> {
kem::decapsulate(algo, private_key, ciphertext)
}
}
impl CryptoProvider for AwsLcProvider {
fn provider_name(&self) -> &'static str {
PROVIDER_NAME
}
fn lineage(&self) -> &'static str {
// AWS-LC is a fork of BoringSSL; they share code and assembly.
"boringssl"
}
/// `true` only for a `fips` build whose AWS-LC-FIPS module reports FIPS
/// mode at runtime (D-26).
fn fips_mode(&self) -> bool {
*self.fips.get_or_init(|| {
let on = fips::fips_mode();
log::info!(
"[ccc-crypto-awslc] AWS-LC {} FIPS mode: {on}",
fips::awslc_version()
);
on
})
}
fn capabilities(&self) -> ProviderCapabilities {
self.caps
.get_or_init(|| capabilities::probe_capabilities(self.kats(), Some(self.bench())))
.clone()
}
fn self_test(&self) -> SelfTestReport {
self.kats().clone()
}
fn benchmark(&self) -> BenchmarkReport {
self.bench().clone()
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn identity_and_self_test() {
let p = AwsLcProvider::new();
assert_eq!(p.provider_name(), "awslc");
assert_eq!(p.fips_mode(), cfg!(feature = "fips"));
assert!(p.self_test().all_passed);
}
#[test]
fn trait_objects_work() {
let p: Box<dyn CryptoProvider> = Box::new(AwsLcProvider::new());
let key = [1u8; 32];
let nonce = [2u8; 12];
let ct = p
.encrypt_aead(AeadAlgorithm::AesGcm256, &key, &nonce, b"m", b"a")
.unwrap();
let pt = p
.decrypt_aead(AeadAlgorithm::AesGcm256, &key, &nonce, &ct, b"a")
.unwrap();
assert_eq!(pt, b"m");
}
}

View File

@ -0,0 +1,420 @@
//! Embedded known-answer self-test (KAT) for every algorithm the provider
//! offers. An algorithm without a passing KAT is never marked available.
//!
//! Sources (hex vectors shared with the RustCrypto and wolfSSL self-tests):
//!
//! - AES-256-GCM: NIST SP 800-38D test case 16.
//! - AES-256-GCM-SIV: RFC 8452 appendix C.2.
//! - ChaCha20-Poly1305: RFC 8439 §2.8.2.
//! - SHA-2 / SHA-3: FIPS 180-4 / FIPS 202 "abc".
//! - HMAC: RFC 4231 test case 2.
//! - HKDF: RFC 5869 test cases 1 and 3 (SHA-256), and the case 1 inputs for
//! SHA-384/512, checked against OpenSSL 3.6 and the other providers.
//! - X25519: RFC 7748 §6.1.
//! - ML-KEM-768/1024: the seed-00..3f key of the IETF LAMPS examples. The
//! expanded decapsulation keys and the ciphertexts (encapsulation
//! randomness `40..6b`, OpenSSL `hexikme`) were produced by OpenSSL 3.6.1
//! and are stored under `kat/`; their public-key and ciphertext SHA3-256
//! values and the shared secrets are the ones the RustCrypto provider pins.
//! aws-lc-rs has no deterministic encapsulation, so the KAT checks
//! decapsulation (and implicit rejection), then a fresh encapsulation to
//! the known public key.
use ccc_crypto_core::{
algorithms::{AeadAlgorithm, HashAlgorithm, KdfAlgorithm, KemAlgorithm, MacAlgorithm},
types::{AlgoTestResult, SelfTestReport},
};
use crate::{aead, hash, kdf, kem, mac, PROVIDER_NAME};
type Check = fn() -> Result<(), String>;
/// Every KAT: (algorithm ID, test name, check).
const KATS: &[(u32, &str, Check)] = &[
(
AeadAlgorithm::AesGcm256 as u32,
"AES-256-GCM SP 800-38D TC16",
aes_gcm,
),
(
AeadAlgorithm::AesGcmSiv256 as u32,
"AES-256-GCM-SIV RFC 8452 C.2",
aes_gcm_siv,
),
(
AeadAlgorithm::ChaCha20Poly1305 as u32,
"ChaCha20-Poly1305 RFC 8439 2.8.2",
chacha,
),
(HashAlgorithm::Sha256 as u32, "SHA-256 abc", || {
digest(HashAlgorithm::Sha256, SHA256_ABC)
}),
(HashAlgorithm::Sha384 as u32, "SHA-384 abc", || {
digest(HashAlgorithm::Sha384, SHA384_ABC)
}),
(HashAlgorithm::Sha512 as u32, "SHA-512 abc", || {
digest(HashAlgorithm::Sha512, SHA512_ABC)
}),
(HashAlgorithm::Sha3_256 as u32, "SHA3-256 abc", || {
digest(HashAlgorithm::Sha3_256, SHA3_256_ABC)
}),
(HashAlgorithm::Sha3_512 as u32, "SHA3-512 abc", || {
digest(HashAlgorithm::Sha3_512, SHA3_512_ABC)
}),
(
MacAlgorithm::HmacSha256 as u32,
"HMAC-SHA-256 RFC 4231 TC2",
|| hmac(MacAlgorithm::HmacSha256, HMAC256_TC2),
),
(
MacAlgorithm::HmacSha384 as u32,
"HMAC-SHA-384 RFC 4231 TC2",
|| hmac(MacAlgorithm::HmacSha384, HMAC384_TC2),
),
(
MacAlgorithm::HmacSha512 as u32,
"HMAC-SHA-512 RFC 4231 TC2",
|| hmac(MacAlgorithm::HmacSha512, HMAC512_TC2),
),
(
KdfAlgorithm::Sha256 as u32,
"HKDF-SHA-256 RFC 5869 TC1",
|| hkdf(KdfAlgorithm::Sha256, HKDF256_TC1),
),
(
KdfAlgorithm::Sha256 as u32,
"HKDF-SHA-256 RFC 5869 TC3 (empty salt)",
hkdf_empty_salt,
),
(
KdfAlgorithm::Sha384 as u32,
"HKDF-SHA-384 TC1 inputs",
|| hkdf(KdfAlgorithm::Sha384, HKDF384_TC1),
),
(
KdfAlgorithm::Sha512 as u32,
"HKDF-SHA-512 TC1 inputs",
|| hkdf(KdfAlgorithm::Sha512, HKDF512_TC1),
),
(KemAlgorithm::X25519 as u32, "X25519 RFC 7748 6.1", x25519),
(
KemAlgorithm::MlKem768 as u32,
"ML-KEM-768 seed KAT",
mlkem768,
),
(
KemAlgorithm::MlKem1024 as u32,
"ML-KEM-1024 seed KAT",
mlkem1024,
),
];
/// Run every KAT. Never panics; failures are reported per algorithm.
pub fn run() -> SelfTestReport {
let results = KATS
.iter()
.map(|(id, name, check)| {
let outcome = check();
AlgoTestResult {
algo_id: *id,
algo_name: (*name).into(),
passed: outcome.is_ok(),
error_message: outcome.err(),
}
})
.collect();
SelfTestReport::finalise(PROVIDER_NAME, results)
}
// ── Helpers ──────────────────────────────────────────────────────────────────
fn hx(s: &str) -> Vec<u8> {
(0..s.len() / 2)
.map(|i| u8::from_str_radix(&s[2 * i..2 * i + 2], 16).unwrap_or(0))
.collect()
}
fn expect(what: &str, got: &[u8], want_hex: &str) -> Result<(), String> {
if got == hx(want_hex).as_slice() {
Ok(())
} else {
Err(format!("{what}: output mismatch"))
}
}
fn sha3(data: &[u8]) -> Vec<u8> {
hash::hash(HashAlgorithm::Sha3_256, data).unwrap_or_default()
}
fn e<E: core::fmt::Display>(err: E) -> String {
err.to_string()
}
// ── AEAD ─────────────────────────────────────────────────────────────────────
fn aead_kat(
algo: AeadAlgorithm,
key: &str,
nonce: &str,
aad: &str,
pt: &str,
ct: &str,
) -> Result<(), String> {
let (key, nonce, aad, pt) = (hx(key), hx(nonce), hx(aad), hx(pt));
let sealed = aead::encrypt(algo, &key, &nonce, &pt, &aad).map_err(e)?;
expect("seal", &sealed, ct)?;
let opened = aead::decrypt(algo, &key, &nonce, &sealed, &aad).map_err(e)?;
if opened != pt {
return Err("open: plaintext mismatch".into());
}
let mut bad = sealed;
let last = bad.len() - 1;
bad[last] ^= 0x80;
if aead::decrypt(algo, &key, &nonce, &bad, &aad).is_ok() {
return Err("open accepted a tampered tag".into());
}
Ok(())
}
fn aes_gcm() -> Result<(), String> {
aead_kat(
AeadAlgorithm::AesGcm256,
"feffe9928665731c6d6a8f9467308308feffe9928665731c6d6a8f9467308308",
"cafebabefacedbaddecaf888",
"feedfacedeadbeeffeedfacedeadbeefabaddad2",
"d9313225f88406e5a55909c5aff5269a86a7a9531534f7da2e4c303d8a318a72\
1c3c0c95956809532fcf0e2449a6b525b16aedf5aa0de657ba637b39",
"522dc1f099567d07f47f37a32a84427d643a8cdcbfe5c0c97598a2bd2555d1aa\
8cb08e48590dbb3da7b08b1056828838c5f61e6393ba7a0abcc9f662\
76fc6ece0f4e1768cddf8853bb2d551b",
)
}
fn aes_gcm_siv() -> Result<(), String> {
let key = "0100000000000000000000000000000000000000000000000000000000000000";
let nonce = "030000000000000000000000";
aead_kat(
AeadAlgorithm::AesGcmSiv256,
key,
nonce,
"",
"",
"07f5f4169bbf55a8400cd47ea6fd400f",
)?;
aead_kat(
AeadAlgorithm::AesGcmSiv256,
key,
nonce,
"",
"0100000000000000",
"c2ef328e5c71c83b843122130f7364b761e0b97427e3df28",
)
}
fn chacha() -> Result<(), String> {
aead_kat(
AeadAlgorithm::ChaCha20Poly1305,
"808182838485868788898a8b8c8d8e8f909192939495969798999a9b9c9d9e9f",
"070000004041424344454647",
"50515253c0c1c2c3c4c5c6c7",
"4c616469657320616e642047656e746c656d656e206f662074686520636c6173\
73206f66202739393a204966204920636f756c64206f6666657220796f75206f6e6c79206f6e6520746970\
20666f7220746865206675747572652c2073756e73637265656e20776f756c642062652069742e",
"d31a8d34648e60db7b86afbc53ef7ec2a4aded51296e08fea9e2b5a736ee62d63dbea45e8ca967128\
2fafb69da92728b1a71de0a9e060b2905d6a5b67ecd3b3692ddbd7f2d778b8c9803aee328091b58fa\
b324e4fad675945585808b4831d7bc3ff4def08e4b7a9de576d26586cec64b6116\
1ae10b594f09e26a7e902ecbd0600691",
)
}
// ── Hash ─────────────────────────────────────────────────────────────────────
const SHA256_ABC: &str = "ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad";
const SHA384_ABC: &str = "cb00753f45a35e8bb5a03d699ac65007272c32ab0eded1631a8b605a43ff5bed\
8086072ba1e7cc2358baeca134c825a7";
const SHA512_ABC: &str = "ddaf35a193617abacc417349ae20413112e6fa4e89a97ea20a9eeee64b55d39a\
2192992a274fc1a836ba3c23a3feebbd454d4423643ce80e2a9ac94fa54ca49f";
const SHA3_256_ABC: &str = "3a985da74fe225b2045c172d6bd390bd855f086e3e9d525b46bfe24511431532";
const SHA3_512_ABC: &str = "b751850b1a57168a5693cd924b6b096e08f621827444f70d884f5d0240d2712e\
10e116e9192af3c91a7ec57647e3934057340b4cf408d5a56592f8274eec53f0";
fn digest(algo: HashAlgorithm, want: &str) -> Result<(), String> {
expect("digest", &hash::hash(algo, b"abc").map_err(e)?, want)
}
// ── MAC ──────────────────────────────────────────────────────────────────────
const HMAC256_TC2: &str = "5bdcc146bf60754e6a042426089575c75a003f089d2739839dec58b964ec3843";
const HMAC384_TC2: &str = "af45d2e376484031617f78d2b58a6b1b9c7ef464f5a01b47e42ec3736322445e\
8e2240ca5e69e2c78b3239ecfab21649";
const HMAC512_TC2: &str = "164b7a7bfcf819e2e395fbe73b56e0a387bd64222e831fd610270cd7ea250554\
9758bf75c05a994a6d034f65f8f0e6fdcaeab1a34d4a6b4b636e070a38bce737";
fn hmac(algo: MacAlgorithm, want: &str) -> Result<(), String> {
let (key, data) = (b"Jefe", b"what do ya want for nothing?");
let tag = mac::compute_mac(algo, key, data).map_err(e)?;
expect("tag", &tag, want)?;
if !mac::verify_mac(algo, key, data, &tag).map_err(e)? {
return Err("verify rejected a valid tag".into());
}
let mut bad = tag;
bad[0] ^= 1;
if mac::verify_mac(algo, key, data, &bad).map_err(e)? {
return Err("verify accepted a tampered tag".into());
}
Ok(())
}
// ── KDF ──────────────────────────────────────────────────────────────────────
const HKDF256_TC1: &str = "3cb25f25faacd57a90434f64d0362f2a2d2d0a90cf1a5a4c5db02d56ecc4c5bf\
34007208d5b887185865";
const HKDF384_TC1: &str = "9b5097a86038b805309076a44b3a9f38063e25b516dcbf369f394cfab43685f7\
48b6457763e4f0204fc5";
const HKDF512_TC1: &str = "832390086cda71fb47625bb5ceb168e4c8e26a1a16ed34d9fc7fe92c14815793\
38da362cb8d9f925d7cb";
fn hkdf(algo: KdfAlgorithm, want: &str) -> Result<(), String> {
let okm = kdf::derive_key(
algo,
&hx("0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b"),
&hx("000102030405060708090a0b0c"),
&hx("f0f1f2f3f4f5f6f7f8f9"),
42,
)
.map_err(e)?;
expect("okm", &okm, want)
}
/// The empty-salt rule the cascade and HPKE schedules rely on.
fn hkdf_empty_salt() -> Result<(), String> {
let okm = kdf::derive_key(
KdfAlgorithm::Sha256,
&hx("0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b"),
b"",
b"",
42,
)
.map_err(e)?;
expect(
"okm",
&okm,
"8da4e775a563c18f715f802a063c5a31b8a11f5c5ee1879ec3454e5f3c738d2d\
9d201395faa4b61a96c8",
)
}
// ── KEM ──────────────────────────────────────────────────────────────────────
fn x25519() -> Result<(), String> {
let alice = hx("77076d0a7318a57d3c16c17251b26645df4c2f87ebc0992ab177fba51db92c2a");
let alice_pub = "8520f0098930a754748b7ddcb43ef75a0dbf3a0d26381af4eba4a98eaa9b4e6a";
let bob = hx("5dab087e624a8a4b79e17f8b83800ee66f3bb1292618b6fd1c2f8b27ff88e0eb");
let bob_pub = hx("de9edb7d7b7dc1b4d35b61c2ece435373f8343c85b78674dadfc7e146f882b4f");
let shared = "4a5d9d5ba4ce2de1728e3bf480350f25e07e21c947d19e3376f09b3c1e161742";
// Encapsulating with Alice's key as the ephemeral gives her public key as
// the ciphertext; Bob decapsulates it.
let enc = kem::x25519_encapsulate_deterministic(&alice, &bob_pub).map_err(e)?;
expect("ciphertext", &enc.ciphertext, alice_pub)?;
expect("encap secret", &enc.shared_secret, shared)?;
let ss = kem::decapsulate(KemAlgorithm::X25519, &bob, &enc.ciphertext).map_err(e)?;
expect("decap secret", &ss, shared)
}
struct MlKemKat {
algo: KemAlgorithm,
params: kem::MlKemParams,
name: &'static str,
dk: &'static [u8],
ct: &'static [u8],
dk_sha3: &'static str,
pk_sha3: &'static str,
ct_sha3: &'static str,
ss: &'static str,
}
fn mlkem_kat(k: &MlKemKat) -> Result<(), String> {
let p = k.params;
// The stored inputs are the pinned ones.
expect("decapsulation key", &sha3(k.dk), k.dk_sha3)?;
expect("ciphertext", &sha3(k.ct), k.ct_sha3)?;
// FIPS 203 dk = dk_pke || ek || H(ek) || z, with dk_pke as long as ek - 32.
let ek_start = p.ek_len - 32;
let pk = &k.dk[ek_start..ek_start + p.ek_len];
expect("public key", &sha3(pk), k.pk_sha3)?;
let ss = kem::decapsulate(k.algo, k.dk, k.ct).map_err(e)?;
expect("decap secret", &ss, k.ss)?;
let mut bad = k.ct.to_vec();
bad[0] ^= 1;
let rejected = kem::decapsulate(k.algo, k.dk, &bad).map_err(e)?;
if rejected.as_slice() == hx(k.ss).as_slice() {
return Err("implicit rejection returned the real secret".into());
}
let enc = kem::mlkem_encapsulate(p, k.name, pk).map_err(e)?;
let ss = kem::decapsulate(k.algo, k.dk, &enc.ciphertext).map_err(e)?;
if *ss != enc.shared_secret {
return Err("encapsulation to the known key does not decapsulate".into());
}
Ok(())
}
fn mlkem768() -> Result<(), String> {
mlkem_kat(&MlKemKat {
algo: KemAlgorithm::MlKem768,
params: kem::MLKEM768,
name: "ML-KEM-768",
dk: include_bytes!("../kat/mlkem768_seed00_dk.bin"),
ct: include_bytes!("../kat/mlkem768_seed00_ct.bin"),
dk_sha3: "1149f17c3c4ac6ab1e3e2d9d8bd0171355ac0fa31bb8855c48ceade874c0864b",
pk_sha3: "a24e16d8f8f9383a95b77050f4d9fd2f5733eec1d63ef3c23ebf9918173669a7",
ct_sha3: "c5190623f119891d14904e62cd28a79677df85afe5ad9151cb962caa00002de4",
ss: "71e6c52c0066736b5d2e9cfe2d9694804a4c6dd57c9ed1d615df96c018782de3",
})
}
fn mlkem1024() -> Result<(), String> {
mlkem_kat(&MlKemKat {
algo: KemAlgorithm::MlKem1024,
params: kem::MLKEM1024,
name: "ML-KEM-1024",
dk: include_bytes!("../kat/mlkem1024_seed00_dk.bin"),
ct: include_bytes!("../kat/mlkem1024_seed00_ct.bin"),
dk_sha3: "f0db5d938027fcd9bad87847d52c14cf0c4abcf0703b749793f212111ffb303b",
pk_sha3: "61349e5c131a7e116a0463861d7d18663c5627c38c7147ddaadfd48acd7a4535",
ct_sha3: "6e264ea88c427017fceeebf87f12c106bb2e511843d5ed525fdd4d45a0205daa",
ss: "ccff2f30e61151de4c3257ca1d3a8a9de661b81c5ba34efe9b1a4af770caf9df",
})
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn all_kats_pass() {
let report = run();
for r in &report.results {
assert!(r.passed, "{}: {:?}", r.algo_name, r.error_message);
}
assert!(report.all_passed);
assert_eq!(report.provider_name, "awslc");
}
#[test]
fn kat_detects_a_wrong_answer() {
assert!(expect("x", b"abc", "616264").is_err());
assert!(expect("x", b"abc", "616263").is_ok());
}
#[test]
fn every_offered_algorithm_has_a_kat() {
let ids: Vec<u32> = KATS.iter().map(|k| k.0).collect();
for id in [
12u32, 13, 16, 1, 2, 3, 30, 31, 32, 40, 41, 42, 44, 45, 50, 52, 53,
] {
assert!(ids.contains(&id), "no KAT for {id}");
}
}
}

View File

@ -0,0 +1,29 @@
[package]
name = "ccc-crypto-boring"
version.workspace = true
edition.workspace = true
authors.workspace = true
license.workspace = true
description = "BoringSSL provider for the CCC crypto system, via Cloudflare's boring crate. Licences: boring Apache-2.0, boring-sys MIT, BoringSSL Apache-2.0."
[dependencies]
ccc-crypto-core.workspace = true
zeroize.workspace = true
log.workspace = true
# Pinned exactly: a BoringSSL bump changes the native code we vouch for.
# `mlkem` exposes BoringSSL's ML-KEM-768/1024 (FIPS 203).
boring = { version = "=5.5.0", features = ["mlkem"] }
[features]
default = []
# Build BoringCrypto in FIPS mode (boring/fips) from the vendored source: the
# update stream of a validated module, not a certified build, so fips_mode()
# stays false. Linux and Android only.
fips = ["boring/fips"]
# The builder attests that BORING_BSSL_FIPS_PATH points at a validated
# BoringCrypto build; only then does fips_mode() report true. build.rs
# refuses this feature without that variable.
fips-validated = ["fips"]
[dev-dependencies]
hex = "0.4"

View File

@ -0,0 +1,12 @@
//! Refuses `fips-validated` unless the build links a prebuilt validated
//! BoringCrypto (`BORING_BSSL_FIPS_PATH`), so the provider never reports FIPS
//! mode for a module built from source.
fn main() {
println!("cargo:rerun-if-env-changed=BORING_BSSL_FIPS_PATH");
if std::env::var_os("CARGO_FEATURE_FIPS_VALIDATED").is_some()
&& std::env::var_os("BORING_BSSL_FIPS_PATH").is_none_or(|p| p.is_empty())
{
panic!("feature fips-validated needs BORING_BSSL_FIPS_PATH set to a validated BoringCrypto build");
}
}

View File

@ -0,0 +1,2 @@
4b94c29450111191823b3514c9ac1ea3d9825ccb86393a2dfb04654fa2192d37bfad1c497c6502eee5ca80a73bfce0baf5a54a88585a401397a3d232f426a7afb082bc21a44317090eaac7592c2ea88a653c4491ea193931335f52e989a3c4cc56d9c553732d57c470fb41ab759b65d2d04445382fcd9c4e344a1128fa9e11e04358e192ed014b23232a7ee2b22e23717f44111ee33575399c37646da9813ec9b212afe94e5dc5c2330a7294cc1f4234a6d3fbb4f1685ab8892c04acb17cd1c170d7b0611b6a7176c794cc8c67f55fc923c2ad203100f365991882c30243d77813843b5ec7c964032263706092ecf00c7516be64e4598ca4226c069bb5e67e4175cf2286c8dd5c488a6c5861f31baa0bd0269470e8b551dd3bcd38c86c12f9cdb176c77dc8b6c02a701f478902c8553f694c0d82727b4c4a5c2c1041212aa1274808b82111b377ec75214e9b1978f76004d4139d98613f4b8e98d20af7b534073a509a959b7a7564f9b40ca218bf61829320a8502017954d328d7ac6c769ec29700756e7b0685b340d5e118059504a49a9a50a10198eb10a5784678eb427d7b4babb9552933b062897973e1318eaf0a0eac37584a65401b1703e042accd837531483f241cadcd1c1d378119e694429db199ac891e4c5343757085bb3ae783667350c4458d97672e861e80b1d2679510ea3a6f2360c77a46942c7a06a554d228080c84b47aef14db17620cb16c06ab30a1be4cda7082be9f87e9c211c46916349a5ba8eaa5201c7294a3c0885b53b657452108825ec646c90a04612324ee7d031afe5343132cbef67b6efb1a5ec2809b773538ce77b3d8b04eb0b3c2256011e4c716c19a8ba0752bf71492117649f0615c3290fc29a46fde4bd52db9286d603388244259c15a7ac2b640a60cc03376a5841a3fb8a473568fa9b1a267215f34c01697b0f0e627175d72105b7707c29b9e614bdc33a6f6c818a95370b427882d7b476796a9ec6eb993274cd9b2391a82ba45e3393d2e9ae9721ca9d6c1b988b5827713f90a6585de9433528c02b03ce10bb5f720138d0fbb4c30c1266b918e52925dfe17b37f95d22bca54f475919ac859098c0f0d08ac5875ef29b56fd141e6ef15f700a0b66f39595c588177373c4669b21bc071e4c3aa5f0b4a31b6258f35da24ac3cd29c7f2092410c5078355b138fb53a6b9ae6e0b9c08243e7baa45c47376eb8c7f13d4cf51aa736fa31540c9241f370da544bf9f9c28d9a57e2f2a7ca95a4e4b466e641ab3bcc76adf1139d567a6f12b52f3a65e7ec0aae26bcaa8c55833b04e59998ebc9a1930fbb6d2233c53d2c1f8b9518e3c2de73a19dee6b380a5b32971cf64e129fd6c1fa6e75d4a234501e966dd3a540af5c8f4f34a6b4a253ee28492566d5e67c6f55855fcb0506fb06c156744d9a03a31a26fa94cad14f157b7f303d07a69c773768fcb4d079c09059703a0c3a94de4b99ea3a2f16583d0f9170a3950db07b4f0bc30802927f9f7961b6259892636a9502a2705303637799dd344da451c1cf7bf67840ceb3079ab8c6b8c1927f64053c612450c45c9e603bc16666e596b3471e103b6f15447424d17022048111ffbd37e1c670f64f14b8a7b32b94c1a49b45dd2fc38cd5289d910ad63602cf5e13042c64ac6797b89fb551ad08e05a92d200cccb7e712ef23c9312cb350f029ab537e287347fd3075ac10906a783f1c6c07ccb88f41228c4be1c640f790b5c3a5d5d3ca792495d74bc461562658c07ac600276b924ab5bc9be1f0494cb76f82f460a7480972663381e169996061d799859ec54d4f5ca5c411c01db1597b165977669de13a928a34afbac258fea8c4764239c9421dc3119bf5b47699206978327b1c5345ef746a7983841f056e2534100ab24d4e9abbd0b17c6a95bd4c3c0e40f69e1612aceeb28b99086c95116e7204273893390bf46b899b36286b0ebf1947bb9884f732ca27da82b19b5dc0cc7f8885714910888b2310c4f9319d410b34e6433b9003e2176bb995257456106e8952163b8ba592530cc5aa0aeb43ad398fe9e97baa523d7a4431677c3d3af0719e475db85ca95af5089beabeb05b2faab4896ba60f81c88472a57b46a828826a0cdfb446f8189182d2bf5eac4ec1cc5deaf599c8a13e48235406d17ffddc8344b6c66984a868aa92fa02227a086950eb0c8701ed58dc628776b983882e1175
5e924d02507a1bf7b54a687b3ca7ec8f56a764b82ed7375ef5431c28ba3a7d86e8093b7d92162c6f0cbaae7e3757a1e4441867520537a64a12c68499104ca16a6fb251e8551a238172e761c64fc38968da3f027336339030277d2fd976f26aaf77eb46d8ec743ee79c7fa8f77e7b5f4648d95e56afc87eeadecf274df0c15d8e6e18822617a17db23ff09f86788c106379e6b1745e92fffdeaf794f6ee541e8dc2462a38903bd6bfb801ed57050b21482620401645ac5a18c152c503ac3e983a66650fa114cd40ad15de1acf1a3f66b2856ca62e23b82ed1f88b59a53973208b87c3f0dc67ba8809b0ccd005301ade5764d6b072357bdb5793c258c9ee5d57e314dce17dd44e95322822fad18c15d35d2fb78d390d7a2e744f0766efd94ca497056a3a93489d3120fd3d12e1438530a4163ebd5291bb70de703572f76758c42511f163c65dbdffe417683cfe93caec7c234644dba2b427eabc87796e76895ff0d282e8f7c36cd7f271c8a78186e6705527c53827ea73109fd48fb26c123297e479894da2b85abf4bcf4719e71479d1a1acc1821a917f3c610f6c197c49dff6b4537152fd6b1381f7ee28c6e5afb121002d00b4b921746c782f4b5e8152c0f48da91a3a0719b29b45e1e52e2d576de908bec674416987a8903c8dba43c6934915106a93fff3abf6c1c7954843922ae4bae3c33b20b65772c75d50c07d05dc102647da5c09700069c46fe2bb052f1d39a05f03521420f5849cec8cd5bf47b10512cda0b06c6829813dbd7c9c26ef41e8457026469e25d39b4da29e4283d3e513e1856ebe9dee313096c04d663794f55733d6a9eff0f6b44a328373207679b83438fa58e618380dc2b5b6846265270354c213e13ba0e186020e3158d8fb4c5fdbdf6cbeace7c1ca8114b07cf1fe8baa311f714e2965364824acb25b968b1835fe38b3ba226dc8f481e1b281ae169d8f43a186e5815636d517987207a25f6b6339f192535353946f32f56fd258b9bf216505767046e7f3188c10c32443181257985c4d451f30aeaba842e7034e1a6c3b7c3f15df8211f363b4b9e2b6e2f5ea9881771d4058aa3dad1f2dc0bb93c9c0c3ff6f4a95e6d6be550e4c8d66dca1dff000d86a0e89fb740a22a61a7b3932d181b7c900887ea95ab24400b331b742a82ae26f59adcaea179968210796d2b944a0caf04c70404d2e07a77a99acb6db628d6c5db20cf339ac09b6a32e160dc9d6ed6b7f07fa860f0ba834c5a452fab0ea48928fb3bc920665edf196dadad42fd0ccebef67f305445fa2b9508e22ab3e49769ce628ca6f88d2bc30ee09b281923f6b7b5265c049617c17c18a2b29c452e4e4e43f16ce1e53f509da76415ec2edbd300b90f5e15d5f6859bd4c5b97f8bb24d90185ae48f932bc0df1e624a436b6ab7c60ff4ae43eb754d8593cf82a1804ebab2f95ef5be0bba935c3a27ce97c88369c59fb53081513c36d99edb7157395339b74a452cad749af343daa9049048169f5b11f6dbdaea088289ba0fed3831175fddfe0a64111542676c8ab84b67660e4ff96e50aa61b01ac8bb287a46e3e37895eaaedccbec672f4f97c36366b71d86a118516a5e1261f84b726866f71e0d5eca1b6889a749a7c9293e5bceaea116e329e6a0c61901f43f5119c667fdf14a0fad9d4a07b2b8462c0c8cb1a45d2399581b63b735394dadab94a2b0ef1595feb3d459a5c689835bfd2b7a5cf1ef2e36ebc5535d650e0ec663aed27f6e7573a341948b61a7f19ea4682c717a4b19d21aeb4b61c93e88fa9a9c27c5147a27fa8987a530c3ca3efac02c4aa7f11e34f529e2b47721003dbb9a53fdec45cbd2bd317bf41b56b6398b22cfb7939dee77f7999545b05f8c24f2e6374cf6e5a6dbeb7a4fb7a591244320e8e664a8a6aef41875fc883b983d9bd26231ae33e9ffbf20072a981e7ce05fe69edd5a37b2c6c4a0a6477b2a52f7f059d44aa69edd7aad1e6332f8e7aeaf95c4cf25cd0bbaf112476340c3454640b765debcbcf40e6cc3e0116895abb26f7f0f4f8ba0d134ce9060c051e55c25b3199e135c28b112fd5f7dc04f48dfcdd767547ff062027115b682989826427febe395c9c65c16ce3b703298896d29b6fabede47829f1ed91a0c4f6eb07d590b167f2ca1fd951ff387fdfcc9aa8db3c17990cf0422fe4a2f57efb8da539a3b0834835e5250e79affe96e53f63134b96d6

View File

@ -0,0 +1,2 @@
298aa10d423c8dda069d02bc59e6cdf03a096b8b3da4cab9b80ca4a14907672ccef1ec4faf234a0bc5b7e9d473f2b3133b3b26a1d175cb67a7805919699c02f76531b99c5f89180704bb4ca4535c5b8972679c660a07c5e514b87009c862eb8f5157695efb3fc40a9def6b81c1cc02a249ae4f094ad0d9bd3485c1c1c68080520a7c8c632032cee738154e5c5176c07da56024776a430fe76eacf665a3f7b832102215bc82f10939c8355704336a8fac1d81e4bb0485aa5d7c74d6b59bbe5c5e972a0d8bac411b55b5d5557cd680a1a8f71b4eb86bc48c9a0509731a54bd9d7290b27963e4372dc9b199cfdcac0b01acd28a62395112e4c43648d622c48c8234d01440e8cc376c927f23a5afc9ac0474c662274e424525c8552ece3b3fe26516de901bc7d515bde89558e626c95c80b93342f8010004f39e6c6c94871c5e344cab3966c835f9a96a59afd31c40286b38b1c1a78470bab947518934453ce86736a919f1f5a6d510a86f5454fc3980cb5c765bd2bd5f7b36b1410d6635c8ceb47c4dda0d76a28eac939c71c3024804866c71626658442163c2c22117e50acefce6378a985652302a4ef0c2ce0cc716b7796e2b6b2e3777dfa1ac3da259a31b5a9b530f8cb638a81a62ac301849abaf95a7301bda30068909bfdb7e67dbccbb38a5551a25b1a3a0f685748ad5753d8880f0016c627486166384c5571fe2365900364d038311e2d875db366686932b5ec602430a369e87a6ef5c338786657825bd4c057aceb923eb0935e6905e63b4ced7f80857a773dd64b150d26612ea9ac12052db2017bf1843ccb4b3281b690dc728adfa85c00281b8e3c09287335f856b4fc2892f69a2f57921ada01914c40988662d57769662a786351b9b66493dab79594d986de2100d65ba0ff4ea58b81538d24a4435a258fac25404aa7f41f658b1385065e158dcb60115732720f40459aaac15e406953a90ac52997d1ccd070060efc65db9e653354467fad56ec713c86e7540c423acf2669f52fa6f4ac6888d871ef3e847c029a8aafbb92e17b24aa079b1f419ba6175b442afb11909d4a56b70a0335b28739218aa7c9348e2c3c2f3eb3d15a41e6417c0dd94bfeb21419b311a7bb13a180bbe833218a9a6b17447cc85f225859587a73077049acbcfd44d0f025438e15d1538270d586e1bf83192a9459cf63c0e972f85297679831ecf121509851cb8340f6f107b0fa1a0efd1b36a8189bc085c4f5cb784e553f41b918f80397ce1956f785bee377ca9aa8be6998ada30c26b7c3d8c6b55254cc96203b20c42aee0ac4e1ebb408e49a9e3f879d0ab0785eb7025425d1305a2299c015e120d163b0e19494ce57253d0246d182745cb8197ab7438b3c1bb7972bec5a306eba3567855c014699fef65ae54c770a0d85c18400cf642aedc660777ba4b138502bd5a7812f621f84a48296b98dd4322b6f15828b8a8f0e00a8ba44a53c3a8b143571b0740abd567daf1cde9c79c204b6d5e259d1766a31bbbcb4e6a05cf4502176b301c1c2f41247750157bcec85e809b30a4d60d7747cdd0f5b99aa8c826987517793aaa8080a0b124a8558df72bbe37b75f4edbb6be8216d6c633fb2b2280e25113d8695e43481c3eeb397eb192505229b67a201ea893c3e2cb32da8bc342fa4dea0578
db23415b8bac62fe0ae978ea80c9451eef09a2ab787964411a41820b032307fdeb30d5ff06752c376e4be14643617a294769571b066ef5998b2846ccfbdc56a2d589d9e091c76f1cb38b9f9e639f57a5b56592d5b1f79fe29429d424637c720afa967bf852145741e85721a6f0d34093732c3a3fc2907bf17752fb47b154e22ae15a593e726ce1f0a340f8b822ced00ae7bbd926b01dfb89b4e961d4d593d61a5434469bc0bd5eacbaaf2a4d2da2927b9419cd08572fe9822fe2abf1294fc9933365fac74613b0e3dc73dbdc2ac00ec79c16c3dad76852a9fad46edb855daec954be54e0b560a6e0c59296f2b4ab1fe48ea3415872653e51ab516cefb5a31bf3e52eb93b9c5d8694fa4890bcdbd4d3806b1321250c5910b51123dd47974d9f1b52b64e86458b09e1d50613d9f6b4f38865ea6bb4cc68946c7284137965b8aef0242c3b8b18a390189a0c029659e23ef954419f34e94eab7aa0da6d44b12f2bcb06a8a5435f4e03dc49c4134075c6186e6365a6e7e8a26df55cda09e3a09fbd4d8e99dd87eb5b05cdb18b914ae910963869ffc5bc0d1481f6bd46e8ce9e8e94b5e46b1754a65dfdc30ffd0cdc074cc13ba91b5a124bbe2dfa09be6854b657fc38e01a3b1dee8938c805d42b800e513b5aed6f15fa880f9b6851c40e312f55efebcf12f0ba6fb33f30e8673877a4b1a7c6c9d1a98278ee1ea2c6f0e1b8dc44540b94c70948d473c3a37ebe04873c10295ea591db7ab860ee5dcdd3238149d7fb96a069542b9db377e773f4453a18362a1ef7e3b0ea3512a7d45551e9cbed9f66eb4bfe695070b88d0773e1ac03d788bb81e841d9edaae75b153eb2041ed0eeba19400118ef306fa123e6f7b195fb281f4136db4a51f7bfa463ac033b9e14d561bc947b8a9d35287233916e7e215c8d2dc6c9ba5f3c5ee8521dcffee1be481319526b3a007a4011a00d4112abd99461d1c5578d1e831b3d4423cf81dea159755defe3d7b339ea432a7cbd8ca903bcc2ad9d41930306b7434b2740ac389df216e90aa5b3a97559ce1aba173942bd95a78de3a7fdc796bf0721a3783e5596f3aa78ce8134629e3df9ce542cb3fac484c7a8a40dc84109aeb5c7cc0e50f9f5b3e968250451babf87bc582cc802aed90dfd4961d1b02af19dfbc4df934dc32bad12679c42e036c3f84ceb961cd0a83cde116864e16b467afcb6c94a3ca70f7f06b29a063597af146601b8633256e1689a3e52673d4c66fb422543c410779627f18d1ee74f46c4f1e1387e272d81da19eba4f2cfc2520c84d2d79a41ea9dbdb93e7b45cd3f41096e279118f327a08896d9edeaf41b21f9043866c76a81fc9c0841daf0db0b40380cc07f3151ad63f3870ee84b5af1d62cd4121e6a493d2443555e5fd84f2af9d0306c03526f0378756a4b39b7ae2e65834d1d39cf1c3195ef1b0d5499911ad1cd912d60c3cd5f43ff59871aee494215a58b4e5be586c522461595adff7b0c6887debc6212aebab7ce8db45091975db1a624c108252c1c84e14d24d6383c

View File

@ -0,0 +1,223 @@
//! AEADs from BoringSSL's `EVP_AEAD` interface.
//!
//! Wire format matches the other providers: `ciphertext || 16-byte tag`.
//!
//! | Algorithm | BoringSSL |
//! |--------------------|---------------------------------|
//! | AES-256-GCM | `EVP_aead_aes_256_gcm` |
//! | ChaCha20-Poly1305 | `EVP_aead_chacha20_poly1305` |
//! | XChaCha20-Poly1305 | `EVP_aead_xchacha20_poly1305` |
//!
//! BoringSSL has AES-256-GCM-SIV, but `boring` exposes it only through a raw
//! pointer (`unsafe`), so ID 16 is not offered. Ascon is not in BoringSSL.
//! Those IDs return [`CryptoError::FeatureNotCompiled`].
//!
//! The key schedule lives in the `EVP_AEAD_CTX`, which BoringSSL wipes when
//! it is freed (`OPENSSL_free` cleanses).
use boring::aead::{AeadCtx, Algorithm};
use zeroize::Zeroize;
use ccc_crypto_core::{algorithms::AeadAlgorithm, error::CryptoError};
const TAG_LEN: usize = 16;
fn algorithm(algo: AeadAlgorithm) -> Result<Algorithm, CryptoError> {
match algo {
AeadAlgorithm::AesGcm256 => Ok(Algorithm::aes_256_gcm()),
AeadAlgorithm::ChaCha20Poly1305 => Ok(Algorithm::chacha20_poly1305()),
AeadAlgorithm::XChaCha20Poly1305 => Ok(Algorithm::xchacha20_poly1305()),
AeadAlgorithm::AesGcmSiv256 | AeadAlgorithm::Ascon128a | AeadAlgorithm::AsconAead128 => {
Err(CryptoError::FeatureNotCompiled(format!(
"{} is not offered by the boring provider",
algo.name()
)))
}
}
}
fn context(algo: AeadAlgorithm, key: &[u8], nonce: &[u8]) -> Result<AeadCtx, CryptoError> {
let alg = algorithm(algo)?;
if key.len() != algo.key_len() {
return Err(CryptoError::InvalidKey(format!(
"{}: expected {}-byte key, got {}",
algo.name(),
algo.key_len(),
key.len()
)));
}
if nonce.len() != algo.nonce_len() {
return Err(CryptoError::InvalidNonce(format!(
"{}: expected {}-byte nonce, got {}",
algo.name(),
algo.nonce_len(),
nonce.len()
)));
}
AeadCtx::new(&alg, key, TAG_LEN)
.map_err(|e| CryptoError::InternalError(format!("{}: {e}", algo.name())))
}
/// Encrypt `plaintext`; returns `ciphertext || tag`.
pub fn encrypt(
algo: AeadAlgorithm,
key: &[u8],
nonce: &[u8],
plaintext: &[u8],
aad: &[u8],
) -> Result<Vec<u8>, CryptoError> {
let mut ctx = context(algo, key, nonce)?;
let mut out = Vec::with_capacity(plaintext.len() + TAG_LEN);
out.extend_from_slice(plaintext);
out.resize(plaintext.len() + TAG_LEN, 0);
let (body, tag) = out.split_at_mut(plaintext.len());
let written = match ctx.seal_in_place_mut(nonce, body, tag, aad) {
Ok(t) => t.len(),
Err(e) => {
// `out` may still hold the plaintext.
out.zeroize();
return Err(CryptoError::InvalidInput(format!(
"{}: seal failed: {e}",
algo.name()
)));
}
};
if written != TAG_LEN {
out.zeroize();
return Err(CryptoError::InternalError(format!(
"{}: unexpected {written}-byte tag",
algo.name()
)));
}
Ok(out)
}
/// Authenticate and decrypt `ciphertext || tag`.
///
/// Returns [`CryptoError::AuthenticationFailed`] if the tag does not verify;
/// no unauthenticated plaintext is returned or left in memory.
pub fn decrypt(
algo: AeadAlgorithm,
key: &[u8],
nonce: &[u8],
ciphertext_and_tag: &[u8],
aad: &[u8],
) -> Result<Vec<u8>, CryptoError> {
let mut ctx = context(algo, key, nonce)?;
if ciphertext_and_tag.len() < TAG_LEN {
return Err(CryptoError::InvalidInput(format!(
"{}: ciphertext too short (no room for tag)",
algo.name()
)));
}
let (ct, tag) = ciphertext_and_tag.split_at(ciphertext_and_tag.len() - TAG_LEN);
let mut buf = ct.to_vec();
// Key and nonce lengths were checked above, so a failure is the tag.
if ctx.open_in_place_mut(nonce, &mut buf, tag, aad).is_err() {
buf.zeroize();
return Err(CryptoError::AuthenticationFailed);
}
Ok(buf)
}
#[cfg(test)]
mod tests {
use super::*;
const OFFERED: [AeadAlgorithm; 3] = [
AeadAlgorithm::AesGcm256,
AeadAlgorithm::ChaCha20Poly1305,
AeadAlgorithm::XChaCha20Poly1305,
];
fn inputs(algo: AeadAlgorithm) -> (Vec<u8>, Vec<u8>) {
let key = (0..algo.key_len() as u8).collect();
let nonce = (0..algo.nonce_len() as u8).map(|b| b ^ 0x5a).collect();
(key, nonce)
}
#[test]
fn roundtrip_all_offered() {
for algo in OFFERED {
let (key, nonce) = inputs(algo);
for (pt, aad) in [
(&b"hello cascade"[..], &b"hdr"[..]),
(b"", b""),
(b"x", b""),
(b"", b"aad only"),
] {
let ct = encrypt(algo, &key, &nonce, pt, aad).unwrap();
assert_eq!(ct.len(), pt.len() + TAG_LEN, "{}", algo.name());
assert_eq!(decrypt(algo, &key, &nonce, &ct, aad).unwrap(), pt);
}
}
}
#[test]
fn tampering_is_rejected() {
for algo in OFFERED {
let (key, nonce) = inputs(algo);
let ct = encrypt(algo, &key, &nonce, b"payload", b"aad").unwrap();
for i in [0, ct.len() - 1] {
let mut bad = ct.clone();
bad[i] ^= 0x01;
assert!(matches!(
decrypt(algo, &key, &nonce, &bad, b"aad"),
Err(CryptoError::AuthenticationFailed)
));
}
assert!(matches!(
decrypt(algo, &key, &nonce, &ct, b"aaD"),
Err(CryptoError::AuthenticationFailed)
));
}
}
#[test]
fn bad_lengths_are_rejected() {
for algo in OFFERED {
let (key, nonce) = inputs(algo);
assert!(matches!(
encrypt(algo, &key[1..], &nonce, b"", b""),
Err(CryptoError::InvalidKey(_))
));
assert!(matches!(
encrypt(algo, &key, &nonce[1..], b"", b""),
Err(CryptoError::InvalidNonce(_))
));
assert!(matches!(
decrypt(algo, &key, &nonce, &[0u8; 15], b""),
Err(CryptoError::InvalidInput(_))
));
}
}
#[test]
fn missing_aeads_are_not_compiled() {
for algo in [
AeadAlgorithm::AesGcmSiv256,
AeadAlgorithm::Ascon128a,
AeadAlgorithm::AsconAead128,
] {
let (key, nonce) = inputs(algo);
assert!(matches!(
encrypt(algo, &key, &nonce, b"", b""),
Err(CryptoError::FeatureNotCompiled(_))
));
assert!(matches!(
decrypt(algo, &key, &nonce, &[0u8; 16], b""),
Err(CryptoError::FeatureNotCompiled(_))
));
}
}
#[test]
fn algorithms_are_not_interchangeable() {
let key = [7u8; 32];
let nonce = [9u8; 12];
let gcm = encrypt(AeadAlgorithm::AesGcm256, &key, &nonce, b"same", b"").unwrap();
let cha = encrypt(AeadAlgorithm::ChaCha20Poly1305, &key, &nonce, b"same", b"").unwrap();
assert_ne!(gcm, cha);
assert!(decrypt(AeadAlgorithm::ChaCha20Poly1305, &key, &nonce, &gcm, b"").is_err());
}
}

View File

@ -0,0 +1,270 @@
//! Live capability probes and the AEAD throughput benchmark.
//!
//! An algorithm is `available` only when a live probe succeeds **and** its
//! known-answer self-test passed, so a failing KAT removes the algorithm
//! (fail closed, D-28). Every other ID is listed as unavailable.
use std::time::Instant;
use ccc_crypto_core::{
algorithms::{AeadAlgorithm, HashAlgorithm, KdfAlgorithm, KemAlgorithm, MacAlgorithm},
capabilities::{AlgorithmCapability, ProviderCapabilities},
types::{AlgoBenchResult, BenchmarkReport, SelfTestReport},
};
use crate::{aead, hash, kdf, kem, mac, PROVIDER_NAME};
/// AEADs this provider implements, in benchmark order.
pub const AEADS: [AeadAlgorithm; 3] = [
AeadAlgorithm::AesGcm256,
AeadAlgorithm::ChaCha20Poly1305,
AeadAlgorithm::XChaCha20Poly1305,
];
/// KDFs this provider implements.
pub const KDFS: [KdfAlgorithm; 3] = [
KdfAlgorithm::Sha256,
KdfAlgorithm::Sha384,
KdfAlgorithm::Sha512,
];
/// MACs this provider implements.
pub const MACS: [MacAlgorithm; 3] = [
MacAlgorithm::HmacSha256,
MacAlgorithm::HmacSha384,
MacAlgorithm::HmacSha512,
];
/// Hashes this provider implements.
pub const HASHES: [HashAlgorithm; 3] = [
HashAlgorithm::Sha256,
HashAlgorithm::Sha384,
HashAlgorithm::Sha512,
];
/// KEMs this provider implements.
pub const KEMS: [KemAlgorithm; 3] = [
KemAlgorithm::X25519,
KemAlgorithm::MlKem768,
KemAlgorithm::MlKem1024,
];
const ALL_KDFS: [KdfAlgorithm; 6] = [
KdfAlgorithm::Sha256,
KdfAlgorithm::Sha384,
KdfAlgorithm::Sha512,
KdfAlgorithm::Blake2b512,
KdfAlgorithm::Argon2id,
KdfAlgorithm::Kmac256,
];
const ALL_MACS: [MacAlgorithm; 5] = [
MacAlgorithm::HmacSha256,
MacAlgorithm::HmacSha384,
MacAlgorithm::HmacSha512,
MacAlgorithm::Blake2bMac,
MacAlgorithm::Poly1305,
];
const ALL_HASHES: [HashAlgorithm; 6] = [
HashAlgorithm::Sha256,
HashAlgorithm::Sha384,
HashAlgorithm::Sha512,
HashAlgorithm::Blake2b512,
HashAlgorithm::Sha3_256,
HashAlgorithm::Sha3_512,
];
fn kat_passed(report: &SelfTestReport, id: u32) -> bool {
let mut results = report.results.iter().filter(|r| r.algo_id == id).peekable();
// An algorithm without a KAT is never marked available.
results.peek().is_some() && results.all(|r| r.passed)
}
fn cap(available: bool, deterministic_io: bool, efficiency_score: u8) -> AlgorithmCapability {
if !available {
return AlgorithmCapability::unavailable();
}
AlgorithmCapability {
available,
deterministic_io,
efficiency_score,
reliability_score: 100,
}
}
fn aead_probe(algo: AeadAlgorithm) -> bool {
let key = vec![0u8; algo.key_len()];
let nonce = vec![0u8; algo.nonce_len()];
aead::encrypt(algo, &key, &nonce, b"x", b"")
.and_then(|ct| aead::decrypt(algo, &key, &nonce, &ct, b""))
.is_ok_and(|pt| pt == b"x")
}
fn kem_probe(algo: KemAlgorithm) -> bool {
let Ok(kp) = kem::generate_keypair(algo) else {
return false;
};
let Ok(enc) = kem::encapsulate(algo, &kp.public_key) else {
return false;
};
kem::decapsulate(algo, &kp.private_key, &enc.ciphertext)
.is_ok_and(|ss| *ss == enc.shared_secret)
}
/// Build the capability matrix from live probes, the self-test report and
/// (optionally) benchmark scores.
pub fn probe_capabilities(
self_test: &SelfTestReport,
benchmarks: Option<&BenchmarkReport>,
) -> ProviderCapabilities {
let mut caps = ProviderCapabilities::empty(PROVIDER_NAME);
let score = |id: u32| {
benchmarks
.and_then(|b| b.results.iter().find(|r| r.algo_id == id))
.map(|r| r.efficiency_score)
.unwrap_or(0)
};
for algo in AeadAlgorithm::ALL {
let ok = AEADS.contains(&algo) && aead_probe(algo) && kat_passed(self_test, algo as u32);
caps = caps.with_aead(algo, cap(ok, true, score(algo as u32)));
}
for algo in ALL_KDFS {
let ok = KDFS.contains(&algo)
&& kdf::derive_key(algo, b"key", b"salt", b"info", 32).is_ok()
&& kat_passed(self_test, algo as u32);
caps = caps.with_kdf(algo, cap(ok, true, 80));
}
for algo in ALL_MACS {
let ok = MACS.contains(&algo)
&& mac::compute_mac(algo, &[0x42; 32], b"data").is_ok()
&& kat_passed(self_test, algo as u32);
caps = caps.with_mac(algo, cap(ok, true, 85));
}
for algo in ALL_HASHES {
let ok = HASHES.contains(&algo)
&& hash::hash(algo, b"probe").is_ok()
&& kat_passed(self_test, algo as u32);
caps = caps.with_hash(algo, cap(ok, true, 90));
}
for algo in KemAlgorithm::ALL {
let ok = KEMS.contains(&algo) && kem_probe(algo) && kat_passed(self_test, algo as u32);
// Key generation and encapsulation are randomised.
caps = caps.with_kem(algo, cap(ok, false, 80));
}
caps
}
/// The provider benchmark: 100 × 1 MiB per AEAD, as in the other providers.
pub fn run_benchmark() -> BenchmarkReport {
run_benchmark_with(1024 * 1024, 100)
}
/// Encrypt `iters` × `size` bytes per AEAD and score each relative to the
/// fastest (0–100).
pub fn run_benchmark_with(size: usize, iters: u32) -> BenchmarkReport {
let plaintext = vec![0xABu8; size];
let mut raw: Vec<(AeadAlgorithm, f64)> = Vec::new();
for algo in AEADS {
if !aead_probe(algo) {
continue;
}
let key = vec![0u8; algo.key_len()];
let nonce = vec![0u8; algo.nonce_len()];
let start = Instant::now();
for _ in 0..iters {
let _ = aead::encrypt(algo, &key, &nonce, &plaintext, b"");
}
let secs = start.elapsed().as_secs_f64().max(1e-9);
raw.push((
algo,
(size as f64 * iters as f64) / (1024.0 * 1024.0 * secs),
));
}
let max = raw.iter().map(|(_, t)| *t).fold(0.0, f64::max);
let results = raw
.into_iter()
.map(|(algo, throughput)| AlgoBenchResult {
algo_id: algo as u32,
algo_name: algo.name().into(),
throughput_mbps: throughput,
efficiency_score: if max > 0.0 {
((throughput / max) * 100.0).round() as u8
} else {
0
},
})
.collect();
BenchmarkReport {
provider_name: PROVIDER_NAME.into(),
results,
}
}
#[cfg(test)]
mod tests {
use super::*;
use ccc_crypto_core::types::AlgoTestResult;
#[test]
fn only_kat_backed_algorithms_are_available() {
let report = crate::self_test::run();
let caps = probe_capabilities(&report, None);
assert_eq!(caps.provider_name, "boring");
let has_kat = |id: u32| report.results.iter().any(|r| r.algo_id == id && r.passed);
for (algo, c) in &caps.aead {
assert_eq!(c.available, AEADS.contains(algo), "{}", algo.name());
assert!(!c.available || has_kat(*algo as u32));
}
for (algo, c) in &caps.kdf {
assert_eq!(c.available, KDFS.contains(algo), "{}", algo.name());
assert!(!c.available || has_kat(*algo as u32));
}
for (algo, c) in &caps.mac {
assert_eq!(c.available, MACS.contains(algo), "{}", algo.name());
assert!(!c.available || has_kat(*algo as u32));
}
for (algo, c) in &caps.hash {
assert_eq!(c.available, HASHES.contains(algo), "{}", algo.name());
assert!(!c.available || has_kat(*algo as u32));
}
for (algo, c) in &caps.kem {
assert_eq!(c.available, KEMS.contains(algo), "{}", algo.name());
assert!(!c.available || has_kat(*algo as u32));
}
// Every registry ID is listed, available or not.
assert_eq!(caps.aead.len(), AeadAlgorithm::ALL.len());
assert_eq!(caps.kdf.len(), ALL_KDFS.len());
assert_eq!(caps.mac.len(), ALL_MACS.len());
assert_eq!(caps.hash.len(), ALL_HASHES.len());
assert_eq!(caps.kem.len(), KemAlgorithm::ALL.len());
}
#[test]
fn failed_kat_makes_algorithm_unavailable() {
let mut report = crate::self_test::run();
report.results.push(AlgoTestResult {
algo_id: AeadAlgorithm::AesGcm256 as u32,
algo_name: "forced failure".into(),
passed: false,
error_message: Some("test".into()),
});
report
.results
.retain(|r| r.algo_id != KemAlgorithm::MlKem1024 as u32);
let caps = probe_capabilities(&report, None);
assert!(!caps.aead[&AeadAlgorithm::AesGcm256].available);
assert!(caps.aead[&AeadAlgorithm::ChaCha20Poly1305].available);
// A missing KAT counts as a failed one.
assert!(!caps.kem[&KemAlgorithm::MlKem1024].available);
assert!(caps.kem[&KemAlgorithm::MlKem768].available);
}
#[test]
fn small_benchmark_scores_every_aead() {
let report = run_benchmark_with(4096, 2);
assert_eq!(report.results.len(), AEADS.len());
assert!(report.results.iter().any(|r| r.efficiency_score == 100));
}
}

View File

@ -0,0 +1,58 @@
//! Hash functions: SHA-256, SHA-384 and SHA-512 from BoringSSL.
//!
//! BoringSSL has no SHA-3 or BLAKE2b, so those IDs return
//! [`CryptoError::FeatureNotCompiled`].
use boring::sha;
use ccc_crypto_core::{algorithms::HashAlgorithm, error::CryptoError};
/// Compute the digest of `data`.
pub fn hash(algo: HashAlgorithm, data: &[u8]) -> Result<Vec<u8>, CryptoError> {
match algo {
HashAlgorithm::Sha256 => Ok(sha::sha256(data).to_vec()),
HashAlgorithm::Sha384 => Ok(sha::sha384(data).to_vec()),
HashAlgorithm::Sha512 => Ok(sha::sha512(data).to_vec()),
HashAlgorithm::Blake2b512 | HashAlgorithm::Sha3_256 | HashAlgorithm::Sha3_512 => Err(
CryptoError::FeatureNotCompiled(format!("{} is not in BoringSSL", algo.name())),
),
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn digest_lengths_match_registry() {
for algo in [
HashAlgorithm::Sha256,
HashAlgorithm::Sha384,
HashAlgorithm::Sha512,
] {
assert_eq!(hash(algo, b"abc").unwrap().len(), algo.digest_len());
}
}
#[test]
fn sha256_abc() {
assert_eq!(
hex::encode(hash(HashAlgorithm::Sha256, b"abc").unwrap()),
"ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad"
);
}
#[test]
fn missing_hashes_are_not_compiled() {
for algo in [
HashAlgorithm::Blake2b512,
HashAlgorithm::Sha3_256,
HashAlgorithm::Sha3_512,
] {
assert!(matches!(
hash(algo, b""),
Err(CryptoError::FeatureNotCompiled(_))
));
}
}
}

View File

@ -0,0 +1,152 @@
//! KDFs: HKDF-SHA-256/384/512 (RFC 5869) from BoringSSL's `HKDF_extract`
//! and `HKDF_expand`.
//!
//! Semantics match the wolfSSL and RustCrypto providers byte for byte: an
//! empty salt is the all-zero salt of hash length (RFC 5869 §2.2), and the
//! output is capped at 255 × hash length. BoringSSL has no Argon2id,
//! BLAKE2b or KMAC, so those IDs return [`CryptoError::FeatureNotCompiled`].
//!
//! The PRK is wiped after Expand. `boring` returns it by value in a plain
//! stack buffer, so a copy may outlive this function on the stack until it
//! is overwritten; avoiding that would need `unsafe` FFI.
use boring::hash::MessageDigest;
use boring::hkdf::HkdfSuite;
use zeroize::{Zeroize, Zeroizing};
use ccc_crypto_core::{algorithms::KdfAlgorithm, error::CryptoError};
/// Derive `length` bytes from `ikm`.
pub fn derive_key(
algo: KdfAlgorithm,
ikm: &[u8],
salt: &[u8],
info: &[u8],
length: usize,
) -> Result<Zeroizing<Vec<u8>>, CryptoError> {
let md = match algo {
KdfAlgorithm::Sha256 => MessageDigest::sha256(),
KdfAlgorithm::Sha384 => MessageDigest::sha384(),
KdfAlgorithm::Sha512 => MessageDigest::sha512(),
KdfAlgorithm::Blake2b512 | KdfAlgorithm::Argon2id | KdfAlgorithm::Kmac256 => {
return Err(CryptoError::FeatureNotCompiled(format!(
"{} is not in BoringSSL",
algo.name()
)))
}
};
hkdf(md, ikm, salt, info, length)
}
fn hkdf(
md: MessageDigest,
ikm: &[u8],
salt: &[u8],
info: &[u8],
length: usize,
) -> Result<Zeroizing<Vec<u8>>, CryptoError> {
let suite = HkdfSuite::new(md);
let max_len = 255 * suite.prk_size();
if length > max_len {
return Err(CryptoError::InvalidInput(format!(
"HKDF: requested length {length} exceeds maximum {max_len}"
)));
}
let internal = |e: boring::error::ErrorStack| CryptoError::InternalError(format!("HKDF: {e}"));
// BoringSSL treats an empty salt as HashLen zero bytes, as RFC 5869 says.
let mut prk = suite.extract(salt, ikm).map_err(internal)?;
let mut okm = Zeroizing::new(vec![0u8; length]);
let res = suite.expand(&prk, info, &mut okm);
prk.zeroize();
res.map_err(internal)?;
Ok(okm)
}
#[cfg(test)]
mod tests {
use super::*;
fn h(s: &str) -> Vec<u8> {
hex::decode(s).unwrap()
}
fn tc1(algo: KdfAlgorithm) -> String {
let okm = derive_key(
algo,
&h("0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b"),
&h("000102030405060708090a0b0c"),
&h("f0f1f2f3f4f5f6f7f8f9"),
42,
)
.unwrap();
hex::encode(&*okm)
}
#[test]
fn hkdf_rfc5869_tc1_inputs() {
assert_eq!(
tc1(KdfAlgorithm::Sha256),
"3cb25f25faacd57a90434f64d0362f2a2d2d0a90cf1a5a4c5db02d56ecc4c5bf34007208d5b887185865"
);
// The SHA-512 value the wolfSSL HKDF-SHA-512 fix pinned.
assert_eq!(
tc1(KdfAlgorithm::Sha512),
"832390086cda71fb47625bb5ceb168e4c8e26a1a16ed34d9fc7fe92c1481579338da362cb8d9f925d7cb"
);
}
#[test]
fn hkdf_sha256_rfc5869_tc3_empty_salt_and_info() {
let okm = derive_key(
KdfAlgorithm::Sha256,
&h("0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b"),
b"",
b"",
42,
)
.unwrap();
assert_eq!(
hex::encode(&*okm),
"8da4e775a563c18f715f802a063c5a31b8a11f5c5ee1879ec3454e5f3c738d2d9d201395faa4b61a96c8"
);
}
#[test]
fn hkdf_empty_salt_is_zero_salt() {
for (algo, n) in [
(KdfAlgorithm::Sha256, 32),
(KdfAlgorithm::Sha384, 48),
(KdfAlgorithm::Sha512, 64),
] {
let a = derive_key(algo, b"ikm", b"", b"info", 32).unwrap();
let b = derive_key(algo, b"ikm", &vec![0u8; n], b"info", 32).unwrap();
assert_eq!(*a, *b);
}
}
#[test]
fn hkdf_length_limits() {
assert!(derive_key(KdfAlgorithm::Sha256, b"k", b"", b"", 0)
.unwrap()
.is_empty());
assert!(derive_key(KdfAlgorithm::Sha512, b"k", b"", b"", 255 * 64).is_ok());
assert!(matches!(
derive_key(KdfAlgorithm::Sha256, b"k", b"", b"", 255 * 32 + 1),
Err(CryptoError::InvalidInput(_))
));
}
#[test]
fn missing_kdfs_are_not_compiled() {
for algo in [
KdfAlgorithm::Blake2b512,
KdfAlgorithm::Argon2id,
KdfAlgorithm::Kmac256,
] {
assert!(matches!(
derive_key(algo, b"k", b"saltsalt", b"", 32),
Err(CryptoError::FeatureNotCompiled(_))
));
}
}
}

View File

@ -0,0 +1,329 @@
//! KEMs: X25519 (`EVP_PKEY_X25519`) and ML-KEM-768/1024 (FIPS 203) from
//! BoringSSL.
//!
//! Key and ciphertext formats match the wolfSSL and RustCrypto providers:
//!
//! | Algorithm | Private key | Public key | Ciphertext | Secret |
//! |-------------|------------------------|------------|-----------------------|--------|
//! | X25519 | 32-byte scalar (LE) | 32 | 32 (ephemeral public) | 32 |
//! | ML-KEM-768 | 64-byte seed `d \|\| z` | 1184 | 1088 | 32 |
//! | ML-KEM-1024 | 64-byte seed `d \|\| z` | 1568 | 1568 | 32 |
//!
//! X25519 follows the providers' KEM convention: encapsulation makes an
//! ephemeral key pair, the ciphertext is its public key and the secret is
//! the raw RFC 7748 shared value. BoringSSL rejects an all-zero shared value
//! (a low-order peer point). `boring` has no raw X25519 key import, so keys
//! go in through their fixed RFC 8410 DER wrappers (PKCS#8 and SPKI).
//!
//! X448, X-Wing, Classic McEliece, HQC and FrodoKEM are not in the `boring`
//! API and return [`CryptoError::FeatureNotCompiled`].
use boring::derive::Deriver;
use boring::mlkem::{self, MlKemPrivateKey, MlKemPublicKey};
use boring::pkey::{Id, PKey, Private, Public};
use zeroize::Zeroizing;
use ccc_crypto_core::{
algorithms::KemAlgorithm,
error::CryptoError,
types::{KemEncapResult, KemKeyPair},
};
/// Generate a key pair.
pub fn generate_keypair(algo: KemAlgorithm) -> Result<KemKeyPair, CryptoError> {
match algo {
KemAlgorithm::X25519 => {
let sk = PKey::generate(Id::X25519).map_err(internal("X25519 keygen"))?;
Ok(KemKeyPair {
public_key: x25519_raw_public(&sk)?,
private_key: x25519_raw_private(&sk)?.to_vec(),
})
}
KemAlgorithm::MlKem768 | KemAlgorithm::MlKem1024 => {
let (pk, sk) =
MlKemPrivateKey::generate(mlkem_alg(algo)?).map_err(internal(algo.name()))?;
Ok(KemKeyPair {
public_key: pk.as_bytes().to_vec(),
private_key: sk.seed_bytes().to_vec(),
})
}
_ => not_compiled(algo),
}
}
/// Encapsulate a fresh shared secret to `public_key`.
pub fn encapsulate(algo: KemAlgorithm, public_key: &[u8]) -> Result<KemEncapResult, CryptoError> {
match algo {
KemAlgorithm::X25519 => {
let peer = x25519_public(public_key)?;
let eph = PKey::generate(Id::X25519).map_err(internal("X25519 keygen"))?;
let ss = x25519_derive(&eph, &peer)?;
Ok(KemEncapResult {
ciphertext: x25519_raw_public(&eph)?,
shared_secret: ss.to_vec(),
})
}
KemAlgorithm::MlKem768 | KemAlgorithm::MlKem1024 => {
let pk = MlKemPublicKey::from_slice(mlkem_alg(algo)?, public_key).map_err(|_| {
CryptoError::InvalidKey(format!("{}: invalid public key", algo.name()))
})?;
let (ct, ss) = pk.encapsulate().map_err(internal(algo.name()))?;
let ss = Zeroizing::new(ss);
Ok(KemEncapResult {
ciphertext: ct,
shared_secret: ss.to_vec(),
})
}
_ => not_compiled(algo),
}
}
/// Recover the shared secret from `ciphertext` with `private_key`.
pub fn decapsulate(
algo: KemAlgorithm,
private_key: &[u8],
ciphertext: &[u8],
) -> Result<Zeroizing<Vec<u8>>, CryptoError> {
match algo {
KemAlgorithm::X25519 => {
let sk = x25519_private(private_key)?;
let peer = x25519_public(ciphertext)?;
x25519_derive(&sk, &peer)
}
KemAlgorithm::MlKem768 | KemAlgorithm::MlKem1024 => {
let alg = mlkem_alg(algo)?;
let seed: Zeroizing<mlkem::MlKemPrivateKeySeed> =
Zeroizing::new(private_key.try_into().map_err(|_| {
CryptoError::InvalidKey(format!(
"{}: private key must be a {}-byte seed",
algo.name(),
mlkem::PRIVATE_KEY_SEED_BYTES
))
})?);
if ciphertext.len() != alg.ciphertext_bytes() {
return Err(CryptoError::InvalidInput(format!(
"{}: wrong ciphertext length",
algo.name()
)));
}
// The private key wipes its seed and expanded form on drop.
let sk = MlKemPrivateKey::from_seed(alg, &seed).map_err(internal(algo.name()))?;
let ss = Zeroizing::new(sk.decapsulate(ciphertext).map_err(internal(algo.name()))?);
Ok(Zeroizing::new(ss.to_vec()))
}
_ => not_compiled(algo),
}
}
fn not_compiled<T>(algo: KemAlgorithm) -> Result<T, CryptoError> {
Err(CryptoError::FeatureNotCompiled(format!(
"{} is not offered by the boring provider",
algo.name()
)))
}
fn internal(what: &str) -> impl Fn(boring::error::ErrorStack) -> CryptoError + '_ {
move |e| CryptoError::InternalError(format!("{what}: {e}"))
}
fn mlkem_alg(algo: KemAlgorithm) -> Result<mlkem::Algorithm, CryptoError> {
match algo {
KemAlgorithm::MlKem768 => Ok(mlkem::Algorithm::MlKem768),
KemAlgorithm::MlKem1024 => Ok(mlkem::Algorithm::MlKem1024),
_ => not_compiled(algo),
}
}
// ── X25519 ───────────────────────────────────────────────────────────────────
/// RFC 8410 PKCS#8 `OneAsymmetricKey` prefix for a 32-byte X25519 key.
const X25519_PKCS8_PREFIX: [u8; 16] = [
0x30, 0x2e, 0x02, 0x01, 0x00, 0x30, 0x05, 0x06, 0x03, 0x2b, 0x65, 0x6e, 0x04, 0x22, 0x04, 0x20,
];
/// RFC 8410 `SubjectPublicKeyInfo` prefix for a 32-byte X25519 key.
const X25519_SPKI_PREFIX: [u8; 12] = [
0x30, 0x2a, 0x30, 0x05, 0x06, 0x03, 0x2b, 0x65, 0x6e, 0x03, 0x21, 0x00,
];
fn x25519_private(raw: &[u8]) -> Result<PKey<Private>, CryptoError> {
if raw.len() != 32 {
return Err(CryptoError::InvalidKey(
"X25519: private key must be 32 bytes".into(),
));
}
let mut der = Zeroizing::new(Vec::with_capacity(48));
der.extend_from_slice(&X25519_PKCS8_PREFIX);
der.extend_from_slice(raw);
PKey::private_key_from_der(&der)
.map_err(|_| CryptoError::InvalidKey("X25519: invalid private key".into()))
}
fn x25519_public(raw: &[u8]) -> Result<PKey<Public>, CryptoError> {
if raw.len() != 32 {
return Err(CryptoError::InvalidKey(
"X25519: public key must be 32 bytes".into(),
));
}
let mut der = Vec::with_capacity(44);
der.extend_from_slice(&X25519_SPKI_PREFIX);
der.extend_from_slice(raw);
PKey::public_key_from_der(&der)
.map_err(|_| CryptoError::InvalidKey("X25519: invalid public key".into()))
}
fn x25519_raw_public(key: &PKey<Private>) -> Result<Vec<u8>, CryptoError> {
let mut buf = [0u8; 32];
let pk = key
.raw_public_key(&mut buf)
.map_err(internal("X25519 public key"))?;
Ok(pk.to_vec())
}
fn x25519_raw_private(key: &PKey<Private>) -> Result<Zeroizing<[u8; 32]>, CryptoError> {
let mut buf = Zeroizing::new([0u8; 32]);
let len = key
.raw_private_key(&mut buf[..])
.map_err(internal("X25519 private key"))?
.len();
if len != 32 {
return Err(CryptoError::InternalError(
"X25519: unexpected private key length".into(),
));
}
Ok(buf)
}
fn x25519_derive(
sk: &PKey<Private>,
peer: &PKey<Public>,
) -> Result<Zeroizing<Vec<u8>>, CryptoError> {
let low_order =
|| CryptoError::InvalidKey("X25519: low-order public key (all-zero shared secret)".into());
let mut d = Deriver::new(sk).map_err(internal("X25519 derive"))?;
d.set_peer(peer).map_err(internal("X25519 derive"))?;
let mut ss = Zeroizing::new(vec![0u8; 32]);
// BoringSSL fails the derivation exactly when the result is all zero.
let len = d.derive(&mut ss).map_err(|_| low_order())?;
if len != 32 {
return Err(CryptoError::InternalError(
"X25519: unexpected shared secret length".into(),
));
}
Ok(ss)
}
#[cfg(test)]
mod tests {
use super::*;
const OFFERED: [KemAlgorithm; 3] = [
KemAlgorithm::X25519,
KemAlgorithm::MlKem768,
KemAlgorithm::MlKem1024,
];
fn h(s: &str) -> Vec<u8> {
hex::decode(s).unwrap()
}
#[test]
fn roundtrip_all_offered() {
for algo in OFFERED {
let kp = generate_keypair(algo).unwrap();
let enc = encapsulate(algo, &kp.public_key).unwrap();
let ss = decapsulate(algo, &kp.private_key, &enc.ciphertext).unwrap();
assert_eq!(*ss, enc.shared_secret, "{}", algo.name());
assert_eq!(ss.len(), 32);
}
}
#[test]
fn sizes() {
for (algo, sk, pk, ct) in [
(KemAlgorithm::X25519, 32, 32, 32),
(KemAlgorithm::MlKem768, 64, 1184, 1088),
(KemAlgorithm::MlKem1024, 64, 1568, 1568),
] {
let kp = generate_keypair(algo).unwrap();
assert_eq!(kp.private_key.len(), sk);
assert_eq!(kp.public_key.len(), pk);
assert_eq!(
encapsulate(algo, &kp.public_key).unwrap().ciphertext.len(),
ct
);
}
}
#[test]
fn x25519_rfc7748() {
let alice = h("77076d0a7318a57d3c16c17251b26645df4c2f87ebc0992ab177fba51db92c2a");
let alice_pub = "8520f0098930a754748b7ddcb43ef75a0dbf3a0d26381af4eba4a98eaa9b4e6a";
let bob = h("5dab087e624a8a4b79e17f8b83800ee66f3bb1292618b6fd1c2f8b27ff88e0eb");
let bob_pub = h("de9edb7d7b7dc1b4d35b61c2ece435373f8343c85b78674dadfc7e146f882b4f");
let shared = "4a5d9d5ba4ce2de1728e3bf480350f25e07e21c947d19e3376f09b3c1e161742";
let ss = decapsulate(KemAlgorithm::X25519, &alice, &bob_pub).unwrap();
assert_eq!(hex::encode(&*ss), shared);
let ss = decapsulate(KemAlgorithm::X25519, &bob, &h(alice_pub)).unwrap();
assert_eq!(hex::encode(&*ss), shared);
let sk = x25519_private(&alice).unwrap();
assert_eq!(hex::encode(x25519_raw_public(&sk).unwrap()), alice_pub);
assert_eq!(*x25519_raw_private(&sk).unwrap(), alice[..]);
}
#[test]
fn x25519_low_order_point_rejected() {
let sk = [0x11u8; 32];
assert!(matches!(
decapsulate(KemAlgorithm::X25519, &sk, &[0u8; 32]),
Err(CryptoError::InvalidKey(_))
));
}
#[test]
fn wrong_lengths_rejected() {
for algo in OFFERED {
let kp = generate_keypair(algo).unwrap();
let enc = encapsulate(algo, &kp.public_key).unwrap();
assert!(encapsulate(algo, &kp.public_key[1..]).is_err());
assert!(decapsulate(algo, &kp.private_key[1..], &enc.ciphertext).is_err());
assert!(decapsulate(algo, &kp.private_key, &enc.ciphertext[1..]).is_err());
}
}
#[test]
fn mlkem_implicit_rejection() {
for algo in [KemAlgorithm::MlKem768, KemAlgorithm::MlKem1024] {
let kp = generate_keypair(algo).unwrap();
let enc = encapsulate(algo, &kp.public_key).unwrap();
let mut ct = enc.ciphertext.clone();
ct[0] ^= 1;
let ss = decapsulate(algo, &kp.private_key, &ct).unwrap();
assert_ne!(*ss, enc.shared_secret);
}
}
#[test]
fn unsupported_kems() {
for algo in [
KemAlgorithm::X448,
KemAlgorithm::XWing,
KemAlgorithm::ClassicMcEliece460896,
KemAlgorithm::ClassicMcEliece460896f,
KemAlgorithm::Hqc192,
KemAlgorithm::FrodoKem976Shake,
] {
assert!(matches!(
generate_keypair(algo),
Err(CryptoError::FeatureNotCompiled(_))
));
assert!(matches!(
encapsulate(algo, &[0u8; 32]),
Err(CryptoError::FeatureNotCompiled(_))
));
assert!(matches!(
decapsulate(algo, &[0u8; 32], &[0u8; 32]),
Err(CryptoError::FeatureNotCompiled(_))
));
}
}
}

View File

@ -0,0 +1,48 @@
//! # ccc-crypto-boring
//!
//! BoringSSL implementation of the CCC provider traits, through Cloudflare's
//! [`boring`] crate. It adds a native library family next to wolfSSL and
//! RustCrypto (design: "Provider diversity").
//!
//! With the `fips` feature, `boring-sys` builds BoringCrypto in FIPS mode.
//! The vendored source is the update stream of a validated module, not a
//! certified build, so `fips_mode()` stays `false`. A certified build links
//! a prebuilt validated module through `BORING_BSSL_FIPS_PATH`; the
//! `fips-validated` feature attests that and is the only way `fips_mode()`
//! reports `true`. BoringSSL's FIPS build needs ELF objects, so it works on
//! Linux and Android only, not on macOS or iOS.
//!
//! Licences: `boring` is Apache-2.0 and `boring-sys` is MIT. The vendored
//! BoringSSL (libcrypto) is Apache-2.0 throughout, including the files that
//! came from OpenSSL; only its Go test harness, which is not linked, is under
//! the Go licence.
//!
//! The crate does not depend on the AWS-LC provider, but AWS-LC is a
//! BoringSSL fork: they share code and assembly, so both report the lineage
//! `"boringssl"` and count as one library for diversity rules.
//!
//! Call [`init()`] once at start-up to register it in the global
//! [`ProviderRegistry`][ccc_crypto_core::registry::ProviderRegistry].
#![forbid(unsafe_code)]
pub mod aead;
pub mod capabilities;
pub mod hash;
pub mod kdf;
pub mod kem;
pub mod mac;
pub mod provider;
pub mod self_test;
pub use provider::BoringProvider;
/// The provider's registry name.
pub const PROVIDER_NAME: &str = "boring";
/// Register a [`BoringProvider`] in the global registry.
pub fn init() {
ccc_crypto_core::ProviderRegistry::global()
.register(PROVIDER_NAME, Box::new(BoringProvider::new()));
log::info!("[ccc-crypto-boring] provider registered");
}

View File

@ -0,0 +1,119 @@
//! MACs: HMAC-SHA-256/384/512 from BoringSSL's `HMAC_CTX`.
//!
//! Verification compares in constant time with `CRYPTO_memcmp`
//! ([`boring::memcmp::eq`]). BoringSSL's Poly1305 and BLAKE2b are not in the
//! safe `boring` API, so those IDs return [`CryptoError::FeatureNotCompiled`].
use boring::hash::MessageDigest;
use boring::hmac::Hmac;
use ccc_crypto_core::{algorithms::MacAlgorithm, error::CryptoError};
/// Compute a MAC tag over `data`. Any key length is accepted (RFC 2104).
pub fn compute_mac(algo: MacAlgorithm, key: &[u8], data: &[u8]) -> Result<Vec<u8>, CryptoError> {
let md = digest(algo)?;
hmac(&md, key, data)
}
/// Verify a MAC tag in constant time. A mismatch is `Ok(false)`.
pub fn verify_mac(
algo: MacAlgorithm,
key: &[u8],
data: &[u8],
mac: &[u8],
) -> Result<bool, CryptoError> {
let expected = zeroize::Zeroizing::new(compute_mac(algo, key, data)?);
// `memcmp::eq` panics on unequal lengths; the length is public.
Ok(expected.len() == mac.len() && boring::memcmp::eq(&expected, mac))
}
fn digest(algo: MacAlgorithm) -> Result<MessageDigest, CryptoError> {
match algo {
MacAlgorithm::HmacSha256 => Ok(MessageDigest::sha256()),
MacAlgorithm::HmacSha384 => Ok(MessageDigest::sha384()),
MacAlgorithm::HmacSha512 => Ok(MessageDigest::sha512()),
MacAlgorithm::Blake2bMac | MacAlgorithm::Poly1305 => Err(CryptoError::FeatureNotCompiled(
format!("{} is not in the boring API", algo.name()),
)),
}
}
/// HMAC with `md`. BoringSSL wipes the key schedule when the context is
/// freed (`HMAC_CTX_cleanup`).
fn hmac(md: &MessageDigest, key: &[u8], data: &[u8]) -> Result<Vec<u8>, CryptoError> {
let internal = |e: boring::error::ErrorStack| CryptoError::InternalError(format!("HMAC: {e}"));
let mut m = Hmac::init(key, md).map_err(internal)?;
m.update(data).map_err(internal)?;
m.finalize().map_err(internal)
}
#[cfg(test)]
mod tests {
use super::*;
const OFFERED: [MacAlgorithm; 3] = [
MacAlgorithm::HmacSha256,
MacAlgorithm::HmacSha384,
MacAlgorithm::HmacSha512,
];
#[test]
fn tag_lengths_and_verify() {
let key = [0x42u8; 32];
for algo in OFFERED {
let tag = compute_mac(algo, &key, b"data").unwrap();
assert_eq!(tag.len(), algo.tag_len(), "{}", algo.name());
assert!(verify_mac(algo, &key, b"data", &tag).unwrap());
let mut bad = tag.clone();
bad[0] ^= 1;
assert!(!verify_mac(algo, &key, b"data", &bad).unwrap());
assert!(!verify_mac(algo, &key, b"data", &tag[1..]).unwrap());
assert!(!verify_mac(algo, &key, b"data", &[]).unwrap());
assert!(!verify_mac(algo, &key, b"Data", &tag).unwrap());
}
}
#[test]
fn hmac_sha256_rfc4231_tc2() {
let tag = compute_mac(
MacAlgorithm::HmacSha256,
b"Jefe",
b"what do ya want for nothing?",
)
.unwrap();
assert_eq!(
hex::encode(tag),
"5bdcc146bf60754e6a042426089575c75a003f089d2739839dec58b964ec3843"
);
}
#[test]
fn empty_and_long_keys() {
// RFC 4231 TC6: a 131-byte key is hashed first.
let tag = compute_mac(
MacAlgorithm::HmacSha256,
&[0xaa; 131],
b"Test Using Larger Than Block-Size Key - Hash Key First",
)
.unwrap();
assert_eq!(
hex::encode(tag),
"60e431591ee0b67f0d8a26aacbf5b77f8e0bc6213728c5140546040f0ee37f54"
);
assert!(compute_mac(MacAlgorithm::HmacSha512, b"", b"x").is_ok());
}
#[test]
fn missing_macs_are_not_compiled() {
for algo in [MacAlgorithm::Blake2bMac, MacAlgorithm::Poly1305] {
assert!(matches!(
compute_mac(algo, &[1u8; 32], b"x"),
Err(CryptoError::FeatureNotCompiled(_))
));
assert!(matches!(
verify_mac(algo, &[1u8; 32], b"x", &[0u8; 16]),
Err(CryptoError::FeatureNotCompiled(_))
));
}
}
}

View File

@ -0,0 +1,188 @@
//! [`BoringProvider`]: the [`CryptoProvider`] implementation.
use std::sync::OnceLock;
use zeroize::Zeroizing;
use ccc_crypto_core::{
algorithms::{AeadAlgorithm, HashAlgorithm, KdfAlgorithm, KemAlgorithm, MacAlgorithm},
capabilities::ProviderCapabilities,
error::CryptoError,
provider::{AeadProvider, CryptoProvider, HashProvider, KdfProvider, KemProvider, MacProvider},
types::{BenchmarkReport, KemEncapResult, KemKeyPair, SelfTestReport},
};
use crate::{aead, capabilities, hash, kdf, kem, mac, self_test, PROVIDER_NAME};
/// The BoringSSL provider. Self-test, benchmark and capabilities are
/// computed lazily on first use and cached.
#[derive(Default)]
pub struct BoringProvider {
caps: OnceLock<ProviderCapabilities>,
bench: OnceLock<BenchmarkReport>,
kats: OnceLock<SelfTestReport>,
}
impl BoringProvider {
/// Create a provider; no work is done until it is queried.
pub fn new() -> Self {
Self::default()
}
fn kats(&self) -> &SelfTestReport {
self.kats.get_or_init(self_test::run)
}
fn bench(&self) -> &BenchmarkReport {
self.bench.get_or_init(|| {
log::info!("[ccc-crypto-boring] running throughput benchmark…");
capabilities::run_benchmark()
})
}
}
impl AeadProvider for BoringProvider {
fn encrypt_aead(
&self,
algo: AeadAlgorithm,
key: &[u8],
nonce: &[u8],
plaintext: &[u8],
aad: &[u8],
) -> Result<Vec<u8>, CryptoError> {
aead::encrypt(algo, key, nonce, plaintext, aad)
}
fn decrypt_aead(
&self,
algo: AeadAlgorithm,
key: &[u8],
nonce: &[u8],
ciphertext_and_tag: &[u8],
aad: &[u8],
) -> Result<Vec<u8>, CryptoError> {
aead::decrypt(algo, key, nonce, ciphertext_and_tag, aad)
}
}
impl KdfProvider for BoringProvider {
fn derive_key(
&self,
algo: KdfAlgorithm,
ikm: &[u8],
salt: &[u8],
info: &[u8],
length: usize,
) -> Result<Zeroizing<Vec<u8>>, CryptoError> {
kdf::derive_key(algo, ikm, salt, info, length)
}
}
impl MacProvider for BoringProvider {
fn compute_mac(
&self,
algo: MacAlgorithm,
key: &[u8],
data: &[u8],
) -> Result<Vec<u8>, CryptoError> {
mac::compute_mac(algo, key, data)
}
fn verify_mac(
&self,
algo: MacAlgorithm,
key: &[u8],
data: &[u8],
mac_bytes: &[u8],
) -> Result<bool, CryptoError> {
mac::verify_mac(algo, key, data, mac_bytes)
}
}
impl HashProvider for BoringProvider {
fn hash(&self, algo: HashAlgorithm, data: &[u8]) -> Result<Vec<u8>, CryptoError> {
hash::hash(algo, data)
}
}
impl KemProvider for BoringProvider {
fn generate_keypair(&self, algo: KemAlgorithm) -> Result<KemKeyPair, CryptoError> {
kem::generate_keypair(algo)
}
fn encapsulate(
&self,
algo: KemAlgorithm,
public_key: &[u8],
) -> Result<KemEncapResult, CryptoError> {
kem::encapsulate(algo, public_key)
}
fn decapsulate(
&self,
algo: KemAlgorithm,
private_key: &[u8],
ciphertext: &[u8],
) -> Result<Zeroizing<Vec<u8>>, CryptoError> {
kem::decapsulate(algo, private_key, ciphertext)
}
}
impl CryptoProvider for BoringProvider {
fn provider_name(&self) -> &'static str {
PROVIDER_NAME
}
fn lineage(&self) -> &'static str {
// AWS-LC is a fork of BoringSSL; they share code and assembly.
"boringssl"
}
/// `true` only for a `fips-validated` build (a prebuilt validated
/// BoringCrypto, see build.rs) whose module reports FIPS mode at run time.
/// A `fips` build from source is not a certified module, so it is false.
fn fips_mode(&self) -> bool {
cfg!(feature = "fips-validated") && boring::fips::enabled()
}
fn capabilities(&self) -> ProviderCapabilities {
self.caps
.get_or_init(|| capabilities::probe_capabilities(self.kats(), Some(self.bench())))
.clone()
}
fn self_test(&self) -> SelfTestReport {
self.kats().clone()
}
fn benchmark(&self) -> BenchmarkReport {
self.bench().clone()
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn identity_and_self_test() {
let p = BoringProvider::new();
assert_eq!(p.provider_name(), "boring");
assert_eq!(p.fips_mode(), cfg!(feature = "fips-validated"));
assert!(p.self_test().all_passed);
}
#[test]
fn trait_objects_work() {
let p: Box<dyn CryptoProvider> = Box::new(BoringProvider::new());
let key = [1u8; 32];
let nonce = [2u8; 12];
let ct = p
.encrypt_aead(AeadAlgorithm::AesGcm256, &key, &nonce, b"m", b"a")
.unwrap();
let pt = p
.decrypt_aead(AeadAlgorithm::AesGcm256, &key, &nonce, &ct, b"a")
.unwrap();
assert_eq!(pt, b"m");
}
}

View File

@ -0,0 +1,373 @@
//! Embedded known-answer self-test (KAT) for every algorithm the provider
//! offers. The vectors are the ones the RustCrypto and wolfSSL providers
//! use, so all three are held to the same answers.
//!
//! Sources:
//!
//! - AES-256-GCM: NIST SP 800-38D test case 16.
//! - ChaCha20-Poly1305: RFC 8439 §2.8.2.
//! - XChaCha20-Poly1305: draft-irtf-cfrg-xchacha-03 §A.3.1.
//! - SHA-2: FIPS 180-4 "abc".
//! - HMAC: RFC 4231 test case 2; HKDF: RFC 5869 test case 1 (SHA-256) and
//! the same inputs for SHA-384/512, checked against OpenSSL 3.6.
//! - X25519: RFC 7748 §6.1.
//! - ML-KEM-768/1024: seed keys from the IETF LAMPS examples (seed 00..3f).
//! `kat/mlkem*.hex` holds the public key and the ciphertext that OpenSSL
//! 3.6 made with fixed encapsulation randomness; their SHA3-256 values
//! are the ones the RustCrypto KAT pins. `boring` has no deterministic
//! encapsulation, so the KAT checks decapsulation of that ciphertext, the
//! implicit-rejection secret for a flipped bit (also from OpenSSL), and a
//! random encapsulation to the pinned public key.
use ccc_crypto_core::{
algorithms::{AeadAlgorithm, HashAlgorithm, KdfAlgorithm, KemAlgorithm, MacAlgorithm},
types::{AlgoTestResult, SelfTestReport},
};
use crate::{aead, hash, kdf, kem, mac, PROVIDER_NAME};
type Check = fn() -> Result<(), String>;
/// Every KAT: (algorithm ID, test name, check).
const KATS: &[(u32, &str, Check)] = &[
(
AeadAlgorithm::AesGcm256 as u32,
"AES-256-GCM SP 800-38D TC16",
aes_gcm,
),
(
AeadAlgorithm::ChaCha20Poly1305 as u32,
"ChaCha20-Poly1305 RFC 8439 2.8.2",
chacha,
),
(
AeadAlgorithm::XChaCha20Poly1305 as u32,
"XChaCha20-Poly1305 draft A.3.1",
xchacha,
),
(HashAlgorithm::Sha256 as u32, "SHA-256 abc", || {
digest(HashAlgorithm::Sha256, SHA256_ABC)
}),
(HashAlgorithm::Sha384 as u32, "SHA-384 abc", || {
digest(HashAlgorithm::Sha384, SHA384_ABC)
}),
(HashAlgorithm::Sha512 as u32, "SHA-512 abc", || {
digest(HashAlgorithm::Sha512, SHA512_ABC)
}),
(
MacAlgorithm::HmacSha256 as u32,
"HMAC-SHA-256 RFC 4231 TC2",
|| hmac(MacAlgorithm::HmacSha256, HMAC256_TC2),
),
(
MacAlgorithm::HmacSha384 as u32,
"HMAC-SHA-384 RFC 4231 TC2",
|| hmac(MacAlgorithm::HmacSha384, HMAC384_TC2),
),
(
MacAlgorithm::HmacSha512 as u32,
"HMAC-SHA-512 RFC 4231 TC2",
|| hmac(MacAlgorithm::HmacSha512, HMAC512_TC2),
),
(
KdfAlgorithm::Sha256 as u32,
"HKDF-SHA-256 RFC 5869 TC1",
|| hkdf(KdfAlgorithm::Sha256, HKDF256_TC1),
),
(
KdfAlgorithm::Sha384 as u32,
"HKDF-SHA-384 TC1 inputs",
|| hkdf(KdfAlgorithm::Sha384, HKDF384_TC1),
),
(
KdfAlgorithm::Sha512 as u32,
"HKDF-SHA-512 TC1 inputs",
|| hkdf(KdfAlgorithm::Sha512, HKDF512_TC1),
),
(KemAlgorithm::X25519 as u32, "X25519 RFC 7748 6.1", x25519),
(
KemAlgorithm::MlKem768 as u32,
"ML-KEM-768 seed KAT",
mlkem768,
),
(
KemAlgorithm::MlKem1024 as u32,
"ML-KEM-1024 seed KAT",
mlkem1024,
),
];
/// Run every KAT. Never panics; failures are reported per algorithm.
pub fn run() -> SelfTestReport {
let results = KATS
.iter()
.map(|(id, name, check)| {
let outcome = check();
AlgoTestResult {
algo_id: *id,
algo_name: (*name).into(),
passed: outcome.is_ok(),
error_message: outcome.err(),
}
})
.collect();
SelfTestReport::finalise(PROVIDER_NAME, results)
}
// ── Helpers ──────────────────────────────────────────────────────────────────
/// Decode a hex vector. Malformed hex yields an empty vector, which matches
/// no pinned output, so a typo fails the test instead of passing silently.
fn hx(s: &str) -> Vec<u8> {
let s = s.trim();
if !s.len().is_multiple_of(2) {
return Vec::new();
}
(0..s.len() / 2)
.map(|i| u8::from_str_radix(&s[2 * i..2 * i + 2], 16).ok())
.collect::<Option<Vec<u8>>>()
.unwrap_or_default()
}
fn expect(what: &str, got: &[u8], want_hex: &str) -> Result<(), String> {
if got == hx(want_hex).as_slice() {
Ok(())
} else {
Err(format!("{what}: output mismatch"))
}
}
fn e<E: core::fmt::Display>(err: E) -> String {
err.to_string()
}
// ── AEAD ─────────────────────────────────────────────────────────────────────
fn aead_kat(
algo: AeadAlgorithm,
key: &str,
nonce: &str,
aad: &str,
pt: &str,
ct: &str,
) -> Result<(), String> {
let (key, nonce, aad, pt) = (hx(key), hx(nonce), hx(aad), hx(pt));
let sealed = aead::encrypt(algo, &key, &nonce, &pt, &aad).map_err(e)?;
expect("seal", &sealed, ct)?;
let opened = aead::decrypt(algo, &key, &nonce, &sealed, &aad).map_err(e)?;
if opened != pt {
return Err("open: plaintext mismatch".into());
}
let mut bad = sealed;
let last = bad.len() - 1;
bad[last] ^= 0x80;
if aead::decrypt(algo, &key, &nonce, &bad, &aad).is_ok() {
return Err("open accepted a tampered tag".into());
}
Ok(())
}
const RFC8439_KEY: &str = "808182838485868788898a8b8c8d8e8f909192939495969798999a9b9c9d9e9f";
const RFC8439_AAD: &str = "50515253c0c1c2c3c4c5c6c7";
const SUNSCREEN: &str = "4c616469657320616e642047656e746c656d656e206f662074686520636c6173\
73206f66202739393a204966204920636f756c64206f6666657220796f75206f6e6c79206f6e6520746970\
20666f7220746865206675747572652c2073756e73637265656e20776f756c642062652069742e";
fn aes_gcm() -> Result<(), String> {
aead_kat(
AeadAlgorithm::AesGcm256,
"feffe9928665731c6d6a8f9467308308feffe9928665731c6d6a8f9467308308",
"cafebabefacedbaddecaf888",
"feedfacedeadbeeffeedfacedeadbeefabaddad2",
"d9313225f88406e5a55909c5aff5269a86a7a9531534f7da2e4c303d8a318a72\
1c3c0c95956809532fcf0e2449a6b525b16aedf5aa0de657ba637b39",
"522dc1f099567d07f47f37a32a84427d643a8cdcbfe5c0c97598a2bd2555d1aa\
8cb08e48590dbb3da7b08b1056828838c5f61e6393ba7a0abcc9f662\
76fc6ece0f4e1768cddf8853bb2d551b",
)
}
fn chacha() -> Result<(), String> {
aead_kat(
AeadAlgorithm::ChaCha20Poly1305,
RFC8439_KEY,
"070000004041424344454647",
RFC8439_AAD,
SUNSCREEN,
"d31a8d34648e60db7b86afbc53ef7ec2a4aded51296e08fea9e2b5a736ee62d63dbea45e8ca967128\
2fafb69da92728b1a71de0a9e060b2905d6a5b67ecd3b3692ddbd7f2d778b8c9803aee328091b58fa\
b324e4fad675945585808b4831d7bc3ff4def08e4b7a9de576d26586cec64b6116\
1ae10b594f09e26a7e902ecbd0600691",
)
}
fn xchacha() -> Result<(), String> {
aead_kat(
AeadAlgorithm::XChaCha20Poly1305,
RFC8439_KEY,
"404142434445464748494a4b4c4d4e4f5051525354555657",
RFC8439_AAD,
SUNSCREEN,
"bd6d179d3e83d43b9576579493c0e939572a1700252bfaccbed2902c21396cbb731c7f1b0b4aa6440\
bf3a82f4eda7e39ae64c6708c54c216cb96b72e1213b4522f8c9ba40db5d945b11b69b982c1bb9e3f\
3fac2bc369488f76b2383565d3fff921f9664c97637da9768812f615c68b13b52e\
c0875924c1c7987947deafd8780acf49",
)
}
// ── Hash ─────────────────────────────────────────────────────────────────────
const SHA256_ABC: &str = "ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad";
const SHA384_ABC: &str = "cb00753f45a35e8bb5a03d699ac65007272c32ab0eded1631a8b605a43ff5bed\
8086072ba1e7cc2358baeca134c825a7";
const SHA512_ABC: &str = "ddaf35a193617abacc417349ae20413112e6fa4e89a97ea20a9eeee64b55d39a\
2192992a274fc1a836ba3c23a3feebbd454d4423643ce80e2a9ac94fa54ca49f";
fn digest(algo: HashAlgorithm, want: &str) -> Result<(), String> {
expect("digest", &hash::hash(algo, b"abc").map_err(e)?, want)
}
// ── MAC ──────────────────────────────────────────────────────────────────────
const HMAC256_TC2: &str = "5bdcc146bf60754e6a042426089575c75a003f089d2739839dec58b964ec3843";
const HMAC384_TC2: &str = "af45d2e376484031617f78d2b58a6b1b9c7ef464f5a01b47e42ec3736322445e\
8e2240ca5e69e2c78b3239ecfab21649";
const HMAC512_TC2: &str = "164b7a7bfcf819e2e395fbe73b56e0a387bd64222e831fd610270cd7ea250554\
9758bf75c05a994a6d034f65f8f0e6fdcaeab1a34d4a6b4b636e070a38bce737";
fn hmac(algo: MacAlgorithm, want: &str) -> Result<(), String> {
let (key, data) = (b"Jefe", b"what do ya want for nothing?");
let tag = mac::compute_mac(algo, key, data).map_err(e)?;
expect("tag", &tag, want)?;
if !mac::verify_mac(algo, key, data, &tag).map_err(e)? {
return Err("verify rejected a valid tag".into());
}
let mut bad = tag;
bad[0] ^= 1;
if mac::verify_mac(algo, key, data, &bad).map_err(e)? {
return Err("verify accepted a tampered tag".into());
}
Ok(())
}
// ── KDF ──────────────────────────────────────────────────────────────────────
const HKDF256_TC1: &str = "3cb25f25faacd57a90434f64d0362f2a2d2d0a90cf1a5a4c5db02d56ecc4c5bf\
34007208d5b887185865";
const HKDF384_TC1: &str = "9b5097a86038b805309076a44b3a9f38063e25b516dcbf369f394cfab43685f7\
48b6457763e4f0204fc5";
const HKDF512_TC1: &str = "832390086cda71fb47625bb5ceb168e4c8e26a1a16ed34d9fc7fe92c14815793\
38da362cb8d9f925d7cb";
fn hkdf(algo: KdfAlgorithm, want: &str) -> Result<(), String> {
let okm = kdf::derive_key(
algo,
&hx("0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b"),
&hx("000102030405060708090a0b0c"),
&hx("f0f1f2f3f4f5f6f7f8f9"),
42,
)
.map_err(e)?;
expect("okm", &okm, want)
}
// ── KEM ──────────────────────────────────────────────────────────────────────
fn x25519() -> Result<(), String> {
let alice = hx("77076d0a7318a57d3c16c17251b26645df4c2f87ebc0992ab177fba51db92c2a");
let alice_pub = "8520f0098930a754748b7ddcb43ef75a0dbf3a0d26381af4eba4a98eaa9b4e6a";
let bob = hx("5dab087e624a8a4b79e17f8b83800ee66f3bb1292618b6fd1c2f8b27ff88e0eb");
let bob_pub = "de9edb7d7b7dc1b4d35b61c2ece435373f8343c85b78674dadfc7e146f882b4f";
let shared = "4a5d9d5ba4ce2de1728e3bf480350f25e07e21c947d19e3376f09b3c1e161742";
let mut base = [0u8; 32];
base[0] = 9;
let dh = |sk: &[u8], pk: &[u8]| kem::decapsulate(KemAlgorithm::X25519, sk, pk).map_err(e);
expect("alice public", &dh(&alice, &base)?, alice_pub)?;
expect("bob public", &dh(&bob, &base)?, bob_pub)?;
expect("alice secret", &dh(&alice, &hx(bob_pub))?, shared)?;
expect("bob secret", &dh(&bob, &hx(alice_pub))?, shared)?;
// The encapsulation path (random ephemeral key) must round-trip too.
let enc = kem::encapsulate(KemAlgorithm::X25519, &hx(bob_pub)).map_err(e)?;
if *dh(&bob, &enc.ciphertext)? != enc.shared_secret {
return Err("encapsulation round trip mismatch".into());
}
Ok(())
}
/// `pk_ct` is `kat/mlkem*.hex`: the public key line, then the ciphertext line.
/// The ciphertext was made by OpenSSL 3.6 with
/// `-pkeyopt hexikme:4041424344454647484950515253545556575859606162636465666768696a6b`.
fn mlkem_kat(algo: KemAlgorithm, pk_ct: &str, ss: &str, rejected: &str) -> Result<(), String> {
let mut lines = pk_ct.lines();
let (pk, ct) = match (lines.next(), lines.next()) {
(Some(pk), Some(ct)) => (hx(pk), hx(ct)),
_ => return Err("KAT data file is malformed".into()),
};
let seed: Vec<u8> = (0u8..64).collect();
let got = kem::decapsulate(algo, &seed, &ct).map_err(e)?;
expect("decap secret", &got, ss)?;
let mut bad = ct;
bad[0] ^= 1;
let got = kem::decapsulate(algo, &seed, &bad).map_err(e)?;
expect("implicit rejection secret", &got, rejected)?;
let enc = kem::encapsulate(algo, &pk).map_err(e)?;
let got = kem::decapsulate(algo, &seed, &enc.ciphertext).map_err(e)?;
if *got != enc.shared_secret {
return Err("encapsulation to the pinned key does not round-trip".into());
}
Ok(())
}
fn mlkem768() -> Result<(), String> {
mlkem_kat(
KemAlgorithm::MlKem768,
include_str!("../kat/mlkem768.hex"),
"71e6c52c0066736b5d2e9cfe2d9694804a4c6dd57c9ed1d615df96c018782de3",
"a4bc996dcdd0a8f03df88aa3544323c5474ef678f9b23b3c0e1be07f607c42ba",
)
}
fn mlkem1024() -> Result<(), String> {
mlkem_kat(
KemAlgorithm::MlKem1024,
include_str!("../kat/mlkem1024.hex"),
"ccff2f30e61151de4c3257ca1d3a8a9de661b81c5ba34efe9b1a4af770caf9df",
"50d6b4f3258582bf211083704ae2af2c276446269b768623d4c158405aa4cc04",
)
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn all_kats_pass() {
let report = run();
for r in &report.results {
assert!(r.passed, "{}: {:?}", r.algo_name, r.error_message);
}
assert!(report.all_passed);
assert_eq!(report.provider_name, "boring");
assert_eq!(report.results.len(), KATS.len());
}
#[test]
fn kat_detects_a_wrong_answer() {
assert!(expect("x", b"abc", "616264").is_err());
assert!(expect("x", b"abc", "616263").is_ok());
}
#[test]
fn mlkem_kat_rejects_a_wrong_secret() {
let wrong = "00".repeat(32);
assert!(mlkem_kat(
KemAlgorithm::MlKem768,
include_str!("../kat/mlkem768.hex"),
&wrong,
&wrong
)
.is_err());
assert!(mlkem_kat(KemAlgorithm::MlKem768, "", &wrong, &wrong).is_err());
}
}

View File

@ -1,8 +1,9 @@
//! Algorithm enumerations for the CCC crypto system.
//!
//! **Important**: every discriminant value matches the corresponding integer
//! constant in `cipher_constants.dart`. Do NOT change them without making a
//! matching change in Dart.
//! This registry is the single source of truth for algorithm IDs (G-8, R3-1).
//! The IDs that existed before CCC v2 still match `cipher_constants.dart`,
//! which today's Dart engine uses until the cutover (R10); never renumber them.
//! New IDs are added at the end of each range.
use serde::{Deserialize, Serialize};
@ -25,6 +26,21 @@ pub enum AeadAlgorithm {
XChaCha20Poly1305 = 14,
/// Ascon-AEAD-128a (lightweight AEAD). Dart constant `15`.
Ascon128a = 15,
/// AES-256-GCM-SIV (RFC 8452), nonce-misuse resistant.
AesGcmSiv256 = 16,
/// Ascon-AEAD128 (NIST SP 800-232).
AsconAead128 = 17,
}
/// How much an algorithm is trusted (design: "Algorithm tiers", S4).
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub enum Tier {
/// A standard AEAD from a mature implementation. Every suite needs one.
Vetted,
/// A well-studied alternative design family; allowed in any position.
Conservative,
/// Research algorithms: additive only, behind a feature, badged in the UI.
Experimental,
}
impl AeadAlgorithm {
@ -35,6 +51,8 @@ impl AeadAlgorithm {
13 => Some(Self::ChaCha20Poly1305),
14 => Some(Self::XChaCha20Poly1305),
15 => Some(Self::Ascon128a),
16 => Some(Self::AesGcmSiv256),
17 => Some(Self::AsconAead128),
_ => None,
}
}
@ -46,6 +64,8 @@ impl AeadAlgorithm {
Self::ChaCha20Poly1305 => "ChaCha20-Poly1305",
Self::XChaCha20Poly1305 => "XChaCha20-Poly1305",
Self::Ascon128a => "Ascon-AEAD-128a",
Self::AesGcmSiv256 => "AES-256-GCM-SIV",
Self::AsconAead128 => "Ascon-AEAD128",
}
}
@ -56,6 +76,8 @@ impl AeadAlgorithm {
Self::ChaCha20Poly1305 => 12,
Self::XChaCha20Poly1305 => 24,
Self::Ascon128a => 16,
Self::AesGcmSiv256 => 12,
Self::AsconAead128 => 16,
}
}
@ -66,8 +88,43 @@ impl AeadAlgorithm {
Self::ChaCha20Poly1305 => 32,
Self::XChaCha20Poly1305 => 32,
Self::Ascon128a => 16,
Self::AesGcmSiv256 => 32,
Self::AsconAead128 => 16,
}
}
/// Authentication tag length in bytes (every supported AEAD uses 16).
pub fn tag_len(self) -> usize {
16
}
/// The algorithm's tier.
pub fn tier(self) -> Tier {
match self {
Self::AesGcm256
| Self::ChaCha20Poly1305
| Self::XChaCha20Poly1305
| Self::AesGcmSiv256 => Tier::Vetted,
Self::AsconAead128 | Self::Ascon128a => Tier::Conservative,
}
}
/// Whether this is an approved AEAD in a FIPS 140-3 module (SP 800-38D
/// AES-GCM). ChaCha20-Poly1305, XChaCha and AES-GCM-SIV are not, even
/// when a FIPS module implements them.
pub fn fips_approved(self) -> bool {
matches!(self, Self::AesGcm256)
}
/// Every AEAD ID, for capability probes and conformance tests.
pub const ALL: [AeadAlgorithm; 6] = [
Self::AesGcm256,
Self::ChaCha20Poly1305,
Self::XChaCha20Poly1305,
Self::Ascon128a,
Self::AesGcmSiv256,
Self::AsconAead128,
];
}
// ──────────────────────────────────────────────────────────────────────────────
@ -267,6 +324,17 @@ pub enum KemAlgorithm {
MlKem1024 = 53,
/// Classic McEliece 460896. Dart constant `54`.
ClassicMcEliece460896 = 54,
/// X-Wing hybrid KEM (ML-KEM-768 + X25519), the LGP receive and ingest key.
XWing = 55,
/// Classic McEliece 460896f (NIST level 3, "f" key generation), the Ultra
/// conservative KEM layer (U2). Same key and ciphertext format as 460896;
/// the "f" variant only makes key generation steady.
ClassicMcEliece460896f = 56,
/// HQC-192 (code-based, NIST level 3), as liboqs 0.13 implements it (the
/// round-4 submission; FIPS 207 is not final, so the bytes may change).
Hqc192 = 57,
/// FrodoKEM-976-SHAKE (plain LWE, NIST level 3).
FrodoKem976Shake = 58,
}
impl KemAlgorithm {
@ -278,6 +346,10 @@ impl KemAlgorithm {
52 => Some(Self::MlKem768),
53 => Some(Self::MlKem1024),
54 => Some(Self::ClassicMcEliece460896),
55 => Some(Self::XWing),
56 => Some(Self::ClassicMcEliece460896f),
57 => Some(Self::Hqc192),
58 => Some(Self::FrodoKem976Shake),
_ => None,
}
}
@ -290,6 +362,78 @@ impl KemAlgorithm {
Self::MlKem768 => "ML-KEM-768",
Self::MlKem1024 => "ML-KEM-1024",
Self::ClassicMcEliece460896 => "Classic-McEliece-460896",
Self::XWing => "X-Wing",
Self::ClassicMcEliece460896f => "Classic-McEliece-460896f",
Self::Hqc192 => "HQC-192",
Self::FrodoKem976Shake => "FrodoKEM-976-SHAKE",
}
}
/// The algorithm's tier (design: "Algorithm tiers").
///
/// - Vetted: X25519 and X448 (RFC 7748), ML-KEM (FIPS 203) and X-Wing,
/// whose two halves are both vetted and whose combiner has a proof.
/// - Conservative: Classic McEliece (code-based, unbroken since 1978 and
/// the Ultra U2 layer) and HQC (code-based, selected by NIST in 2025).
/// Both rest on a different hard problem than ML-KEM, which is the
/// point of an extra KEM layer.
/// - Experimental: FrodoKEM. Its plain-LWE design is conservative, but
/// NIST dropped it after round 3 and the ISO text is not final, so we
/// have no standard to pin its bytes to. It is additive only.
pub fn tier(self) -> Tier {
match self {
Self::X25519 | Self::X448 | Self::MlKem768 | Self::MlKem1024 | Self::XWing => {
Tier::Vetted
}
Self::ClassicMcEliece460896
| Self::ClassicMcEliece460896f
| Self::Hqc192 => Tier::Conservative,
Self::FrodoKem976Shake => Tier::Experimental,
}
}
/// Every KEM ID, for capability probes and conformance tests.
pub const ALL: [KemAlgorithm; 9] = [
Self::X25519,
Self::X448,
Self::MlKem768,
Self::MlKem1024,
Self::ClassicMcEliece460896,
Self::XWing,
Self::ClassicMcEliece460896f,
Self::Hqc192,
Self::FrodoKem976Shake,
];
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn mceliece_ids_are_distinct() {
let f = KemAlgorithm::from_u32(56).unwrap();
assert_eq!(f, KemAlgorithm::ClassicMcEliece460896f);
assert_eq!(f.name(), "Classic-McEliece-460896f");
assert_eq!(
KemAlgorithm::from_u32(54),
Some(KemAlgorithm::ClassicMcEliece460896)
);
}
#[test]
fn kem_ids_round_trip() {
for algo in KemAlgorithm::ALL {
assert_eq!(KemAlgorithm::from_u32(algo as u32), Some(algo));
}
assert_eq!(KemAlgorithm::from_u32(59), None);
}
#[test]
fn kem_tiers() {
assert_eq!(KemAlgorithm::MlKem768.tier(), Tier::Vetted);
assert_eq!(KemAlgorithm::ClassicMcEliece460896f.tier(), Tier::Conservative);
assert_eq!(KemAlgorithm::Hqc192.tier(), Tier::Conservative);
assert_eq!(KemAlgorithm::FrodoKem976Shake.tier(), Tier::Experimental);
}
}

View File

@ -16,7 +16,7 @@ pub mod registry;
pub mod types;
// Re-export everything a provider crate or the bridge crate needs.
pub use algorithms::{AeadAlgorithm, HashAlgorithm, KdfAlgorithm, KemAlgorithm, MacAlgorithm};
pub use algorithms::{AeadAlgorithm, HashAlgorithm, KdfAlgorithm, KemAlgorithm, MacAlgorithm, Tier};
pub use capabilities::{AlgorithmCapability, ProviderCapabilities};
pub use error::CryptoError;
pub use provider::{AeadProvider, CryptoProvider, HashProvider, KdfProvider, KemProvider, MacProvider};

View File

@ -172,6 +172,21 @@ pub trait CryptoProvider:
/// in `ccc_provider_spec.dart`.
fn provider_name(&self) -> &'static str;
/// The code base this provider's implementations come from. Providers
/// built from forks of one library share assembly and bugs, so diversity
/// rules compare lineages, not names: AWS-LC and BoringSSL are both
/// `"boringssl"`. Defaults to [`CryptoProvider::provider_name`].
fn lineage(&self) -> &'static str {
self.provider_name()
}
/// Whether this provider runs as a FIPS 140-3 validated module in FIPS
/// mode. Release policy requires the vetted layer of every suite to come
/// from such a provider (D-26). Defaults to `false`.
fn fips_mode(&self) -> bool {
false
}
/// Return the full runtime capability matrix for this provider.
///
/// Called once at startup after [`CryptoProvider::self_test`] and

View File

@ -0,0 +1,28 @@
[package]
name = "ccc-crypto-oqs"
version.workspace = true
edition.workspace = true
authors.workspace = true
license.workspace = true
description = "Experimental liboqs provider for the CCC crypto system (post-quantum KEMs)."
[dependencies]
ccc-crypto-core.workspace = true
zeroize.workspace = true
log.workspace = true
# liboqs 0.13.0, built from the vendored C source with cmake (no OpenSSL).
oqs = { version = "0.11", default-features = false, features = ["std", "vendored", "classic_mceliece", "hqc", "frodokem"], optional = true }
# The self-test's seeded stream and digests.
sha3 = { version = "0.12", optional = true }
getrandom = { version = "0.4", optional = true }
[features]
# Off by default: without it the crate is a stub provider that offers
# nothing, so a default workspace build never needs cmake or liboqs.
default = []
liboqs = ["dep:oqs", "dep:sha3", "dep:getrandom"]
[dev-dependencies]
# Classic McEliece interop: liboqs is the oracle for the RustCrypto code.
ccc-crypto-rustcrypto.workspace = true

View File

@ -0,0 +1,219 @@
//! KEMs over liboqs 0.13.0 (the `oqs` crate).
//!
//! | Algorithm | Private key | Public key | Ciphertext | Secret |
//! |--------------------------|-------------|------------|------------|--------|
//! | Classic-McEliece-460896f | 13,608 | 524,160 | 156 | 32 |
//! | HQC-192 | 4,586 | 4,522 | 8,978 | 64 |
//! | FrodoKEM-976-SHAKE | 31,296 | 15,632 | 15,744 | 24 |
//!
//! Keys are the liboqs byte strings. Classic McEliece interoperates with the
//! RustCrypto provider (tested both ways in `tests/mceliece_interop.rs`).
//!
//! HQC is the round-4 submission as liboqs 0.13 ships it. liboqs turns HQC
//! off by default in that release pending a fixed implementation; that is
//! one more reason this provider stays experimental.
//!
//! Every call that draws liboqs randomness holds [`RNG_LOCK`], so the
//! self-test can swap in its seeded RNG without another thread drawing from
//! it. Classic McEliece runs on a worker thread with a large stack, as in
//! the RustCrypto provider.
use std::sync::{Mutex, MutexGuard, Once};
use oqs::kem::{Algorithm, Kem};
use zeroize::Zeroizing;
use ccc_crypto_core::{
algorithms::KemAlgorithm,
error::CryptoError,
types::{KemEncapResult, KemKeyPair},
};
/// KEMs this provider offers.
pub const OFFERED: [KemAlgorithm; 3] = [
KemAlgorithm::ClassicMcEliece460896f,
KemAlgorithm::Hqc192,
KemAlgorithm::FrodoKem976Shake,
];
/// Worker stack size for Classic McEliece (see `ccc-crypto-rustcrypto`).
const STACK_SIZE: usize = 8 * 1024 * 1024;
/// Held by every call that draws randomness from liboqs.
static RNG_LOCK: Mutex<()> = Mutex::new(());
pub(crate) fn rng_lock() -> MutexGuard<'static, ()> {
RNG_LOCK.lock().unwrap_or_else(|p| p.into_inner())
}
fn oqs_algorithm(algo: KemAlgorithm) -> Result<Algorithm, CryptoError> {
match algo {
KemAlgorithm::ClassicMcEliece460896f => Ok(Algorithm::ClassicMcEliece460896f),
KemAlgorithm::Hqc192 => Ok(Algorithm::Hqc192),
KemAlgorithm::FrodoKem976Shake => Ok(Algorithm::FrodoKem976Shake),
_ => Err(CryptoError::UnsupportedAlgorithm(format!(
"{} is not offered by the oqs provider",
algo.name()
))),
}
}
fn new_kem(algo: KemAlgorithm) -> Result<Kem, CryptoError> {
static INIT: Once = Once::new();
INIT.call_once(oqs::init);
Kem::new(oqs_algorithm(algo)?)
.map_err(|e| CryptoError::FeatureNotCompiled(format!("{}: {e}", algo.name())))
}
fn internal(algo: KemAlgorithm, e: oqs::Error) -> CryptoError {
CryptoError::InternalError(format!("{}: liboqs: {e}", algo.name()))
}
/// Run `f` on a big-stack worker for Classic McEliece, inline otherwise.
fn run<T: Send>(algo: KemAlgorithm, f: impl FnOnce() -> T + Send) -> Result<T, CryptoError> {
if algo != KemAlgorithm::ClassicMcEliece460896f {
return Ok(f());
}
std::thread::scope(|s| {
std::thread::Builder::new()
.name("ccc-oqs-mceliece".into())
.stack_size(STACK_SIZE)
.spawn_scoped(s, f)
.map_err(|e| CryptoError::InternalError(format!("McEliece worker: {e}")))?
.join()
.map_err(|_| CryptoError::InternalError("McEliece worker panicked".into()))
})
}
/// Key generation without taking [`RNG_LOCK`]; the caller holds it.
pub(crate) fn generate_locked(algo: KemAlgorithm) -> Result<KemKeyPair, CryptoError> {
let kem = new_kem(algo)?;
run(algo, || {
let (pk, sk) = kem.keypair().map_err(|e| internal(algo, e))?;
Ok(KemKeyPair {
public_key: pk.into_vec(),
private_key: sk.into_vec(),
})
})?
}
/// Encapsulation without taking [`RNG_LOCK`]; the caller holds it.
pub(crate) fn encapsulate_locked(
algo: KemAlgorithm,
public_key: &[u8],
) -> Result<KemEncapResult, CryptoError> {
let kem = new_kem(algo)?;
let pk = kem
.public_key_from_bytes(public_key)
.ok_or_else(|| CryptoError::InvalidKey(format!("{}: wrong public key length", algo.name())))?;
run(algo, || {
let (ct, ss) = kem.encapsulate(pk).map_err(|e| internal(algo, e))?;
Ok(KemEncapResult {
ciphertext: ct.into_vec(),
shared_secret: ss.into_vec(),
})
})?
}
/// Generate a key pair.
pub fn generate_keypair(algo: KemAlgorithm) -> Result<KemKeyPair, CryptoError> {
let _rng = rng_lock();
generate_locked(algo)
}
/// Encapsulate a fresh shared secret to `public_key`.
pub fn encapsulate(algo: KemAlgorithm, public_key: &[u8]) -> Result<KemEncapResult, CryptoError> {
let _rng = rng_lock();
encapsulate_locked(algo, public_key)
}
/// Recover the shared secret. Decapsulation draws no randomness. A
/// tampered ciphertext gives a different secret (McEliece, FrodoKEM) or
/// `AuthenticationFailed` (HQC).
pub fn decapsulate(
algo: KemAlgorithm,
private_key: &[u8],
ciphertext: &[u8],
) -> Result<Zeroizing<Vec<u8>>, CryptoError> {
let kem = new_kem(algo)?;
let sk = kem
.secret_key_from_bytes(private_key)
.ok_or_else(|| CryptoError::InvalidKey(format!("{}: wrong private key length", algo.name())))?;
let ct = kem
.ciphertext_from_bytes(ciphertext)
.ok_or_else(|| CryptoError::InvalidInput(format!("{}: wrong ciphertext length", algo.name())))?;
run(algo, || {
// HQC reports a failed re-encryption check as an error instead of
// returning its rejection secret; either way the layer fails.
let ss = kem.decapsulate(sk, ct).map_err(|_| CryptoError::AuthenticationFailed)?;
Ok(Zeroizing::new(ss.into_vec()))
})?
}
#[cfg(test)]
mod tests {
use super::*;
use std::time::Instant;
#[test]
fn roundtrip_sizes_and_timings() {
for (algo, sk, pk, ct, ss) in [
(KemAlgorithm::ClassicMcEliece460896f, 13_608, 524_160, 156, 32),
(KemAlgorithm::Hqc192, 4_586, 4_522, 8_978, 64),
(KemAlgorithm::FrodoKem976Shake, 31_296, 15_632, 15_744, 24),
] {
let t = Instant::now();
let kp = generate_keypair(algo).unwrap();
let keygen = t.elapsed();
let t = Instant::now();
let enc = encapsulate(algo, &kp.public_key).unwrap();
let encap = t.elapsed();
let t = Instant::now();
let got = decapsulate(algo, &kp.private_key, &enc.ciphertext).unwrap();
let decap = t.elapsed();
assert_eq!(*got, enc.shared_secret, "{}", algo.name());
assert_eq!(
(kp.private_key.len(), kp.public_key.len(), enc.ciphertext.len(), got.len()),
(sk, pk, ct, ss),
"{}",
algo.name()
);
println!(
"{}: keygen {keygen:?} encap {encap:?} decap {decap:?}",
algo.name()
);
}
}
#[test]
fn tampered_ciphertext_is_rejected() {
for algo in OFFERED {
let kp = generate_keypair(algo).unwrap();
let enc = encapsulate(algo, &kp.public_key).unwrap();
let mut ct = enc.ciphertext.clone();
ct[0] ^= 1;
match decapsulate(algo, &kp.private_key, &ct) {
Ok(got) => assert_ne!(*got, enc.shared_secret, "{}", algo.name()),
Err(e) => assert!(
algo == KemAlgorithm::Hqc192 && matches!(e, CryptoError::AuthenticationFailed),
"{}: {e}",
algo.name()
),
}
}
}
#[test]
fn wrong_lengths_and_algorithms_rejected() {
let algo = KemAlgorithm::Hqc192;
let kp = generate_keypair(algo).unwrap();
let enc = encapsulate(algo, &kp.public_key).unwrap();
assert!(encapsulate(algo, &kp.public_key[1..]).is_err());
assert!(decapsulate(algo, &kp.private_key[1..], &enc.ciphertext).is_err());
assert!(decapsulate(algo, &kp.private_key, &enc.ciphertext[1..]).is_err());
assert!(matches!(
generate_keypair(KemAlgorithm::MlKem768),
Err(CryptoError::UnsupportedAlgorithm(_))
));
}
}

View File

@ -0,0 +1,44 @@
//! # ccc-crypto-oqs
//!
//! Experimental provider over [liboqs](https://openquantumsafe.org) (R3-5).
//! It offers post-quantum KEMs that neither wolfCrypt nor RustCrypto has, and
//! it is the independent oracle for the RustCrypto Classic McEliece code.
//!
//! liboqs states that it is for prototyping, not production. So this
//! provider only adds layers: it is never a suite's vetted layer, and it
//! offers no AEAD, KDF, MAC or hash.
//!
//! # Features
//!
//! - `liboqs` (off by default): build liboqs 0.13.0 from the vendored C
//! source with cmake and offer Classic-McEliece-460896f, HQC-192 and
//! FrodoKEM-976-SHAKE. Without it the crate builds a stub provider that
//! offers nothing, so a default workspace build needs no cmake.
//!
//! Call [`init()`] once at start-up to register it in the global
//! [`ProviderRegistry`][ccc_crypto_core::registry::ProviderRegistry].
#[cfg(feature = "liboqs")]
pub mod kem;
pub mod provider;
#[cfg(feature = "liboqs")]
pub mod self_test;
pub use provider::OqsProvider;
/// The provider's registry name.
pub const PROVIDER_NAME: &str = "oqs";
/// Register an [`OqsProvider`] in the global registry.
pub fn init() {
ccc_crypto_core::ProviderRegistry::global()
.register(PROVIDER_NAME, Box::new(OqsProvider::new()));
log::info!(
"[ccc-crypto-oqs] provider registered (liboqs {})",
if cfg!(feature = "liboqs") {
"enabled"
} else {
"not compiled"
}
);
}

View File

@ -0,0 +1,289 @@
//! [`OqsProvider`]: the [`CryptoProvider`] implementation.
//!
//! Only KEMs are offered. Every AEAD, KDF, MAC and hash call fails with
//! `UnsupportedAlgorithm`; without the `liboqs` feature every KEM call fails
//! with `FeatureNotCompiled`.
use std::sync::OnceLock;
use zeroize::Zeroizing;
use ccc_crypto_core::{
algorithms::{AeadAlgorithm, HashAlgorithm, KdfAlgorithm, KemAlgorithm, MacAlgorithm},
capabilities::{AlgorithmCapability, ProviderCapabilities},
error::CryptoError,
provider::{AeadProvider, CryptoProvider, HashProvider, KdfProvider, KemProvider, MacProvider},
types::{BenchmarkReport, KemEncapResult, KemKeyPair, SelfTestReport},
};
use crate::PROVIDER_NAME;
/// The liboqs provider. The self-test and capabilities are computed on
/// first use and cached.
#[derive(Default)]
pub struct OqsProvider {
caps: OnceLock<ProviderCapabilities>,
kats: OnceLock<SelfTestReport>,
}
impl OqsProvider {
/// Create a provider; no work is done until it is queried.
pub fn new() -> Self {
Self::default()
}
fn kats(&self) -> &SelfTestReport {
self.kats.get_or_init(run_self_test)
}
}
#[cfg(feature = "liboqs")]
fn run_self_test() -> SelfTestReport {
crate::self_test::run()
}
#[cfg(not(feature = "liboqs"))]
fn run_self_test() -> SelfTestReport {
SelfTestReport::finalise(PROVIDER_NAME, Vec::new())
}
fn unsupported<T>(what: &str) -> Result<T, CryptoError> {
Err(CryptoError::UnsupportedAlgorithm(format!(
"the oqs provider offers KEMs only, not {what}"
)))
}
impl AeadProvider for OqsProvider {
fn encrypt_aead(
&self,
algo: AeadAlgorithm,
_key: &[u8],
_nonce: &[u8],
_plaintext: &[u8],
_aad: &[u8],
) -> Result<Vec<u8>, CryptoError> {
unsupported(algo.name())
}
fn decrypt_aead(
&self,
algo: AeadAlgorithm,
_key: &[u8],
_nonce: &[u8],
_ciphertext_and_tag: &[u8],
_aad: &[u8],
) -> Result<Vec<u8>, CryptoError> {
unsupported(algo.name())
}
}
impl KdfProvider for OqsProvider {
fn derive_key(
&self,
algo: KdfAlgorithm,
_ikm: &[u8],
_salt: &[u8],
_info: &[u8],
_length: usize,
) -> Result<Zeroizing<Vec<u8>>, CryptoError> {
unsupported(algo.name())
}
}
impl MacProvider for OqsProvider {
fn compute_mac(
&self,
algo: MacAlgorithm,
_key: &[u8],
_data: &[u8],
) -> Result<Vec<u8>, CryptoError> {
unsupported(algo.name())
}
fn verify_mac(
&self,
algo: MacAlgorithm,
_key: &[u8],
_data: &[u8],
_mac: &[u8],
) -> Result<bool, CryptoError> {
unsupported(algo.name())
}
}
impl HashProvider for OqsProvider {
fn hash(&self, algo: HashAlgorithm, _data: &[u8]) -> Result<Vec<u8>, CryptoError> {
unsupported(algo.name())
}
}
#[cfg(feature = "liboqs")]
impl KemProvider for OqsProvider {
fn generate_keypair(&self, algo: KemAlgorithm) -> Result<KemKeyPair, CryptoError> {
crate::kem::generate_keypair(algo)
}
fn encapsulate(
&self,
algo: KemAlgorithm,
public_key: &[u8],
) -> Result<KemEncapResult, CryptoError> {
crate::kem::encapsulate(algo, public_key)
}
fn decapsulate(
&self,
algo: KemAlgorithm,
private_key: &[u8],
ciphertext: &[u8],
) -> Result<Zeroizing<Vec<u8>>, CryptoError> {
crate::kem::decapsulate(algo, private_key, ciphertext)
}
}
#[cfg(not(feature = "liboqs"))]
fn not_compiled<T>(algo: KemAlgorithm) -> Result<T, CryptoError> {
Err(CryptoError::FeatureNotCompiled(format!(
"{}: ccc-crypto-oqs was built without the `liboqs` feature",
algo.name()
)))
}
#[cfg(not(feature = "liboqs"))]
impl KemProvider for OqsProvider {
fn generate_keypair(&self, algo: KemAlgorithm) -> Result<KemKeyPair, CryptoError> {
not_compiled(algo)
}
fn encapsulate(
&self,
algo: KemAlgorithm,
_public_key: &[u8],
) -> Result<KemEncapResult, CryptoError> {
not_compiled(algo)
}
fn decapsulate(
&self,
algo: KemAlgorithm,
_private_key: &[u8],
_ciphertext: &[u8],
) -> Result<Zeroizing<Vec<u8>>, CryptoError> {
not_compiled(algo)
}
}
/// KEMs this build offers.
#[cfg(feature = "liboqs")]
fn offered() -> &'static [KemAlgorithm] {
&crate::kem::OFFERED
}
#[cfg(not(feature = "liboqs"))]
fn offered() -> &'static [KemAlgorithm] {
&[]
}
/// A KEM is available only when its KAT passed (fail closed, D-28). The
/// KAT runs keygen, encapsulation and decapsulation through the same code
/// as real calls, so no separate probe is needed.
fn probe_capabilities(self_test: &SelfTestReport) -> ProviderCapabilities {
let mut caps = ProviderCapabilities::empty(PROVIDER_NAME);
for algo in KemAlgorithm::ALL {
let mut kats = self_test
.results
.iter()
.filter(|r| r.algo_id == algo as u32)
.peekable();
let ok = offered().contains(&algo) && kats.peek().is_some() && kats.all(|r| r.passed);
let cap = if ok {
AlgorithmCapability {
available: true,
deterministic_io: false,
efficiency_score: 50,
reliability_score: 100,
}
} else {
AlgorithmCapability::unavailable()
};
caps = caps.with_kem(algo, cap);
}
caps
}
impl CryptoProvider for OqsProvider {
fn provider_name(&self) -> &'static str {
PROVIDER_NAME
}
/// liboqs is not a FIPS module.
fn fips_mode(&self) -> bool {
false
}
fn capabilities(&self) -> ProviderCapabilities {
self.caps
.get_or_init(|| probe_capabilities(self.kats()))
.clone()
}
fn self_test(&self) -> SelfTestReport {
self.kats().clone()
}
/// No AEAD throughput to measure.
fn benchmark(&self) -> BenchmarkReport {
BenchmarkReport {
provider_name: PROVIDER_NAME.into(),
results: Vec::new(),
}
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn identity_and_non_kem_calls() {
let p = OqsProvider::new();
assert_eq!(p.provider_name(), "oqs");
assert!(!p.fips_mode());
assert!(matches!(
p.hash(HashAlgorithm::Sha256, b"x"),
Err(CryptoError::UnsupportedAlgorithm(_))
));
assert!(p
.encrypt_aead(AeadAlgorithm::AesGcm256, &[0; 32], &[0; 12], b"", b"")
.is_err());
assert!(p.benchmark().results.is_empty());
}
#[test]
fn capabilities_match_the_build() {
let p = OqsProvider::new();
assert!(p.self_test().all_passed);
let caps = p.capabilities();
assert_eq!(caps.provider_name, "oqs");
for algo in KemAlgorithm::ALL {
assert_eq!(
caps.kem[&algo].available,
offered().contains(&algo),
"{}",
algo.name()
);
}
assert!(caps.aead.is_empty());
}
#[cfg(not(feature = "liboqs"))]
#[test]
fn stub_offers_nothing() {
let p = OqsProvider::new();
assert!(matches!(
p.generate_keypair(KemAlgorithm::Hqc192),
Err(CryptoError::FeatureNotCompiled(_))
));
assert!(!p.capabilities().has_any_available());
}
}

View File

@ -0,0 +1,257 @@
//! Seeded known-answer self-test for every KEM the provider offers.
//!
//! liboqs draws all randomness through `OQS_randombytes`. For the KAT the
//! provider swaps in a deterministic stream, the same one the RustCrypto
//! McEliece KAT uses: `SHA3-256(label || be64(0)) || SHA3-256(label ||
//! be64(1)) || ...`, consumed by key generation and then encapsulation.
//! Every liboqs call that draws randomness holds the provider's RNG lock, so
//! no other caller can draw from the seeded stream; the system RNG is
//! restored before the lock is released, even if the KAT panics.
//!
//! Sources of the expected values:
//!
//! - Classic-McEliece-460896f: the values of the RustCrypto provider's KAT
//! (label `ccc-kat/mceliece460896f`), produced there by
//! `classic-mceliece-rust` 3.1.0 and reproduced here by liboqs 0.13.0.
//! Two independent code bases agree, so the vector is a real cross-check.
//! - HQC-192 and FrodoKEM-976-SHAKE: produced by liboqs 0.13.0 itself, so
//! they only catch a changed or miscompiled build, not a wrong one.
//! liboqs checks these algorithms against the NIST KAT files in its CI.
//!
//! Large values are pinned as SHA3-256 digests.
use std::sync::Mutex;
use oqs::ffi::rand::{OQS_randombytes_custom_algorithm, OQS_randombytes_switch_algorithm};
use oqs::ffi::common::OQS_STATUS;
use ccc_crypto_core::{
algorithms::KemAlgorithm,
types::{AlgoTestResult, SelfTestReport},
};
use crate::{kem, PROVIDER_NAME};
/// One KAT: the stream label and the expected digests.
struct Kat {
algo: KemAlgorithm,
label: &'static [u8],
pk_sha3: &'static str,
sk_sha3: &'static str,
ct_sha3: &'static str,
ss: &'static str,
}
const KATS: [Kat; 3] = [
Kat {
algo: KemAlgorithm::ClassicMcEliece460896f,
label: b"ccc-kat/mceliece460896f",
pk_sha3: "e0e4f4faf27adcfedb35b8822a05f7938e80c62fd492f726e6ff76a549b43194",
sk_sha3: "59bf486dc9b6c93f6eb9854821eb237000b421c92710a2172c10570a6a014cf4",
ct_sha3: "a69376ae13d09fe536c544ea6049ee22f64d73761d209e3b44528f646d52a358",
ss: "ce2f2240ab5e51e313b7a1ee3c30e2f1882e37fbba0c8f5cb337b2e01d3e4cf3",
},
Kat {
algo: KemAlgorithm::Hqc192,
label: b"ccc-kat/hqc192",
pk_sha3: "3e89ff491e0dca52e7978f5d820402197e2d6d7275e4e3835b1d2d9f2061706b",
sk_sha3: "04b467a8fa815cf2fafbf27c8c8869c508401103398af6b73eb0feaa50dda09e",
ct_sha3: "c9389a0f0158ccc04e00b13e54a93feeb4069e4a032062a305d2484f3f26adc3",
ss: "593ad41c4f81b2497d1241042c4a79f6ca7363008413a0b00078522e6aa9fced\
d3a1ba57be71c49b9252a8a97ddea64b45f4c77897c7c9a358fb9d6bd395b58f",
},
Kat {
algo: KemAlgorithm::FrodoKem976Shake,
label: b"ccc-kat/frodokem976shake",
pk_sha3: "9dd9f14f5975415b4cfd519dcb2b6642780c71b1ed208b5bf199d6110c071a3d",
sk_sha3: "2bad1349b0a2e951e342f70940942911de7a156a8aeb1b88627d8839710760f5",
ct_sha3: "3b9c60a6c65119ec5481856200b5b98bc10fd6b02cd043bd398ae2f803301431",
ss: "97c1484033bcd60c51cbd6890ed7c1fc89cbdb851090cd56",
},
];
/// Run every KAT. Never panics; failures are reported per algorithm.
pub fn run() -> SelfTestReport {
let results = KATS
.iter()
.map(|kat| {
let outcome = check(kat);
AlgoTestResult {
algo_id: kat.algo as u32,
algo_name: format!("{} seeded KAT", kat.algo.name()),
passed: outcome.is_ok(),
error_message: outcome.err(),
}
})
.collect();
SelfTestReport::finalise(PROVIDER_NAME, results)
}
/// The values a KAT produces: SHA3-256 of pk, sk and ct, and the secret.
pub(crate) type KatOutput = [Vec<u8>; 4];
/// Keygen and encapsulation from the seeded stream for `label`, then
/// decapsulation, which must give the same secret.
pub(crate) fn kat_output(algo: KemAlgorithm, label: &'static [u8]) -> Result<KatOutput, String> {
let (kp, enc) = {
let _rng = kem::rng_lock();
let _seeded = SeededRng::install(label);
let kp = kem::generate_locked(algo).map_err(|e| e.to_string())?;
let enc = kem::encapsulate_locked(algo, &kp.public_key).map_err(|e| e.to_string())?;
(kp, enc)
};
let ss = kem::decapsulate(algo, &kp.private_key, &enc.ciphertext).map_err(|e| e.to_string())?;
if *ss != enc.shared_secret {
return Err("decapsulated secret differs".into());
}
Ok([
sha3_256(&kp.public_key).to_vec(),
sha3_256(&kp.private_key).to_vec(),
sha3_256(&enc.ciphertext).to_vec(),
enc.shared_secret.clone(),
])
}
fn check(kat: &Kat) -> Result<(), String> {
let got = kat_output(kat.algo, kat.label)?;
for (what, got, want) in [
("public key", &got[0], kat.pk_sha3),
("private key", &got[1], kat.sk_sha3),
("ciphertext", &got[2], kat.ct_sha3),
("secret", &got[3], kat.ss),
] {
if hex(got) != want {
return Err(format!("{what}: output mismatch"));
}
}
Ok(())
}
fn hex(bytes: &[u8]) -> String {
bytes.iter().map(|b| format!("{b:02x}")).collect()
}
fn sha3_256(data: &[u8]) -> [u8; 32] {
use sha3::Digest;
sha3::Sha3_256::digest(data).into()
}
/// The seeded stream. `None` when no KAT is running.
static STREAM: Mutex<Option<Stream>> = Mutex::new(None);
struct Stream {
label: &'static [u8],
counter: u64,
block: [u8; 32],
used: usize,
}
impl Stream {
fn fill(&mut self, out: &mut [u8]) {
for b in out {
if self.used == 32 {
let mut input = self.label.to_vec();
input.extend_from_slice(&self.counter.to_be_bytes());
self.block = sha3_256(&input);
self.counter += 1;
self.used = 0;
}
*b = self.block[self.used];
self.used += 1;
}
}
}
/// liboqs randomness callback while a KAT runs.
///
/// It must not unwind into C, so it never panics. If called with no KAT
/// running (which the RNG lock rules out), it falls back to the OS RNG and
/// aborts if that fails rather than hand out predictable bytes.
unsafe extern "C" fn seeded_randombytes(buf: *mut u8, len: usize) {
if buf.is_null() || len == 0 {
return;
}
// SAFETY: liboqs passes a writable buffer of `len` bytes.
let out = unsafe { std::slice::from_raw_parts_mut(buf, len) };
let mut stream = STREAM.lock().unwrap_or_else(|p| p.into_inner());
match stream.as_mut() {
Some(s) => s.fill(out),
None => {
if getrandom::fill(out).is_err() {
std::process::abort();
}
}
}
}
/// Installs the seeded stream; dropping it restores the system RNG. The
/// caller must hold the RNG lock for the guard's whole life.
struct SeededRng;
impl SeededRng {
fn install(label: &'static [u8]) -> Self {
*STREAM.lock().unwrap_or_else(|p| p.into_inner()) = Some(Stream {
label,
counter: 0,
block: [0; 32],
used: 32,
});
// SAFETY: the callback has the signature liboqs expects and stays
// valid for the life of the program.
unsafe { OQS_randombytes_custom_algorithm(Some(seeded_randombytes)) };
SeededRng
}
}
impl Drop for SeededRng {
fn drop(&mut self) {
// SAFETY: a NUL-terminated algorithm name liboqs always knows.
let status = unsafe { OQS_randombytes_switch_algorithm(c"system".as_ptr()) };
if status != OQS_STATUS::OQS_SUCCESS {
// Never leave liboqs on the seeded stream.
std::process::abort();
}
*STREAM.lock().unwrap_or_else(|p| p.into_inner()) = None;
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn all_kats_pass() {
let report = run();
for r in &report.results {
assert!(r.passed, "{}: {:?}", r.algo_name, r.error_message);
}
assert!(report.all_passed);
}
#[test]
fn system_rng_is_restored() {
let a = kat_output(KemAlgorithm::Hqc192, b"ccc-kat/hqc192").unwrap();
let b = kat_output(KemAlgorithm::Hqc192, b"ccc-kat/hqc192").unwrap();
assert_eq!(a, b);
let x = kem::generate_keypair(KemAlgorithm::Hqc192).unwrap();
let y = kem::generate_keypair(KemAlgorithm::Hqc192).unwrap();
assert_ne!(x.public_key, y.public_key);
assert_ne!(sha3_256(&x.public_key).to_vec(), a[0]);
}
#[test]
#[ignore = "prints the KAT values; run when liboqs changes"]
fn print_kat_values() {
for kat in &KATS {
let got = kat_output(kat.algo, kat.label).unwrap();
println!(
"{}: pk {} sk {} ct {} ss {}",
kat.algo.name(),
hex(&got[0]),
hex(&got[1]),
hex(&got[2]),
hex(&got[3])
);
}
}
}

View File

@ -0,0 +1,42 @@
//! liboqs as the oracle for the RustCrypto Classic McEliece code: keys and
//! ciphertexts from either side work on the other.
#![cfg(feature = "liboqs")]
use ccc_crypto_core::{algorithms::KemAlgorithm, provider::KemProvider};
use ccc_crypto_oqs::OqsProvider;
use ccc_crypto_rustcrypto::RustCryptoProvider;
const ALGO: KemAlgorithm = KemAlgorithm::ClassicMcEliece460896f;
#[test]
fn rustcrypto_ciphertext_opens_in_oqs() {
let (oqs, rc) = (OqsProvider::new(), RustCryptoProvider::new());
let kp = oqs.generate_keypair(ALGO).unwrap();
let enc = rc.encapsulate(ALGO, &kp.public_key).unwrap();
let ss = oqs.decapsulate(ALGO, &kp.private_key, &enc.ciphertext).unwrap();
assert_eq!(*ss, enc.shared_secret);
}
#[test]
fn oqs_ciphertext_opens_in_rustcrypto() {
let (oqs, rc) = (OqsProvider::new(), RustCryptoProvider::new());
let kp = rc.generate_keypair(ALGO).unwrap();
let enc = oqs.encapsulate(ALGO, &kp.public_key).unwrap();
let ss = rc.decapsulate(ALGO, &kp.private_key, &enc.ciphertext).unwrap();
assert_eq!(*ss, enc.shared_secret);
}
#[test]
fn both_reject_a_tampered_ciphertext_alike() {
let (oqs, rc) = (OqsProvider::new(), RustCryptoProvider::new());
let kp = rc.generate_keypair(ALGO).unwrap();
let enc = rc.encapsulate(ALGO, &kp.public_key).unwrap();
let mut ct = enc.ciphertext.clone();
ct[7] ^= 0x10;
let a = oqs.decapsulate(ALGO, &kp.private_key, &ct).unwrap();
let b = rc.decapsulate(ALGO, &kp.private_key, &ct).unwrap();
// Implicit rejection is deterministic, so both derive the same secret.
assert_ne!(*a, enc.shared_secret);
assert_eq!(*a, *b);
}

View File

@ -0,0 +1,54 @@
[package]
name = "ccc-crypto-rustcrypto"
version.workspace = true
edition.workspace = true
authors.workspace = true
license.workspace = true
description = "Pure-Rust (RustCrypto) provider for the CCC crypto system."
[dependencies]
ccc-crypto-core.workspace = true
zeroize.workspace = true
log.workspace = true
# AEAD
aes-gcm = { version = "0.11", default-features = false, features = ["aes", "alloc", "zeroize"] }
aes-gcm-siv = { version = "0.12", default-features = false, features = ["aes", "alloc", "zeroize"] }
chacha20poly1305 = { version = "0.11", default-features = false, features = ["alloc", "zeroize"] }
# Ascon-AEAD128 as standardised in NIST SP 800-232 (not the pre-standard Ascon-128a).
# Default features are needed: they pull in the optional zeroize dependency
# that the crate's own "zeroize" feature forgets to enable.
ascon-aead = { version = "0.6", features = ["zeroize"] }
# Hash and MAC
sha2 = "0.11"
sha3 = "0.12"
blake2 = "0.11"
hmac = "0.13"
poly1305 = "0.9"
subtle = "2.6"
# KDF
hkdf = "0.13"
argon2 = { version = "0.6", default-features = false, features = ["alloc", "zeroize"] }
# KEM. `hazmat` exposes deterministic encapsulation for the self-test KATs.
x25519-dalek = { version = "3.0", features = ["static_secrets"] }
ml-kem = { version = "0.3", features = ["hazmat", "zeroize"] }
# X-Wing draft-connolly-cfrg-xwing-kem-06 (ML-KEM-768 + X25519).
x-wing = { version = "0.1", features = ["hazmat", "zeroize"] }
getrandom = "0.4"
# Classic McEliece 460896f (Ultra U2), the version the R0-6 spike measured.
# Keep its default features: without "zeroize" the crate does not build.
classic-mceliece-rust = { version = "3.1.0", features = ["mceliece460896f"], optional = true }
# classic-mceliece-rust takes rand_core 0.6 RNGs.
rand_core = { version = "0.6", optional = true }
[features]
default = ["mceliece"]
# Classic McEliece 460896f. The crate builds one parameter set per build,
# so nothing else in the dependency graph may pick another one.
mceliece = ["dep:classic-mceliece-rust", "dep:rand_core"]
[dev-dependencies]
hex = "0.4"

View File

@ -0,0 +1,239 @@
//! AEAD implementations from the RustCrypto `aead` 0.6 family.
//!
//! Wire format matches the wolfSSL provider: `ciphertext || 16-byte tag`.
//!
//! | Algorithm | Crate |
//! |--------------------|-----------------------|
//! | AES-256-GCM | `aes-gcm` |
//! | AES-256-GCM-SIV | `aes-gcm-siv` |
//! | ChaCha20-Poly1305 | `chacha20poly1305` |
//! | XChaCha20-Poly1305 | `chacha20poly1305` |
//! | Ascon-AEAD128 | `ascon-aead` (SP 800-232) |
//!
//! The pre-standard Ascon-128a (ID 15) is not offered: `ascon-aead` 0.6
//! implements only the final NIST SP 800-232 Ascon-AEAD128, which is a
//! different algorithm, so ID 15 returns [`CryptoError::FeatureNotCompiled`].
use aes_gcm::aead::{Aead, KeyInit, Nonce, Payload};
use aes_gcm::Aes256Gcm;
use aes_gcm_siv::Aes256GcmSiv;
use ascon_aead::AsconAead128;
use chacha20poly1305::{ChaCha20Poly1305, XChaCha20Poly1305};
use ccc_crypto_core::{algorithms::AeadAlgorithm, error::CryptoError};
const TAG_LEN: usize = 16;
/// Encrypt `plaintext`; returns `ciphertext || tag`.
pub fn encrypt(
algo: AeadAlgorithm,
key: &[u8],
nonce: &[u8],
plaintext: &[u8],
aad: &[u8],
) -> Result<Vec<u8>, CryptoError> {
validate_key_nonce(algo, key, nonce)?;
match algo {
AeadAlgorithm::AesGcm256 => seal::<Aes256Gcm>(algo, key, nonce, plaintext, aad),
AeadAlgorithm::AesGcmSiv256 => seal::<Aes256GcmSiv>(algo, key, nonce, plaintext, aad),
AeadAlgorithm::ChaCha20Poly1305 => {
seal::<ChaCha20Poly1305>(algo, key, nonce, plaintext, aad)
}
AeadAlgorithm::XChaCha20Poly1305 => {
seal::<XChaCha20Poly1305>(algo, key, nonce, plaintext, aad)
}
AeadAlgorithm::AsconAead128 => seal::<AsconAead128>(algo, key, nonce, plaintext, aad),
AeadAlgorithm::Ascon128a => Err(CryptoError::FeatureNotCompiled(algo.name().into())),
}
}
/// Authenticate and decrypt `ciphertext || tag`.
///
/// Returns [`CryptoError::AuthenticationFailed`] if the tag does not verify.
pub fn decrypt(
algo: AeadAlgorithm,
key: &[u8],
nonce: &[u8],
ciphertext_and_tag: &[u8],
aad: &[u8],
) -> Result<Vec<u8>, CryptoError> {
validate_key_nonce(algo, key, nonce)?;
if ciphertext_and_tag.len() < TAG_LEN {
return Err(CryptoError::InvalidInput(format!(
"{}: ciphertext too short (no room for tag)",
algo.name()
)));
}
let ct = ciphertext_and_tag;
match algo {
AeadAlgorithm::AesGcm256 => open::<Aes256Gcm>(algo, key, nonce, ct, aad),
AeadAlgorithm::AesGcmSiv256 => open::<Aes256GcmSiv>(algo, key, nonce, ct, aad),
AeadAlgorithm::ChaCha20Poly1305 => open::<ChaCha20Poly1305>(algo, key, nonce, ct, aad),
AeadAlgorithm::XChaCha20Poly1305 => open::<XChaCha20Poly1305>(algo, key, nonce, ct, aad),
AeadAlgorithm::AsconAead128 => open::<AsconAead128>(algo, key, nonce, ct, aad),
AeadAlgorithm::Ascon128a => Err(CryptoError::FeatureNotCompiled(algo.name().into())),
}
}
fn validate_key_nonce(algo: AeadAlgorithm, key: &[u8], nonce: &[u8]) -> Result<(), CryptoError> {
if key.len() != algo.key_len() {
return Err(CryptoError::InvalidKey(format!(
"{}: expected {}-byte key, got {}",
algo.name(),
algo.key_len(),
key.len()
)));
}
if nonce.len() != algo.nonce_len() {
return Err(CryptoError::InvalidNonce(format!(
"{}: expected {}-byte nonce, got {}",
algo.name(),
algo.nonce_len(),
nonce.len()
)));
}
Ok(())
}
fn cipher<C: KeyInit>(algo: AeadAlgorithm, key: &[u8]) -> Result<C, CryptoError> {
C::new_from_slice(key).map_err(|_| CryptoError::InvalidKey(algo.name().into()))
}
fn nonce_of<C: Aead>(algo: AeadAlgorithm, nonce: &[u8]) -> Result<Nonce<C>, CryptoError> {
Nonce::<C>::try_from(nonce).map_err(|_| CryptoError::InvalidNonce(algo.name().into()))
}
fn seal<C: KeyInit + Aead>(
algo: AeadAlgorithm,
key: &[u8],
nonce: &[u8],
plaintext: &[u8],
aad: &[u8],
) -> Result<Vec<u8>, CryptoError> {
let c = cipher::<C>(algo, key)?;
let n = nonce_of::<C>(algo, nonce)?;
c.encrypt(
&n,
Payload {
msg: plaintext,
aad,
},
)
.map_err(|_| CryptoError::InvalidInput(format!("{}: input too long", algo.name())))
}
fn open<C: KeyInit + Aead>(
algo: AeadAlgorithm,
key: &[u8],
nonce: &[u8],
ciphertext_and_tag: &[u8],
aad: &[u8],
) -> Result<Vec<u8>, CryptoError> {
let c = cipher::<C>(algo, key)?;
let n = nonce_of::<C>(algo, nonce)?;
c.decrypt(
&n,
Payload {
msg: ciphertext_and_tag,
aad,
},
)
.map_err(|_| CryptoError::AuthenticationFailed)
}
#[cfg(test)]
mod tests {
use super::*;
const OFFERED: [AeadAlgorithm; 5] = [
AeadAlgorithm::AesGcm256,
AeadAlgorithm::AesGcmSiv256,
AeadAlgorithm::ChaCha20Poly1305,
AeadAlgorithm::XChaCha20Poly1305,
AeadAlgorithm::AsconAead128,
];
fn inputs(algo: AeadAlgorithm) -> (Vec<u8>, Vec<u8>) {
let key = (0..algo.key_len() as u8).collect();
let nonce = (0..algo.nonce_len() as u8).map(|b| b ^ 0x5a).collect();
(key, nonce)
}
#[test]
fn roundtrip_all_offered() {
for algo in OFFERED {
let (key, nonce) = inputs(algo);
for (pt, aad) in [
(&b"hello cascade"[..], &b"hdr"[..]),
(b"", b""),
(b"x", b""),
(b"", b"aad only"),
] {
let ct = encrypt(algo, &key, &nonce, pt, aad).unwrap();
assert_eq!(ct.len(), pt.len() + TAG_LEN, "{}", algo.name());
assert_eq!(decrypt(algo, &key, &nonce, &ct, aad).unwrap(), pt);
}
}
}
#[test]
fn tampering_is_rejected() {
for algo in OFFERED {
let (key, nonce) = inputs(algo);
let ct = encrypt(algo, &key, &nonce, b"payload", b"aad").unwrap();
for i in [0, ct.len() - 1] {
let mut bad = ct.clone();
bad[i] ^= 0x01;
assert!(matches!(
decrypt(algo, &key, &nonce, &bad, b"aad"),
Err(CryptoError::AuthenticationFailed)
));
}
assert!(matches!(
decrypt(algo, &key, &nonce, &ct, b"aaD"),
Err(CryptoError::AuthenticationFailed)
));
}
}
#[test]
fn bad_lengths_are_rejected() {
for algo in OFFERED {
let (key, nonce) = inputs(algo);
assert!(matches!(
encrypt(algo, &key[1..], &nonce, b"", b""),
Err(CryptoError::InvalidKey(_))
));
assert!(matches!(
encrypt(algo, &key, &nonce[1..], b"", b""),
Err(CryptoError::InvalidNonce(_))
));
assert!(matches!(
decrypt(algo, &key, &nonce, &[0u8; 15], b""),
Err(CryptoError::InvalidInput(_))
));
}
}
#[test]
fn ascon128a_is_not_compiled() {
let key = [0u8; 16];
let nonce = [0u8; 16];
assert!(matches!(
encrypt(AeadAlgorithm::Ascon128a, &key, &nonce, b"", b""),
Err(CryptoError::FeatureNotCompiled(_))
));
}
#[test]
fn algorithms_are_not_interchangeable() {
let key = [7u8; 32];
let nonce = [9u8; 12];
let gcm = encrypt(AeadAlgorithm::AesGcm256, &key, &nonce, b"same", b"").unwrap();
let siv = encrypt(AeadAlgorithm::AesGcmSiv256, &key, &nonce, b"same", b"").unwrap();
let cha = encrypt(AeadAlgorithm::ChaCha20Poly1305, &key, &nonce, b"same", b"").unwrap();
assert_ne!(gcm, siv);
assert_ne!(gcm, cha);
assert!(decrypt(AeadAlgorithm::AesGcmSiv256, &key, &nonce, &gcm, b"").is_err());
}
}

View File

@ -0,0 +1,270 @@
//! Live capability probes and the AEAD throughput benchmark.
//!
//! An algorithm is `available` only when a live probe succeeds **and** its
//! known-answer self-test passed, so a failing KAT removes the algorithm
//! (fail closed, D-28) instead of leaving a silently wrong implementation in
//! the catalog.
use std::time::Instant;
use ccc_crypto_core::{
algorithms::{AeadAlgorithm, HashAlgorithm, KdfAlgorithm, KemAlgorithm, MacAlgorithm},
capabilities::{AlgorithmCapability, ProviderCapabilities},
types::{AlgoBenchResult, BenchmarkReport, SelfTestReport},
};
use crate::{aead, hash, kdf, kem, mac, PROVIDER_NAME};
/// AEADs this provider implements, in benchmark order.
pub const AEADS: [AeadAlgorithm; 5] = [
AeadAlgorithm::AesGcm256,
AeadAlgorithm::AesGcmSiv256,
AeadAlgorithm::ChaCha20Poly1305,
AeadAlgorithm::XChaCha20Poly1305,
AeadAlgorithm::AsconAead128,
];
const KDFS: [KdfAlgorithm; 5] = [
KdfAlgorithm::Sha256,
KdfAlgorithm::Sha384,
KdfAlgorithm::Sha512,
KdfAlgorithm::Blake2b512,
KdfAlgorithm::Argon2id,
];
const MACS: [MacAlgorithm; 5] = [
MacAlgorithm::HmacSha256,
MacAlgorithm::HmacSha384,
MacAlgorithm::HmacSha512,
MacAlgorithm::Blake2bMac,
MacAlgorithm::Poly1305,
];
const HASHES: [HashAlgorithm; 6] = [
HashAlgorithm::Sha256,
HashAlgorithm::Sha384,
HashAlgorithm::Sha512,
HashAlgorithm::Blake2b512,
HashAlgorithm::Sha3_256,
HashAlgorithm::Sha3_512,
];
const KEMS: &[KemAlgorithm] = &[
KemAlgorithm::X25519,
KemAlgorithm::MlKem768,
KemAlgorithm::MlKem1024,
KemAlgorithm::XWing,
#[cfg(feature = "mceliece")]
KemAlgorithm::ClassicMcEliece460896f,
];
fn kat_passed(report: &SelfTestReport, id: u32) -> bool {
let mut results = report.results.iter().filter(|r| r.algo_id == id).peekable();
// An algorithm without a KAT is never marked available.
results.peek().is_some() && results.all(|r| r.passed)
}
fn cap(available: bool, deterministic_io: bool, efficiency_score: u8) -> AlgorithmCapability {
if !available {
return AlgorithmCapability::unavailable();
}
AlgorithmCapability {
available,
deterministic_io,
efficiency_score,
reliability_score: 100,
}
}
fn aead_probe(algo: AeadAlgorithm) -> bool {
let key = vec![0u8; algo.key_len()];
let nonce = vec![0u8; algo.nonce_len()];
aead::encrypt(algo, &key, &nonce, b"x", b"")
.and_then(|ct| aead::decrypt(algo, &key, &nonce, &ct, b""))
.is_ok_and(|pt| pt == b"x")
}
fn kdf_probe(algo: KdfAlgorithm) -> bool {
if algo == KdfAlgorithm::Argon2id {
// Same code path as derive_key, with probe-sized costs.
return kdf::argon2id(b"key", b"saltsalt", 32, 32, 1, 1).is_ok();
}
kdf::derive_key(algo, b"key", b"salt", b"info", 32).is_ok()
}
fn kem_probe(algo: KemAlgorithm) -> bool {
if algo == KemAlgorithm::ClassicMcEliece460896f {
// Its KAT already ran keygen, encapsulation and decapsulation through
// the same code; a second ~200 ms keygen here would only slow start-up.
return true;
}
let Ok(kp) = kem::generate_keypair(algo) else {
return false;
};
let Ok(enc) = kem::encapsulate(algo, &kp.public_key) else {
return false;
};
kem::decapsulate(algo, &kp.private_key, &enc.ciphertext)
.is_ok_and(|ss| *ss == enc.shared_secret)
}
/// Build the capability matrix from live probes, the self-test report and
/// (optionally) benchmark scores.
pub fn probe_capabilities(
self_test: &SelfTestReport,
benchmarks: Option<&BenchmarkReport>,
) -> ProviderCapabilities {
let mut caps = ProviderCapabilities::empty(PROVIDER_NAME);
let score = |id: u32| {
benchmarks
.and_then(|b| b.results.iter().find(|r| r.algo_id == id))
.map(|r| r.efficiency_score)
.unwrap_or(0)
};
for algo in AeadAlgorithm::ALL {
let ok = AEADS.contains(&algo) && aead_probe(algo) && kat_passed(self_test, algo as u32);
caps = caps.with_aead(algo, cap(ok, true, score(algo as u32)));
}
for algo in KDFS {
let ok = kdf_probe(algo) && kat_passed(self_test, algo as u32);
let eff = if algo == KdfAlgorithm::Argon2id {
10
} else {
80
};
caps = caps.with_kdf(algo, cap(ok, true, eff));
}
caps = caps.with_kdf(KdfAlgorithm::Kmac256, AlgorithmCapability::unavailable());
for algo in MACS {
let ok = mac::compute_mac(algo, &[0x42; 32], b"data").is_ok()
&& kat_passed(self_test, algo as u32);
caps = caps.with_mac(algo, cap(ok, true, 85));
}
for algo in HASHES {
let ok = hash::hash(algo, b"probe").is_ok() && kat_passed(self_test, algo as u32);
caps = caps.with_hash(algo, cap(ok, true, 90));
}
for &algo in KEMS {
let ok = kem_probe(algo) && kat_passed(self_test, algo as u32);
// Key generation and encapsulation are randomised.
caps = caps.with_kem(algo, cap(ok, false, 80));
}
for algo in [
KemAlgorithm::X448,
KemAlgorithm::ClassicMcEliece460896,
#[cfg(not(feature = "mceliece"))]
KemAlgorithm::ClassicMcEliece460896f,
KemAlgorithm::Hqc192,
KemAlgorithm::FrodoKem976Shake,
] {
caps = caps.with_kem(algo, AlgorithmCapability::unavailable());
}
caps
}
/// The provider benchmark: 100 × 1 MiB per AEAD, as in the wolfSSL provider.
pub fn run_benchmark() -> BenchmarkReport {
run_benchmark_with(1024 * 1024, 100)
}
/// Encrypt `iters` × `size` bytes per AEAD and score each relative to the
/// fastest (0–100).
pub fn run_benchmark_with(size: usize, iters: u32) -> BenchmarkReport {
let plaintext = vec![0xABu8; size];
let mut raw: Vec<(AeadAlgorithm, f64)> = Vec::new();
for algo in AEADS {
if !aead_probe(algo) {
continue;
}
let key = vec![0u8; algo.key_len()];
let nonce = vec![0u8; algo.nonce_len()];
let start = Instant::now();
for _ in 0..iters {
let _ = aead::encrypt(algo, &key, &nonce, &plaintext, b"");
}
let secs = start.elapsed().as_secs_f64().max(1e-9);
raw.push((
algo,
(size as f64 * iters as f64) / (1024.0 * 1024.0 * secs),
));
}
let max = raw.iter().map(|(_, t)| *t).fold(0.0, f64::max);
let results = raw
.into_iter()
.map(|(algo, throughput)| AlgoBenchResult {
algo_id: algo as u32,
algo_name: algo.name().into(),
throughput_mbps: throughput,
efficiency_score: if max > 0.0 {
((throughput / max) * 100.0).round() as u8
} else {
0
},
})
.collect();
BenchmarkReport {
provider_name: PROVIDER_NAME.into(),
results,
}
}
#[cfg(test)]
mod tests {
use super::*;
use ccc_crypto_core::types::AlgoTestResult;
#[test]
fn offered_algorithms_are_available() {
let caps = probe_capabilities(&crate::self_test::run(), None);
assert_eq!(caps.provider_name, "rustcrypto");
for algo in AEADS {
assert!(caps.aead[&algo].available, "{}", algo.name());
}
assert!(!caps.aead[&AeadAlgorithm::Ascon128a].available);
assert!(KDFS.iter().all(|a| caps.kdf[a].available));
assert!(!caps.kdf[&KdfAlgorithm::Kmac256].available);
assert!(MACS.iter().all(|a| caps.mac[a].available));
assert!(HASHES.iter().all(|a| caps.hash[a].available));
assert!(KEMS.iter().all(|a| caps.kem[a].available));
assert!(!caps.kem[&KemAlgorithm::X448].available);
assert_eq!(
caps.kem[&KemAlgorithm::ClassicMcEliece460896f].available,
cfg!(feature = "mceliece")
);
}
#[cfg(feature = "mceliece")]
#[test]
fn failed_mceliece_kat_makes_it_unavailable() {
let mut report = crate::self_test::run();
for r in &mut report.results {
if r.algo_id == KemAlgorithm::ClassicMcEliece460896f as u32 {
r.passed = false;
}
}
let caps = probe_capabilities(&report, None);
assert!(!caps.kem[&KemAlgorithm::ClassicMcEliece460896f].available);
}
#[test]
fn failed_kat_makes_algorithm_unavailable() {
let mut report = crate::self_test::run();
report.results.push(AlgoTestResult {
algo_id: AeadAlgorithm::AesGcm256 as u32,
algo_name: "forced failure".into(),
passed: false,
error_message: Some("test".into()),
});
let caps = probe_capabilities(&report, None);
assert!(!caps.aead[&AeadAlgorithm::AesGcm256].available);
assert!(caps.aead[&AeadAlgorithm::ChaCha20Poly1305].available);
}
#[test]
fn small_benchmark_scores_every_aead() {
let report = run_benchmark_with(4096, 2);
assert_eq!(report.results.len(), AEADS.len());
assert!(report.results.iter().any(|r| r.efficiency_score == 100));
}
}

View File

@ -0,0 +1,46 @@
//! Hash functions: SHA-2 (`sha2`), SHA-3 (`sha3`) and BLAKE2b-512 (`blake2`).
use blake2::Blake2b512;
use sha2::{Digest, Sha256, Sha384, Sha512};
use sha3::{Sha3_256, Sha3_512};
use ccc_crypto_core::{algorithms::HashAlgorithm, error::CryptoError};
/// Compute the digest of `data`.
pub fn hash(algo: HashAlgorithm, data: &[u8]) -> Result<Vec<u8>, CryptoError> {
Ok(match algo {
HashAlgorithm::Sha256 => Sha256::digest(data).to_vec(),
HashAlgorithm::Sha384 => Sha384::digest(data).to_vec(),
HashAlgorithm::Sha512 => Sha512::digest(data).to_vec(),
HashAlgorithm::Blake2b512 => Blake2b512::digest(data).to_vec(),
HashAlgorithm::Sha3_256 => Sha3_256::digest(data).to_vec(),
HashAlgorithm::Sha3_512 => Sha3_512::digest(data).to_vec(),
})
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn digest_lengths_match_registry() {
for algo in [
HashAlgorithm::Sha256,
HashAlgorithm::Sha384,
HashAlgorithm::Sha512,
HashAlgorithm::Blake2b512,
HashAlgorithm::Sha3_256,
HashAlgorithm::Sha3_512,
] {
assert_eq!(hash(algo, b"abc").unwrap().len(), algo.digest_len());
}
}
#[test]
fn sha256_abc() {
assert_eq!(
hex::encode(hash(HashAlgorithm::Sha256, b"abc").unwrap()),
"ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad"
);
}
}

View File

@ -0,0 +1,220 @@
//! KDFs: HKDF-SHA-2 (`hkdf`), the BLAKE2b-512 KDF and Argon2id (`argon2`).
//!
//! Semantics match the wolfSSL provider exactly, so either provider can
//! derive the same key:
//!
//! - HKDF (RFC 5869); an empty salt means the all-zero salt of hash length,
//! and the output is capped at 255 × hash length.
//! - BLAKE2b-512 KDF: `BLAKE2b-512(ikm || salt || info)` truncated to
//! `length` (at most 64 bytes).
//! - Argon2id v1.3 with the app defaults: 64 MiB, 3 passes, 4 lanes; the salt
//! must be at least 8 bytes and `info` is not used.
use argon2::{Algorithm, Argon2, Params, Version};
use hkdf::Hkdf;
use sha2::{Sha256, Sha384, Sha512};
use zeroize::Zeroizing;
use ccc_crypto_core::{
algorithms::{HashAlgorithm, KdfAlgorithm},
error::CryptoError,
};
/// Argon2id memory cost in KiB (64 MiB), as in the wolfSSL provider.
pub const ARGON2_M_COST_KIB: u32 = 65_536;
/// Argon2id passes.
pub const ARGON2_T_COST: u32 = 3;
/// Argon2id lanes.
pub const ARGON2_P_COST: u32 = 4;
/// Derive `length` bytes from `ikm`.
pub fn derive_key(
algo: KdfAlgorithm,
ikm: &[u8],
salt: &[u8],
info: &[u8],
length: usize,
) -> Result<Zeroizing<Vec<u8>>, CryptoError> {
match algo {
KdfAlgorithm::Sha256 | KdfAlgorithm::Sha384 | KdfAlgorithm::Sha512 => {
hkdf(algo, ikm, salt, info, length)
}
KdfAlgorithm::Blake2b512 => blake2b_kdf(ikm, salt, info, length),
KdfAlgorithm::Argon2id => argon2id(
ikm,
salt,
length,
ARGON2_M_COST_KIB,
ARGON2_T_COST,
ARGON2_P_COST,
),
KdfAlgorithm::Kmac256 => Err(CryptoError::FeatureNotCompiled(algo.name().into())),
}
}
fn hkdf(
algo: KdfAlgorithm,
ikm: &[u8],
salt: &[u8],
info: &[u8],
length: usize,
) -> Result<Zeroizing<Vec<u8>>, CryptoError> {
let hash_len = match algo {
KdfAlgorithm::Sha256 => 32,
KdfAlgorithm::Sha384 => 48,
_ => 64,
};
let max_len = 255 * hash_len;
if length > max_len {
return Err(CryptoError::InvalidInput(format!(
"HKDF: requested length {length} exceeds maximum {max_len}"
)));
}
// `None` is the RFC 5869 zero salt, the same as wolfSSL's empty salt.
let salt = if salt.is_empty() { None } else { Some(salt) };
let mut okm = Zeroizing::new(vec![0u8; length]);
let res = match algo {
KdfAlgorithm::Sha256 => Hkdf::<Sha256>::new(salt, ikm).expand(info, &mut okm),
KdfAlgorithm::Sha384 => Hkdf::<Sha384>::new(salt, ikm).expand(info, &mut okm),
_ => Hkdf::<Sha512>::new(salt, ikm).expand(info, &mut okm),
};
res.map_err(|_| CryptoError::InvalidInput("HKDF: output too long".into()))?;
Ok(okm)
}
fn blake2b_kdf(
ikm: &[u8],
salt: &[u8],
info: &[u8],
length: usize,
) -> Result<Zeroizing<Vec<u8>>, CryptoError> {
if length > 64 {
return Err(CryptoError::InvalidInput(
"BLAKE2b-512 KDF: requested length exceeds 64 bytes; use HKDF-SHA512".into(),
));
}
let mut input = Zeroizing::new(Vec::with_capacity(ikm.len() + salt.len() + info.len()));
input.extend_from_slice(ikm);
input.extend_from_slice(salt);
input.extend_from_slice(info);
let digest = Zeroizing::new(crate::hash::hash(HashAlgorithm::Blake2b512, &input)?);
Ok(Zeroizing::new(digest[..length].to_vec()))
}
/// Argon2id v1.3 with explicit cost parameters.
///
/// [`derive_key`] uses the app defaults; this entry point exists for tests
/// and for callers that store their own parameters.
pub fn argon2id(
password: &[u8],
salt: &[u8],
length: usize,
m_cost_kib: u32,
t_cost: u32,
p_cost: u32,
) -> Result<Zeroizing<Vec<u8>>, CryptoError> {
if salt.len() < 8 {
return Err(CryptoError::InvalidInput(
"Argon2id requires at least 8-byte salt".into(),
));
}
let params = Params::new(m_cost_kib, t_cost, p_cost, Some(length))
.map_err(|e| CryptoError::InvalidInput(format!("Argon2 params error: {e}")))?;
let argon2 = Argon2::new(Algorithm::Argon2id, Version::V0x13, params);
let mut out = Zeroizing::new(vec![0u8; length]);
argon2
.hash_password_into(password, salt, &mut out)
.map_err(|e| CryptoError::InvalidInput(format!("Argon2id hash error: {e}")))?;
Ok(out)
}
#[cfg(test)]
mod tests {
use super::*;
fn h(s: &str) -> Vec<u8> {
hex::decode(s).unwrap()
}
#[test]
fn hkdf_sha256_rfc5869_tc1() {
let okm = derive_key(
KdfAlgorithm::Sha256,
&h("0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b"),
&h("000102030405060708090a0b0c"),
&h("f0f1f2f3f4f5f6f7f8f9"),
42,
)
.unwrap();
assert_eq!(
hex::encode(&*okm),
"3cb25f25faacd57a90434f64d0362f2a2d2d0a90cf1a5a4c5db02d56ecc4c5bf34007208d5b887185865"
);
}
#[test]
fn hkdf_sha512_rfc5869_tc1_inputs() {
// Reference value pinned for the wolfSSL HKDF-SHA-512 fix.
let okm = derive_key(
KdfAlgorithm::Sha512,
&h("0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b"),
&h("000102030405060708090a0b0c"),
&h("f0f1f2f3f4f5f6f7f8f9"),
42,
)
.unwrap();
assert_eq!(
hex::encode(&*okm),
"832390086cda71fb47625bb5ceb168e4c8e26a1a16ed34d9fc7fe92c1481579338da362cb8d9f925d7cb"
);
}
#[test]
fn hkdf_empty_salt_is_zero_salt() {
for (algo, n) in [
(KdfAlgorithm::Sha256, 32),
(KdfAlgorithm::Sha384, 48),
(KdfAlgorithm::Sha512, 64),
] {
let a = derive_key(algo, b"ikm", b"", b"info", 32).unwrap();
let b = derive_key(algo, b"ikm", &vec![0u8; n], b"info", 32).unwrap();
assert_eq!(*a, *b);
}
}
#[test]
fn hkdf_length_limit() {
assert!(derive_key(KdfAlgorithm::Sha256, b"k", b"", b"", 255 * 32).is_ok());
assert!(matches!(
derive_key(KdfAlgorithm::Sha256, b"k", b"", b"", 255 * 32 + 1),
Err(CryptoError::InvalidInput(_))
));
}
#[test]
fn blake2b_kdf_is_hash_of_concatenation() {
let okm = derive_key(KdfAlgorithm::Blake2b512, b"a", b"b", b"c", 64).unwrap();
let digest = crate::hash::hash(HashAlgorithm::Blake2b512, b"abc").unwrap();
assert_eq!(*okm, digest);
let short = derive_key(KdfAlgorithm::Blake2b512, b"a", b"b", b"c", 16).unwrap();
assert_eq!(*short, digest[..16]);
assert!(derive_key(KdfAlgorithm::Blake2b512, b"a", b"", b"", 65).is_err());
}
#[test]
fn argon2id_rules() {
assert!(argon2id(b"pw", b"short", 32, 64, 1, 1).is_err());
let a = argon2id(b"pw", b"saltsalt", 32, 64, 1, 1).unwrap();
let b = argon2id(b"pw", b"saltsalt", 32, 64, 1, 1).unwrap();
assert_eq!(*a, *b);
assert_ne!(*a, *argon2id(b"pw", b"saltsalT", 32, 64, 1, 1).unwrap());
}
#[test]
fn kmac_is_not_compiled() {
assert!(matches!(
derive_key(KdfAlgorithm::Kmac256, b"k", b"", b"", 32),
Err(CryptoError::FeatureNotCompiled(_))
));
}
}

View File

@ -0,0 +1,366 @@
//! KEMs: X25519 (`x25519-dalek`), ML-KEM-768/1024 (`ml-kem`, FIPS 203) and
//! X-Wing (`x-wing`, draft-connolly-cfrg-xwing-kem-06).
//!
//! Key and ciphertext formats:
//!
//! | Algorithm | Private key | Public key | Ciphertext | Secret |
//! |-------------|------------------------|------------|-----------------------|--------|
//! | X25519 | 32-byte scalar (LE) | 32 | 32 (ephemeral public) | 32 |
//! | ML-KEM-768 | 64-byte seed `d \|\| z` | 1184 | 1088 | 32 |
//! | ML-KEM-1024 | 64-byte seed `d \|\| z` | 1568 | 1568 | 32 |
//! | X-Wing | 32-byte seed | 1216 | 1120 | 32 |
//!
//! X25519 follows the wolfSSL provider's KEM convention: encapsulation makes
//! an ephemeral key pair, the ciphertext is its public key and the secret is
//! the raw RFC 7748 shared value. An all-zero shared value (a low-order
//! peer point) is rejected.
//!
//! Classic McEliece 460896f (`mceliece` feature, on by default) lives in
//! [`crate::mceliece`]. X448 and Classic McEliece 460896 (non-"f") are not
//! offered by this provider.
use ml_kem::array::Array;
use ml_kem::kem::{Decapsulate, KeyExport, TryKeyInit};
use x25519_dalek::{PublicKey, StaticSecret};
use zeroize::Zeroizing;
use ccc_crypto_core::{
algorithms::KemAlgorithm,
error::CryptoError,
types::{KemEncapResult, KemKeyPair},
};
/// Generate a key pair.
pub fn generate_keypair(algo: KemAlgorithm) -> Result<KemKeyPair, CryptoError> {
match algo {
KemAlgorithm::X25519 => {
let sk = random::<32>()?;
let pk = PublicKey::from(&StaticSecret::from(*sk));
Ok(KemKeyPair {
public_key: pk.as_bytes().to_vec(),
private_key: sk.to_vec(),
})
}
KemAlgorithm::MlKem768 => mlkem768::generate(),
KemAlgorithm::MlKem1024 => mlkem1024::generate(),
KemAlgorithm::XWing => {
let seed = random::<32>()?;
Ok(KemKeyPair {
public_key: xwing_public_key(&seed[..])?,
private_key: seed.to_vec(),
})
}
#[cfg(feature = "mceliece")]
KemAlgorithm::ClassicMcEliece460896f => crate::mceliece::generate(),
#[cfg(not(feature = "mceliece"))]
KemAlgorithm::ClassicMcEliece460896f => not_compiled(algo),
KemAlgorithm::X448
| KemAlgorithm::ClassicMcEliece460896
| KemAlgorithm::Hqc192
| KemAlgorithm::FrodoKem976Shake => not_compiled(algo),
}
}
/// Encapsulate a fresh shared secret to `public_key`.
pub fn encapsulate(algo: KemAlgorithm, public_key: &[u8]) -> Result<KemEncapResult, CryptoError> {
match algo {
KemAlgorithm::X25519 => {
let eph = random::<32>()?;
x25519_encapsulate_deterministic(&eph[..], public_key)
}
KemAlgorithm::MlKem768 => mlkem768::encapsulate_deterministic(public_key, &*random()?),
KemAlgorithm::MlKem1024 => mlkem1024::encapsulate_deterministic(public_key, &*random()?),
KemAlgorithm::XWing => xwing_encapsulate_deterministic(public_key, &*random()?),
#[cfg(feature = "mceliece")]
KemAlgorithm::ClassicMcEliece460896f => crate::mceliece::encapsulate(public_key),
#[cfg(not(feature = "mceliece"))]
KemAlgorithm::ClassicMcEliece460896f => not_compiled(algo),
KemAlgorithm::X448
| KemAlgorithm::ClassicMcEliece460896
| KemAlgorithm::Hqc192
| KemAlgorithm::FrodoKem976Shake => not_compiled(algo),
}
}
/// Recover the shared secret from `ciphertext` with `private_key`.
pub fn decapsulate(
algo: KemAlgorithm,
private_key: &[u8],
ciphertext: &[u8],
) -> Result<Zeroizing<Vec<u8>>, CryptoError> {
match algo {
KemAlgorithm::X25519 => x25519_dh(private_key, ciphertext),
KemAlgorithm::MlKem768 => mlkem768::decapsulate(private_key, ciphertext),
KemAlgorithm::MlKem1024 => mlkem1024::decapsulate(private_key, ciphertext),
KemAlgorithm::XWing => xwing_decapsulate(private_key, ciphertext),
#[cfg(feature = "mceliece")]
KemAlgorithm::ClassicMcEliece460896f => crate::mceliece::decapsulate(private_key, ciphertext),
#[cfg(not(feature = "mceliece"))]
KemAlgorithm::ClassicMcEliece460896f => not_compiled(algo),
KemAlgorithm::X448
| KemAlgorithm::ClassicMcEliece460896
| KemAlgorithm::Hqc192
| KemAlgorithm::FrodoKem976Shake => not_compiled(algo),
}
}
fn not_compiled<T>(algo: KemAlgorithm) -> Result<T, CryptoError> {
Err(CryptoError::FeatureNotCompiled(format!(
"{} is not offered by the rustcrypto provider",
algo.name()
)))
}
fn random<const N: usize>() -> Result<Zeroizing<[u8; N]>, CryptoError> {
let mut buf = Zeroizing::new([0u8; N]);
getrandom::fill(&mut buf[..])
.map_err(|e| CryptoError::InternalError(format!("getrandom failed: {e}")))?;
Ok(buf)
}
fn array32(bytes: &[u8], what: &str) -> Result<Zeroizing<[u8; 32]>, CryptoError> {
let arr: [u8; 32] = bytes
.try_into()
.map_err(|_| CryptoError::InvalidKey(format!("{what}: expected 32 bytes")))?;
Ok(Zeroizing::new(arr))
}
// ── X25519 ───────────────────────────────────────────────────────────────────
/// X25519 encapsulation with a caller-chosen ephemeral scalar (for KATs).
pub fn x25519_encapsulate_deterministic(
ephemeral_private: &[u8],
public_key: &[u8],
) -> Result<KemEncapResult, CryptoError> {
let eph = StaticSecret::from(*array32(ephemeral_private, "X25519 private key")?);
let ct = PublicKey::from(&eph).as_bytes().to_vec();
let ss = x25519_dh(eph.as_bytes(), public_key)?;
Ok(KemEncapResult {
ciphertext: ct,
shared_secret: ss.to_vec(),
})
}
fn x25519_dh(private_key: &[u8], public_key: &[u8]) -> Result<Zeroizing<Vec<u8>>, CryptoError> {
if private_key.len() != 32 || public_key.len() != 32 {
return Err(CryptoError::InvalidKey(
"X25519: keys must be 32 bytes each".into(),
));
}
let sk = StaticSecret::from(*array32(private_key, "X25519 private key")?);
let pk = PublicKey::from(*array32(public_key, "X25519 public key")?);
let ss = sk.diffie_hellman(&pk);
if !ss.was_contributory() {
return Err(CryptoError::InvalidKey(
"X25519: low-order public key (all-zero shared secret)".into(),
));
}
Ok(Zeroizing::new(ss.as_bytes().to_vec()))
}
// ── ML-KEM ───────────────────────────────────────────────────────────────────
macro_rules! mlkem_impl {
($module:ident, $params:ident, $name:literal) => {
pub(crate) mod $module {
use super::*;
use ml_kem::$params::{Ciphertext, DecapsulationKey, EncapsulationKey};
fn dk_from_seed(seed: &[u8]) -> Result<DecapsulationKey, CryptoError> {
let seed = ml_kem::Seed::try_from(seed).map_err(|_| {
CryptoError::InvalidKey(
concat!($name, ": private key must be a 64-byte seed").into(),
)
})?;
Ok(DecapsulationKey::from_seed(seed))
}
/// Public key for a 64-byte seed (FIPS 203 `ML-KEM.KeyGen_internal`).
pub(crate) fn public_key(seed: &[u8]) -> Result<Vec<u8>, CryptoError> {
Ok(dk_from_seed(seed)?.encapsulation_key().to_bytes().to_vec())
}
pub(super) fn generate() -> Result<KemKeyPair, CryptoError> {
let seed = random::<64>()?;
Ok(KemKeyPair {
public_key: public_key(&seed[..])?,
private_key: seed.to_vec(),
})
}
/// Encapsulate with caller-chosen randomness `m` (for KATs).
pub(crate) fn encapsulate_deterministic(
public_key: &[u8],
m: &[u8; 32],
) -> Result<KemEncapResult, CryptoError> {
let ek = EncapsulationKey::new_from_slice(public_key).map_err(|_| {
CryptoError::InvalidKey(concat!($name, ": invalid public key").into())
})?;
let (ct, ss) = ek.encapsulate_deterministic(&Array::from(*m));
Ok(KemEncapResult {
ciphertext: ct.to_vec(),
shared_secret: ss.to_vec(),
})
}
pub(super) fn decapsulate(
private_key: &[u8],
ciphertext: &[u8],
) -> Result<Zeroizing<Vec<u8>>, CryptoError> {
let dk = dk_from_seed(private_key)?;
let ct = Ciphertext::try_from(ciphertext).map_err(|_| {
CryptoError::InvalidInput(concat!($name, ": wrong ciphertext length").into())
})?;
Ok(Zeroizing::new(dk.decapsulate(&ct).to_vec()))
}
}
};
}
mlkem_impl!(mlkem768, ml_kem_768, "ML-KEM-768");
mlkem_impl!(mlkem1024, ml_kem_1024, "ML-KEM-1024");
// ── X-Wing ───────────────────────────────────────────────────────────────────
fn xwing_dk(seed: &[u8]) -> Result<x_wing::DecapsulationKey, CryptoError> {
Ok(x_wing::DecapsulationKey::from(*array32(
seed,
"X-Wing private key",
)?))
}
pub(crate) fn xwing_public_key(seed: &[u8]) -> Result<Vec<u8>, CryptoError> {
use x_wing::Decapsulator;
Ok(xwing_dk(seed)?.encapsulation_key().to_bytes().to_vec())
}
/// X-Wing encapsulation with caller-chosen 64-byte randomness (for KATs).
pub(crate) fn xwing_encapsulate_deterministic(
public_key: &[u8],
eseed: &[u8; 64],
) -> Result<KemEncapResult, CryptoError> {
let ek = x_wing::EncapsulationKey::try_from(public_key)
.map_err(|_| CryptoError::InvalidKey("X-Wing: invalid public key".into()))?;
let (ct, ss) = ek.encapsulate_deterministic(&Array::from(*eseed));
Ok(KemEncapResult {
ciphertext: ct.to_vec(),
shared_secret: ss.to_vec(),
})
}
fn xwing_decapsulate(
private_key: &[u8],
ciphertext: &[u8],
) -> Result<Zeroizing<Vec<u8>>, CryptoError> {
let dk = xwing_dk(private_key)?;
let ss = dk
.decapsulate_slice(ciphertext)
.map_err(|_| CryptoError::InvalidInput("X-Wing: wrong ciphertext length".into()))?;
Ok(Zeroizing::new(ss.to_vec()))
}
#[cfg(test)]
mod tests {
use super::*;
const OFFERED: [KemAlgorithm; 4] = [
KemAlgorithm::X25519,
KemAlgorithm::MlKem768,
KemAlgorithm::MlKem1024,
KemAlgorithm::XWing,
];
#[test]
fn roundtrip_all_offered() {
for algo in OFFERED {
let kp = generate_keypair(algo).unwrap();
let enc = encapsulate(algo, &kp.public_key).unwrap();
let ss = decapsulate(algo, &kp.private_key, &enc.ciphertext).unwrap();
assert_eq!(*ss, enc.shared_secret, "{}", algo.name());
assert_eq!(ss.len(), 32);
}
}
#[test]
fn sizes() {
for (algo, sk, pk, ct) in [
(KemAlgorithm::X25519, 32, 32, 32),
(KemAlgorithm::MlKem768, 64, 1184, 1088),
(KemAlgorithm::MlKem1024, 64, 1568, 1568),
(KemAlgorithm::XWing, 32, 1216, 1120),
] {
let kp = generate_keypair(algo).unwrap();
assert_eq!(kp.private_key.len(), sk);
assert_eq!(kp.public_key.len(), pk);
assert_eq!(
encapsulate(algo, &kp.public_key).unwrap().ciphertext.len(),
ct
);
}
}
#[test]
fn x25519_rfc7748() {
let alice = hex::decode("77076d0a7318a57d3c16c17251b26645df4c2f87ebc0992ab177fba51db92c2a")
.unwrap();
let bob_pub =
hex::decode("de9edb7d7b7dc1b4d35b61c2ece435373f8343c85b78674dadfc7e146f882b4f")
.unwrap();
let ss = decapsulate(KemAlgorithm::X25519, &alice, &bob_pub).unwrap();
assert_eq!(
hex::encode(&*ss),
"4a5d9d5ba4ce2de1728e3bf480350f25e07e21c947d19e3376f09b3c1e161742"
);
}
#[test]
fn x25519_low_order_point_rejected() {
let sk = [0x11u8; 32];
assert!(matches!(
decapsulate(KemAlgorithm::X25519, &sk, &[0u8; 32]),
Err(CryptoError::InvalidKey(_))
));
}
#[test]
fn wrong_lengths_rejected() {
for algo in OFFERED {
let kp = generate_keypair(algo).unwrap();
let enc = encapsulate(algo, &kp.public_key).unwrap();
assert!(encapsulate(algo, &kp.public_key[1..]).is_err());
assert!(decapsulate(algo, &kp.private_key[1..], &enc.ciphertext).is_err());
assert!(decapsulate(algo, &kp.private_key, &enc.ciphertext[1..]).is_err());
}
}
#[test]
fn mlkem_implicit_rejection() {
for algo in [
KemAlgorithm::MlKem768,
KemAlgorithm::MlKem1024,
KemAlgorithm::XWing,
] {
let kp = generate_keypair(algo).unwrap();
let enc = encapsulate(algo, &kp.public_key).unwrap();
let mut ct = enc.ciphertext.clone();
ct[0] ^= 1;
let ss = decapsulate(algo, &kp.private_key, &ct).unwrap();
assert_ne!(*ss, enc.shared_secret);
}
}
#[test]
fn unsupported_kems() {
for algo in [
KemAlgorithm::X448,
KemAlgorithm::ClassicMcEliece460896,
#[cfg(not(feature = "mceliece"))]
KemAlgorithm::ClassicMcEliece460896f,
] {
assert!(matches!(
generate_keypair(algo),
Err(CryptoError::FeatureNotCompiled(_))
));
}
}
}

View File

@ -0,0 +1,34 @@
//! # ccc-crypto-rustcrypto
//!
//! Pure-Rust implementation of the CCC provider traits, built on the
//! RustCrypto crates. It is the independent second implementation next to
//! `ccc-crypto-wolfssl` (design: "Provider diversity") and the provider a
//! web build would use. It is not a FIPS module: `fips_mode()` is `false`.
//!
//! Call [`init()`] once at start-up to register it in the global
//! [`ProviderRegistry`][ccc_crypto_core::registry::ProviderRegistry].
#![forbid(unsafe_code)]
pub mod aead;
pub mod capabilities;
pub mod hash;
pub mod kdf;
pub mod kem;
pub mod mac;
#[cfg(feature = "mceliece")]
pub mod mceliece;
pub mod provider;
pub mod self_test;
pub use provider::RustCryptoProvider;
/// The provider's registry name.
pub const PROVIDER_NAME: &str = "rustcrypto";
/// Register a [`RustCryptoProvider`] in the global registry.
pub fn init() {
ccc_crypto_core::ProviderRegistry::global()
.register(PROVIDER_NAME, Box::new(RustCryptoProvider::new()));
log::info!("[ccc-crypto-rustcrypto] provider registered");
}

View File

@ -0,0 +1,112 @@
//! MACs: HMAC-SHA-2 (`hmac`), keyed BLAKE2b-512 (`blake2`) and one-time
//! Poly1305 (`poly1305`).
//!
//! Keyed BLAKE2b follows the wolfSSL provider: key of 1–64 bytes, 64-byte
//! tag, no salt or personalisation (RFC 7693 keyed mode).
use blake2::Blake2bMac512;
use hmac::{Hmac, KeyInit, Mac};
use poly1305::Poly1305;
use sha2::{Sha256, Sha384, Sha512};
use subtle::ConstantTimeEq;
use ccc_crypto_core::{algorithms::MacAlgorithm, error::CryptoError};
/// Compute a MAC tag over `data`.
pub fn compute_mac(algo: MacAlgorithm, key: &[u8], data: &[u8]) -> Result<Vec<u8>, CryptoError> {
match algo {
MacAlgorithm::HmacSha256 => hmac::<Hmac<Sha256>>(key, data),
MacAlgorithm::HmacSha384 => hmac::<Hmac<Sha384>>(key, data),
MacAlgorithm::HmacSha512 => hmac::<Hmac<Sha512>>(key, data),
MacAlgorithm::Blake2bMac => blake2b_mac(key, data),
MacAlgorithm::Poly1305 => poly1305(key, data),
}
}
/// Verify a MAC tag in constant time. A mismatch is `Ok(false)`.
pub fn verify_mac(
algo: MacAlgorithm,
key: &[u8],
data: &[u8],
mac: &[u8],
) -> Result<bool, CryptoError> {
let expected = compute_mac(algo, key, data)?;
Ok(expected.len() == mac.len() && bool::from(expected.ct_eq(mac)))
}
/// HMAC with any `hmac` instance; any key length is accepted (RFC 2104).
pub(crate) fn hmac<M: Mac + KeyInit>(key: &[u8], data: &[u8]) -> Result<Vec<u8>, CryptoError> {
let mut m = <M as KeyInit>::new_from_slice(key)
.map_err(|_| CryptoError::InvalidKey("HMAC key".into()))?;
m.update(data);
Ok(m.finalize().into_bytes().to_vec())
}
fn blake2b_mac(key: &[u8], data: &[u8]) -> Result<Vec<u8>, CryptoError> {
if key.is_empty() || key.len() > 64 {
return Err(CryptoError::InvalidKey(
"BLAKE2b-MAC: key must be 1–64 bytes".into(),
));
}
let mut m = Blake2bMac512::new_with_salt_and_personal(Some(key), &[], &[])
.map_err(|_| CryptoError::InvalidKey("BLAKE2b-MAC key".into()))?;
m.update(data);
Ok(m.finalize().into_bytes().to_vec())
}
fn poly1305(key: &[u8], data: &[u8]) -> Result<Vec<u8>, CryptoError> {
let p = Poly1305::new_from_slice(key)
.map_err(|_| CryptoError::InvalidKey("Poly1305: key must be 32 bytes".into()))?;
Ok(p.compute_unpadded(data).to_vec())
}
#[cfg(test)]
mod tests {
use super::*;
const ALL: [MacAlgorithm; 5] = [
MacAlgorithm::HmacSha256,
MacAlgorithm::HmacSha384,
MacAlgorithm::HmacSha512,
MacAlgorithm::Blake2bMac,
MacAlgorithm::Poly1305,
];
#[test]
fn tag_lengths_and_verify() {
let key = [0x42u8; 32];
for algo in ALL {
let tag = compute_mac(algo, &key, b"data").unwrap();
assert_eq!(tag.len(), algo.tag_len(), "{}", algo.name());
assert!(verify_mac(algo, &key, b"data", &tag).unwrap());
let mut bad = tag.clone();
bad[0] ^= 1;
assert!(!verify_mac(algo, &key, b"data", &bad).unwrap());
assert!(!verify_mac(algo, &key, b"data", &tag[1..]).unwrap());
assert!(!verify_mac(algo, &key, b"Data", &tag).unwrap());
}
}
#[test]
fn hmac_sha256_rfc4231_tc2() {
let tag = compute_mac(
MacAlgorithm::HmacSha256,
b"Jefe",
b"what do ya want for nothing?",
)
.unwrap();
assert_eq!(
hex::encode(tag),
"5bdcc146bf60754e6a042426089575c75a003f089d2739839dec58b964ec3843"
);
}
#[test]
fn key_length_rules() {
assert!(compute_mac(MacAlgorithm::Blake2bMac, b"", b"x").is_err());
assert!(compute_mac(MacAlgorithm::Blake2bMac, &[1u8; 65], b"x").is_err());
assert!(compute_mac(MacAlgorithm::Blake2bMac, &[1u8; 64], b"x").is_ok());
assert!(compute_mac(MacAlgorithm::Poly1305, &[1u8; 16], b"x").is_err());
assert!(compute_mac(MacAlgorithm::HmacSha512, b"", b"x").is_ok());
}
}

View File

@ -0,0 +1,251 @@
//! Classic McEliece 460896f (`classic-mceliece-rust`, pure Rust), the Ultra
//! conservative KEM layer (U2). Built with the `mceliece` feature.
//!
//! | Private key | Public key | Ciphertext | Secret |
//! |-------------|------------|------------|--------|
//! | 13,608 | 524,160 | 156 | 32 |
//!
//! Keys use the NIST round-4 byte format, so they interoperate with liboqs
//! (`Classic-McEliece-460896f`); the `ccc-crypto-oqs` tests check this both
//! ways.
//!
//! The reference code keeps large matrices on the stack. Every operation
//! runs on a scoped worker thread with [`STACK_SIZE`] bytes of stack, so a
//! caller on a small thread (an iOS secondary thread has 512 KiB, a debug
//! build needs much more than a release one) never overflows. Keys and
//! ciphertexts are copied to the heap, never to the worker's stack.
use rand_core::{CryptoRng, RngCore};
use zeroize::Zeroizing;
use classic_mceliece_rust as cm;
use ccc_crypto_core::{
error::CryptoError,
types::{KemEncapResult, KemKeyPair},
};
/// Public key length in bytes.
pub const PUBLIC_KEY_LEN: usize = cm::CRYPTO_PUBLICKEYBYTES;
/// Private key length in bytes.
pub const PRIVATE_KEY_LEN: usize = cm::CRYPTO_SECRETKEYBYTES;
/// Ciphertext length in bytes.
pub const CIPHERTEXT_LEN: usize = cm::CRYPTO_CIPHERTEXTBYTES;
/// Worker stack size. The R0-6 spike ran a release build on 256 KiB; the
/// margin covers unoptimised builds.
pub const STACK_SIZE: usize = 8 * 1024 * 1024;
const _: () = assert!(PUBLIC_KEY_LEN == 524_160 && CIPHERTEXT_LEN == 156);
/// Run `f` on a worker thread with a [`STACK_SIZE`] stack and wait for it.
fn on_big_stack<T: Send>(f: impl FnOnce() -> T + Send) -> Result<T, CryptoError> {
std::thread::scope(|s| {
std::thread::Builder::new()
.name("ccc-mceliece".into())
.stack_size(STACK_SIZE)
.spawn_scoped(s, f)
.map_err(|e| CryptoError::InternalError(format!("McEliece worker: {e}")))?
.join()
.map_err(|_| CryptoError::InternalError("McEliece worker panicked".into()))
})
}
/// The OS RNG (`getrandom`) behind the `rand_core` 0.6 traits the crate
/// expects. A failing OS RNG panics inside the worker, which surfaces as an
/// `InternalError`, never as a key made from bad randomness.
struct OsRng;
impl RngCore for OsRng {
fn next_u32(&mut self) -> u32 {
rand_core::impls::next_u32_via_fill(self)
}
fn next_u64(&mut self) -> u64 {
rand_core::impls::next_u64_via_fill(self)
}
fn fill_bytes(&mut self, dest: &mut [u8]) {
getrandom::fill(dest).expect("getrandom failed");
}
fn try_fill_bytes(&mut self, dest: &mut [u8]) -> Result<(), rand_core::Error> {
self.fill_bytes(dest);
Ok(())
}
}
impl CryptoRng for OsRng {}
/// Deterministic randomness for the known-answer test, never for real keys:
/// the stream `SHA3-256(label || be64(0)) || SHA3-256(label || be64(1)) || ...`,
/// consumed in order by key generation and then encapsulation. Simple to
/// rebuild elsewhere, so other implementations can reproduce the vector.
pub(crate) struct KatRng {
label: &'static [u8],
counter: u64,
block: [u8; 32],
used: usize,
}
impl KatRng {
pub(crate) fn new(label: &'static [u8]) -> Self {
Self { label, counter: 0, block: [0; 32], used: 32 }
}
}
impl RngCore for KatRng {
fn next_u32(&mut self) -> u32 {
rand_core::impls::next_u32_via_fill(self)
}
fn next_u64(&mut self) -> u64 {
rand_core::impls::next_u64_via_fill(self)
}
fn fill_bytes(&mut self, dest: &mut [u8]) {
use sha3::Digest;
for b in dest {
if self.used == 32 {
let mut h = sha3::Sha3_256::new();
h.update(self.label);
h.update(self.counter.to_be_bytes());
self.block.copy_from_slice(&h.finalize());
self.counter += 1;
self.used = 0;
}
*b = self.block[self.used];
self.used += 1;
}
}
fn try_fill_bytes(&mut self, dest: &mut [u8]) -> Result<(), rand_core::Error> {
self.fill_bytes(dest);
Ok(())
}
}
impl CryptoRng for KatRng {}
fn boxed<const N: usize>(bytes: &[u8], what: &str) -> Result<Box<[u8; N]>, CryptoError> {
if bytes.len() != N {
return Err(CryptoError::InvalidKey(format!(
"Classic-McEliece-460896f: {what} must be {N} bytes"
)));
}
bytes
.to_vec()
.into_boxed_slice()
.try_into()
.map_err(|_| CryptoError::InternalError("length checked above".into()))
}
/// Generate a key pair from `rng` (the OS RNG, or a seeded one for KATs).
pub(crate) fn generate_with<R: RngCore + CryptoRng + Send>(
rng: &mut R,
) -> Result<KemKeyPair, CryptoError> {
on_big_stack(|| {
let (pk, sk) = cm::keypair_boxed(rng);
KemKeyPair {
public_key: pk.as_array().to_vec(),
private_key: sk.as_array().to_vec(),
}
})
}
/// Encapsulate to `public_key` with randomness from `rng`.
pub(crate) fn encapsulate_with<R: RngCore + CryptoRng + Send>(
public_key: &[u8],
rng: &mut R,
) -> Result<KemEncapResult, CryptoError> {
let pk = cm::PublicKey::from(boxed::<PUBLIC_KEY_LEN>(public_key, "public key")?);
on_big_stack(|| {
let (ct, ss) = cm::encapsulate_boxed(&pk, rng);
KemEncapResult {
ciphertext: ct.as_array().to_vec(),
shared_secret: ss.as_array().to_vec(),
}
})
}
/// Generate a key pair with the OS RNG.
pub fn generate() -> Result<KemKeyPair, CryptoError> {
generate_with(&mut OsRng)
}
/// Encapsulate a fresh secret to `public_key`.
pub fn encapsulate(public_key: &[u8]) -> Result<KemEncapResult, CryptoError> {
encapsulate_with(public_key, &mut OsRng)
}
/// Recover the secret from `ciphertext`. A modified ciphertext yields a
/// pseudo-random secret (implicit rejection), not an error.
pub fn decapsulate(
private_key: &[u8],
ciphertext: &[u8],
) -> Result<Zeroizing<Vec<u8>>, CryptoError> {
let sk = cm::SecretKey::from(boxed::<PRIVATE_KEY_LEN>(private_key, "private key")?);
let ct: [u8; CIPHERTEXT_LEN] = ciphertext.try_into().map_err(|_| {
CryptoError::InvalidInput("Classic-McEliece-460896f: wrong ciphertext length".into())
})?;
let ct = cm::Ciphertext::from(ct);
on_big_stack(|| Zeroizing::new(cm::decapsulate_boxed(&ct, &sk).as_array().to_vec()))
}
#[cfg(test)]
mod tests {
use super::*;
use std::time::Instant;
#[test]
fn roundtrip_sizes_and_timings() {
let t = Instant::now();
let kp = generate().unwrap();
let keygen = t.elapsed();
let t = Instant::now();
let enc = encapsulate(&kp.public_key).unwrap();
let encap = t.elapsed();
let t = Instant::now();
let ss = decapsulate(&kp.private_key, &enc.ciphertext).unwrap();
let decap = t.elapsed();
assert_eq!(*ss, enc.shared_secret);
assert_eq!(kp.public_key.len(), 524_160);
assert_eq!(kp.private_key.len(), 13_608);
assert_eq!(enc.ciphertext.len(), 156);
assert_eq!(ss.len(), 32);
println!(
"Classic-McEliece-460896f: pk {} sk {} ct {}; keygen {keygen:?} encap {encap:?} \
decap {decap:?}",
kp.public_key.len(),
kp.private_key.len(),
enc.ciphertext.len()
);
}
#[test]
fn runs_from_a_small_caller_stack() {
// A 128 KiB caller thread is far below what keygen needs.
std::thread::Builder::new()
.stack_size(128 * 1024)
.spawn(|| {
let kp = generate().unwrap();
let enc = encapsulate(&kp.public_key).unwrap();
let ss = decapsulate(&kp.private_key, &enc.ciphertext).unwrap();
assert_eq!(*ss, enc.shared_secret);
})
.unwrap()
.join()
.unwrap();
}
#[test]
fn implicit_rejection_and_lengths() {
let kp = generate().unwrap();
let enc = encapsulate(&kp.public_key).unwrap();
let mut ct = enc.ciphertext.clone();
ct[0] ^= 1;
assert_ne!(*decapsulate(&kp.private_key, &ct).unwrap(), enc.shared_secret);
assert!(encapsulate(&kp.public_key[1..]).is_err());
assert!(decapsulate(&kp.private_key[1..], &enc.ciphertext).is_err());
assert!(decapsulate(&kp.private_key, &enc.ciphertext[1..]).is_err());
}
}

View File

@ -0,0 +1,182 @@
//! [`RustCryptoProvider`]: the [`CryptoProvider`] implementation.
use std::sync::OnceLock;
use zeroize::Zeroizing;
use ccc_crypto_core::{
algorithms::{AeadAlgorithm, HashAlgorithm, KdfAlgorithm, KemAlgorithm, MacAlgorithm},
capabilities::ProviderCapabilities,
error::CryptoError,
provider::{AeadProvider, CryptoProvider, HashProvider, KdfProvider, KemProvider, MacProvider},
types::{BenchmarkReport, KemEncapResult, KemKeyPair, SelfTestReport},
};
use crate::{aead, capabilities, hash, kdf, kem, mac, self_test, PROVIDER_NAME};
/// The pure-Rust provider. Self-test, benchmark and capabilities are
/// computed lazily on first use and cached.
#[derive(Default)]
pub struct RustCryptoProvider {
caps: OnceLock<ProviderCapabilities>,
bench: OnceLock<BenchmarkReport>,
kats: OnceLock<SelfTestReport>,
}
impl RustCryptoProvider {
/// Create a provider; no work is done until it is queried.
pub fn new() -> Self {
Self::default()
}
fn kats(&self) -> &SelfTestReport {
self.kats.get_or_init(self_test::run)
}
fn bench(&self) -> &BenchmarkReport {
self.bench.get_or_init(|| {
log::info!("[ccc-crypto-rustcrypto] running throughput benchmark…");
capabilities::run_benchmark()
})
}
}
impl AeadProvider for RustCryptoProvider {
fn encrypt_aead(
&self,
algo: AeadAlgorithm,
key: &[u8],
nonce: &[u8],
plaintext: &[u8],
aad: &[u8],
) -> Result<Vec<u8>, CryptoError> {
aead::encrypt(algo, key, nonce, plaintext, aad)
}
fn decrypt_aead(
&self,
algo: AeadAlgorithm,
key: &[u8],
nonce: &[u8],
ciphertext_and_tag: &[u8],
aad: &[u8],
) -> Result<Vec<u8>, CryptoError> {
aead::decrypt(algo, key, nonce, ciphertext_and_tag, aad)
}
}
impl KdfProvider for RustCryptoProvider {
fn derive_key(
&self,
algo: KdfAlgorithm,
ikm: &[u8],
salt: &[u8],
info: &[u8],
length: usize,
) -> Result<Zeroizing<Vec<u8>>, CryptoError> {
kdf::derive_key(algo, ikm, salt, info, length)
}
}
impl MacProvider for RustCryptoProvider {
fn compute_mac(
&self,
algo: MacAlgorithm,
key: &[u8],
data: &[u8],
) -> Result<Vec<u8>, CryptoError> {
mac::compute_mac(algo, key, data)
}
fn verify_mac(
&self,
algo: MacAlgorithm,
key: &[u8],
data: &[u8],
mac_bytes: &[u8],
) -> Result<bool, CryptoError> {
mac::verify_mac(algo, key, data, mac_bytes)
}
}
impl HashProvider for RustCryptoProvider {
fn hash(&self, algo: HashAlgorithm, data: &[u8]) -> Result<Vec<u8>, CryptoError> {
hash::hash(algo, data)
}
}
impl KemProvider for RustCryptoProvider {
fn generate_keypair(&self, algo: KemAlgorithm) -> Result<KemKeyPair, CryptoError> {
kem::generate_keypair(algo)
}
fn encapsulate(
&self,
algo: KemAlgorithm,
public_key: &[u8],
) -> Result<KemEncapResult, CryptoError> {
kem::encapsulate(algo, public_key)
}
fn decapsulate(
&self,
algo: KemAlgorithm,
private_key: &[u8],
ciphertext: &[u8],
) -> Result<Zeroizing<Vec<u8>>, CryptoError> {
kem::decapsulate(algo, private_key, ciphertext)
}
}
impl CryptoProvider for RustCryptoProvider {
fn provider_name(&self) -> &'static str {
PROVIDER_NAME
}
/// Not a FIPS 140-3 module; it never supplies a suite's vetted layer in
/// release builds (D-26).
fn fips_mode(&self) -> bool {
false
}
fn capabilities(&self) -> ProviderCapabilities {
self.caps
.get_or_init(|| capabilities::probe_capabilities(self.kats(), Some(self.bench())))
.clone()
}
fn self_test(&self) -> SelfTestReport {
self.kats().clone()
}
fn benchmark(&self) -> BenchmarkReport {
self.bench().clone()
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn identity_and_self_test() {
let p = RustCryptoProvider::new();
assert_eq!(p.provider_name(), "rustcrypto");
assert!(!p.fips_mode());
assert!(p.self_test().all_passed);
}
#[test]
fn trait_objects_work() {
let p: Box<dyn CryptoProvider> = Box::new(RustCryptoProvider::new());
let key = [1u8; 32];
let nonce = [2u8; 12];
let ct = p
.encrypt_aead(AeadAlgorithm::AesGcmSiv256, &key, &nonce, b"m", b"a")
.unwrap();
let pt = p
.decrypt_aead(AeadAlgorithm::AesGcmSiv256, &key, &nonce, &ct, b"a")
.unwrap();
assert_eq!(pt, b"m");
}
}

View File

@ -0,0 +1,563 @@
//! Embedded known-answer self-test (KAT) for every algorithm the provider
//! offers.
//!
//! Sources:
//!
//! - AES-256-GCM: NIST SP 800-38D test case 16.
//! - AES-256-GCM-SIV: RFC 8452 appendix C.2.
//! - ChaCha20-Poly1305: RFC 8439 §2.8.2; Poly1305: RFC 8439 §2.5.2.
//! - XChaCha20-Poly1305: draft-irtf-cfrg-xchacha-03 §A.3.1.
//! - Ascon-AEAD128: NIST SP 800-232 reference KAT (`LWC_AEAD_KAT_128_128`, count 1059).
//! - SHA-2 / SHA-3: FIPS 180-4 / FIPS 202 "abc"; BLAKE2b: RFC 7693 appendix A
//! and the reference keyed KAT.
//! - HMAC: RFC 4231 test case 2; HKDF: RFC 5869 test case 1 (SHA-256) and
//! the same inputs for SHA-384/512, checked against OpenSSL 3.6.
//! - Argon2id: RFC 9106 §5.3 (the core with secret and associated data).
//! - X25519: RFC 7748 §6.1.
//! - ML-KEM-768/1024: seed keys from the IETF LAMPS examples (seed 00..3f);
//! public keys, deterministic-encapsulation ciphertexts and secrets checked
//! against OpenSSL 3.6 (`ikme`). Large values are pinned as SHA3-256.
//! - X-Wing: draft-connolly-cfrg-xwing-kem test vector 0.
//! - Classic McEliece 460896f: no published vector uses an RNG we can
//! rebuild cheaply, so the randomness is the SHA3-256 counter stream of
//! `mceliece::KatRng` (label `ccc-kat/mceliece460896f`). The values were
//! produced by `classic-mceliece-rust` 3.1.0 and reproduced by liboqs
//! 0.13.0 fed the same stream (the `ccc-crypto-oqs` cross-check test).
use ccc_crypto_core::{
algorithms::{AeadAlgorithm, HashAlgorithm, KdfAlgorithm, KemAlgorithm, MacAlgorithm},
types::{AlgoTestResult, SelfTestReport},
};
use crate::{aead, hash, kdf, kem, mac};
type Check = fn() -> Result<(), String>;
/// Every KAT: (algorithm ID, test name, check).
const KATS: &[(u32, &str, Check)] = &[
(
AeadAlgorithm::AesGcm256 as u32,
"AES-256-GCM SP 800-38D TC16",
aes_gcm,
),
(
AeadAlgorithm::AesGcmSiv256 as u32,
"AES-256-GCM-SIV RFC 8452 C.2",
aes_gcm_siv,
),
(
AeadAlgorithm::ChaCha20Poly1305 as u32,
"ChaCha20-Poly1305 RFC 8439 2.8.2",
chacha,
),
(
AeadAlgorithm::XChaCha20Poly1305 as u32,
"XChaCha20-Poly1305 draft A.3.1",
xchacha,
),
(
AeadAlgorithm::AsconAead128 as u32,
"Ascon-AEAD128 SP 800-232 KAT",
ascon,
),
(HashAlgorithm::Sha256 as u32, "SHA-256 abc", || {
digest(HashAlgorithm::Sha256, SHA256_ABC)
}),
(HashAlgorithm::Sha384 as u32, "SHA-384 abc", || {
digest(HashAlgorithm::Sha384, SHA384_ABC)
}),
(HashAlgorithm::Sha512 as u32, "SHA-512 abc", || {
digest(HashAlgorithm::Sha512, SHA512_ABC)
}),
(HashAlgorithm::Sha3_256 as u32, "SHA3-256 abc", || {
digest(HashAlgorithm::Sha3_256, SHA3_256_ABC)
}),
(HashAlgorithm::Sha3_512 as u32, "SHA3-512 abc", || {
digest(HashAlgorithm::Sha3_512, SHA3_512_ABC)
}),
(HashAlgorithm::Blake2b512 as u32, "BLAKE2b-512 abc", || {
digest(HashAlgorithm::Blake2b512, BLAKE2B_ABC)
}),
(
MacAlgorithm::HmacSha256 as u32,
"HMAC-SHA-256 RFC 4231 TC2",
|| hmac(MacAlgorithm::HmacSha256, HMAC256_TC2),
),
(
MacAlgorithm::HmacSha384 as u32,
"HMAC-SHA-384 RFC 4231 TC2",
|| hmac(MacAlgorithm::HmacSha384, HMAC384_TC2),
),
(
MacAlgorithm::HmacSha512 as u32,
"HMAC-SHA-512 RFC 4231 TC2",
|| hmac(MacAlgorithm::HmacSha512, HMAC512_TC2),
),
(
MacAlgorithm::Blake2bMac as u32,
"BLAKE2b-MAC keyed KAT",
blake2b_mac,
),
(
MacAlgorithm::Poly1305 as u32,
"Poly1305 RFC 8439 2.5.2",
poly1305,
),
(
KdfAlgorithm::Sha256 as u32,
"HKDF-SHA-256 RFC 5869 TC1",
|| hkdf(KdfAlgorithm::Sha256, HKDF256_TC1),
),
(
KdfAlgorithm::Sha384 as u32,
"HKDF-SHA-384 TC1 inputs",
|| hkdf(KdfAlgorithm::Sha384, HKDF384_TC1),
),
(
KdfAlgorithm::Sha512 as u32,
"HKDF-SHA-512 TC1 inputs",
|| hkdf(KdfAlgorithm::Sha512, HKDF512_TC1),
),
(
KdfAlgorithm::Blake2b512 as u32,
"BLAKE2b-512 KDF",
blake2b_kdf,
),
(
KdfAlgorithm::Argon2id as u32,
"Argon2id RFC 9106 5.3",
argon2id,
),
(KemAlgorithm::X25519 as u32, "X25519 RFC 7748 6.1", x25519),
(
KemAlgorithm::MlKem768 as u32,
"ML-KEM-768 seed KAT",
mlkem768,
),
(
KemAlgorithm::MlKem1024 as u32,
"ML-KEM-1024 seed KAT",
mlkem1024,
),
(KemAlgorithm::XWing as u32, "X-Wing draft vector 0", xwing),
#[cfg(feature = "mceliece")]
(
KemAlgorithm::ClassicMcEliece460896f as u32,
"Classic-McEliece-460896f seeded KAT",
mceliece460896f,
),
];
/// Run every KAT. Never panics; failures are reported per algorithm.
pub fn run() -> SelfTestReport {
let results = KATS
.iter()
.map(|(id, name, check)| {
let outcome = check();
AlgoTestResult {
algo_id: *id,
algo_name: (*name).into(),
passed: outcome.is_ok(),
error_message: outcome.err(),
}
})
.collect();
SelfTestReport::finalise("rustcrypto", results)
}
// ── Helpers ──────────────────────────────────────────────────────────────────
fn hx(s: &str) -> Vec<u8> {
(0..s.len() / 2)
.map(|i| u8::from_str_radix(&s[2 * i..2 * i + 2], 16).unwrap_or(0))
.collect()
}
fn expect(what: &str, got: &[u8], want_hex: &str) -> Result<(), String> {
if got == hx(want_hex).as_slice() {
Ok(())
} else {
Err(format!("{what}: output mismatch"))
}
}
fn sha3(data: &[u8]) -> Vec<u8> {
hash::hash(HashAlgorithm::Sha3_256, data).unwrap_or_default()
}
fn e<E: core::fmt::Display>(err: E) -> String {
err.to_string()
}
// ── AEAD ─────────────────────────────────────────────────────────────────────
fn aead_kat(
algo: AeadAlgorithm,
key: &str,
nonce: &str,
aad: &str,
pt: &str,
ct: &str,
) -> Result<(), String> {
let (key, nonce, aad, pt) = (hx(key), hx(nonce), hx(aad), hx(pt));
let sealed = aead::encrypt(algo, &key, &nonce, &pt, &aad).map_err(e)?;
expect("seal", &sealed, ct)?;
let opened = aead::decrypt(algo, &key, &nonce, &sealed, &aad).map_err(e)?;
if opened != pt {
return Err("open: plaintext mismatch".into());
}
let mut bad = sealed;
let last = bad.len() - 1;
bad[last] ^= 0x80;
if aead::decrypt(algo, &key, &nonce, &bad, &aad).is_ok() {
return Err("open accepted a tampered tag".into());
}
Ok(())
}
const RFC8439_KEY: &str = "808182838485868788898a8b8c8d8e8f909192939495969798999a9b9c9d9e9f";
const RFC8439_AAD: &str = "50515253c0c1c2c3c4c5c6c7";
const SUNSCREEN: &str = "4c616469657320616e642047656e746c656d656e206f662074686520636c6173\
73206f66202739393a204966204920636f756c64206f6666657220796f75206f6e6c79206f6e6520746970\
20666f7220746865206675747572652c2073756e73637265656e20776f756c642062652069742e";
fn aes_gcm() -> Result<(), String> {
aead_kat(
AeadAlgorithm::AesGcm256,
"feffe9928665731c6d6a8f9467308308feffe9928665731c6d6a8f9467308308",
"cafebabefacedbaddecaf888",
"feedfacedeadbeeffeedfacedeadbeefabaddad2",
"d9313225f88406e5a55909c5aff5269a86a7a9531534f7da2e4c303d8a318a72\
1c3c0c95956809532fcf0e2449a6b525b16aedf5aa0de657ba637b39",
"522dc1f099567d07f47f37a32a84427d643a8cdcbfe5c0c97598a2bd2555d1aa\
8cb08e48590dbb3da7b08b1056828838c5f61e6393ba7a0abcc9f662\
76fc6ece0f4e1768cddf8853bb2d551b",
)
}
fn aes_gcm_siv() -> Result<(), String> {
let key = "0100000000000000000000000000000000000000000000000000000000000000";
let nonce = "030000000000000000000000";
aead_kat(
AeadAlgorithm::AesGcmSiv256,
key,
nonce,
"",
"",
"07f5f4169bbf55a8400cd47ea6fd400f",
)?;
aead_kat(
AeadAlgorithm::AesGcmSiv256,
key,
nonce,
"",
"0100000000000000",
"c2ef328e5c71c83b843122130f7364b761e0b97427e3df28",
)
}
fn chacha() -> Result<(), String> {
aead_kat(
AeadAlgorithm::ChaCha20Poly1305,
RFC8439_KEY,
"070000004041424344454647",
RFC8439_AAD,
SUNSCREEN,
"d31a8d34648e60db7b86afbc53ef7ec2a4aded51296e08fea9e2b5a736ee62d63dbea45e8ca967128\
2fafb69da92728b1a71de0a9e060b2905d6a5b67ecd3b3692ddbd7f2d778b8c9803aee328091b58fa\
b324e4fad675945585808b4831d7bc3ff4def08e4b7a9de576d26586cec64b6116\
1ae10b594f09e26a7e902ecbd0600691",
)
}
fn xchacha() -> Result<(), String> {
aead_kat(
AeadAlgorithm::XChaCha20Poly1305,
RFC8439_KEY,
"404142434445464748494a4b4c4d4e4f5051525354555657",
RFC8439_AAD,
SUNSCREEN,
"bd6d179d3e83d43b9576579493c0e939572a1700252bfaccbed2902c21396cbb731c7f1b0b4aa6440\
bf3a82f4eda7e39ae64c6708c54c216cb96b72e1213b4522f8c9ba40db5d945b11b69b982c1bb9e3f\
3fac2bc369488f76b2383565d3fff921f9664c97637da9768812f615c68b13b52e\
c0875924c1c7987947deafd8780acf49",
)
}
fn ascon() -> Result<(), String> {
aead_kat(
AeadAlgorithm::AsconAead128,
"000102030405060708090a0b0c0d0e0f",
"000102030405060708090a0b0c0d0e0f",
"0001",
"000102030405060708090a0b0c0d0e0f101112131415161718191a1b1c1d1e1f",
"49e50547ca0c754784f2a6f936ed9497c3a556d34de4cc23f3c21cdb6d447cdb\
0f7324dec1d9f0b3c2125ea5aad85a12",
)
}
// ── Hash ─────────────────────────────────────────────────────────────────────
const SHA256_ABC: &str = "ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad";
const SHA384_ABC: &str = "cb00753f45a35e8bb5a03d699ac65007272c32ab0eded1631a8b605a43ff5bed\
8086072ba1e7cc2358baeca134c825a7";
const SHA512_ABC: &str = "ddaf35a193617abacc417349ae20413112e6fa4e89a97ea20a9eeee64b55d39a\
2192992a274fc1a836ba3c23a3feebbd454d4423643ce80e2a9ac94fa54ca49f";
const SHA3_256_ABC: &str = "3a985da74fe225b2045c172d6bd390bd855f086e3e9d525b46bfe24511431532";
const SHA3_512_ABC: &str = "b751850b1a57168a5693cd924b6b096e08f621827444f70d884f5d0240d2712e\
10e116e9192af3c91a7ec57647e3934057340b4cf408d5a56592f8274eec53f0";
const BLAKE2B_ABC: &str = "ba80a53f981c4d0d6a2797b69f12f6e94c212f14685ac4b74b12bb6fdbffa2d1\
7d87c5392aab792dc252d5de4533cc9518d38aa8dbf1925ab92386edd4009923";
fn digest(algo: HashAlgorithm, want: &str) -> Result<(), String> {
expect("digest", &hash::hash(algo, b"abc").map_err(e)?, want)
}
// ── MAC ──────────────────────────────────────────────────────────────────────
const HMAC256_TC2: &str = "5bdcc146bf60754e6a042426089575c75a003f089d2739839dec58b964ec3843";
const HMAC384_TC2: &str = "af45d2e376484031617f78d2b58a6b1b9c7ef464f5a01b47e42ec3736322445e\
8e2240ca5e69e2c78b3239ecfab21649";
const HMAC512_TC2: &str = "164b7a7bfcf819e2e395fbe73b56e0a387bd64222e831fd610270cd7ea250554\
9758bf75c05a994a6d034f65f8f0e6fdcaeab1a34d4a6b4b636e070a38bce737";
fn mac_kat(algo: MacAlgorithm, key: &[u8], data: &[u8], want: &str) -> Result<(), String> {
let tag = mac::compute_mac(algo, key, data).map_err(e)?;
expect("tag", &tag, want)?;
if !mac::verify_mac(algo, key, data, &tag).map_err(e)? {
return Err("verify rejected a valid tag".into());
}
let mut bad = tag;
bad[0] ^= 1;
if mac::verify_mac(algo, key, data, &bad).map_err(e)? {
return Err("verify accepted a tampered tag".into());
}
Ok(())
}
fn hmac(algo: MacAlgorithm, want: &str) -> Result<(), String> {
mac_kat(algo, b"Jefe", b"what do ya want for nothing?", want)
}
fn blake2b_mac() -> Result<(), String> {
let key: Vec<u8> = (0u8..64).collect();
mac_kat(
MacAlgorithm::Blake2bMac,
&key,
b"",
"10ebb67700b1868efb4417987acf4690ae9d972fb7a590c2f02871799aaa4786\
b5e996e8f0f4eb981fc214b005f42d2ff4233499391653df7aefcbc13fc51568",
)
}
fn poly1305() -> Result<(), String> {
mac_kat(
MacAlgorithm::Poly1305,
&hx("85d6be7857556d337f4452fe42d506a80103808afb0db2fd4abff6af4149f51b"),
b"Cryptographic Forum Research Group",
"a8061dc1305136c6c22b8baf0c0127a9",
)
}
// ── KDF ──────────────────────────────────────────────────────────────────────
const HKDF256_TC1: &str = "3cb25f25faacd57a90434f64d0362f2a2d2d0a90cf1a5a4c5db02d56ecc4c5bf\
34007208d5b887185865";
const HKDF384_TC1: &str = "9b5097a86038b805309076a44b3a9f38063e25b516dcbf369f394cfab43685f7\
48b6457763e4f0204fc5";
const HKDF512_TC1: &str = "832390086cda71fb47625bb5ceb168e4c8e26a1a16ed34d9fc7fe92c14815793\
38da362cb8d9f925d7cb";
fn hkdf(algo: KdfAlgorithm, want: &str) -> Result<(), String> {
let okm = kdf::derive_key(
algo,
&hx("0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b"),
&hx("000102030405060708090a0b0c"),
&hx("f0f1f2f3f4f5f6f7f8f9"),
42,
)
.map_err(e)?;
expect("okm", &okm, want)
}
fn blake2b_kdf() -> Result<(), String> {
// BLAKE2b-512(ikm || salt || info) with "a", "b", "c" is BLAKE2b-512("abc").
let okm = kdf::derive_key(KdfAlgorithm::Blake2b512, b"a", b"b", b"c", 64).map_err(e)?;
expect("okm", &okm, BLAKE2B_ABC)
}
fn argon2id() -> Result<(), String> {
use argon2::{Algorithm, Argon2, AssociatedData, ParamsBuilder, Version};
let params = ParamsBuilder::new()
.m_cost(32)
.t_cost(3)
.p_cost(4)
.data(AssociatedData::new(&[0x04; 12]).map_err(e)?)
.output_len(32)
.build()
.map_err(e)?;
let ctx = Argon2::new_with_secret(&[0x03; 8], Algorithm::Argon2id, Version::V0x13, params)
.map_err(e)?;
let mut out = [0u8; 32];
ctx.hash_password_into(&[0x01; 32], &[0x02; 16], &mut out)
.map_err(e)?;
expect(
"tag",
&out,
"0d640df58d78766c08c037a34a8b53c9d01ef0452d75b65eb52520e96b01e659",
)?;
// The provider entry point (no secret or AD) must run with small costs.
kdf::argon2id(b"password", b"somesalt", 32, 32, 1, 1).map_err(e)?;
Ok(())
}
// ── KEM ──────────────────────────────────────────────────────────────────────
fn x25519() -> Result<(), String> {
let alice = hx("77076d0a7318a57d3c16c17251b26645df4c2f87ebc0992ab177fba51db92c2a");
let alice_pub = "8520f0098930a754748b7ddcb43ef75a0dbf3a0d26381af4eba4a98eaa9b4e6a";
let bob = hx("5dab087e624a8a4b79e17f8b83800ee66f3bb1292618b6fd1c2f8b27ff88e0eb");
let bob_pub = hx("de9edb7d7b7dc1b4d35b61c2ece435373f8343c85b78674dadfc7e146f882b4f");
let shared = "4a5d9d5ba4ce2de1728e3bf480350f25e07e21c947d19e3376f09b3c1e161742";
// Encapsulating with Alice's key as the ephemeral gives her public key as
// the ciphertext; Bob decapsulates it.
let enc = kem::x25519_encapsulate_deterministic(&alice, &bob_pub).map_err(e)?;
expect("ciphertext", &enc.ciphertext, alice_pub)?;
expect("encap secret", &enc.shared_secret, shared)?;
let ss = kem::decapsulate(KemAlgorithm::X25519, &bob, &enc.ciphertext).map_err(e)?;
expect("decap secret", &ss, shared)
}
struct MlKemKat {
pk_sha3: &'static str,
ct_sha3: &'static str,
ss: &'static str,
}
/// Encapsulation randomness used with OpenSSL `-pkeyopt hexikme:` for both sets.
const MLKEM_M: &str = "4041424344454647484950515253545556575859606162636465666768696a6b";
fn mlkem_kat(
algo: KemAlgorithm,
public_key: fn(&[u8]) -> Result<Vec<u8>, ccc_crypto_core::error::CryptoError>,
encap: fn(
&[u8],
&[u8; 32],
) -> Result<
ccc_crypto_core::types::KemEncapResult,
ccc_crypto_core::error::CryptoError,
>,
kat: &MlKemKat,
) -> Result<(), String> {
let seed: Vec<u8> = (0u8..64).collect();
let pk = public_key(&seed).map_err(e)?;
expect("public key", &sha3(&pk), kat.pk_sha3)?;
let mut m = [0u8; 32];
m.copy_from_slice(&hx(MLKEM_M));
let enc = encap(&pk, &m).map_err(e)?;
expect("ciphertext", &sha3(&enc.ciphertext), kat.ct_sha3)?;
expect("encap secret", &enc.shared_secret, kat.ss)?;
let ss = kem::decapsulate(algo, &seed, &enc.ciphertext).map_err(e)?;
expect("decap secret", &ss, kat.ss)
}
fn mlkem768() -> Result<(), String> {
mlkem_kat(
KemAlgorithm::MlKem768,
kem::mlkem768::public_key,
kem::mlkem768::encapsulate_deterministic,
&MlKemKat {
pk_sha3: "a24e16d8f8f9383a95b77050f4d9fd2f5733eec1d63ef3c23ebf9918173669a7",
ct_sha3: "c5190623f119891d14904e62cd28a79677df85afe5ad9151cb962caa00002de4",
ss: "71e6c52c0066736b5d2e9cfe2d9694804a4c6dd57c9ed1d615df96c018782de3",
},
)
}
fn mlkem1024() -> Result<(), String> {
mlkem_kat(
KemAlgorithm::MlKem1024,
kem::mlkem1024::public_key,
kem::mlkem1024::encapsulate_deterministic,
&MlKemKat {
pk_sha3: "61349e5c131a7e116a0463861d7d18663c5627c38c7147ddaadfd48acd7a4535",
ct_sha3: "6e264ea88c427017fceeebf87f12c106bb2e511843d5ed525fdd4d45a0205daa",
ss: "ccff2f30e61151de4c3257ca1d3a8a9de661b81c5ba34efe9b1a4af770caf9df",
},
)
}
fn xwing() -> Result<(), String> {
let seed = hx("7f9c2ba4e88f827d616045507605853ed73b8093f6efbc88eb1a6eacfa66ef26");
let ss_want = "d2df0522128f09dd8e2c92b1e905c793d8f57a54c3da25861f10bf4ca613e384";
let pk = kem::xwing_public_key(&seed).map_err(e)?;
expect(
"public key",
&sha3(&pk),
"5121745904643ad9dfacca7869292c19a8a69533b53e60666b7db910b4ad6367",
)?;
let mut eseed = [0u8; 64];
eseed.copy_from_slice(&hx(
"3cb1eea988004b93103cfb0aeefd2a686e01fa4a58e8a3639ca8a1e3f9ae57e2\
35b8cc873c23dc62b8d260169afa2f75ab916a58d974918835d25e6a435085b2",
));
let enc = kem::xwing_encapsulate_deterministic(&pk, &eseed).map_err(e)?;
expect(
"ciphertext",
&sha3(&enc.ciphertext),
"c0abd149f83f45324ac3a7ddc7606c71f257e5ea86113522834a0ee1bcb34e3e",
)?;
expect("encap secret", &enc.shared_secret, ss_want)?;
let ss = kem::decapsulate(KemAlgorithm::XWing, &seed, &enc.ciphertext).map_err(e)?;
expect("decap secret", &ss, ss_want)
}
/// Keygen then encapsulation from one seeded stream; values pinned as SHA3-256.
#[cfg(feature = "mceliece")]
fn mceliece460896f() -> Result<(), String> {
use crate::mceliece;
let mut rng = mceliece::KatRng::new(b"ccc-kat/mceliece460896f");
let kp = mceliece::generate_with(&mut rng).map_err(e)?;
expect("public key", &sha3(&kp.public_key), MCE_PK_SHA3)?;
expect("private key", &sha3(&kp.private_key), MCE_SK_SHA3)?;
let enc = mceliece::encapsulate_with(&kp.public_key, &mut rng).map_err(e)?;
expect("ciphertext", &sha3(&enc.ciphertext), MCE_CT_SHA3)?;
expect("encap secret", &enc.shared_secret, MCE_SS)?;
let ss = mceliece::decapsulate(&kp.private_key, &enc.ciphertext).map_err(e)?;
expect("decap secret", &ss, MCE_SS)
}
#[cfg(feature = "mceliece")]
const MCE_PK_SHA3: &str =
"e0e4f4faf27adcfedb35b8822a05f7938e80c62fd492f726e6ff76a549b43194";
#[cfg(feature = "mceliece")]
const MCE_SK_SHA3: &str =
"59bf486dc9b6c93f6eb9854821eb237000b421c92710a2172c10570a6a014cf4";
#[cfg(feature = "mceliece")]
const MCE_CT_SHA3: &str =
"a69376ae13d09fe536c544ea6049ee22f64d73761d209e3b44528f646d52a358";
#[cfg(feature = "mceliece")]
const MCE_SS: &str =
"ce2f2240ab5e51e313b7a1ee3c30e2f1882e37fbba0c8f5cb337b2e01d3e4cf3";
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn all_kats_pass() {
let report = run();
for r in &report.results {
assert!(r.passed, "{}: {:?}", r.algo_name, r.error_message);
}
assert!(report.all_passed);
assert_eq!(report.provider_name, "rustcrypto");
}
#[test]
fn kat_detects_a_wrong_answer() {
assert!(expect("x", b"abc", "616264").is_err());
assert!(expect("x", b"abc", "616263").is_ok());
}
}

View File

@ -28,3 +28,6 @@ hex = "0.4"
# Enable this when building without the wolfSSL C library
# (e.g. on docs.rs, or for type-checking in CI without cmake).
stub_ffi = []
# Build against the commercial wolfCrypt FIPS 140-3 bundle at
# WOLFSSL_FIPS_SOURCE_DIR (required; never falls back to open source).
fips = []

View File

@ -18,6 +18,19 @@
//! Android toolchain. Cargokit/Gradle sets this automatically; when
//! invoking `cargo` directly make sure the variable is exported in your
//! shell session.
//!
//! With the `fips` feature (see "FIPS 140-3 builds" in the crate docs):
//!
//! * `WOLFSSL_FIPS_SOURCE_DIR` – Required. The unpacked commercial
//! wolfCrypt FIPS 140-3 bundle. There is no fallback to the open-source
//! tree: the build fails when it is missing or is not a FIPS bundle.
//! * `WOLFSSL_FIPS_VERSION` – `v5` (default; certificate #4718, wolfCrypt
//! 5.2.1) or `v6`; passed as `--enable-fips=<version>`.
//! * `WOLFSSL_FIPS_CORE_HASH` – The in-core integrity hash of the final
//! binary, passed as `-DWOLFCRYPT_FIPS_CORE_HASH_VALUE`. Without it the
//! power-on self-test fails and `fips_mode()` is `false`.
//! * `WOLFSSL_FIPS_CONFIGURE_ARGS` – Extra `configure` arguments, e.g.
//! `--host=aarch64-linux-android` for cross builds.
use std::{
env,
@ -25,6 +38,11 @@ use std::{
};
fn main() {
let fips = env::var("CARGO_FEATURE_FIPS").is_ok();
if fips && env::var("CARGO_FEATURE_STUB_FFI").is_ok() {
panic!("\n\nThe `fips` and `stub_ffi` features cannot be combined.\n");
}
// When the `stub_ffi` feature is enabled (e.g. for type-checking without
// the wolfSSL C library), skip all build steps and write an empty bindings
// file so the `include!()` in lib.rs still compiles.
@ -42,7 +60,10 @@ fn main() {
// ── 1. Locate wolfSSL ────────────────────────────────────────────────────
let (include_dir, lib_dir) = if let Ok(install_dir) = env::var("WOLFSSL_INSTALL_DIR") {
let (include_dir, lib_dir) = if fips {
// Never fall back to the open-source build.
build_wolfssl_fips(&out_dir)
} else if let Ok(install_dir) = env::var("WOLFSSL_INSTALL_DIR") {
// Use a pre-installed wolfSSL — skip the CMake build.
let p = PathBuf::from(&install_dir);
println!(
@ -89,6 +110,14 @@ fn main() {
// Re-run the build script if any of these change.
println!("cargo:rerun-if-env-changed=WOLFSSL_SOURCE_DIR");
println!("cargo:rerun-if-env-changed=WOLFSSL_INSTALL_DIR");
for var in [
"WOLFSSL_FIPS_SOURCE_DIR",
"WOLFSSL_FIPS_VERSION",
"WOLFSSL_FIPS_CORE_HASH",
"WOLFSSL_FIPS_CONFIGURE_ARGS",
] {
println!("cargo:rerun-if-env-changed={var}");
}
// ── 3. Generate FFI bindings via bindgen ─────────────────────────────────
@ -201,6 +230,110 @@ fn build_wolfssl_cmake(source_dir: &Path, _out_dir: &Path) -> (PathBuf, PathBuf)
(include_dir, lib_dir)
}
/// The `fips` feature was asked for but no bundle was given.
const FIPS_SOURCE_MISSING: &str = "\n\n\
The `fips` feature needs the commercial wolfCrypt FIPS 140-3 bundle.\n\
Set WOLFSSL_FIPS_SOURCE_DIR to the unpacked bundle, for example:\n \
export WOLFSSL_FIPS_SOURCE_DIR=$HOME/src/wolfssl-5.2.1-commercial-fips-v5\n\
There is no fallback to the open-source wolfSSL tree.\n";
/// Files only a FIPS bundle has; the open-source tree lacks the first two.
const FIPS_BUNDLE_MARKERS: [&str; 3] =
["wolfcrypt/src/fips.c", "wolfcrypt/src/fips_test.c", "configure"];
/// Build the commercial wolfCrypt FIPS bundle with its own autotools build.
/// wolfSSL's CMake has no FIPS support (its CMakeLists marks it as a TODO),
/// so the bundle's `configure` is the only supported route. Returns
/// `(include_dir, lib_dir)`.
fn build_wolfssl_fips(out_dir: &Path) -> (PathBuf, PathBuf) {
let source = env::var_os("WOLFSSL_FIPS_SOURCE_DIR")
.filter(|v| !v.is_empty())
.map(PathBuf::from)
.unwrap_or_else(|| panic!("{FIPS_SOURCE_MISSING}"));
for marker in FIPS_BUNDLE_MARKERS {
if !source.join(marker).exists() {
panic!(
"\n\nWOLFSSL_FIPS_SOURCE_DIR={} is not a wolfCrypt FIPS bundle \
({marker} is missing).\n{FIPS_SOURCE_MISSING}",
source.display()
);
}
}
if env::var_os("WOLFSSL_INSTALL_DIR").is_some() {
panic!("\n\nWOLFSSL_INSTALL_DIR cannot be used with the `fips` feature.\n");
}
if env::var("CARGO_CFG_TARGET_OS").as_deref() == Ok("windows") {
panic!(
"\n\nFIPS builds for Windows use the bundle's IDE/WIN10 project, \
not this build script.\n"
);
}
let version = env::var("WOLFSSL_FIPS_VERSION").unwrap_or_else(|_| "v5".into());
if !matches!(version.as_str(), "v5" | "v6") {
panic!("\n\nWOLFSSL_FIPS_VERSION must be v5 or v6, not {version:?}.\n");
}
println!(
"cargo:warning=Building wolfCrypt FIPS {version} from {}",
source.display()
);
// configure and make run in a copy: the build writes into the tree.
let tree = out_dir.join("wolfssl-fips-src");
let prefix = out_dir.join("wolfssl-fips-install");
let _ = std::fs::remove_dir_all(&tree);
run(std::process::Command::new("cp").arg("-R").arg(&source).arg(&tree));
let mut cflags = String::from("-DHAVE_XCHACHA");
if let Ok(hash) = env::var("WOLFSSL_FIPS_CORE_HASH") {
if hash.len() != 64 || !hash.bytes().all(|b| b.is_ascii_hexdigit()) {
panic!("\n\nWOLFSSL_FIPS_CORE_HASH must be 64 hex digits.\n");
}
cflags.push_str(&format!(" -DWOLFCRYPT_FIPS_CORE_HASH_VALUE={hash}"));
} else {
println!(
"cargo:warning=WOLFSSL_FIPS_CORE_HASH is not set: the FIPS self-test \
will fail and fips_mode() will be false until the final binary's \
hash is set (see the crate docs)"
);
}
let mut configure = std::process::Command::new(tree.join("configure"));
configure
.current_dir(&tree)
.arg(format!("--enable-fips={version}"))
.arg(format!("--prefix={}", prefix.display()))
// Static, wolfCrypt only, no test or example programs.
.args(["--enable-static", "--disable-shared", "--enable-cryptonly"])
.args(["--disable-examples", "--disable-crypttests"])
// Approved services the provider uses.
.args(["--enable-aesgcm", "--enable-sha384", "--enable-sha512", "--enable-sha3"])
.args(["--enable-hkdf", "--enable-pwdbased", "--enable-keygen"])
// Non-approved services, outside the FIPS boundary but in the module.
.args(["--enable-chacha", "--enable-poly1305", "--enable-xchacha"])
.args(["--enable-curve25519", "--enable-curve448", "--enable-blake2"])
.arg(format!("CFLAGS={cflags}"));
if let Ok(extra) = env::var("WOLFSSL_FIPS_CONFIGURE_ARGS") {
configure.args(extra.split_whitespace());
}
run(&mut configure);
let jobs = env::var("NUM_JOBS").unwrap_or_else(|_| "4".into());
run(std::process::Command::new("make")
.current_dir(&tree)
.arg(format!("-j{jobs}")));
run(std::process::Command::new("make").current_dir(&tree).arg("install"));
(prefix.join("include"), prefix.join("lib"))
}
fn run(cmd: &mut std::process::Command) {
let status = cmd
.status()
.unwrap_or_else(|e| panic!("\n\nfailed to run {cmd:?}: {e}\n"));
if !status.success() {
panic!("\n\n{cmd:?} failed with {status}\n");
}
}
/// Parse the CMake-generated `options.h` to extract all `#define` directives.
/// Returns a list of `-DNAME` clang args.
fn parse_options_defines(include_dir: &Path) -> Vec<String> {

View File

@ -29,7 +29,9 @@ pub fn encrypt(
AeadAlgorithm::AesGcm256 => aes_gcm_256_encrypt(key, nonce, plaintext, aad),
AeadAlgorithm::ChaCha20Poly1305 => chacha20_poly1305_encrypt(key, nonce, plaintext, aad),
AeadAlgorithm::XChaCha20Poly1305 => xchacha20_poly1305_encrypt(key, nonce, plaintext, aad),
AeadAlgorithm::Ascon128a => Err(CryptoError::FeatureNotCompiled("Ascon-128a".into())),
AeadAlgorithm::Ascon128a | AeadAlgorithm::AesGcmSiv256 | AeadAlgorithm::AsconAead128 => {
Err(CryptoError::FeatureNotCompiled(algo.name().into()))
}
}
}
@ -53,7 +55,9 @@ pub fn decrypt(
AeadAlgorithm::XChaCha20Poly1305 => {
xchacha20_poly1305_decrypt(key, nonce, ciphertext_and_tag, aad)
}
AeadAlgorithm::Ascon128a => Err(CryptoError::FeatureNotCompiled("Ascon-128a".into())),
AeadAlgorithm::Ascon128a | AeadAlgorithm::AesGcmSiv256 | AeadAlgorithm::AsconAead128 => {
Err(CryptoError::FeatureNotCompiled(algo.name().into()))
}
}
}

View File

@ -55,7 +55,13 @@ pub fn probe_capabilities(benchmarks: Option<&BenchmarkReport>) -> ProviderCapab
}
// Ascon-128a is not in this wolfSSL build.
caps = caps.with_aead(AeadAlgorithm::Ascon128a, AlgorithmCapability::unavailable());
for unavailable in [
AeadAlgorithm::Ascon128a,
AeadAlgorithm::AesGcmSiv256,
AeadAlgorithm::AsconAead128,
] {
caps = caps.with_aead(unavailable, AlgorithmCapability::unavailable());
}
// ── KDF ──────────────────────────────────────────────────────────────────
for algo in [
@ -168,6 +174,9 @@ pub fn probe_capabilities(benchmarks: Option<&BenchmarkReport>) -> ProviderCapab
KemAlgorithm::MlKem768,
KemAlgorithm::MlKem1024,
KemAlgorithm::ClassicMcEliece460896,
KemAlgorithm::ClassicMcEliece460896f,
KemAlgorithm::Hqc192,
KemAlgorithm::FrodoKem976Shake,
] {
caps = caps.with_kem(algo, AlgorithmCapability::unavailable());
}

View File

@ -0,0 +1,77 @@
//! FIPS 140-3 status of the linked wolfCrypt.
//!
//! Only a build with the `fips` feature links the commercial wolfCrypt FIPS
//! module; every other build reports `false` without asking the library.
#[cfg(feature = "fips")]
mod ffi {
use std::os::raw::{c_char, c_int};
extern "C" {
/// 0 once the power-on self-test and the in-core integrity check
/// passed; a negative wolfCrypt error code otherwise.
pub fn wolfCrypt_GetStatus_fips() -> c_int;
/// The in-core hash the last integrity check computed (hex).
pub fn wolfCrypt_GetCoreHash_fips() -> *const c_char;
}
}
/// The FIPS module status: `Some(0)` when the self-tests passed, `Some(err)`
/// when they failed, `None` without the `fips` feature.
pub fn fips_status() -> Option<i32> {
#[cfg(feature = "fips")]
{
// SAFETY: a plain status query without arguments.
Some(unsafe { ffi::wolfCrypt_GetStatus_fips() })
}
#[cfg(not(feature = "fips"))]
{
None
}
}
/// `true` only when built with the `fips` feature and the module's
/// power-on self-test (including the in-core integrity check) passed.
pub fn fips_mode() -> bool {
fips_status() == Some(0)
}
/// The in-core hash wolfCrypt computed for this binary, to set as
/// `WOLFSSL_FIPS_CORE_HASH` when the integrity check fails after a relink.
/// `None` without the `fips` feature.
pub fn fips_core_hash() -> Option<String> {
#[cfg(feature = "fips")]
{
// SAFETY: returns NULL or a NUL-terminated static string.
let p = unsafe { ffi::wolfCrypt_GetCoreHash_fips() };
if p.is_null() {
return None;
}
// SAFETY: checked non-null above; wolfCrypt owns the buffer.
let s = unsafe { std::ffi::CStr::from_ptr(p) };
Some(s.to_string_lossy().into_owned())
}
#[cfg(not(feature = "fips"))]
{
None
}
}
#[cfg(test)]
mod tests {
use super::*;
#[cfg(not(feature = "fips"))]
#[test]
fn open_source_build_is_not_fips() {
assert_eq!(fips_status(), None);
assert!(!fips_mode());
assert_eq!(fips_core_hash(), None);
}
#[cfg(feature = "fips")]
#[test]
fn fips_build_passes_its_self_test() {
assert!(fips_mode(), "status {:?}, core hash {:?}", fips_status(), fips_core_hash());
}
}

View File

@ -8,7 +8,8 @@
//! available HKDF primitive is `wc_Tls13_HKDF_Extract` (RFC 5869 Extract step)
//! together with the `wc_Hmac*` family. We implement RFC 5869 HKDF in Rust:
//!
//! - **Extract**: `PRK = HMAC-Hash(salt, IKM)` via `wc_Tls13_HKDF_Extract`.
//! - **Extract**: `PRK = HMAC-Hash(salt, IKM)` computed with wolfSSL HMAC
//! (`wc_Tls13_HKDF_Extract` rejects SHA-512, so it is not used).
//! - **Expand**: `OKM = T(1)||T(2)||…` where
//! `T(i) = HMAC(PRK, T(i-1) || info || i)` computed with wolfSSL HMAC.
//!
@ -64,8 +65,7 @@ pub fn derive_key(
/// HKDF: Extract then Expand (RFC 5869).
///
/// Extract uses `wc_Tls13_HKDF_Extract` (wolfSSL's RFC 5869 Extract).
/// Expand is implemented in Rust using wolfSSL's HMAC primitives.
/// Both steps are implemented in Rust using wolfSSL's HMAC primitives.
fn hkdf(
hash_type: i32,
ikm: &[u8],
@ -85,40 +85,19 @@ fn hkdf(
hkdf_expand(hash_type, &prk, info, length)
}
/// HKDF-Extract: `PRK = HMAC-Hash(salt, IKM)`.
/// HKDF-Extract: `PRK = HMAC-Hash(salt, IKM)` (RFC 5869 §2.2).
///
/// Wraps `wc_Tls13_HKDF_Extract` which takes a mutable IKM pointer.
/// Computed with wolfSSL's HMAC directly. `wc_Tls13_HKDF_Extract` was used
/// before, but it rejects SHA-512 in this build (BAD_FUNC_ARG), so
/// HKDF-SHA-512, the CCC v2 key schedule, failed on every call.
fn hkdf_extract(
hash_type: i32,
salt: &[u8],
ikm: &[u8],
) -> Result<Zeroizing<Vec<u8>>, CryptoError> {
let hash_len = hash_output_len(hash_type);
let mut prk = Zeroizing::new(vec![0u8; hash_len]);
// wolfSSL's wc_Tls13_HKDF_Extract takes `byte* ikm` (mutable), so we
// make a writable copy.
let mut ikm_buf = ikm.to_vec();
unsafe {
let ret = crate::sys::wc_Tls13_HKDF_Extract(
prk.as_mut_ptr(),
if salt.is_empty() {
std::ptr::null()
} else {
salt.as_ptr()
},
salt.len() as u32,
ikm_buf.as_mut_ptr(),
ikm_buf.len() as u32,
hash_type,
);
if ret != 0 {
return Err(CryptoError::InternalError(format!(
"wc_Tls13_HKDF_Extract returned {ret}"
)));
}
}
Ok(prk)
let prk = crate::mac::hmac(hash_type, salt, ikm, hash_len)?;
Ok(Zeroizing::new(prk))
}
/// HKDF-Expand: `OKM = T(1) || T(2) || …` truncated to `length` bytes.
@ -251,3 +230,33 @@ fn argon2id(
Ok(out)
}
#[cfg(test)]
mod hkdf_tests {
use super::*;
fn rfc5869_case1(algo: KdfAlgorithm) -> String {
let ikm = [0x0bu8; 22];
let salt: Vec<u8> = (0u8..13).collect();
let info: Vec<u8> = (0xf0u8..0xfa).collect();
let okm = derive_key(algo, &ikm, &salt, &info, 42).unwrap();
okm.iter().map(|b| format!("{b:02x}")).collect()
}
#[test]
fn hkdf_sha256_matches_rfc5869() {
assert_eq!(
rfc5869_case1(KdfAlgorithm::Sha256),
"3cb25f25faacd57a90434f64d0362f2a2d2d0a90cf1a5a4c5db02d56ecc4c5bf34007208d5b887185865"
);
}
#[test]
fn hkdf_sha512_matches_reference() {
// RFC 5869 case 1 inputs with SHA-512 (computed with Python's hmac).
assert_eq!(
rfc5869_case1(KdfAlgorithm::Sha512),
"832390086cda71fb47625bb5ceb168e4c8e26a1a16ed34d9fc7fe92c1481579338da362cb8d9f925d7cb"
);
}
}

View File

@ -24,8 +24,12 @@ pub fn generate_keypair(algo: KemAlgorithm) -> Result<KemKeyPair, CryptoError> {
KemAlgorithm::MlKem768 | KemAlgorithm::MlKem1024 => Err(CryptoError::FeatureNotCompiled(
"ML-KEM is deferred to Phase 5 (requires wolfSSL PQ build)".into(),
)),
KemAlgorithm::ClassicMcEliece460896 => Err(CryptoError::FeatureNotCompiled(
"Classic-McEliece is deferred to Phase 5".into(),
KemAlgorithm::ClassicMcEliece460896
| KemAlgorithm::ClassicMcEliece460896f
| KemAlgorithm::Hqc192
| KemAlgorithm::FrodoKem976Shake
| KemAlgorithm::XWing => Err(CryptoError::FeatureNotCompiled(
"Classic-McEliece, HQC, FrodoKEM and X-Wing are not offered by wolfCrypt".into(),
)),
}
}
@ -46,8 +50,12 @@ pub fn encapsulate(
KemAlgorithm::MlKem768 | KemAlgorithm::MlKem1024 => Err(CryptoError::FeatureNotCompiled(
"ML-KEM is deferred to Phase 5".into(),
)),
KemAlgorithm::ClassicMcEliece460896 => Err(CryptoError::FeatureNotCompiled(
"Classic-McEliece is deferred to Phase 5".into(),
KemAlgorithm::ClassicMcEliece460896
| KemAlgorithm::ClassicMcEliece460896f
| KemAlgorithm::Hqc192
| KemAlgorithm::FrodoKem976Shake
| KemAlgorithm::XWing => Err(CryptoError::FeatureNotCompiled(
"Classic-McEliece, HQC, FrodoKEM and X-Wing are not offered by wolfCrypt".into(),
)),
}
}
@ -65,8 +73,12 @@ pub fn decapsulate(
KemAlgorithm::MlKem768 | KemAlgorithm::MlKem1024 => Err(CryptoError::FeatureNotCompiled(
"ML-KEM is deferred to Phase 5".into(),
)),
KemAlgorithm::ClassicMcEliece460896 => Err(CryptoError::FeatureNotCompiled(
"Classic-McEliece is deferred to Phase 5".into(),
KemAlgorithm::ClassicMcEliece460896
| KemAlgorithm::ClassicMcEliece460896f
| KemAlgorithm::Hqc192
| KemAlgorithm::FrodoKem976Shake
| KemAlgorithm::XWing => Err(CryptoError::FeatureNotCompiled(
"Classic-McEliece, HQC, FrodoKEM and X-Wing are not offered by wolfCrypt".into(),
)),
}
}

View File

@ -9,9 +9,47 @@
//! Call [`init()`] once at application start (from the bridge crate's
//! `ccc_init()` function). That registers a [`WolfSslProvider`] into the
//! global [`ProviderRegistry`][ccc_crypto_core::registry::ProviderRegistry].
//!
//! ## FIPS 140-3 builds
//!
//! Release builds link the commercial wolfCrypt FIPS 140-3 module (R3-7,
//! D-26). Build with `--features fips` and point the build at the unpacked
//! bundle:
//!
//! ```text
//! export WOLFSSL_FIPS_SOURCE_DIR=/path/to/wolfssl-x.y.z-commercial-fips-v5
//! export WOLFSSL_FIPS_VERSION=v5 # or v6; default v5
//! export WOLFSSL_FIPS_CORE_HASH=<64 hex> # after the first run, see below
//! cargo build --release --features fips
//! ```
//!
//! - The build fails if `WOLFSSL_FIPS_SOURCE_DIR` is unset or is not a FIPS
//! bundle (no `wolfcrypt/src/fips.c`). It never falls back to the
//! open-source tree, and `WOLFSSL_INSTALL_DIR` and `stub_ffi` are refused.
//! - wolfSSL's CMake has no FIPS support, so the bundle is built with its own
//! `configure`: `--enable-fips=<v5|v6> --enable-cryptonly --enable-static
//! --disable-shared --enable-aesgcm --enable-sha384 --enable-sha512
//! --enable-sha3 --enable-hkdf --enable-pwdbased --enable-keygen` for the
//! approved services, plus `--enable-chacha --enable-poly1305
//! --enable-xchacha --enable-curve25519 --enable-curve448 --enable-blake2`,
//! which are non-approved services of the module. Cross builds pass
//! `--host=...` through `WOLFSSL_FIPS_CONFIGURE_ARGS`. Windows uses the
//! bundle's `IDE/WIN10` project instead.
//! - In-core integrity hash: the module hashes its own code in the final,
//! linked binary, so the hash changes with every relink of a static
//! library. Build once, read [`fips::fips_core_hash()`] from the failing
//! binary, set `WOLFSSL_FIPS_CORE_HASH` (it becomes
//! `-DWOLFCRYPT_FIPS_CORE_HASH_VALUE`) and rebuild. To keep the hash
//! stable across application changes, the final link (the bridge cdylib)
//! should place the FIPS objects with a linker script, as wolfSSL's
//! static-linking guide describes.
//! - [`CryptoProvider::fips_mode()`][ccc_crypto_core::CryptoProvider::fips_mode]
//! is `true` only for a `fips` build whose power-on self-test passed
//! (`wolfCrypt_GetStatus_fips() == 0`); every other build reports `false`.
pub mod aead;
pub mod capabilities;
pub mod fips;
pub mod hash;
pub mod kdf;
pub mod kem;

View File

@ -167,6 +167,11 @@ impl CryptoProvider for WolfSslProvider {
"wolfssl"
}
/// `true` only for a `fips` build whose FIPS self-tests passed.
fn fips_mode(&self) -> bool {
crate::fips::fips_mode()
}
fn capabilities(&self) -> ProviderCapabilities {
self.caps
.get_or_init(|| {

View File

@ -4,11 +4,11 @@
//! gate the provider from being marked `available` in the capability catalog.
use ccc_crypto_core::{
algorithms::AeadAlgorithm,
algorithms::{AeadAlgorithm, HashAlgorithm, KdfAlgorithm, MacAlgorithm},
types::{AlgoTestResult, SelfTestReport},
};
use crate::aead;
use crate::{aead, hash, kdf, mac};
// ──────────────────────────────────────────────────────────────────────────────
// AEAD vectors
@ -55,8 +55,97 @@ static AEAD_VECTORS: &[AeadVector] = &[
ct_tag: "d31a8d34648e60db7b86afbc53ef7ec2a4aded51296e08fea9e2b5a736ee62d6\
3dbea45e8ca96712f180d4e9016c65a7dde15e3106075ebd",
},
// ── XChaCha20-Poly1305: pinned cross-provider conformance vector ────
// (vectors/conformance_v1.json; wolfSSL and RustCrypto agree on it).
AeadVector {
algo: AeadAlgorithm::XChaCha20Poly1305,
key: "6e15bc630ab158ffa64df49b42e99037de852cd37a21c86f16bd640bb25900a7",
nonce: "7a21c86f16bd640bb25900a74ef59c43ea9138df862dd47b",
aad: "00a74ef59c43ea9138df862dd47b22c97017be65",
pt: "862dd47b22c97017be650cb35a01a84ff69d44eb9239e0872ed57c23ca7118bf660db45b02",
ct_tag: "cdbbd52a0f0f78264d4fea4f8b614b3fc36c2d269e70b502ff8491992e36fad2\
9c2a7df2af333c37b4584f08340e7623753b54b6c4",
},
];
// ──────────────────────────────────────────────────────────────────────────────
// KDF and MAC vectors (the cascade key schedule and the HPKE schedule depend
// on these; the policy refuses a suite whose KDF has no passing vector)
// ──────────────────────────────────────────────────────────────────────────────
/// RFC 5869 test case 1 inputs; SHA-512 output computed with Python's hmac.
static KDF_VECTORS: &[(KdfAlgorithm, &str)] = &[
(
KdfAlgorithm::Sha256,
"3cb25f25faacd57a90434f64d0362f2a2d2d0a90cf1a5a4c5db02d56ecc4c5bf34007208d5b887185865",
),
(
KdfAlgorithm::Sha512,
"832390086cda71fb47625bb5ceb168e4c8e26a1a16ed34d9fc7fe92c1481579338da362cb8d9f925d7cb",
),
];
/// RFC 4231 test case 2 (key "Jefe").
static MAC_VECTORS: &[(MacAlgorithm, &str)] = &[
(MacAlgorithm::HmacSha256, "5bdcc146bf60754e6a042426089575c75a003f089d2739839dec58b964ec3843"),
(
MacAlgorithm::HmacSha512,
"164b7a7bfcf819e2e395fbe73b56e0a387bd64222e831fd610270cd7ea2505549758bf75c05a994a6d034f65f8f0e6fdcaeab1a34d4a6b4b636e070a38bce737",
),
];
/// FIPS 180-4 examples: the digest of "abc".
static HASH_VECTORS: &[(HashAlgorithm, &str)] = &[
(HashAlgorithm::Sha256, "ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad"),
(
HashAlgorithm::Sha512,
"ddaf35a193617abacc417349ae20413112e6fa4e89a97ea20a9eeee64b55d39a2192992a274fc1a836ba3c23a3feebbd454d4423643ce80e2a9ac94fa54ca49f",
),
];
fn hex(bytes: &[u8]) -> String {
bytes.iter().map(|b| format!("{b:02x}")).collect()
}
fn result(algo_id: u32, name: String, outcome: Result<String, String>, expected: &str) -> AlgoTestResult {
match outcome {
Ok(got) if got == expected => AlgoTestResult { algo_id, algo_name: name, passed: true, error_message: None },
Ok(_) => AlgoTestResult {
algo_id,
algo_name: name,
passed: false,
error_message: Some("output mismatch".into()),
},
Err(e) => AlgoTestResult { algo_id, algo_name: name, passed: false, error_message: Some(e) },
}
}
fn run_kdf_vectors(results: &mut Vec<AlgoTestResult>) {
let ikm = [0x0bu8; 22];
let salt: Vec<u8> = (0u8..13).collect();
let info: Vec<u8> = (0xf0u8..0xfa).collect();
for (algo, expected) in KDF_VECTORS {
let out = kdf::derive_key(*algo, &ikm, &salt, &info, 42).map(|k| hex(&k)).map_err(|e| e.to_string());
results.push(result(*algo as u32, format!("HKDF {algo:?} RFC 5869 case 1"), out, expected));
}
}
fn run_mac_vectors(results: &mut Vec<AlgoTestResult>) {
for (algo, expected) in MAC_VECTORS {
let out = mac::compute_mac(*algo, b"Jefe", b"what do ya want for nothing?")
.map(|t| hex(&t))
.map_err(|e| e.to_string());
results.push(result(*algo as u32, format!("{} RFC 4231 case 2", algo.name()), out, expected));
}
}
fn run_hash_vectors(results: &mut Vec<AlgoTestResult>) {
for (algo, expected) in HASH_VECTORS {
let out = hash::hash(*algo, b"abc").map(|d| hex(&d)).map_err(|e| e.to_string());
results.push(result(*algo as u32, format!("{} FIPS 180-4 \"abc\"", algo.name()), out, expected));
}
}
// ──────────────────────────────────────────────────────────────────────────────
// Runner
// ──────────────────────────────────────────────────────────────────────────────
@ -67,6 +156,9 @@ pub(crate) fn run() -> SelfTestReport {
for v in AEAD_VECTORS {
results.push(run_aead_vector(v));
}
run_kdf_vectors(&mut results);
run_mac_vectors(&mut results);
run_hash_vectors(&mut results);
SelfTestReport::finalise("wolfssl", results)
}
@ -111,3 +203,14 @@ fn run_aead_vector(v: &AeadVector) -> AlgoTestResult {
},
}
}
#[cfg(test)]
mod tests {
#[test]
fn every_embedded_vector_passes() {
let r = super::run();
let failed: Vec<_> = r.results.iter().filter(|t| !t.passed).map(|t| t.algo_name.clone()).collect();
assert!(failed.is_empty(), "failed: {failed:?}");
assert_eq!(r.results.len(), 9);
}
}

View File

@ -0,0 +1,43 @@
==========================
CCC v2 cascade benchmarks
==========================
:Date: 2026-11-16
:Machine: Apple M3 Max, macOS, one thread, release build, Rust 1.93.1
:Command: ``cargo run --release -p ccc-cascade --example bench_cascade``
Layers alternate between wolfSSL (open-source 5.7.2) and RustCrypto: AES-256-GCM, XChaCha20-Poly1305,
ChaCha20-Poly1305, AES-256-GCM-SIV, XChaCha20-Poly1305, Ascon-AEAD128, repeated. Every layer of every round derives
its own key and nonce with HKDF-SHA-512. Overhead is one 16-byte tag per layer per round.
+--------+--------+---------+---------+---------+------------+
| Layers | Rounds | Message | Seal µs | Open µs | Overhead B |
+========+========+=========+=========+=========+============+
| 3 | 1 | 1 KiB | 18 | 18 | 48 |
+--------+--------+---------+---------+---------+------------+
| 3 | 1 | 4 KiB | 50 | 48 | 48 |
+--------+--------+---------+---------+---------+------------+
| 3 | 16 | 1 KiB | 341 | 331 | 768 |
+--------+--------+---------+---------+---------+------------+
| 3 | 16 | 4 KiB | 801 | 792 | 768 |
+--------+--------+---------+---------+---------+------------+
| 9 | 1 | 1 KiB | 48 | 48 | 144 |
+--------+--------+---------+---------+---------+------------+
| 9 | 1 | 4 KiB | 122 | 121 | 144 |
+--------+--------+---------+---------+---------+------------+
| 9 | 16 | 1 KiB | 1,178 | 1,186 | 2,304 |
+--------+--------+---------+---------+---------+------------+
| 9 | 16 | 4 KiB | 2,333 | 2,290 | 2,304 |
+--------+--------+---------+---------+---------+------------+
| 48 | 1 | 1 KiB | 283 | 277 | 768 |
+--------+--------+---------+---------+---------+------------+
| 48 | 1 | 4 KiB | 634 | 642 | 768 |
+--------+--------+---------+---------+---------+------------+
| 48 | 16 | 1 KiB | 15,177 | 15,106 | 12,288 |
+--------+--------+---------+---------+---------+------------+
| 48 | 16 | 4 KiB | 20,682 | 21,222 | 12,288 |
+--------+--------+---------+---------+---------+------------+
Reading: the Ultra profile (3 layers, 16 rounds, 4 KiB bucket) costs under 1 ms per message here; phones are expected
to be 2–4x slower. Key derivation dominates small messages (one HKDF per layer per round), which is why 16 rounds of
3 layers cost about as much as one round of 48. A 48-layer, 16-round suite adds 12 KiB per message and about 20 ms.

View File

@ -8,12 +8,26 @@ publish = false # Test binary — never published to crates.io.
[[bin]]
name = "conformance"
path = "src/main.rs"
required-features = ["wolfssl"]
[dependencies]
ccc-crypto-core = { path = "../../crates/ccc-crypto-core" }
ccc-crypto-wolfssl = { path = "../../crates/ccc-crypto-wolfssl" }
ccc-crypto-wolfssl = { path = "../../crates/ccc-crypto-wolfssl", optional = true }
anyhow = { workspace = true }
hex = "0.4"
log = { workspace = true }
env_logger = { workspace = true }
[features]
# wolfSSL is GPLv3 (or commercial) and off by default; turn it on to
# cross-check it and to regenerate the vectors with every provider.
wolfssl = ["dep:ccc-crypto-wolfssl"]
[dev-dependencies]
ccc-crypto-rustcrypto = { workspace = true }
ccc-crypto-boring = { path = "../../crates/ccc-crypto-boring" }
ccc-crypto-awslc = { path = "../../crates/ccc-crypto-awslc" }
ccc-cascade = { workspace = true }
serde = { workspace = true }
serde_json = { workspace = true }

View File

@ -0,0 +1,149 @@
//! The pinned CCC v2 vectors (`vectors/cascade_v2.json`) with layers moved
//! to the awslc provider must give byte-identical ciphertext, and the pinned
//! ciphertexts must open. The anchor layer (AES-256-GCM) supplies the key
//! schedule's HKDF-SHA-512, so this also checks awslc's KDF in the cascade.
//!
//! Layers are remapped by algorithm, not by provider name, so the check does
//! not depend on which provider the built-in suites name today.
use std::sync::{Arc, OnceLock};
use ccc_cascade::{
open, seal, suites, Context, Policy, ProviderSet, StreamOpener, StreamSealer, Suite,
};
use ccc_crypto_awslc::AwsLcProvider;
use ccc_crypto_core::AeadAlgorithm;
use serde_json::Value;
const PATH: &str = concat!(env!("CARGO_MANIFEST_DIR"), "/../../vectors/cascade_v2.json");
const DOMAIN: &[u8] = b"ccc/v2/kat";
/// One set for all tests: resolving a suite runs each provider's benchmark
/// once, which is slow in debug builds.
fn providers() -> &'static ProviderSet {
static SET: OnceLock<ProviderSet> = OnceLock::new();
SET.get_or_init(|| {
let mut p = ProviderSet::new();
p.add(Arc::new(ccc_crypto_rustcrypto::RustCryptoProvider::new()));
p.add(Arc::new(AwsLcProvider::new()));
p
})
}
fn unhex(v: &Value) -> Vec<u8> {
hex::decode(v.as_str().expect("hex string")).expect("hex")
}
fn pinned() -> Value {
serde_json::from_str(&std::fs::read_to_string(PATH).expect("read cascade_v2.json"))
.expect("parse cascade_v2.json")
}
/// `suite` with every layer for which `pick` holds moved to awslc.
fn on_awslc(mut suite: Suite, pick: impl Fn(AeadAlgorithm) -> bool) -> Suite {
for l in &mut suite.layers {
if pick(l.aead) {
l.provider = "awslc";
}
}
suite
}
fn offered_by_awslc(a: AeadAlgorithm) -> bool {
ccc_crypto_awslc::capabilities::AEADS.contains(&a)
}
fn check_cascade(pick: impl Fn(AeadAlgorithm) -> bool + Copy) {
let p = providers();
let v = pinned();
let mut moved = 0;
for case in v["cascade"].as_array().expect("cascade cases") {
let id = case["suite"].as_u64().expect("suite id") as u16;
let base = suites::by_id(id).expect("built-in suite");
let suite = on_awslc(base.clone(), pick);
moved += suite
.layers
.iter()
.filter(|l| l.provider == "awslc")
.count();
let r = p.resolve(&suite, &Policy::development()).expect("resolve");
let rounds = case["rounds"].as_u64().expect("rounds") as u8;
let (key, salt, aad, pt, ct) = (
unhex(&case["key"]),
unhex(&case["salt"]),
unhex(&case["aad"]),
unhex(&case["pt"]),
unhex(&case["ct"]),
);
let ctx = Context {
domain: DOMAIN,
aad: &aad,
};
let got = seal(&r, rounds, &key, &salt, ctx, &pt).expect("seal");
assert_eq!(
got, ct,
"suite {} on awslc drifted from the pinned vector",
base.name
);
let opened = open(&r, rounds, &key, &salt, ctx, &ct).expect("open");
assert_eq!(opened.as_slice(), pt.as_slice(), "suite {}", base.name);
}
assert!(moved > 0, "no layer was moved to awslc");
}
#[test]
fn anchor_on_awslc_matches_pinned_cascade() {
check_cascade(|a| a == AeadAlgorithm::AesGcm256);
}
#[test]
fn every_awslc_layer_matches_pinned_cascade() {
check_cascade(offered_by_awslc);
}
#[test]
fn stream_on_awslc_matches_pinned_segments() {
let p = providers();
let st = &pinned()["stream"];
let id = st["suite"].as_u64().expect("suite id") as u16;
let suite = on_awslc(suites::by_id(id).expect("built-in suite"), offered_by_awslc);
assert!(suite.layers.iter().any(|l| l.provider == "awslc"));
let r = p.resolve(&suite, &Policy::development()).expect("resolve");
let (key, salt, aad) = (unhex(&st["key"]), unhex(&st["salt"]), unhex(&st["aad"]));
let segs: Vec<Vec<u8>> = st["segments"]
.as_array()
.expect("segments")
.iter()
.map(unhex)
.collect();
let ctx = Context {
domain: DOMAIN,
aad: &aad,
};
// Rebuild the pinned blob (same pattern as the generator) and reseal.
let blob_len = st["blob_len"].as_u64().expect("blob_len") as usize;
let blob: Vec<u8> = (0..blob_len)
.map(|i| (i as u8).wrapping_mul(31).wrapping_add(5))
.collect();
let mut s = StreamSealer::new(&r, &key, &salt, ctx).expect("sealer");
let chunks: Vec<&[u8]> = blob.chunks(ccc_cascade::SEGMENT_LEN).collect();
assert_eq!(chunks.len(), segs.len());
for (i, c) in chunks.iter().enumerate() {
let got = s
.seal_segment(c, i == chunks.len() - 1)
.expect("seal segment");
assert_eq!(got, segs[i], "segment {i} drifted");
}
let mut o = StreamOpener::new(&r, &key, &salt, ctx).expect("opener");
let mut out: Vec<u8> = Vec::new();
for (i, seg) in segs.iter().enumerate() {
out.extend_from_slice(
&o.open_segment(seg, i == segs.len() - 1)
.expect("open segment"),
);
}
o.finish().expect("finish");
assert_eq!(out, blob);
}

View File

@ -0,0 +1,560 @@
//! Cross-provider conformance (R3-6): every algorithm offered by more than
//! one provider must produce byte-identical output on the shared vectors in
//! `vectors/conformance_v1.json`.
//!
//! Each vector lists the providers that offer its algorithm. The test
//! checks that every listed provider reproduces the pinned output, opens the
//! other providers' ciphertexts and rejects tampered tags, and that every
//! unlisted provider still reports the algorithm as unsupported (so a
//! provider gaining an algorithm forces the file to be regenerated).
//!
//! Regenerate (only when inputs or the provider set change on purpose):
//!
//! ```sh
//! cargo test -p ccc-conformance-tests --test cross_provider -- --ignored regenerate
//! ```
use std::path::PathBuf;
use serde::{Deserialize, Serialize};
use ccc_crypto_awslc::AwsLcProvider;
use ccc_crypto_boring::BoringProvider;
use ccc_crypto_core::{
algorithms::{AeadAlgorithm, HashAlgorithm, KdfAlgorithm, KemAlgorithm, MacAlgorithm},
error::CryptoError,
provider::{CryptoProvider, KemProvider},
};
use ccc_crypto_rustcrypto::RustCryptoProvider;
#[cfg(feature = "wolfssl")]
use ccc_crypto_wolfssl::WolfSslProvider;
// ── Providers ────────────────────────────────────────────────────────────────
trait Provider: CryptoProvider + KemProvider {}
impl<T: CryptoProvider + KemProvider> Provider for T {}
fn providers() -> Vec<Box<dyn Provider>> {
vec![
#[cfg(feature = "wolfssl")]
Box::new(WolfSslProvider::new()),
Box::new(RustCryptoProvider::new()),
Box::new(BoringProvider::new()),
Box::new(AwsLcProvider::new()),
]
}
fn unsupported<T>(r: &Result<T, CryptoError>) -> bool {
matches!(
r,
Err(CryptoError::FeatureNotCompiled(_)) | Err(CryptoError::UnsupportedAlgorithm(_))
)
}
// ── File format ──────────────────────────────────────────────────────────────
#[derive(Serialize, Deserialize, Debug, PartialEq)]
struct Vectors {
version: u32,
note: String,
aead: Vec<AeadVec>,
kdf: Vec<KdfVec>,
mac: Vec<MacVec>,
hash: Vec<HashVec>,
x25519: Vec<DhVec>,
}
#[derive(Serialize, Deserialize, Debug, PartialEq)]
struct AeadVec {
algo: String,
id: u32,
key: String,
nonce: String,
aad: String,
pt: String,
ct: String,
providers: Vec<String>,
}
#[derive(Serialize, Deserialize, Debug, PartialEq)]
struct KdfVec {
algo: String,
id: u32,
ikm: String,
salt: String,
info: String,
length: usize,
okm: String,
providers: Vec<String>,
}
#[derive(Serialize, Deserialize, Debug, PartialEq)]
struct MacVec {
algo: String,
id: u32,
key: String,
data: String,
tag: String,
providers: Vec<String>,
}
#[derive(Serialize, Deserialize, Debug, PartialEq)]
struct HashVec {
algo: String,
id: u32,
data: String,
digest: String,
providers: Vec<String>,
}
#[derive(Serialize, Deserialize, Debug, PartialEq)]
struct DhVec {
a_private: String,
a_public: String,
b_private: String,
b_public: String,
shared: String,
providers: Vec<String>,
}
fn vectors_path() -> PathBuf {
PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("../../vectors/conformance_v1.json")
}
fn load() -> Vectors {
let text = std::fs::read_to_string(vectors_path()).expect("read conformance_v1.json");
serde_json::from_str(&text).expect("parse conformance_v1.json")
}
fn h(s: &str) -> Vec<u8> {
hex::decode(s).expect("hex")
}
// ── Deterministic inputs ─────────────────────────────────────────────────────
/// Reproducible pseudo-random bytes (not a CSPRNG; inputs only).
fn bytes(label: u8, len: usize) -> Vec<u8> {
(0..len)
.map(|i| {
(i as u32)
.wrapping_mul(167)
.wrapping_add(label as u32 * 59 + 13) as u8
})
.collect()
}
const AEADS: [AeadAlgorithm; 6] = AeadAlgorithm::ALL;
const KDFS: [KdfAlgorithm; 5] = [
KdfAlgorithm::Sha256,
KdfAlgorithm::Sha384,
KdfAlgorithm::Sha512,
KdfAlgorithm::Blake2b512,
KdfAlgorithm::Argon2id,
];
const MACS: [MacAlgorithm; 5] = [
MacAlgorithm::HmacSha256,
MacAlgorithm::HmacSha384,
MacAlgorithm::HmacSha512,
MacAlgorithm::Blake2bMac,
MacAlgorithm::Poly1305,
];
const HASHES: [HashAlgorithm; 6] = [
HashAlgorithm::Sha256,
HashAlgorithm::Sha384,
HashAlgorithm::Sha512,
HashAlgorithm::Blake2b512,
HashAlgorithm::Sha3_256,
HashAlgorithm::Sha3_512,
];
/// Plaintext / AAD length pairs: empty, short, block-unaligned, multi-block.
const AEAD_SHAPES: [(usize, usize); 5] = [(0, 0), (1, 0), (0, 13), (37, 20), (300, 65)];
const HASH_LENS: [usize; 4] = [0, 3, 64, 1000];
fn x25519_base() -> Vec<u8> {
let mut b = vec![0u8; 32];
b[0] = 9;
b
}
// ── Generator ────────────────────────────────────────────────────────────────
/// Compute `f` on every provider; the providers that return `Ok` must agree.
fn agree<T: PartialEq + std::fmt::Debug>(
what: &str,
f: impl Fn(&dyn Provider) -> Result<T, CryptoError>,
) -> Option<(T, Vec<String>)> {
let mut out: Option<T> = None;
let mut names = Vec::new();
for p in providers() {
match f(p.as_ref()) {
Ok(v) => {
if let Some(prev) = &out {
assert_eq!(prev, &v, "{what}: providers disagree while generating");
} else {
out = Some(v);
}
names.push(p.provider_name().to_string());
}
Err(CryptoError::FeatureNotCompiled(_) | CryptoError::UnsupportedAlgorithm(_)) => {}
Err(e) => panic!("{what}: {} failed: {e}", p.provider_name()),
}
}
out.map(|v| (v, names))
}
fn generate() -> Vectors {
let mut v = Vectors {
version: 1,
note: "Generated once by `regenerate`; every listed provider must reproduce \
these outputs byte for byte."
.into(),
aead: vec![],
kdf: vec![],
mac: vec![],
hash: vec![],
x25519: vec![],
};
for (n, algo) in AEADS.into_iter().enumerate() {
for (s, (pt_len, aad_len)) in AEAD_SHAPES.into_iter().enumerate() {
let label = (n * 8 + s) as u8;
let key = bytes(label, algo.key_len());
let nonce = bytes(label + 100, algo.nonce_len());
let aad = bytes(label + 150, aad_len);
let pt = bytes(label + 200, pt_len);
if let Some((ct, providers)) = agree(algo.name(), |p| {
p.encrypt_aead(algo, &key, &nonce, &pt, &aad)
}) {
v.aead.push(AeadVec {
algo: algo.name().into(),
id: algo as u32,
key: hex::encode(&key),
nonce: hex::encode(&nonce),
aad: hex::encode(&aad),
pt: hex::encode(&pt),
ct: hex::encode(ct),
providers,
});
}
}
}
for (n, algo) in KDFS.into_iter().enumerate() {
let shapes: &[(usize, usize, usize, usize)] = match algo {
// Argon2id runs at the app's fixed 64 MiB cost: keep it to one vector.
KdfAlgorithm::Argon2id => &[(16, 16, 0, 32)],
KdfAlgorithm::Blake2b512 => &[(32, 0, 0, 64), (32, 32, 16, 32), (5, 7, 9, 1)],
_ => &[(32, 0, 0, 32), (22, 13, 10, 42), (80, 80, 80, 200)],
};
for (s, &(ikm_len, salt_len, info_len, length)) in shapes.iter().enumerate() {
let label = (n * 8 + s) as u8;
let ikm = bytes(label, ikm_len);
let salt = bytes(label + 50, salt_len);
let info = bytes(label + 90, info_len);
if let Some((okm, providers)) = agree(algo.name(), |p| {
p.derive_key(algo, &ikm, &salt, &info, length)
.map(|k| k.to_vec())
}) {
v.kdf.push(KdfVec {
algo: algo.name().into(),
id: algo as u32,
ikm: hex::encode(&ikm),
salt: hex::encode(&salt),
info: hex::encode(&info),
length,
okm: hex::encode(okm),
providers,
});
}
}
}
for (n, algo) in MACS.into_iter().enumerate() {
let key_lens: &[usize] = match algo {
MacAlgorithm::Poly1305 => &[32],
MacAlgorithm::Blake2bMac => &[16, 64],
_ => &[4, 32, 200],
};
for (s, &key_len) in key_lens.iter().enumerate() {
let label = (n * 8 + s) as u8;
let key = bytes(label, key_len);
let data = bytes(label + 70, 100 + s * 50);
if let Some((tag, providers)) = agree(algo.name(), |p| p.compute_mac(algo, &key, &data))
{
v.mac.push(MacVec {
algo: algo.name().into(),
id: algo as u32,
key: hex::encode(&key),
data: hex::encode(&data),
tag: hex::encode(tag),
providers,
});
}
}
}
for (n, algo) in HASHES.into_iter().enumerate() {
for (s, len) in HASH_LENS.into_iter().enumerate() {
let data = bytes((n * 8 + s) as u8, len);
if let Some((digest, providers)) = agree(algo.name(), |p| p.hash(algo, &data)) {
v.hash.push(HashVec {
algo: algo.name().into(),
id: algo as u32,
data: hex::encode(&data),
digest: hex::encode(digest),
providers,
});
}
}
}
for s in 0..3u8 {
let a = bytes(s * 2 + 1, 32);
let b = bytes(s * 2 + 2, 32);
let dh = |sk: &[u8], pk: &[u8]| {
agree("X25519", |p| {
p.decapsulate(KemAlgorithm::X25519, sk, pk)
.map(|k| k.to_vec())
})
.expect("X25519 offered")
};
let (a_pub, providers) = dh(&a, &x25519_base());
let (b_pub, _) = dh(&b, &x25519_base());
let (shared, _) = dh(&a, &b_pub);
v.x25519.push(DhVec {
a_private: hex::encode(&a),
a_public: hex::encode(&a_pub),
b_private: hex::encode(&b),
b_public: hex::encode(&b_pub),
shared: hex::encode(shared),
providers,
});
}
v
}
#[test]
#[ignore = "writes vectors/conformance_v1.json; run only to regenerate"]
fn regenerate() {
if !cfg!(feature = "wolfssl") {
panic!("regenerate with --features wolfssl so every provider is listed");
}
let json = serde_json::to_string_pretty(&generate()).unwrap() + "\n";
std::fs::write(vectors_path(), json).unwrap();
}
// ── Assertions ───────────────────────────────────────────────────────────────
/// For one vector: listed providers must give `want`; the rest must report
/// the algorithm as unsupported.
fn check<T: PartialEq + std::fmt::Debug>(
what: &str,
listed: &[String],
want: &T,
f: impl Fn(&dyn Provider) -> Result<T, CryptoError>,
) {
assert!(!listed.is_empty(), "{what}: vector lists no provider");
for p in providers() {
let got = f(p.as_ref());
let name = p.provider_name();
if listed.iter().any(|l| l == name) {
match got {
Ok(v) => assert_eq!(&v, want, "{what}: {name} drifted from the pinned vector"),
Err(e) => panic!("{what}: {name} failed: {e}"),
}
} else {
assert!(
unsupported(&got),
"{what}: {name} now offers this algorithm; regenerate the vectors"
);
}
}
}
#[test]
fn file_covers_shared_algorithms() {
let v = load();
assert_eq!(v.version, 1);
let shared = |p: &[String]| p.len() >= 2;
// The algorithms at least two providers offer today must be cross-checked.
for id in [12u32, 13, 14, 16] {
assert!(
v.aead.iter().any(|a| a.id == id && shared(&a.providers)),
"AEAD {id}"
);
}
for id in [1u32, 2, 3, 4, 5] {
assert!(
v.kdf.iter().any(|k| k.id == id && shared(&k.providers)),
"KDF {id}"
);
}
for id in [30u32, 31, 32, 33] {
assert!(
v.mac.iter().any(|m| m.id == id && shared(&m.providers)),
"MAC {id}"
);
}
for id in [40u32, 41, 42, 43, 44, 45] {
assert!(
v.hash.iter().any(|m| m.id == id && shared(&m.providers)),
"hash {id}"
);
}
assert!(v.x25519.iter().all(|d| shared(&d.providers)));
}
#[test]
fn aead_vectors_match_and_interoperate() {
for v in load().aead {
let algo = AeadAlgorithm::from_u32(v.id).expect("known AEAD id");
let (key, nonce, aad, pt, ct) = (h(&v.key), h(&v.nonce), h(&v.aad), h(&v.pt), h(&v.ct));
let what = format!("{} pt={} aad={}", v.algo, pt.len(), aad.len());
check(&what, &v.providers, &ct, |p| {
p.encrypt_aead(algo, &key, &nonce, &pt, &aad)
});
// Every listed provider opens the pinned ciphertext (and so each
// other's) and rejects a flipped tag bit or a changed AAD.
check(&what, &v.providers, &pt, |p| {
p.decrypt_aead(algo, &key, &nonce, &ct, &aad)
});
let mut bad_tag = ct.clone();
*bad_tag.last_mut().unwrap() ^= 0x01;
let mut bad_aad = aad.clone();
bad_aad.push(0);
for p in providers() {
if !v.providers.iter().any(|l| l == p.provider_name()) {
continue;
}
for (bad_ct, bad_ad) in [(&bad_tag, &aad), (&ct, &bad_aad)] {
assert!(
matches!(
p.decrypt_aead(algo, &key, &nonce, bad_ct, bad_ad),
Err(CryptoError::AuthenticationFailed)
),
"{what}: {} accepted a tampered message",
p.provider_name()
);
}
}
}
}
#[test]
fn kdf_vectors_match() {
for v in load().kdf {
let algo = KdfAlgorithm::from_u32(v.id).expect("known KDF id");
let (ikm, salt, info) = (h(&v.ikm), h(&v.salt), h(&v.info));
check(&v.algo, &v.providers, &h(&v.okm), |p| {
p.derive_key(algo, &ikm, &salt, &info, v.length)
.map(|k| k.to_vec())
});
}
}
#[test]
fn mac_vectors_match_and_verify() {
for v in load().mac {
let algo = MacAlgorithm::from_u32(v.id).expect("known MAC id");
let (key, data, tag) = (h(&v.key), h(&v.data), h(&v.tag));
check(&v.algo, &v.providers, &tag, |p| {
p.compute_mac(algo, &key, &data)
});
let mut bad = tag.clone();
bad[0] ^= 0x80;
check(&v.algo, &v.providers, &true, |p| {
p.verify_mac(algo, &key, &data, &tag)
});
check(&v.algo, &v.providers, &false, |p| {
p.verify_mac(algo, &key, &data, &bad)
});
}
}
#[test]
fn hash_vectors_match() {
for v in load().hash {
let algo = HashAlgorithm::from_u32(v.id).expect("known hash id");
let data = h(&v.data);
check(&v.algo, &v.providers, &h(&v.digest), |p| {
p.hash(algo, &data)
});
}
}
#[test]
fn x25519_vectors_match() {
let dh = |sk: Vec<u8>, pk: Vec<u8>| {
move |p: &dyn Provider| {
p.decapsulate(KemAlgorithm::X25519, &sk, &pk)
.map(|k| k.to_vec())
}
};
for v in load().x25519 {
let (a, b) = (h(&v.a_private), h(&v.b_private));
let (a_pub, b_pub, shared) = (h(&v.a_public), h(&v.b_public), h(&v.shared));
check(
"X25519 a·G",
&v.providers,
&a_pub,
dh(a.clone(), x25519_base()),
);
check(
"X25519 b·G",
&v.providers,
&b_pub,
dh(b.clone(), x25519_base()),
);
check("X25519 a·B", &v.providers, &shared, dh(a, b_pub));
check("X25519 b·A", &v.providers, &shared, dh(b, a_pub));
}
}
#[test]
fn kem_encapsulation_interoperates() {
// Randomised, so not pinned: every provider pair must agree both ways.
for algo in [
KemAlgorithm::X25519,
KemAlgorithm::MlKem768,
KemAlgorithm::MlKem1024,
KemAlgorithm::XWing,
] {
let ps = providers();
for recv in &ps {
let Ok(kp) = recv.generate_keypair(algo) else {
continue;
};
for send in &ps {
let Ok(enc) = send.encapsulate(algo, &kp.public_key) else {
continue;
};
let ss = recv
.decapsulate(algo, &kp.private_key, &enc.ciphertext)
.unwrap();
assert_eq!(
*ss,
enc.shared_secret,
"{}: {} -> {}",
algo.name(),
send.provider_name(),
recv.provider_name()
);
}
}
}
}
#[test]
#[cfg_attr(
not(feature = "wolfssl"),
ignore = "the pinned file lists wolfSSL too; run with --features wolfssl"
)]
fn pinned_file_is_current() {
// Catches edits to the inputs above that were not regenerated.
assert_eq!(
load(),
generate(),
"vectors/conformance_v1.json is stale; regenerate"
);
}

71
vectors/cascade_v2.json Normal file

File diff suppressed because one or more lines are too long

1006
vectors/conformance_v1.json Normal file

File diff suppressed because it is too large Load Diff