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
This commit is contained in:
parent
355bfe3c2e
commit
b39272228f
|
|
@ -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(_))
|
||||||
|
));
|
||||||
|
}
|
||||||
|
}
|
||||||
Loading…
Reference in New Issue