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
This commit is contained in:
parent
af11468d97
commit
5184dbd6ef
|
|
@ -0,0 +1,239 @@
|
|||
//! 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; 4] = [
|
||||
KemAlgorithm::X25519,
|
||||
KemAlgorithm::MlKem768,
|
||||
KemAlgorithm::MlKem1024,
|
||||
KemAlgorithm::XWing,
|
||||
];
|
||||
|
||||
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 {
|
||||
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] {
|
||||
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);
|
||||
}
|
||||
|
||||
#[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));
|
||||
}
|
||||
}
|
||||
|
|
@ -4,12 +4,29 @@
|
|||
//! 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;
|
||||
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");
|
||||
}
|
||||
|
|
|
|||
|
|
@ -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");
|
||||
}
|
||||
}
|
||||
Loading…
Reference in New Issue