SPB Git

Repository Public Apache-2.0

mod.rs 13.9 KB 407 lines rust

1// =============================================================================2//                  SP BOUCHER | SOFTWARE & RESEARCH3//             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// Project          : SPB Quantum Crypto7// File             : crates/spb-pqc-core/src/encoding/mod.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//! Standard key containers: X.509 `SubjectPublicKeyInfo` and PKCS #842//! `OneAsymmetricKey` (v1) for the NIST algorithm identifiers.43//!44//! Profiles followed (pinned 2026-12-03):45//!46//! * ML-KEM: RFC 9935 — `id-alg-ml-kem-*`, private key `CHOICE { seed [0],47//!   expandedKey OCTET STRING, both SEQUENCE }`;48//! * ML-DSA: RFC 9881 — `id-ml-dsa-*`, same three-way `CHOICE`;49//! * SLH-DSA: RFC 9909 — `id-slh-dsa-*`, the private key is the raw `4n` bytes.50//!51//! No object identifier is invented here: all of them are the NIST-assigned52//! arcs `2.16.840.1.101.3.4.{3,4}.*`. `AlgorithmIdentifier.parameters` is53//! absent, as the three profiles require.54//!55//! Scope and limits, stated plainly:56//!57//! * **Encoding** always produces the `expandedKey` form (this library does not58//!   retain seeds after key generation).59//! * **Decoding** accepts `expandedKey` and `both` (using the expanded key and60//!   ignoring the seed, without checking that they match); a `seed`-only61//!   private key is rejected with [`Error::UnsupportedAlgorithm`].62//! * The DER reader is strict: definite minimal lengths, no trailing bytes, no63//!   attributes, version 0 only.64//!65//! This parser handles attacker-controlled input; it is fuzzed (`tests/fuzz`).6667use crate::ct::Secret;68use crate::error::{Error, Result};69use crate::kem::{KemAlg, KemPrivateKey, KemPublicKey};70use crate::signature::{SigAlg, SigPrivateKey, SigPublicKey};7172/// A decoded public key of either kind.73#[derive(Clone, Debug, PartialEq, Eq)]74pub enum PublicKey {75    /// An ML-KEM encapsulation key.76    Kem(KemPublicKey),77    /// An ML-DSA or SLH-DSA verification key.78    Sig(SigPublicKey),79}8081/// A decoded private key of either kind.82#[derive(Debug)]83pub enum PrivateKey {84    /// An ML-KEM decapsulation key.85    Kem(KemPrivateKey),86    /// An ML-DSA or SLH-DSA signing key.87    Sig(SigPrivateKey),88}8990/// DER of the common OID prefix `2.16.840.1.101.3.4` (without tag and length).91const NIST_ALG_PREFIX: [u8; 7] = [0x60, 0x86, 0x48, 0x01, 0x65, 0x03, 0x04];9293#[derive(Clone, Copy, PartialEq, Eq)]94enum Alg {95    Kem(KemAlg),96    Sig(SigAlg),97}9899impl Alg {100    /// The two trailing arcs: `4.x` for KEMs, `3.x` for signatures.101    fn arcs(self) -> [u8; 2] {102        match self {103            Alg::Kem(KemAlg::MlKem512) => [4, 1],104            Alg::Kem(KemAlg::MlKem768) => [4, 2],105            Alg::Kem(KemAlg::MlKem1024) => [4, 3],106            Alg::Sig(s) => [3, s.oid_arc()],107        }108    }109110    fn from_arcs(arcs: [u8; 2]) -> Result<Self> {111        if let Some(k) = KemAlg::ALL112            .into_iter()113            .find(|k| Alg::Kem(*k).arcs() == arcs)114        {115            return Ok(Alg::Kem(k));116        }117        SigAlg::ALL118            .into_iter()119            .find(|s| Alg::Sig(*s).arcs() == arcs)120            .map(Alg::Sig)121            .ok_or(Error::UnsupportedAlgorithm)122    }123124    /// `AlgorithmIdentifier ::= SEQUENCE { algorithm OBJECT IDENTIFIER }`.125    fn algorithm_identifier(self) -> Vec<u8> {126        let mut oid = NIST_ALG_PREFIX.to_vec();127        oid.extend_from_slice(&self.arcs());128        tlv(0x30, &tlv(0x06, &oid))129    }130}131132/// Encodes one DER TLV with a definite, minimal length.133fn tlv(tag: u8, content: &[u8]) -> Vec<u8> {134    let mut out = Vec::with_capacity(content.len() + 6);135    out.push(tag);136    let len = content.len();137    if len < 0x80 {138        out.push(len as u8);139    } else {140        let be = (len as u32).to_be_bytes();141        let skip = be.iter().take_while(|&&b| b == 0).count();142        out.push(0x80 | (4 - skip) as u8);143        out.extend_from_slice(&be[skip..]);144    }145    out.extend_from_slice(content);146    out147}148149/// Strict DER reader over a byte slice.150struct Reader<'a> {151    data: &'a [u8],152}153154impl<'a> Reader<'a> {155    fn new(data: &'a [u8]) -> Self {156        Reader { data }157    }158159    fn is_empty(&self) -> bool {160        self.data.is_empty()161    }162163    fn peek_tag(&self) -> Option<u8> {164        self.data.first().copied()165    }166167    /// Reads one TLV with the expected tag and returns its content.168    fn read(&mut self, tag: u8, err: Error) -> Result<&'a [u8]> {169        let d = self.data;170        if d.len() < 2 || d[0] != tag {171            return Err(err);172        }173        let (len, header) = if d[1] < 0x80 {174            (d[1] as usize, 2)175        } else {176            let nbytes = (d[1] & 0x7F) as usize;177            if nbytes == 0 || nbytes > 3 || d.len() < 2 + nbytes {178                return Err(err); // indefinite or absurd length179            }180            let mut len = 0usize;181            for &b in &d[2..2 + nbytes] {182                len = (len << 8) | b as usize;183            }184            // minimal encoding: no leading zero byte, long form only when needed185            if d[2] == 0 || len < 0x80 {186                return Err(err);187            }188            (len, 2 + nbytes)189        };190        if d.len() - header < len {191            return Err(err);192        }193        let (content, rest) = d[header..].split_at(len);194        self.data = rest;195        Ok(content)196    }197}198199fn read_algorithm(r: &mut Reader<'_>, err: Error) -> Result<Alg> {200    let mut alg_id = Reader::new(r.read(0x30, err)?);201    let oid = alg_id.read(0x06, err)?;202    if !alg_id.is_empty() {203        return Err(err); // parameters must be absent204    }205    if oid.len() != 9 || oid[..7] != NIST_ALG_PREFIX {206        return Err(Error::UnsupportedAlgorithm);207    }208    Alg::from_arcs([oid[7], oid[8]])209}210211fn spki(alg: Alg, key: &[u8]) -> Vec<u8> {212    let mut bits = Vec::with_capacity(key.len() + 1);213    bits.push(0); // no unused bits214    bits.extend_from_slice(key);215    let mut body = alg.algorithm_identifier();216    body.extend_from_slice(&tlv(0x03, &bits));217    tlv(0x30, &body)218}219220/// `SubjectPublicKeyInfo` (DER) of an ML-KEM encapsulation key.221pub fn kem_public_key_to_spki(key: &KemPublicKey) -> Vec<u8> {222    spki(Alg::Kem(key.algorithm()), key.as_bytes())223}224225/// `SubjectPublicKeyInfo` (DER) of a signature verification key.226pub fn sig_public_key_to_spki(key: &SigPublicKey) -> Vec<u8> {227    spki(Alg::Sig(key.algorithm()), key.as_bytes())228}229230/// Parses a DER `SubjectPublicKeyInfo`; the key goes through the same231/// validation as a raw import (FIPS 203 §7.2 for ML-KEM).232pub fn public_key_from_spki(der: &[u8]) -> Result<PublicKey> {233    let err = Error::InvalidPublicKey;234    let mut outer = Reader::new(der);235    let mut seq = Reader::new(outer.read(0x30, err)?);236    if !outer.is_empty() {237        return Err(err);238    }239    let alg = read_algorithm(&mut seq, err)?;240    let bits = seq.read(0x03, err)?;241    if !seq.is_empty() || bits.first() != Some(&0) {242        return Err(err);243    }244    let key = &bits[1..];245    Ok(match alg {246        Alg::Kem(a) => PublicKey::Kem(KemPublicKey::from_bytes(a, key)?),247        Alg::Sig(a) => PublicKey::Sig(SigPublicKey::from_bytes(a, key)?),248    })249}250251fn pkcs8(alg: Alg, expanded: &[u8]) -> Secret {252    // ML-KEM / ML-DSA: privateKey contains `expandedKey OCTET STRING`;253    // SLH-DSA: privateKey contains the raw key bytes.254    let inner = match alg {255        Alg::Sig(s) if !s.is_ml_dsa() => expanded.to_vec(),256        _ => tlv(0x04, expanded),257    };258    let mut body = vec![0x02, 0x01, 0x00]; // version v1(0)259    body.extend_from_slice(&alg.algorithm_identifier());260    body.extend_from_slice(&tlv(0x04, &inner));261    let out = Secret::new(tlv(0x30, &body));262    crate::ct::wipe(&mut body);263    let mut inner = inner;264    crate::ct::wipe(&mut inner);265    out266}267268/// PKCS #8 (DER, unencrypted, `expandedKey` form) of an ML-KEM decapsulation key.269pub fn kem_private_key_to_pkcs8(key: &KemPrivateKey) -> Secret {270    pkcs8(Alg::Kem(key.algorithm()), key.expose_bytes())271}272273/// PKCS #8 (DER, unencrypted) of a signing key.274pub fn sig_private_key_to_pkcs8(key: &SigPrivateKey) -> Secret {275    pkcs8(Alg::Sig(key.algorithm()), key.expose_bytes())276}277278/// Parses an unencrypted PKCS #8 private key (see the module docs for the279/// accepted `CHOICE` alternatives).280pub fn private_key_from_pkcs8(der: &[u8]) -> Result<PrivateKey> {281    let err = Error::InvalidPrivateKey;282    let mut outer = Reader::new(der);283    let mut seq = Reader::new(outer.read(0x30, err)?);284    if !outer.is_empty() {285        return Err(err);286    }287    if seq.read(0x02, err)? != [0] {288        return Err(err); // only version 0, without attributes or public key289    }290    let alg = read_algorithm(&mut seq, err)?;291    let private_key = seq.read(0x04, err)?;292    if !seq.is_empty() {293        return Err(err);294    }295    let expanded: &[u8] = match alg {296        Alg::Sig(s) if !s.is_ml_dsa() => private_key,297        _ => {298            let mut choice = Reader::new(private_key);299            let key = match choice.peek_tag() {300                Some(0x04) => choice.read(0x04, err)?,301                Some(0x30) => {302                    let mut both = Reader::new(choice.read(0x30, err)?);303                    let _seed = both.read(0x04, err)?;304                    let key = both.read(0x04, err)?;305                    if !both.is_empty() {306                        return Err(err);307                    }308                    key309                }310                Some(0x80) => return Err(Error::UnsupportedAlgorithm), // seed-only form311                _ => return Err(err),312            };313            if !choice.is_empty() {314                return Err(err);315            }316            key317        }318    };319    Ok(match alg {320        Alg::Kem(a) => PrivateKey::Kem(KemPrivateKey::from_bytes(a, expanded)?),321        Alg::Sig(a) => PrivateKey::Sig(SigPrivateKey::from_bytes(a, expanded)?),322    })323}324325#[cfg(test)]326mod tests {327    use super::*;328    use crate::{kem, signature};329330    #[test]331    fn tlv_lengths_are_minimal() {332        assert_eq!(tlv(0x04, &[0u8; 5])[..2], [0x04, 0x05]);333        assert_eq!(tlv(0x04, &[0u8; 127])[..2], [0x04, 0x7F]);334        assert_eq!(tlv(0x04, &[0u8; 128])[..3], [0x04, 0x81, 0x80]);335        assert_eq!(tlv(0x04, &[0u8; 300])[..4], [0x04, 0x82, 0x01, 0x2C]);336    }337338    #[test]339    fn spki_and_pkcs8_round_trip_every_family() {340        for alg in KemAlg::ALL {341            let (pk, sk) = kem::generate_keypair(alg).unwrap();342            let der = kem_public_key_to_spki(&pk);343            assert_eq!(public_key_from_spki(&der).unwrap(), PublicKey::Kem(pk));344            let p8 = kem_private_key_to_pkcs8(&sk);345            match private_key_from_pkcs8(p8.expose()).unwrap() {346                PrivateKey::Kem(k) => assert_eq!(k.expose_bytes(), sk.expose_bytes()),347                _ => panic!("wrong kind"),348            }349        }350        for alg in [351            SigAlg::MlDsa44,352            SigAlg::MlDsa87,353            SigAlg::SlhDsaSha2_128f,354            SigAlg::SlhDsaShake256f,355        ] {356            let (pk, sk) = signature::generate_keypair(alg).unwrap();357            let der = sig_public_key_to_spki(&pk);358            assert_eq!(public_key_from_spki(&der).unwrap(), PublicKey::Sig(pk));359            let p8 = sig_private_key_to_pkcs8(&sk);360            match private_key_from_pkcs8(p8.expose()).unwrap() {361                PrivateKey::Sig(k) => {362                    assert_eq!(k.algorithm(), alg);363                    assert_eq!(k.expose_bytes(), sk.expose_bytes());364                }365                _ => panic!("wrong kind"),366            }367        }368    }369370    #[test]371    fn strict_der_rejections() {372        let (pk, _) = kem::generate_keypair(KemAlg::MlKem512).unwrap();373        let der = kem_public_key_to_spki(&pk);374        // trailing byte375        let mut bad = der.clone();376        bad.push(0);377        assert_eq!(378            public_key_from_spki(&bad).err(),379            Some(Error::InvalidPublicKey)380        );381        // truncated at every length must fail, never panic382        for cut in 0..der.len() {383            assert!(public_key_from_spki(&der[..cut]).is_err());384        }385        // unknown algorithm arc386        let mut bad = der.clone();387        let pos = bad.windows(7).position(|w| w == NIST_ALG_PREFIX).unwrap();388        bad[pos + 8] = 0x7E;389        assert_eq!(390            public_key_from_spki(&bad).err(),391            Some(Error::UnsupportedAlgorithm)392        );393        // non-zero unused-bits octet394        let mut bad = der.clone();395        let bit_string = bad.len() - pk.as_bytes().len() - 1;396        bad[bit_string] = 1;397        assert_eq!(398            public_key_from_spki(&bad).err(),399            Some(Error::InvalidPublicKey)400        );401        // empty and garbage inputs402        assert!(public_key_from_spki(&[]).is_err());403        assert!(private_key_from_pkcs8(&[0x30, 0x80]).is_err());404        assert!(private_key_from_pkcs8(&[0x30, 0x84, 0xFF, 0xFF, 0xFF, 0xFF]).is_err());405    }406}407
Files main
Menu

Theme