SPB Git

Repository Public Apache-2.0

mod.rs 10.4 KB 309 lines rust

1// =============================================================================2//                  SP BOUCHER | SOFTWARE & RESEARCH3//             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// Project          : SPB Quantum Crypto7// File             : crates/spb-pqc-core/src/hash/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//! Hash functions and XOFs implemented from FIPS 202 and FIPS 180-4, and the42//! public algorithm-agile digest façade (`hash.digest` / `hash.xof`).4344pub mod keccak;45pub mod sha2;4647use crate::error::{Error, Result};4849/// Upper bound on a single XOF request through the façade (16 MiB).50pub const MAX_XOF_OUTPUT: usize = 1 << 24;5152/// Hash and XOF identifiers. The string names are part of the stable registry53/// (`docs/standards/algorithm-registry.md`).54#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]55#[non_exhaustive]56pub enum HashAlg {57    /// SHA-224 (FIPS 180-4).58    Sha224,59    /// SHA-256 (FIPS 180-4).60    Sha256,61    /// SHA-384 (FIPS 180-4).62    Sha384,63    /// SHA-512 (FIPS 180-4).64    Sha512,65    /// SHA-512/224 (FIPS 180-4).66    Sha512_224,67    /// SHA-512/256 (FIPS 180-4).68    Sha512_256,69    /// SHA3-224 (FIPS 202).70    Sha3_224,71    /// SHA3-256 (FIPS 202).72    Sha3_256,73    /// SHA3-384 (FIPS 202).74    Sha3_384,75    /// SHA3-512 (FIPS 202).76    Sha3_512,77    /// SHAKE128 (FIPS 202); as a pre-hash it outputs 256 bits.78    Shake128,79    /// SHAKE256 (FIPS 202); as a pre-hash it outputs 512 bits.80    Shake256,81}8283impl HashAlg {84    /// Every identifier, in registry order.85    pub const ALL: [HashAlg; 12] = [86        HashAlg::Sha224,87        HashAlg::Sha256,88        HashAlg::Sha384,89        HashAlg::Sha512,90        HashAlg::Sha512_224,91        HashAlg::Sha512_256,92        HashAlg::Sha3_224,93        HashAlg::Sha3_256,94        HashAlg::Sha3_384,95        HashAlg::Sha3_512,96        HashAlg::Shake128,97        HashAlg::Shake256,98    ];99100    /// Stable registry name (NIST spelling).101    pub const fn name(self) -> &'static str {102        match self {103            HashAlg::Sha224 => "SHA2-224",104            HashAlg::Sha256 => "SHA2-256",105            HashAlg::Sha384 => "SHA2-384",106            HashAlg::Sha512 => "SHA2-512",107            HashAlg::Sha512_224 => "SHA2-512/224",108            HashAlg::Sha512_256 => "SHA2-512/256",109            HashAlg::Sha3_224 => "SHA3-224",110            HashAlg::Sha3_256 => "SHA3-256",111            HashAlg::Sha3_384 => "SHA3-384",112            HashAlg::Sha3_512 => "SHA3-512",113            HashAlg::Shake128 => "SHAKE-128",114            HashAlg::Shake256 => "SHAKE-256",115        }116    }117118    /// Parses a registry name (case-insensitive; `SHA-256`, `SHA256` and `SHA2-256` are accepted).119    pub fn from_name(name: &str) -> Result<Self> {120        let n: String = name121            .chars()122            .filter(|c| !matches!(c, '-' | '_' | ' '))123            .map(|c| c.to_ascii_uppercase())124            .collect();125        Ok(match n.as_str() {126            "SHA2224" | "SHA224" => HashAlg::Sha224,127            "SHA2256" | "SHA256" => HashAlg::Sha256,128            "SHA2384" | "SHA384" => HashAlg::Sha384,129            "SHA2512" | "SHA512" => HashAlg::Sha512,130            "SHA2512/224" | "SHA512/224" => HashAlg::Sha512_224,131            "SHA2512/256" | "SHA512/256" => HashAlg::Sha512_256,132            "SHA3224" => HashAlg::Sha3_224,133            "SHA3256" => HashAlg::Sha3_256,134            "SHA3384" => HashAlg::Sha3_384,135            "SHA3512" => HashAlg::Sha3_512,136            "SHAKE128" => HashAlg::Shake128,137            "SHAKE256" => HashAlg::Shake256,138            _ => return Err(Error::UnsupportedAlgorithm),139        })140    }141142    /// Stable numeric identifier of the SPB registry (`0x04xx` = hash / XOF).143    pub const fn id(self) -> u32 {144        match self {145            HashAlg::Sha224 => 0x0401,146            HashAlg::Sha256 => 0x0402,147            HashAlg::Sha384 => 0x0403,148            HashAlg::Sha512 => 0x0404,149            HashAlg::Sha512_224 => 0x0405,150            HashAlg::Sha512_256 => 0x0406,151            HashAlg::Sha3_224 => 0x0407,152            HashAlg::Sha3_256 => 0x0408,153            HashAlg::Sha3_384 => 0x0409,154            HashAlg::Sha3_512 => 0x040A,155            HashAlg::Shake128 => 0x040B,156            HashAlg::Shake256 => 0x040C,157        }158    }159160    /// Looks an algorithm up by registry identifier.161    pub fn from_id(id: u32) -> Result<Self> {162        Self::ALL163            .into_iter()164            .find(|a| a.id() == id)165            .ok_or(Error::UnsupportedAlgorithm)166    }167168    /// Whether this is an extendable-output function.169    pub const fn is_xof(self) -> bool {170        matches!(self, HashAlg::Shake128 | HashAlg::Shake256)171    }172173    /// Digest length in bytes. For the XOFs this is the length used when they174    /// act as a pre-hash in FIPS 204 §5.4 / FIPS 205 §10.2 (256 and 512 bits).175    pub const fn digest_len(self) -> usize {176        match self {177            HashAlg::Sha224 | HashAlg::Sha512_224 | HashAlg::Sha3_224 => 28,178            HashAlg::Sha256 | HashAlg::Sha512_256 | HashAlg::Sha3_256 | HashAlg::Shake128 => 32,179            HashAlg::Sha384 | HashAlg::Sha3_384 => 48,180            HashAlg::Sha512 | HashAlg::Sha3_512 | HashAlg::Shake256 => 64,181        }182    }183184    /// DER encoding of the NIST object identifier `2.16.840.1.101.3.4.2.x`185    /// (tag `06`, length `09`), as concatenated in the pre-hash message186    /// representative of FIPS 204 Algorithm 4 and FIPS 205 Algorithm 23.187    pub const fn oid_der(self) -> [u8; 11] {188        let last = match self {189            HashAlg::Sha256 => 0x01,190            HashAlg::Sha384 => 0x02,191            HashAlg::Sha512 => 0x03,192            HashAlg::Sha224 => 0x04,193            HashAlg::Sha512_224 => 0x05,194            HashAlg::Sha512_256 => 0x06,195            HashAlg::Sha3_224 => 0x07,196            HashAlg::Sha3_256 => 0x08,197            HashAlg::Sha3_384 => 0x09,198            HashAlg::Sha3_512 => 0x0A,199            HashAlg::Shake128 => 0x0B,200            HashAlg::Shake256 => 0x0C,201        };202        [203            0x06, 0x09, 0x60, 0x86, 0x48, 0x01, 0x65, 0x03, 0x04, 0x02, last,204        ]205    }206}207208/// `hash.digest(algorithm, bytes)`: fixed-length digest (`digest_len()` bytes).209pub fn digest(alg: HashAlg, data: &[u8]) -> Vec<u8> {210    let mut out = vec![0u8; alg.digest_len()];211    match alg {212        HashAlg::Sha224 => {213            let mut h = sha2::Sha256::new_224();214            h.update(data);215            h.finalize_into(&mut out);216        }217        HashAlg::Sha256 => {218            let mut h = sha2::Sha256::new();219            h.update(data);220            h.finalize_into(&mut out);221        }222        HashAlg::Sha384 => {223            let mut h = sha2::Sha512::new_384();224            h.update(data);225            h.finalize_into(&mut out);226        }227        HashAlg::Sha512 => {228            let mut h = sha2::Sha512::new();229            h.update(data);230            h.finalize_into(&mut out);231        }232        HashAlg::Sha512_224 => {233            let mut h = sha2::Sha512::new_512_224();234            h.update(data);235            h.finalize_into(&mut out);236        }237        HashAlg::Sha512_256 => {238            let mut h = sha2::Sha512::new_512_256();239            h.update(data);240            h.finalize_into(&mut out);241        }242        HashAlg::Sha3_224 => {243            let mut h = keccak::Sha3::new_224();244            h.update(data);245            h.finalize_into(&mut out);246        }247        HashAlg::Sha3_256 => {248            let mut h = keccak::Sha3::new_256();249            h.update(data);250            h.finalize_into(&mut out);251        }252        HashAlg::Sha3_384 => {253            let mut h = keccak::Sha3::new_384();254            h.update(data);255            h.finalize_into(&mut out);256        }257        HashAlg::Sha3_512 => {258            let mut h = keccak::Sha3::new_512();259            h.update(data);260            h.finalize_into(&mut out);261        }262        HashAlg::Shake128 => keccak::shake128(&[data], &mut out),263        HashAlg::Shake256 => keccak::shake256(&[data], &mut out),264    }265    out266}267268/// `hash.xof(algorithm, bytes, outputLength)`: SHAKE128 / SHAKE256 only.269pub fn xof(alg: HashAlg, data: &[u8], output_len: usize) -> Result<Vec<u8>> {270    if output_len > MAX_XOF_OUTPUT {271        return Err(Error::SizeLimitExceeded);272    }273    let mut out = vec![0u8; output_len];274    match alg {275        HashAlg::Shake128 => keccak::shake128(&[data], &mut out),276        HashAlg::Shake256 => keccak::shake256(&[data], &mut out),277        _ => return Err(Error::UnsupportedAlgorithm),278    }279    Ok(out)280}281282#[cfg(test)]283mod tests {284    use super::*;285286    #[test]287    fn names_round_trip() {288        for a in HashAlg::ALL {289            assert_eq!(HashAlg::from_name(a.name()).unwrap(), a);290            assert_eq!(digest(a, b"x").len(), a.digest_len());291        }292        assert_eq!(HashAlg::from_name("sha-256").unwrap(), HashAlg::Sha256);293        assert_eq!(HashAlg::from_name("md5"), Err(Error::UnsupportedAlgorithm));294    }295296    #[test]297    fn xof_rejects_fixed_hashes_and_huge_outputs() {298        assert_eq!(299            xof(HashAlg::Sha256, b"", 32),300            Err(Error::UnsupportedAlgorithm)301        );302        assert_eq!(303            xof(HashAlg::Shake128, b"", MAX_XOF_OUTPUT + 1),304            Err(Error::SizeLimitExceeded)305        );306        assert_eq!(xof(HashAlg::Shake256, b"", 0).unwrap().len(), 0);307    }308}309
Files main
Menu

Theme