SPB Git

Repository Public Apache-2.0

info.rs 13.6 KB 369 lines rust

1// =============================================================================2//                  SP BOUCHER | SOFTWARE & RESEARCH3//             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// Project          : SPB Quantum Crypto7// File             : crates/spb-pqc-core/src/info.rs8// Module           : Crates9// Repository       : https://git.spboucher.ai/spb-quantum-crypto10// Project Website  : https://pqce.spboucher.ai11// Created          : 2026-12-0312// Last Modified    : 2026-12-0313//14// Author           : Simon-Pierre Boucher15// Position         : Professor of Finance16// Institution      : Université du Québec en Outaouais (UQO)17// Organization     : SP Boucher18// Website          : https://spboucher.ai19// Git              : https://git.spboucher.ai20//21// Preferred Contact: contact@spboucher.ai22// Development      : dev@spboucher.ai23// Support          : support@spboucher.ai24// Security/Admin   : admin@spboucher.ai25//26// Copyright (c) 202627// Simon-Pierre Boucher28// All rights reserved where applicable. This file is governed by the29// applicable project license, copyright notices and relevant law.30// Existing third-party rights and notices remain unaffected.31//32// License          : Apache-2.033//34// Do not embed credentials, private keys, access tokens,35// certificates or confidential personal information.36//37// =============================================================================38// END OF SP BOUCHER SOURCE HEADER39// =============================================================================4041//! Library identity, security status, capability report and self-test.4243use crate::error::{Error, Result};44use crate::hash::{self, HashAlg};45use crate::kem::{self, mlkem, KemAlg};46use crate::signature::{self, mldsa, slhdsa, SigAlg, SignOptions};4748/// Library version (SemVer), identical across every binding built from this core.49pub const VERSION: &str = env!("CARGO_PKG_VERSION");5051/// Version of the C ABI contract (`include/spb_pqc.h`). Bumped on any52/// incompatible change of a function signature, identifier or error code.53pub const ABI_VERSION: u32 = 1;5455/// Human-readable security status shown by every binding and demo.56pub const SECURITY_STATUS: &str = "EXPERIMENTAL / NOT AUDITED";5758/// `version()`.59pub const fn version() -> &'static str {60    VERSION61}6263/// Machine-readable security status.64#[derive(Clone, Copy, Debug, PartialEq, Eq)]65pub struct SecurityStatus {66    /// Short label, [`SECURITY_STATUS`].67    pub label: &'static str,68    /// Whether an independent security audit has been completed (it has not).69    pub audited: bool,70    /// Whether this build is a FIPS 140-3 validated module (it is not; passing71    /// the ACVP vectors is not a validation).72    pub fips_140_3_validated: bool,73    /// Whether the maintainers consider this release fit for production use.74    pub production_ready: bool,75}7677/// `securityStatus()`.78pub const fn security_status() -> SecurityStatus {79    SecurityStatus {80        label: SECURITY_STATUS,81        audited: false,82        fips_140_3_validated: false,83        production_ready: false,84    }85}8687/// `capabilities()` as a JSON document (stable keys, see `docs/API.md`).88///89/// Sizes are in bytes. `envelope` lists the high-level sealing profiles that90/// are implemented *and* tested; it is empty in this release (see91/// `docs/security/composition.md`).92pub fn capabilities_json() -> String {93    let mut s = String::with_capacity(4096);94    s.push_str("{\"library\":\"spb-quantum-crypto\",\"version\":\"");95    s.push_str(VERSION);96    s.push_str("\",\"abiVersion\":");97    s.push_str(&ABI_VERSION.to_string());98    s.push_str(",\"securityStatus\":{\"label\":\"");99    s.push_str(SECURITY_STATUS);100    s.push_str(101        "\",\"audited\":false,\"fips1403Validated\":false,\"productionReady\":false},\"kem\":[",102    );103    for (i, a) in KemAlg::ALL.into_iter().enumerate() {104        if i > 0 {105            s.push(',');106        }107        s.push_str(&format!(108            "{{\"name\":\"{}\",\"id\":{},\"oid\":\"{}\",\"standard\":\"FIPS 203\",\"category\":{},\"publicKey\":{},\"privateKey\":{},\"ciphertext\":{},\"sharedSecret\":{}}}",109            a.name(), a.id(), a.oid(), a.security_category(), a.public_key_len(),110            a.private_key_len(), a.ciphertext_len(), a.shared_secret_len()111        ));112    }113    s.push_str("],\"signature\":[");114    for (i, a) in SigAlg::ALL.into_iter().enumerate() {115        if i > 0 {116            s.push(',');117        }118        s.push_str(&format!(119            "{{\"name\":\"{}\",\"id\":{},\"oid\":\"{}\",\"standard\":\"{}\",\"category\":{},\"publicKey\":{},\"privateKey\":{},\"signature\":{}}}",120            a.name(), a.id(), a.oid(), if a.is_ml_dsa() { "FIPS 204" } else { "FIPS 205" },121            a.security_category(), a.public_key_len(), a.private_key_len(), a.signature_len()122        ));123    }124    s.push_str("],\"hash\":[");125    for (i, a) in HashAlg::ALL.into_iter().enumerate() {126        if i > 0 {127            s.push(',');128        }129        s.push_str(&format!(130            "{{\"name\":\"{}\",\"id\":{},\"digest\":{},\"xof\":{}}}",131            a.name(),132            a.id(),133            a.digest_len(),134            a.is_xof()135        ));136    }137    s.push_str("],\"envelope\":[],\"experimental\":[],\"limits\":{\"context\":255,\"xofOutput\":");138    s.push_str(&hash::MAX_XOF_OUTPUT.to_string());139    s.push_str("}}");140    s141}142143fn unhex<const N: usize>(s: &str) -> [u8; N] {144    let b = s.as_bytes();145    let mut out = [0u8; N];146    let val = |c: u8| match c {147        b'0'..=b'9' => c - b'0',148        b'a'..=b'f' => c - b'a' + 10,149        _ => c - b'A' + 10,150    };151    for i in 0..N {152        out[i] = (val(b[2 * i]) << 4) | val(b[2 * i + 1]);153    }154    out155}156157fn check(cond: bool) -> Result<()> {158    if cond {159        Ok(())160    } else {161        Err(Error::SelfTestFailed)162    }163}164165/// `selfTest()`: quick conformance and consistency checks. Returns the first166/// failure as [`Error::SelfTestFailed`] (or [`Error::RandomFailure`]).167///168/// What it covers, precisely:169///170/// 1. hash known answers from FIPS 180-4 / FIPS 202 examples (SHA-256,171///    SHA-512, SHA3-256, SHAKE128, SHAKE256);172/// 2. key generation known answers taken from the NIST ACVP files (first173///    vector of each set): ML-KEM-512/768/1024, ML-DSA-44/65/87,174///    SLH-DSA-SHA2-128f and SLH-DSA-SHAKE-128f — the lattice outputs are175///    compared through the SHA-256 of the official `pk ‖ sk`;176/// 3. pairwise consistency with fresh randomness: encapsulate/decapsulate and177///    implicit rejection for the three ML-KEM sets, sign/verify and rejection178///    of a modified message for the three ML-DSA sets and one SLH-DSA set;179/// 4. the OS CSPRNG returns data and two draws differ.180///181/// It is a smoke test, not the conformance suite: the full ACVP replay lives in182/// `cargo test`. It takes a few tens of milliseconds natively.183pub fn self_test() -> Result<()> {184    // 1. hashes185    check(186        hash::digest(HashAlg::Sha256, b"abc")187            == unhex::<32>("ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad"),188    )?;189    check(190        hash::digest(HashAlg::Sha512, b"abc")[..16]191            == unhex::<16>("ddaf35a193617abacc417349ae204131"),192    )?;193    check(194        hash::digest(HashAlg::Sha3_256, b"abc")195            == unhex::<32>("3a985da74fe225b2045c172d6bd390bd855f086e3e9d525b46bfe24511431532"),196    )?;197    check(198        hash::xof(HashAlg::Shake128, b"", 32)?199            == unhex::<32>("7f9c2ba4e88f827d616045507605853ed73b8093f6efbc88eb1a6eacfa66ef26"),200    )?;201    check(202        hash::xof(HashAlg::Shake256, b"", 32)?203            == unhex::<32>("46b9dd2b0ba88d13233b3feb743eeb243fcd52ea62b81b82b50c27646ed5762f"),204    )?;205206    // 2a. ML-KEM key generation (ACVP ML-KEM-keyGen-FIPS203, tcId 1 / 26 / 51)207    let mlkem_kats: [(KemAlg, &str, &str, &str); 3] = [208        (209            KemAlg::MlKem512,210            "65C47C5081A788044013AEBD3F969BB255F31333E028C5EA76AEB049BA086A67",211            "F79E9F443EA5C7A8E687AB79CF36AC521F40B777BB09730508BAF649506E8CEC",212            "60cf5d4dfd4d7bc9e6002f4d07ba92039a9490114099514494ee421322658e59",213        ),214        (215            KemAlg::MlKem768,216            "662F991D44C84D2580DD89393968EC2DDD33B905195C3596EC5293CD714F78CB",217            "C843F5583D31B7593C28859DA3A127764D124352B6A7CC5B87D74FFC22894E05",218            "a0003cea7e8280e6e7624227f6a91545504f46f838324e675d2f5ee3690fe0ba",219        ),220        (221            KemAlg::MlKem1024,222            "7C8871D318C2C067887104C7E51C86D10F91CE1EBBFDC1C05584468E878D1114",223            "EF0634E59C78932B723A17FD4053A08B61CEAA9ABEF3B2B16E0D4BABEE33A2A0",224            "f36d67922b3ded480a7600af714865b3ca65098dacca06a3a33757bc8027e0e6",225        ),226    ];227    for (alg, d, z, digest) in mlkem_kats {228        let p = alg.params();229        let mut ek = vec![0u8; p.ek_len()];230        let mut dk = vec![0u8; p.dk_len()];231        mlkem::keygen_internal(&p, &unhex::<32>(d), &unhex::<32>(z), &mut ek, &mut dk)?;232        let got = crate::hash::sha2::sha256(&[&ek, &dk]);233        check(got == unhex::<32>(digest))?;234    }235236    // 2b. ML-DSA key generation (ACVP ML-DSA-keyGen-FIPS204, tcId 1 / 26 / 51)237    let mldsa_kats: [(mldsa::Params, &str, &str); 3] = [238        (239            mldsa::MLDSA_44,240            "0B12FA1C4D28BC2EE27D7973AE400991B26C7D97497B4F4EEF66D2D945BDD22B",241            "f7a7ab2eb6c5bc0c6c728eb4f73ecf978e3ded8ad94716a538f19c07db2d2229",242        ),243        (244            mldsa::MLDSA_65,245            "89FA68C4FB91EF4B99881FEEC9C101B9B58387D20AC49067FCD0948EE63ABDF7",246            "67bcba5890c06b5463c45e01268600874e7d50237fb85658ddf355c67e2545ab",247        ),248        (249            mldsa::MLDSA_87,250            "8998D24AC3C5BC14F7A882DB264AD148BDA19CA0245B5FF3619C23886EAAE8E8",251            "a687a8aaba2a0aa374ea6eecc9049aea0e82fb986f6235e08c67424ceeacd2ce",252        ),253    ];254    for (p, seed, digest) in mldsa_kats {255        let (pk, sk) = mldsa::keygen_internal(&p, &unhex::<32>(seed));256        let got = crate::hash::sha2::sha256(&[&pk, &sk]);257        check(got == unhex::<32>(digest))?;258    }259260    // 2c. SLH-DSA key generation (ACVP SLH-DSA-keyGen-FIPS205, tcId 21 and 31)261    let slh_kats: [(slhdsa::Params, &str, &str, &str, &str); 2] = [262        (263            slhdsa::SLH_DSA_SHA2_128F,264            "E5A7E79DC46B94BDE6CBFFC93ECAD53C",265            "2598A43798E5E2B37CE6554EE2E0B94A",266            "0FE9F62E3BFE273BA8E205BF8B4D8E24",267            "0FE9F62E3BFE273BA8E205BF8B4D8E2487BDF348EE063567C9E4F05FBD7BD7A6",268        ),269        (270            slhdsa::SLH_DSA_SHAKE_128F,271            "F90D489F34B126B49FA16C118464C33A",272            "59BB92C38104A17EC8A779A284F1C881",273            "4DA13165D75C1AB54DE5EF827CD52E57",274            "4DA13165D75C1AB54DE5EF827CD52E57E638B304AFE165140D9FD0934B110563",275        ),276    ];277    for (p, sk_seed, sk_prf, pk_seed, pk_expect) in slh_kats {278        let (_sk, pk) = slhdsa::keygen_internal(279            &p,280            &unhex::<16>(sk_seed),281            &unhex::<16>(sk_prf),282            &unhex::<16>(pk_seed),283        )?;284        check(pk == unhex::<32>(pk_expect))?;285    }286287    // 3a. KEM pairwise consistency and implicit rejection288    for alg in KemAlg::ALL {289        let (pk, sk) = kem::generate_keypair(alg)?;290        let enc = kem::encapsulate(&pk)?;291        let ss = kem::decapsulate(&sk, &enc.ciphertext)?;292        check(crate::ct::eq(ss.expose(), enc.shared_secret.expose()))?;293        let mut bad = enc.ciphertext.clone();294        bad[0] ^= 1;295        let rejected = kem::decapsulate(&sk, &bad)?;296        check(!crate::ct::eq(rejected.expose(), ss.expose()))?;297    }298299    // 3b. signature pairwise consistency300    for alg in [301        SigAlg::MlDsa44,302        SigAlg::MlDsa65,303        SigAlg::MlDsa87,304        SigAlg::SlhDsaSha2_128f,305    ] {306        let (pk, sk) = signature::generate_keypair(alg)?;307        let opts = SignOptions {308            context: b"spb-pqc self-test",309            ..SignOptions::default()310        };311        let sig = signature::sign_with(&sk, b"self-test message", &opts)?;312        check(signature::verify_with(&pk, b"self-test message", &sig, &opts).is_ok())?;313        check(signature::verify_with(&pk, b"self-test messagf", &sig, &opts).is_err())?;314    }315316    // 4. RNG sanity317    let (mut a, mut b) = ([0u8; 32], [0u8; 32]);318    crate::random::fill(&mut a)?;319    crate::random::fill(&mut b)?;320    check(a != b)?;321    Ok(())322}323324#[cfg(test)]325mod tests {326    use super::*;327328    #[test]329    fn self_test_passes() {330        self_test().unwrap();331    }332333    #[test]334    fn self_test_reports_rng_failure() {335        crate::random::testing::force_failure(true);336        assert_eq!(self_test(), Err(Error::RandomFailure));337        crate::random::testing::force_failure(false);338    }339340    #[test]341    fn capabilities_is_valid_json_with_all_algorithms() {342        let v: serde_json::Value = serde_json::from_str(&capabilities_json()).unwrap();343        assert_eq!(v["kem"].as_array().unwrap().len(), 3);344        assert_eq!(v["signature"].as_array().unwrap().len(), 15);345        assert_eq!(v["hash"].as_array().unwrap().len(), 12);346        assert_eq!(v["envelope"].as_array().unwrap().len(), 0);347        assert_eq!(v["securityStatus"]["audited"], false);348        assert_eq!(v["kem"][1]["name"], "ML-KEM-768");349        assert_eq!(v["kem"][1]["publicKey"], 1184);350        assert_eq!(v["signature"][0]["oid"], "2.16.840.1.101.3.4.3.17");351        assert_eq!(v["version"], VERSION);352        // identifiers are unique353        let mut ids: Vec<u64> = ["kem", "signature", "hash"]354            .iter()355            .flat_map(|k| {356                v[*k]357                    .as_array()358                    .unwrap()359                    .iter()360                    .map(|a| a["id"].as_u64().unwrap())361            })362            .collect();363        let n = ids.len();364        ids.sort();365        ids.dedup();366        assert_eq!(ids.len(), n);367    }368}369
Files main
Menu

Theme