diff --git a/CLAUDE.md b/CLAUDE.md index 6f858b53..47afcb05 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -41,8 +41,8 @@ cargo run --release -p mem_usage_benches --bin bench_mldsa_mem_usage The workspace has three top-level kinds of member: -1. `crypto/*` — one sub-crate per primitive (`sha2`, `sha3`, `hmac`, `hkdf`, `mlkem`, `mlkem_lowmemory`, `mldsa`, `mldsa_lowmemory`, `rng`, `hex`, `base64`, `utils`) plus the spine crates `core`, `core-test-framework`, and `factory`. Each crate is published as `bouncycastle-` and depended on internally via the `workspace.dependencies` table in the root `Cargo.toml`. -2. `src/` — the umbrella `bouncycastle` crate, which is just `pub use` re-exports of every sub-crate (e.g. `bouncycastle::sha3`, `bouncycastle::mlkem`). It exists so downstream users can pull the whole library with one dependency; it has no code of its own. +1. `crypto/*` — one sub-crate per primitive (`sha2`, `sha3`, `sm3`, `hmac`, `hkdf`, `mlkem`, `mlkem_lowmemory`, `mldsa`, `mldsa_lowmemory`, `rng`, `hex`, `base64`, `utils`) plus the spine crates `core`, `core-test-framework`, and `factory`. Each crate is published as `bouncycastle-` and depended on internally via the `workspace.dependencies` table in the root `Cargo.toml`. +2. `src/` — the umbrella `bouncycastle` crate, which is just `pub use` re-exports of every sub-crate (e.g. `bouncycastle::sha3`, `bouncycastle::sm3`, `bouncycastle::mlkem`). It exists so downstream users can pull the whole library with one dependency; it has no code of its own. 3. `cli/` — the `bc-rust` binary built on top of `bouncycastle`, exposing every primitive as a streaming stdin→stdout subcommand using `clap`. 4. `mem_usage_benches/` — stand-alone binary crates that measure peak stack usage of algorithms (cannot be done via criterion). diff --git a/Cargo.toml b/Cargo.toml index 82b379fe..75cf184d 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -23,6 +23,7 @@ bouncycastle-mldsa-lowmemory = { path = "./crypto/mldsa-lowmemory" } bouncycastle-rng = { path = "./crypto/rng" } bouncycastle-sha2 = { path = "./crypto/sha2" } bouncycastle-sha3 = { path = "./crypto/sha3" } +bouncycastle-sm3 = { path = "./crypto/sm3" } bouncycastle-utils = { path = "./crypto/utils" } @@ -54,3 +55,4 @@ bouncycastle-mlkem-lowmemory.workspace = true bouncycastle-rng.workspace = true bouncycastle-sha2.workspace = true bouncycastle-sha3.workspace = true +bouncycastle-sm3.workspace = true diff --git a/alpha_0.1.3_release_notes.md b/alpha_0.1.3_release_notes.md index 210a5aeb..371e918d 100644 --- a/alpha_0.1.3_release_notes.md +++ b/alpha_0.1.3_release_notes.md @@ -2,4 +2,13 @@ ## Major features +* New algorithms added to crypto/ (PR #89): + * sm3 -- the SM3 hash (GB/T 32905-2016 / ISO/IEC 10118-3:2018), ported from bc-java. Implements `Hash`, + `Suspendable` and `AlgorithmOID`, supports bit-oriented (partial final byte) messages per GB/T 32905-2016 s. 5.2 + using the same least-significant-bits convention as SHA-2/SHA-3, and is registered in `HashFactory` + (`"SM3"`) with a `bc-rust sm3` CLI subcommand. + * HMAC-SM3, in the hmac crate, registered in `MACFactory` (`"HMAC-SM3"`) with a `bc-rust hmac-sm3` CLI subcommand. + * Test vectors are the GB/T 32905-2016 Appendix A examples plus the bc-java `SM3DigestTest` / `HMac` vectors, with + additional digests cross-checked against OpenSSL and bc-java. + ## Minor features / bug fixes diff --git a/cli/src/mac_cmd.rs b/cli/src/mac_cmd.rs index bb7aafc8..5929ca5d 100644 --- a/cli/src/mac_cmd.rs +++ b/cli/src/mac_cmd.rs @@ -7,11 +7,12 @@ use bouncycastle::core::key_material::{ }; use bouncycastle::core::traits::MAC; use bouncycastle::hex; -use bouncycastle::hmac::{HMAC_SHA256, HMAC_SHA512}; +use bouncycastle::hmac::{HMAC_SHA256, HMAC_SHA512, HMAC_SM3}; pub(crate) enum HMACVariant { SHA256, SHA512, + SM3, } pub(crate) fn mac_cmd( @@ -48,6 +49,10 @@ pub(crate) fn mac_cmd( let mac = HMAC_SHA512::new_allow_weak_key(&key).unwrap(); do_mac(mac, verify_val, output_hex); } + HMACVariant::SM3 => { + let mac = HMAC_SM3::new_allow_weak_key(&key).unwrap(); + do_mac(mac, verify_val, output_hex); + } } } diff --git a/cli/src/main.rs b/cli/src/main.rs index 45205bff..e4192514 100644 --- a/cli/src/main.rs +++ b/cli/src/main.rs @@ -7,6 +7,7 @@ mod mlkem_cmd; mod rng_cmd; mod sha2_cmd; mod sha3_cmd; +mod sm3_cmd; use crate::mac_cmd::HMACVariant; use crate::mldsa_cmd::MLDSAAction; @@ -102,6 +103,14 @@ enum Subcommands { x: bool, }, + /// Perform SM3 of the content provided on stdin. + /// Supports streaming update for low memory footprint. + SM3 { + #[arg(short)] + /// Output the hashes in hex format. + x: bool, + }, + /// Perform SHAKE128 of the content provided on stdin. Requires the output length in bytes. /// Supports streaming update for low memory footprint. SHAKE128 { @@ -173,6 +182,31 @@ enum Subcommands { x: bool, }, + /// Perform HMAC-SM3 of the content provided on stdin. + /// Supports streaming update for low memory footprint. + /// Note: in production uses, secrets should not be passed on the command-line because they get + /// logged in shell history. Use the file-based input instead. + HMAC_SM3 { + /// The MAC key in hex. + /// The `key_file` option is preferred to avoid leaving key material in command history. + #[arg(long)] + key: Option, + + /// A file containing the MAC key in binary. + /// If both key and key_file options are provided, the file will be used. + #[arg(short, long)] + key_file: Option, + + /// A MAC value to be verified. + /// The command will output either 0 for success or -1 for verification failure. + #[arg(short, long)] + verify: Option, + + #[arg(short)] + /// Output the hashes in hex format. + x: bool, + }, + /// Perform HMAC-SHA256 of the content provided on stdin. /// HKDF.extract_and_expand(salt, ikm, additional_info, L) /// Note: in production uses, secrets should not be passed on the command-line because they get @@ -525,6 +559,9 @@ fn main() { Some(Subcommands::SHA3_512 { x }) => { sha3_cmd::sha3_cmd(512, *x); } + Some(Subcommands::SM3 { x }) => { + sm3_cmd::sm3_cmd(*x); + } Some(Subcommands::SHAKE128 { length, x }) => { sha3_cmd::shake_cmd(128, *length, *x); } @@ -537,6 +574,9 @@ fn main() { Some(Subcommands::HMAC_SHA512 { key, key_file, verify, x }) => { mac_cmd::mac_cmd(HMACVariant::SHA512, key, key_file, verify, *x) } + Some(Subcommands::HMAC_SM3 { key, key_file, verify, x }) => { + mac_cmd::mac_cmd(HMACVariant::SM3, key, key_file, verify, *x) + } Some(Subcommands::HKDF_SHA256 { salt, salt_file, diff --git a/cli/src/sm3_cmd.rs b/cli/src/sm3_cmd.rs new file mode 100644 index 00000000..98630c64 --- /dev/null +++ b/cli/src/sm3_cmd.rs @@ -0,0 +1,28 @@ +use bouncycastle::core::traits::Hash; +use std::io; +use std::io::{Read, Write}; + +use bouncycastle::sm3::SM3; + +pub(crate) fn sm3_cmd(output_hex: bool) { + let mut sm3 = SM3::new(); + let mut buf: [u8; 1024] = [0u8; 1024]; + + // read from stdin + let mut bytes_read = io::stdin().read(&mut buf).expect("Failed to read from stdin"); + while bytes_read != 0 { + sm3.do_update(&buf[..bytes_read]); + bytes_read = io::stdin().read(&mut buf).expect("Failed to read from stdin"); + } + + let out = sm3.do_final(); + + if output_hex { + for b in out.iter() { + print!("{b:02x}"); + } + } else { + io::stdout().write_all(&out).unwrap(); + } + println!(); +} diff --git a/crypto/factory/Cargo.toml b/crypto/factory/Cargo.toml index d3060ebd..5be05ba6 100644 --- a/crypto/factory/Cargo.toml +++ b/crypto/factory/Cargo.toml @@ -9,6 +9,7 @@ bouncycastle-hkdf.workspace = true bouncycastle-hmac.workspace = true bouncycastle-sha2.workspace = true bouncycastle-sha3.workspace = true +bouncycastle-sm3.workspace = true bouncycastle-rng.workspace = true [dev-dependencies] diff --git a/crypto/factory/src/hash_factory.rs b/crypto/factory/src/hash_factory.rs index edbfd17a..0dd53c32 100644 --- a/crypto/factory/src/hash_factory.rs +++ b/crypto/factory/src/hash_factory.rs @@ -34,6 +34,8 @@ use bouncycastle_sha2 as sha2; use bouncycastle_sha2::{SHA224_NAME, SHA256_NAME, SHA384_NAME, SHA512_NAME}; use bouncycastle_sha3 as sha3; use bouncycastle_sha3::{SHA3_224_NAME, SHA3_256_NAME, SHA3_384_NAME, SHA3_512_NAME}; +use bouncycastle_sm3 as sm3; +use bouncycastle_sm3::SM3_NAME; /// Wrapper object for all algorithms that impl [`Hash`]. /// Note: no SHAKE because SHAKE is not NIST approved as a hash function. See FIPS 202 section A.2. @@ -55,6 +57,8 @@ pub enum HashFactory { SHA3_384(sha3::SHA3_384), /// SHA3_512(sha3::SHA3_512), + /// + SM3(sm3::SM3), } impl Default for HashFactory { @@ -84,6 +88,7 @@ impl AlgorithmFactory for HashFactory { SHA3_256_NAME => Ok(Self::SHA3_256(sha3::SHA3_256::new())), SHA3_384_NAME => Ok(Self::SHA3_384(sha3::SHA3_384::new())), SHA3_512_NAME => Ok(Self::SHA3_512(sha3::SHA3_512::new())), + SM3_NAME => Ok(Self::SM3(sm3::SM3::new())), _ => Err(FactoryError::UnsupportedAlgorithm(format!( "The algorithm: \"{}\" is not a known Hash", alg_name @@ -112,6 +117,7 @@ impl Hash for HashFactory { Self::SHA3_256(h) => h.block_bitlen(), Self::SHA3_384(h) => h.block_bitlen(), Self::SHA3_512(h) => h.block_bitlen(), + Self::SM3(h) => h.block_bitlen(), } } @@ -125,6 +131,7 @@ impl Hash for HashFactory { Self::SHA3_256(h) => h.output_len(), Self::SHA3_384(h) => h.output_len(), Self::SHA3_512(h) => h.output_len(), + Self::SM3(h) => h.output_len(), } } @@ -138,6 +145,7 @@ impl Hash for HashFactory { Self::SHA3_256(h) => h.hash(data), Self::SHA3_384(h) => h.hash(data), Self::SHA3_512(h) => h.hash(data), + Self::SM3(h) => h.hash(data), } } @@ -153,6 +161,7 @@ impl Hash for HashFactory { Self::SHA3_256(h) => h.hash_out(data, output), Self::SHA3_384(h) => h.hash_out(data, output), Self::SHA3_512(h) => h.hash_out(data, output), + Self::SM3(h) => h.hash_out(data, output), } } @@ -166,6 +175,7 @@ impl Hash for HashFactory { Self::SHA3_256(h) => h.do_update(data), Self::SHA3_384(h) => h.do_update(data), Self::SHA3_512(h) => h.do_update(data), + Self::SM3(h) => h.do_update(data), } } @@ -179,6 +189,7 @@ impl Hash for HashFactory { Self::SHA3_256(h) => h.do_final(), Self::SHA3_384(h) => h.do_final(), Self::SHA3_512(h) => h.do_final(), + Self::SM3(h) => h.do_final(), } } @@ -194,6 +205,7 @@ impl Hash for HashFactory { Self::SHA3_256(h) => h.do_final_out(output), Self::SHA3_384(h) => h.do_final_out(output), Self::SHA3_512(h) => h.do_final_out(output), + Self::SM3(h) => h.do_final_out(output), } } @@ -211,6 +223,7 @@ impl Hash for HashFactory { Self::SHA3_256(h) => h.do_final_partial_bits(partial_byte, num_partial_bits), Self::SHA3_384(h) => h.do_final_partial_bits(partial_byte, num_partial_bits), Self::SHA3_512(h) => h.do_final_partial_bits(partial_byte, num_partial_bits), + Self::SM3(h) => h.do_final_partial_bits(partial_byte, num_partial_bits), } } @@ -237,6 +250,7 @@ impl Hash for HashFactory { Self::SHA3_512(h) => { h.do_final_partial_bits_out(partial_byte, num_partial_bits, output) } + Self::SM3(h) => h.do_final_partial_bits_out(partial_byte, num_partial_bits, output), } } @@ -250,6 +264,7 @@ impl Hash for HashFactory { Self::SHA3_256(h) => h.max_security_strength(), Self::SHA3_384(h) => h.max_security_strength(), Self::SHA3_512(h) => h.max_security_strength(), + Self::SM3(h) => h.max_security_strength(), } } } diff --git a/crypto/factory/src/mac_factory.rs b/crypto/factory/src/mac_factory.rs index f9a46768..9c278441 100644 --- a/crypto/factory/src/mac_factory.rs +++ b/crypto/factory/src/mac_factory.rs @@ -75,12 +75,14 @@ use bouncycastle_core::errors::MACError; use bouncycastle_core::key_material::KeyMaterialTrait; use bouncycastle_core::traits::{MAC, SecurityStrength}; use bouncycastle_hmac as hmac; +use bouncycastle_hmac::HMAC_SM3_NAME; use bouncycastle_hmac::{ HMAC_SHA3_224_NAME, HMAC_SHA3_256_NAME, HMAC_SHA3_384_NAME, HMAC_SHA3_512_NAME, }; use bouncycastle_hmac::{HMAC_SHA224_NAME, HMAC_SHA256_NAME, HMAC_SHA384_NAME, HMAC_SHA512_NAME}; use bouncycastle_sha2 as sha2; use bouncycastle_sha3 as sha3; +use bouncycastle_sm3 as sm3; /*** Defaults ***/ /// @@ -113,6 +115,8 @@ pub enum MACFactory { HMAC_SHA3_384(hmac::HMAC), /// HMAC_SHA3_512(hmac::HMAC), + /// + HMAC_SM3(hmac::HMAC), } impl MACFactory { @@ -142,6 +146,7 @@ impl MACFactory { HMAC_SHA3_256_NAME => Ok(Self::HMAC_SHA3_256(hmac::HMAC::::new(key)?)), HMAC_SHA3_384_NAME => Ok(Self::HMAC_SHA3_384(hmac::HMAC::::new(key)?)), HMAC_SHA3_512_NAME => Ok(Self::HMAC_SHA3_512(hmac::HMAC::::new(key)?)), + HMAC_SM3_NAME => Ok(Self::HMAC_SM3(hmac::HMAC::::new(key)?)), _ => Err(FactoryError::UnsupportedAlgorithm(format!( "The algorithm: \"{}\" is not a known MAC", alg_name @@ -171,6 +176,7 @@ impl MAC for MACFactory { Self::HMAC_SHA3_256(h) => h.output_len(), Self::HMAC_SHA3_384(h) => h.output_len(), Self::HMAC_SHA3_512(h) => h.output_len(), + Self::HMAC_SM3(h) => h.output_len(), } } @@ -184,6 +190,7 @@ impl MAC for MACFactory { Self::HMAC_SHA3_256(h) => h.mac(data), Self::HMAC_SHA3_384(h) => h.mac(data), Self::HMAC_SHA3_512(h) => h.mac(data), + Self::HMAC_SM3(h) => h.mac(data), } } @@ -199,6 +206,7 @@ impl MAC for MACFactory { Self::HMAC_SHA3_256(h) => h.mac_out(data, out), Self::HMAC_SHA3_384(h) => h.mac_out(data, out), Self::HMAC_SHA3_512(h) => h.mac_out(data, out), + Self::HMAC_SM3(h) => h.mac_out(data, out), } } @@ -212,6 +220,7 @@ impl MAC for MACFactory { Self::HMAC_SHA3_256(h) => h.verify(data, mac), Self::HMAC_SHA3_384(h) => h.verify(data, mac), Self::HMAC_SHA3_512(h) => h.verify(data, mac), + Self::HMAC_SM3(h) => h.verify(data, mac), } } @@ -225,6 +234,7 @@ impl MAC for MACFactory { Self::HMAC_SHA3_256(h) => h.do_update(data), Self::HMAC_SHA3_384(h) => h.do_update(data), Self::HMAC_SHA3_512(h) => h.do_update(data), + Self::HMAC_SM3(h) => h.do_update(data), } } @@ -238,6 +248,7 @@ impl MAC for MACFactory { Self::HMAC_SHA3_256(h) => h.do_final(), Self::HMAC_SHA3_384(h) => h.do_final(), Self::HMAC_SHA3_512(h) => h.do_final(), + Self::HMAC_SM3(h) => h.do_final(), } } @@ -253,6 +264,7 @@ impl MAC for MACFactory { Self::HMAC_SHA3_256(h) => h.do_final_out(&mut out), Self::HMAC_SHA3_384(h) => h.do_final_out(&mut out), Self::HMAC_SHA3_512(h) => h.do_final_out(&mut out), + Self::HMAC_SM3(h) => h.do_final_out(&mut out), } } @@ -266,6 +278,7 @@ impl MAC for MACFactory { Self::HMAC_SHA3_256(h) => h.do_verify_final(mac), Self::HMAC_SHA3_384(h) => h.do_verify_final(mac), Self::HMAC_SHA3_512(h) => h.do_verify_final(mac), + Self::HMAC_SM3(h) => h.do_verify_final(mac), } } @@ -279,6 +292,7 @@ impl MAC for MACFactory { Self::HMAC_SHA3_256(h) => h.max_security_strength(), Self::HMAC_SHA3_384(h) => h.max_security_strength(), Self::HMAC_SHA3_512(h) => h.max_security_strength(), + Self::HMAC_SM3(h) => h.max_security_strength(), } } } diff --git a/crypto/factory/tests/hash_factory_tests.rs b/crypto/factory/tests/hash_factory_tests.rs index 31d216bc..905b0691 100644 --- a/crypto/factory/tests/hash_factory_tests.rs +++ b/crypto/factory/tests/hash_factory_tests.rs @@ -56,6 +56,26 @@ mod hash_factory_tests { assert_eq!(sha2.hash(&DUMMY_SEED[..512]), b"\xed\xb9\xbe\xd7\x21\xaa\x6a\x5f\x6f\xbc\x66\x19\xd3\xa3\xc2\xbe\x3d\x04\x30\x43\xf0\x5a\x9a\xeb\xc7\xb1\x19\x7a\x2a\xa9\xc4\x9a\x57\xd5\xdd\xd4\x67\x4c\x17\x85\x78\x50\x88\xd9\xf1\xff\x42\xc7\x97\xa0\x2a\xdc\x9b\x81\x7a\x13\x9a\x50\x97\x0d\xa6\xc9\x95\x24"); } + #[test] + fn sm3_hash_tests() { + use bouncycastle_sm3 as sm3; + // Expected values: GB/T 32905-2016 Appendix A ("abc") and openssl dgst -sm3 (DUMMY_SEED[..512]). + for name in ["SM3", sm3::SM3_NAME] { + let h = HashFactory::new(name).unwrap(); + assert_eq!(h.output_len(), 32); + assert_eq!(h.block_bitlen(), 512); + assert_eq!( + h.hash(&DUMMY_SEED[..512]), + b"\xb2\x1f\x83\x0d\xca\x06\xbe\x8b\x67\x8c\xf9\x87\xf2\x6b\x9a\x43\x6e\x1b\x42\x79\x63\xb4\x45\x03\x32\xf0\x12\x70\xbd\x2d\xf7\x5c" + ); + let h = HashFactory::new(name).unwrap(); + assert_eq!( + h.hash(b"abc"), + b"\x66\xc7\xf0\xf4\x62\xee\xed\xd9\xd1\xf2\xd4\x6b\xdc\x10\xe4\xe2\x41\x67\xc4\x87\x5c\xf2\xf7\xa2\x29\x7d\xa0\x2b\x8f\x4b\xa8\xe0" + ); + } + } + #[test] fn sha3_hash_tests() { // SHA3-224 diff --git a/crypto/factory/tests/mac_factory_tests.rs b/crypto/factory/tests/mac_factory_tests.rs index 912a7587..09e7bbc9 100644 --- a/crypto/factory/tests/mac_factory_tests.rs +++ b/crypto/factory/tests/mac_factory_tests.rs @@ -24,5 +24,29 @@ mod hash_factory_tests { // TODO: at least one test for each type } + + #[test] + fn hmac_sm3_tests() { + // RFC4231 Test Case 1 key/message; expected value from `openssl dgst -sm3 -mac HMAC`, + // confirmed with bc-java's HMac(new SM3Digest()). + let key = KeyMaterial::<32>::from_bytes_as_type( + &hex::decode("0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b").unwrap(), + KeyType::MACKey, + ) + .unwrap(); + for name in ["HMAC-SM3", bouncycastle_hmac::HMAC_SM3_NAME] { + let hmac = MACFactory::new(name, &key).unwrap(); + assert_eq!(hmac.output_len(), 32); + assert!( + hmac.verify( + b"Hi There", + &hex::decode( + "51b00d1fb49832bfb01c3ce27848e59f871d9ba938dc563b338ca964755cce70" + ) + .unwrap(), + ) + ); + } + } } } diff --git a/crypto/hmac/Cargo.toml b/crypto/hmac/Cargo.toml index ebb14077..1c046ffe 100644 --- a/crypto/hmac/Cargo.toml +++ b/crypto/hmac/Cargo.toml @@ -8,6 +8,7 @@ bouncycastle-core.workspace = true bouncycastle-rng.workspace = true bouncycastle-sha2.workspace = true bouncycastle-sha3.workspace = true +bouncycastle-sm3.workspace = true bouncycastle-utils.workspace = true [dev-dependencies] diff --git a/crypto/hmac/benches/hmac_benches.rs b/crypto/hmac/benches/hmac_benches.rs index 0e9dd039..830e5fa3 100644 --- a/crypto/hmac/benches/hmac_benches.rs +++ b/crypto/hmac/benches/hmac_benches.rs @@ -1,6 +1,6 @@ use bouncycastle_core::key_material::{KeyMaterial256, KeyMaterial512, KeyType}; use bouncycastle_core::traits::{MAC, RNG}; -use bouncycastle_hmac::{HMAC_SHA256, HMAC_SHA512}; +use bouncycastle_hmac::{HMAC_SHA256, HMAC_SHA512, HMAC_SM3}; use bouncycastle_rng as rng; use criterion::{Criterion, Throughput, criterion_group, criterion_main}; use std::hint::black_box; @@ -51,5 +51,28 @@ fn bench_hmac_sha512(c: &mut Criterion) { group.finish(); } -criterion_group!(benches, bench_hmac_sha256, bench_hmac_sha512); +fn bench_hmac_sm3(c: &mut Criterion) { + let mut data_block = [0_u8; 1024]; + rng::DefaultRNG::default().next_bytes_out(&mut data_block).unwrap(); + + let mut big_data: Vec = vec![]; + for _ in 0..16 { + big_data.extend_from_slice(&data_block); + } + + let hmac_key = KeyMaterial512::from_bytes_as_type(&data_block[..64], KeyType::MACKey).unwrap(); + let mut out = [0u8; 64]; + + let mut group = c.benchmark_group("hmac::HMAC_SM3::mac_out() -- 16x1024 one-shot"); + group.throughput(Throughput::Bytes(big_data.len() as u64)); + group.bench_function(format!("{} bytes -- ::hashes()", big_data.len() as u64), |b| { + b.iter(|| { + HMAC_SM3::new(&hmac_key).unwrap().mac_out(black_box(&big_data), &mut out).unwrap(); + black_box(&out); + }) + }); + group.finish(); +} + +criterion_group!(benches, bench_hmac_sha256, bench_hmac_sha512, bench_hmac_sm3); criterion_main!(benches); diff --git a/crypto/hmac/src/lib.rs b/crypto/hmac/src/lib.rs index 26d16999..d8f049b5 100644 --- a/crypto/hmac/src/lib.rs +++ b/crypto/hmac/src/lib.rs @@ -193,6 +193,7 @@ use bouncycastle_sha2::{ SHA224, SHA256, SHA384, SHA512, SUSPENDED_SHA256_STATE_LEN, SUSPENDED_SHA512_STATE_LEN, }; use bouncycastle_sha3::{SHA3_224, SHA3_256, SHA3_384, SHA3_512, SUSPENDED_SHA3_STATE_LEN}; +use bouncycastle_sm3::{SM3, SUSPENDED_SM3_STATE_LEN}; use bouncycastle_utils::{ct, secret::Secret}; use core::fmt::{Debug, Display, Formatter}; @@ -213,6 +214,8 @@ pub const HMAC_SHA3_256_NAME: &str = "HMAC-SHA3-256"; pub const HMAC_SHA3_384_NAME: &str = "HMAC-SHA3-384"; /// pub const HMAC_SHA3_512_NAME: &str = "HMAC-SHA3-512"; +/// +pub const HMAC_SM3_NAME: &str = "HMAC-SM3"; /*** Type aliases ***/ /// Public type for HMAC using SHA224. @@ -323,6 +326,20 @@ impl AlgorithmOID for HMAC_SHA3_512 { &[0x06, 0x09, 0x60, 0x86, 0x48, 0x01, 0x65, 0x03, 0x04, 0x02, 0x10]; } +/// Public type for HMAC using SM3 (GB/T 32905-2016). Block length 64 bytes. +#[allow(non_camel_case_types)] +pub type HMAC_SM3 = HMAC; +impl Algorithm for HMAC_SM3 { + const ALG_NAME: &'static str = HMAC_SM3_NAME; + const MAX_SECURITY_STRENGTH: SecurityStrength = SecurityStrength::_128bit; +} +/// Assigned by the Chinese OSCCA (GM/T 0006): sm3-with-key / hmac-sm3 { sm3 2 } = 1.2.156.10197.1.401.2 +impl AlgorithmOID for HMAC_SM3 { + const OID: &'static [u32] = &[1, 2, 156, 10197, 1, 401, 2]; + const OID_DER: &'static [u8] = + &[0x06, 0x09, 0x2A, 0x81, 0x1C, 0xCF, 0x55, 0x01, 0x83, 0x11, 0x02]; +} + // The internal key buffer must be able to hold a key up to the *block length* of the underlying hash: // per RFC 2104, a key no longer than the block is used verbatim (only longer keys are pre-hashed down // to the output length). So the buffer size is a const parameter of the struct, set per hash to its @@ -562,6 +579,8 @@ pub const SUSPENDED_HMAC_SHA3_256_STATE_LEN: usize = SUSPENDED_SHA3_STATE_LEN; pub const SUSPENDED_HMAC_SHA3_384_STATE_LEN: usize = SUSPENDED_SHA3_STATE_LEN; /// Length in bytes of the serialized state of [`HMAC_SHA3_512`]. pub const SUSPENDED_HMAC_SHA3_512_STATE_LEN: usize = SUSPENDED_SHA3_STATE_LEN; +/// Length in bytes of the serialized state of [`HMAC_SM3`]. +pub const SUSPENDED_HMAC_SM3_STATE_LEN: usize = SUSPENDED_SM3_STATE_LEN; /// HMAC is a keyed algorithm, so it implements [`SuspendableKeyed`] (rather than /// [`Suspendable`]) for suspending and resuming in-progress operations. @@ -642,3 +661,4 @@ impl_hmac_keygen!(SHA3_224, 144, 28, HashDRBG_SHA256); impl_hmac_keygen!(SHA3_256, 136, 32, HashDRBG_SHA256); impl_hmac_keygen!(SHA3_384, 104, 48, HashDRBG_SHA512); impl_hmac_keygen!(SHA3_512, 72, 64, HashDRBG_SHA512); +impl_hmac_keygen!(SM3, 64, 32, HashDRBG_SHA256); diff --git a/crypto/hmac/tests/hmac_tests.rs b/crypto/hmac/tests/hmac_tests.rs index 6b211c3b..1d57bca3 100644 --- a/crypto/hmac/tests/hmac_tests.rs +++ b/crypto/hmac/tests/hmac_tests.rs @@ -12,6 +12,7 @@ mod hmac_tests { use bouncycastle_hmac::*; use bouncycastle_sha2::*; use bouncycastle_sha3::{SHA3_224, SHA3_256, SHA3_384, SHA3_512}; + use bouncycastle_sm3::SM3; #[test] fn simple_tests() { @@ -85,6 +86,9 @@ mod hmac_tests { _ = HMAC::::new(&key).unwrap(); _ = HMAC_SHA3_512::new(&key).unwrap(); + + _ = HMAC::::new(&key).unwrap(); + _ = HMAC_SM3::new(&key).unwrap(); } #[test] @@ -283,6 +287,7 @@ mod hmac_tests { assert_eq!(HMAC_SHA3_256::ALG_NAME, HMAC_SHA3_256_NAME); assert_eq!(HMAC_SHA3_384::ALG_NAME, HMAC_SHA3_384_NAME); assert_eq!(HMAC_SHA3_512::ALG_NAME, HMAC_SHA3_512_NAME); + assert_eq!(HMAC_SM3::ALG_NAME, HMAC_SM3_NAME); } #[cfg(test)] @@ -602,6 +607,65 @@ mod hmac_tests { } } + /// HMAC-SM3 known answers. There is no RFC 4231 equivalent for SM3, so these reuse the RFC 4231 + /// keys/messages (cases 1, 2 and 6) with expected values generated by + /// `openssl dgst -sm3 -mac HMAC` and independently confirmed with bc-java's + /// `HMac(new SM3Digest())`, plus a zero-length key. + #[test] + fn hmac_sm3_known_answers() { + use bouncycastle_core::key_material::KeyMaterial; + let test_framework = TestFrameworkMAC::new(); + + // RFC4231 Test Case 1 key/message + test_framework.test_mac::( + &KeyMaterial::<20>::from_bytes_as_type( + &hex::decode("0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b").unwrap(), + KeyType::MACKey, + ) + .unwrap(), + b"Hi There", + &hex::decode("51b00d1fb49832bfb01c3ce27848e59f871d9ba938dc563b338ca964755cce70") + .unwrap(), + ); + // RFC4231 Test Case 2 key/message + test_framework.test_mac::( + &KeyMaterial::<4>::from_bytes_as_type(b"Jefe", KeyType::MACKey).unwrap(), + b"what do ya want for nothing?", + &hex::decode("2e87f1d16862e6d964b50a5200bf2b10b764faa9680a296a2405f24bec39f882") + .unwrap(), + ); + // RFC4231 Test Case 6 key/message: key larger than the 64-byte block, so it is hashed first + test_framework.test_mac::( + &KeyMaterial::<131>::from_bytes_as_type(&[0xaa; 131], KeyType::MACKey).unwrap(), + b"Test Using Larger Than Block-Size Key - Hash Key First", + &hex::decode("b4fd844e13342002f0b2e0690ea7741f1497d993a70494cea601e657bedf67a0") + .unwrap(), + ); + + // zero-length key (weak; needs new_allow_weak_key) + let mut zero_length_key = KeyMaterial256::default(); + key_material::do_hazardous_operations(&mut zero_length_key, |k| { + k.set_key_type(KeyType::MACKey) + }) + .unwrap(); + let mut mac = HMAC_SM3::new_allow_weak_key(&zero_length_key).unwrap(); + mac.do_update(b"abc"); + assert_eq!( + mac.do_final(), + hex::decode("36525058ca466791502435c910517f1a7e86613d5f35ac1f18a94def0eaac81f") + .unwrap() + ); + + assert_eq!( + HMAC_SM3::new( + &KeyMaterial256::from_bytes_as_type(&DUMMY_SEED[..32], KeyType::MACKey).unwrap() + ) + .unwrap() + .output_len(), + 32 + ); + } + #[test] fn suspendable_keyed_state() { use bouncycastle_core::errors::SuspendableError; @@ -658,6 +722,7 @@ mod hmac_tests { round_trip(HMAC_SHA256::new(&key).unwrap(), &key, msg); round_trip(HMAC_SHA512::new(&key).unwrap(), &key, msg); round_trip(HMAC_SHA3_256::new(&key).unwrap(), &key, msg); + round_trip(HMAC_SM3::new(&key).unwrap(), &key, msg); // test suspend / resume with a key larger than block size let long_key = @@ -713,4 +778,5 @@ mod hmac_tests { keygen_test!(keygen_hmac_sha3_256, HMAC_SHA3_256, 32); keygen_test!(keygen_hmac_sha3_384, HMAC_SHA3_384, 48); keygen_test!(keygen_hmac_sha3_512, HMAC_SHA3_512, 64); + keygen_test!(keygen_hmac_sm3, HMAC_SM3, 32); } diff --git a/crypto/sm3/Cargo.toml b/crypto/sm3/Cargo.toml new file mode 100644 index 00000000..e2765b0c --- /dev/null +++ b/crypto/sm3/Cargo.toml @@ -0,0 +1,18 @@ +[package] +name = "bouncycastle-sm3" +version.workspace = true +edition.workspace = true + +[dependencies] +bouncycastle-core.workspace = true +bouncycastle-utils.workspace = true + +[dev-dependencies] +criterion.workspace = true +bouncycastle-core-test-framework.workspace = true +bouncycastle-hex.workspace = true +bouncycastle-rng.workspace = true + +[[bench]] +name = "sm3_benches" +harness = false diff --git a/crypto/sm3/benches/sm3_benches.rs b/crypto/sm3/benches/sm3_benches.rs new file mode 100644 index 00000000..25f407a1 --- /dev/null +++ b/crypto/sm3/benches/sm3_benches.rs @@ -0,0 +1,30 @@ +use criterion::{Criterion, Throughput, criterion_group, criterion_main}; +use std::hint::black_box; + +use bouncycastle_core::traits::{Hash, RNG}; +use bouncycastle_rng as rng; +use bouncycastle_sm3::SM3; + +fn bench_sm3(c: &mut Criterion) { + let mut data = [0_u8; 1024]; + rng::DefaultRNG::default().next_bytes_out(&mut data).unwrap(); + + let mut digest = vec![0; SM3::new().output_len()]; + + let mut group = c.benchmark_group("sm3"); + group.throughput(Throughput::Bytes(16 * 1024)); + group.bench_function("16KiB", |b| { + b.iter(|| { + let mut md = SM3::new(); + for _ in 0..16 { + md.do_update(black_box(&data)); + } + _ = md.do_final_out(&mut digest); + black_box(&digest); + }) + }); + group.finish(); +} + +criterion_group!(benches, bench_sm3); +criterion_main!(benches); diff --git a/crypto/sm3/src/lib.rs b/crypto/sm3/src/lib.rs new file mode 100644 index 00000000..fbc12936 --- /dev/null +++ b/crypto/sm3/src/lib.rs @@ -0,0 +1,132 @@ +//! Implements the SM3 cryptographic hash function as per GB/T 32905-2016 (also ISO/IEC 10118-3:2018 +//! and IETF draft-shen-sm3-hash-01). +//! +//! SM3 is a 256-bit Merkle–Damgård hash with a 512-bit block, structurally similar to SHA-256 but +//! with its own message expansion, round functions and constants. +//! +//! # Examples +//! ## Hash +//! Hash functionality is accessed via the [`Hash`] trait, which is implemented by [`SM3`]. +//! +//! The simplest usage is via the one-shot functions. +//! ``` +//! use bouncycastle_core::traits::Hash; +//! use bouncycastle_sm3::SM3; +//! +//! let data: &[u8] = b"abc"; +//! let output: Vec = SM3::new().hash(data); +//! assert_eq!(output[..4], [0x66, 0xc7, 0xf0, 0xf4]); +//! ``` +//! +//! More advanced usage will require creating an SM3 object to hold state between successive calls, +//! for example if input is received in chunks and not all available at the same time: +//! +//! ``` +//! use bouncycastle_core::traits::Hash; +//! use bouncycastle_sm3::SM3; +//! +//! let data: &[u8] = b"\x00\x01\x02\x03\x04\x05\x06\x07\x08\x09\x0A\x0B\x0C\x0D\x0E\x0F +//! \x10\x11\x12\x13\x14\x15\x16\x17\x18\x19\x1A\x1B\x1C\x1D\x1E\x1F"; +//! let mut sm3 = SM3::new(); +//! +//! for chunk in data.chunks(16) { +//! sm3.do_update(chunk); +//! } +//! +//! let output: Vec = sm3.do_final(); +//! ``` +//! +//! It is also possible to provide input where the final byte contains fewer than 8 bits of data +//! (a bit-oriented message, GB/T 32905-2016 s. 5.2); the partial bits are taken from the least +//! significant bits of the supplied byte. The following hashes 16 bytes plus 3 bits: +//! ``` +//! use bouncycastle_core::traits::Hash; +//! use bouncycastle_sm3::SM3; +//! +//! let data: &[u8] = b"\x00\x01\x02\x03\x04\x05\x06\x07\x08\x09\x0A\x0B\x0C\x0D\x0E\x0F\x05"; +//! let mut sm3 = SM3::new(); +//! sm3.do_update(&data[..16]); +//! let output: Vec = sm3.do_final_partial_bits(data[16], 3).expect("num_partial_bits is in 0..=7"); +//! ``` +//! +//! # Memory Usage +//! +//! No heap memory is used by the algorithm itself; the `Vec`-returning convenience methods +//! allocate only the output buffer, and the `*_out` variants allocate nothing. +//! +//! | Object | Size (bytes) | +//! |----------------------------|--------------| +//! | `SM3` | 112 | +//! | Suspended state | 108 | +//! +//! The object holds the 8-word chaining value plus one 64-byte block of buffered input. The +//! compression function additionally uses a 68-word message schedule (272 bytes) on the stack for +//! the duration of a call. +//! +//! # Security Considerations +//! +//! * SM3 offers 128 bits of collision resistance and 256 bits of preimage resistance. +//! * SM3 is a Merkle–Damgård construction and is therefore subject to length-extension: +//! `H(k || m)` is not a secure MAC. Use HMAC for keyed hashing. +//! * The chaining value and input buffer are held in [`bouncycastle_utils::secret::Secret`] and +//! zeroized on drop. Transient copies (working variables and message schedule) in registers/stack +//! locals during compression are not zeroized. +//! * The implementation contains no data-dependent branches or table lookups. +//! * Messages up to 2^64 bytes are supported (the specification allows 2^64 bits). +//! +//! # Suspending and resuming execution +//! +//! When hashing a large message, it can be advantageous to be able to suspend the operation +//! to a cache and resume it later; for example if waiting for the message to stream over a slow network +//! connection. For this reason, [`SM3`] impls [`Suspendable`]. +//! +//! ```rust +//! use bouncycastle_sm3::SM3; +//! use bouncycastle_core::traits::{Hash, Suspendable}; +//! +//! let msg_part1 = b"The quick brown fox"; +//! let msg_part2 = b" jumped over the lazy dog"; +//! +//! let mut sm3 = SM3::new(); +//! sm3.do_update(msg_part1); +//! +//! // suspend the in-progress hash while "waiting" for the second part of the message. +//! let serialized_state = sm3.suspend(); +//! +//! // ... later, possibly on another host: resume from the serialized state. +//! let mut sm3_resumed = SM3::from_suspended(serialized_state).unwrap(); +//! sm3_resumed.do_update(msg_part2); +//! let h: Vec = sm3_resumed.do_final(); +//! ``` + +#![forbid(unsafe_code)] +#![forbid(missing_docs)] + +mod sm3; + +pub use self::sm3::{SM3, SUSPENDED_SM3_STATE_LEN}; +use bouncycastle_core::traits::{Algorithm, AlgorithmOID, HashAlgParams, SecurityStrength}; + +/*** Imports needed for docs ***/ +#[allow(unused_imports)] +use bouncycastle_core::traits::{Hash, Suspendable}; + +/// Algorithm name string for SM3, as used by the factories and CLI. +pub const SM3_NAME: &str = "SM3"; + +impl Algorithm for SM3 { + const ALG_NAME: &'static str = SM3_NAME; + const MAX_SECURITY_STRENGTH: SecurityStrength = SecurityStrength::_128bit; +} + +/// GB/T 32905-2016: 256-bit digest, 512-bit block. +impl HashAlgParams for SM3 { + const OUTPUT_LEN: usize = 32; + const BLOCK_LEN: usize = 64; +} + +/// Assigned by the Chinese OSCCA: sm3 { 1 2 156 10197 1 401 } +impl AlgorithmOID for SM3 { + const OID: &'static [u32] = &[1, 2, 156, 10197, 1, 401]; + const OID_DER: &'static [u8] = &[0x06, 0x08, 0x2A, 0x81, 0x1C, 0xCF, 0x55, 0x01, 0x83, 0x11]; +} diff --git a/crypto/sm3/src/sm3.rs b/crypto/sm3/src/sm3.rs new file mode 100644 index 00000000..db3515a5 --- /dev/null +++ b/crypto/sm3/src/sm3.rs @@ -0,0 +1,352 @@ +use bouncycastle_core::errors::{HashError, SuspendableError}; +use bouncycastle_core::suspendable_state::{add_lib_ver, check_lib_ver}; +use bouncycastle_core::traits::{Hash, SecurityStrength, Suspendable}; +use bouncycastle_utils::{min, secret::Secret}; +use core::slice; + +/// GB/T 32905-2016 s. 4.1: initial value IV. +const SM3_IV: [u32; 8] = [ + 0x7380166F, 0x4914B2B9, 0x172442D7, 0xDA8A0600, 0xA96F30BC, 0x163138AA, 0xE38DEE4D, 0xB0FB0E4E, +]; + +/// GB/T 32905-2016 s. 4.2: constants T_j = 79CC4519 for 0 <= j <= 15, 7A879D8A for 16 <= j <= 63. +/// The round function uses (T_j <<< (j mod 32)), which is precomputed here at compile time. +const SM3_T: [u32; 64] = { + let mut t = [0u32; 64]; + let mut j = 0; + while j < 64 { + let base: u32 = if j < 16 { 0x79CC4519 } else { 0x7A879D8A }; + t[j] = base.rotate_left((j % 32) as u32); + j += 1; + } + t +}; + +/// GB/T 32905-2016 s. 4.3: boolean functions FF_j and GG_j for 0 <= j <= 15. +#[inline] +fn ff0(x: u32, y: u32, z: u32) -> u32 { + x ^ y ^ z +} + +/// GB/T 32905-2016 s. 4.3: FF_j for 16 <= j <= 63 (majority). +#[inline] +fn ff1(x: u32, y: u32, z: u32) -> u32 { + (x & y) | (x & z) | (y & z) +} + +/// GB/T 32905-2016 s. 4.3: GG_j for 16 <= j <= 63 (choice). +#[inline] +fn gg1(x: u32, y: u32, z: u32) -> u32 { + (x & y) | (!x & z) +} + +/// GB/T 32905-2016 s. 4.4: permutation P0(X) = X ^ (X <<< 9) ^ (X <<< 17). +#[inline] +fn p0(x: u32) -> u32 { + x ^ x.rotate_left(9) ^ x.rotate_left(17) +} + +/// GB/T 32905-2016 s. 4.4: permutation P1(X) = X ^ (X <<< 15) ^ (X <<< 23). +#[inline] +fn p1(x: u32) -> u32 { + x ^ x.rotate_left(15) ^ x.rotate_left(23) +} + +/// The SM3 cryptographic hash function (GB/T 32905-2016). +/// +/// See the [crate-level documentation](crate) for usage. +#[derive(Clone)] +pub struct SM3 { + /// Chaining value V^(i), 8 big-endian words. + v: Secret<[u32; 8]>, + /// Total number of message bytes absorbed so far. Supports messages up to 2^64 bytes. + byte_count: u64, + /// Buffered input that has not yet formed a whole block. + x_buf: Secret<[u8; 64]>, + /// Number of valid bytes in `x_buf` (always < 64). + x_buf_off: usize, +} + +impl SM3 { + /// Creates a new SM3 instance, ready for use. + pub fn new() -> Self { + let mut v = Secret::<[u32; 8]>::new(); + v.copy_from_slice(&SM3_IV); + Self { v, byte_count: 0, x_buf: Secret::new(), x_buf_off: 0 } + } + + /// GB/T 32905-2016 s. 5.3: compression function V^(i+1) = CF(V^(i), B^(i)) for each block. + /// + /// Takes the chaining value rather than `&mut self` so callers can pass `self.x_buf` as the + /// block without a conflicting borrow. + fn compress(v: &mut [u32; 8], blocks: &[[u8; 64]]) { + // s. 5.3.2 message expansion: W_0..W_67. W'_j = W_j ^ W_{j+4} is computed on the fly. + let mut w = [0u32; 68]; + + for block in blocks { + let (chunks, _remainder) = block.as_chunks::<4>(); + for (wj, bytes) in w[..16].iter_mut().zip(chunks) { + *wj = u32::from_be_bytes(*bytes); + } + for j in 16..68 { + // W_j = P1(W_{j-16} ^ W_{j-9} ^ (W_{j-3} <<< 15)) ^ (W_{j-13} <<< 7) ^ W_{j-6} + w[j] = p1(w[j - 16] ^ w[j - 9] ^ w[j - 3].rotate_left(15)) + ^ w[j - 13].rotate_left(7) + ^ w[j - 6]; + } + + // s. 5.3.3 compression: ABCDEFGH <- V^(i) + let [mut a, mut b, mut c, mut d, mut e, mut f, mut g, mut h] = *v; + + // One round of s. 5.3.3. `$ff` / `$gg` select the boolean functions for the round range. + macro_rules! sm3_round { + ($j:expr, $ff:ident, $gg:ident) => { + // SS1 = ((A <<< 12) + E + (T_j <<< (j mod 32))) <<< 7 + let a12 = a.rotate_left(12); + let ss1 = a12.wrapping_add(e).wrapping_add(SM3_T[$j]).rotate_left(7); + // SS2 = SS1 ^ (A <<< 12) + let ss2 = ss1 ^ a12; + // TT1 = FF_j(A,B,C) + D + SS2 + W'_j where W'_j = W_j ^ W_{j+4} + let tt1 = $ff(a, b, c) + .wrapping_add(d) + .wrapping_add(ss2) + .wrapping_add(w[$j] ^ w[$j + 4]); + // TT2 = GG_j(E,F,G) + H + SS1 + W_j + let tt2 = $gg(e, f, g).wrapping_add(h).wrapping_add(ss1).wrapping_add(w[$j]); + // D = C; C = B <<< 9; B = A; A = TT1; H = G; G = F <<< 19; F = E; E = P0(TT2) + d = c; + c = b.rotate_left(9); + b = a; + a = tt1; + h = g; + g = f.rotate_left(19); + f = e; + e = p0(tt2); + }; + } + + // Rounds 0..=15 use FF_0 = GG_0 = XOR (ff0 serves both). + for j in 0..16 { + sm3_round!(j, ff0, ff0); + } + // Rounds 16..=63 use the majority / choice functions. + for j in 16..64 { + sm3_round!(j, ff1, gg1); + } + + // V^(i+1) = ABCDEFGH ^ V^(i) + v[0] ^= a; + v[1] ^= b; + v[2] ^= c; + v[3] ^= d; + v[4] ^= e; + v[5] ^= f; + v[6] ^= g; + v[7] ^= h; + } + } + + /// Pads and compresses the final block(s) as per GB/T 32905-2016 s. 5.2, then writes the digest. + /// + /// `num_partial_bits` (0..=7, validated by the caller) trailing message bits are taken from the + /// least significant bits of `partial_byte`. GB/T 32905-2016 numbers message bits from the most + /// significant bit of each byte (as FIPS 180-4 does), so those bits are shifted to the top of the + /// final message byte and the mandatory "1" padding bit follows them immediately in the same byte. + /// + /// Returns the number of bytes written (`min(output.len(), 32)`); a shorter output buffer + /// truncates the digest, a longer one is zero-filled past the digest. + fn finalize(mut self, partial_byte: u8, num_partial_bits: usize, output: &mut [u8]) -> usize { + debug_assert!(num_partial_bits <= 7); + output.fill(0); + + let n = *min(&output.len(), &32); + + // s. 5.2: final message byte = [partial bits, MSB-first] [1] [0...]. With no partial bits this + // is 0x80. Shifts are done in u16 so that the 8-bit shift for num_partial_bits == 0 cannot + // overflow; the masked value is < 2^num_partial_bits so the result always fits back into a u8. + let mask: u8 = ((1u16 << num_partial_bits) - 1) as u8; + let message_bits = ((partial_byte & mask) as u16) << (8 - num_partial_bits); + let pad_byte = (message_bits as u8) | (0x80u8 >> num_partial_bits); + + self.x_buf[self.x_buf_off] = pad_byte; + self.x_buf_off += 1; + + // ... then k zero bits so that l + 1 + k = 448 mod 512. If the 64-bit length field no longer + // fits in this block, zero-fill and compress, then start a fresh block. + if self.x_buf_off > 56 { + self.x_buf[self.x_buf_off..].fill(0x00); + Self::compress(&mut self.v, slice::from_ref(&self.x_buf)); + self.x_buf_off = 0; + } + self.x_buf[self.x_buf_off..56].fill(0x00); + + // ... then the 64-bit big-endian message length l in bits. byte_count is a byte counter, so + // l = (byte_count << 3) | num_partial_bits (the low three bits of byte_count << 3 are zero). + let bit_len: u64 = (self.byte_count << 3) | (num_partial_bits as u64); + self.x_buf[56..64].copy_from_slice(&bit_len.to_be_bytes()); + Self::compress(&mut self.v, slice::from_ref(&self.x_buf)); + + // s. 5.4: the digest is V^(n) as 8 big-endian words. + let v = &self.v; + for i in 0..(n / 4) { + output[i * 4..i * 4 + 4].copy_from_slice(&v[i].to_be_bytes()); + } + if !n.is_multiple_of(4) { + output[((n / 4) * 4)..((n / 4) * 4) + (n % 4)] + .copy_from_slice(&v[n / 4].to_be_bytes()[0..(n % 4)]); + } + + n + } +} + +impl Default for SM3 { + fn default() -> Self { + Self::new() + } +} + +impl Hash for SM3 { + /// GB/T 32905-2016 s. 5.2: 512-bit blocks. + fn block_bitlen(&self) -> usize { + 512 + } + + fn output_len(&self) -> usize { + 32 + } + + fn hash(self, data: &[u8]) -> Vec { + let mut output = vec![0u8; 32]; + self.hash_out(data, &mut output); + output + } + + fn hash_out(mut self, data: &[u8], output: &mut [u8]) -> usize { + self.do_update(data); + self.do_final_out(output) + } + + fn do_update(&mut self, block: &[u8]) { + let len = block.len(); + + // byte_count is a u64 byte counter, so this supports messages up to 2^64 bytes. + // Exceeding it is infeasible in practice; in debug builds the add panics, in release it wraps. + self.byte_count += len as u64; + + let available = 64 - self.x_buf_off; + if len < available { + self.x_buf[self.x_buf_off..self.x_buf_off + len].copy_from_slice(block); + self.x_buf_off += len; + return; + } + + let mut block = block; + if self.x_buf_off != 0 { + self.x_buf[self.x_buf_off..].copy_from_slice(&block[..available]); + block = &block[available..]; + Self::compress(&mut self.v, slice::from_ref(&self.x_buf)); + } + + let (chunks, remainder) = block.as_chunks::<64>(); + Self::compress(&mut self.v, chunks); + + let remaining = remainder.len(); + self.x_buf[..remaining].copy_from_slice(remainder); + self.x_buf_off = remaining; + } + + fn do_final(self) -> Vec { + let mut output = vec![0u8; 32]; + self.do_final_out(&mut output); + output + } + + fn do_final_out(self, output: &mut [u8]) -> usize { + // A whole-byte message is the zero-partial-bits case of the general padding. + self.finalize(0, 0, output) + } + + fn do_final_partial_bits( + self, + partial_byte: u8, + num_partial_bits: usize, + ) -> Result, HashError> { + let mut output = vec![0u8; 32]; + self.do_final_partial_bits_out(partial_byte, num_partial_bits, &mut output)?; + Ok(output) + } + + /// GB/T 32905-2016 s. 5.2: bit-oriented messages. The `num_partial_bits` least significant bits of + /// `partial_byte` are appended to the message before padding. `num_partial_bits == 0` behaves + /// exactly like [`Hash::do_final_out`]. + fn do_final_partial_bits_out( + self, + partial_byte: u8, + num_partial_bits: usize, + output: &mut [u8], + ) -> Result { + if num_partial_bits > 7 { + return Err(HashError::InvalidLength("num_partial_bits must be in the range [0,7]")); + } + Ok(self.finalize(partial_byte, num_partial_bits, output)) + } + + fn max_security_strength(&self) -> SecurityStrength { + SecurityStrength::_128bit + } +} + +/// Length in bytes of the serialized state of SM3. +/// +/// Layout (after the 3-byte library version header; all integers little-endian): +/// [0 .. 32) v [u32; 8] +/// [32 .. 40) byte_count u64 +/// [40 .. 104) x_buf [u8; 64] +/// [104 .. 105) x_buf_off u8 (always < 64) +pub const SUSPENDED_SM3_STATE_LEN: usize = 3 + 105; + +impl Suspendable for SM3 { + fn suspend(self) -> [u8; SUSPENDED_SM3_STATE_LEN] { + let mut out_to_return = [0u8; SUSPENDED_SM3_STATE_LEN]; + + // infallible: add_lib_ver returns a slice of exactly SUSPENDED_SM3_STATE_LEN - 3 = 105 bytes. + let out: &mut [u8; 105] = add_lib_ver(&mut out_to_return).try_into().unwrap(); + + for i in 0..8 { + out[i * 4..(i * 4) + 4].copy_from_slice(&self.v[i].to_le_bytes()); + } + out[32..40].copy_from_slice(&self.byte_count.to_le_bytes()); + out[40..104].copy_from_slice(&*self.x_buf); + debug_assert!(self.x_buf_off < 64); + out[104] = self.x_buf_off as u8; + + out_to_return + } + + fn from_suspended( + serialized_state: [u8; SUSPENDED_SM3_STATE_LEN], + ) -> Result { + // check the version tag. At the moment, we have no not_before version to specify. + // infallible: check_lib_ver returns a slice of exactly SUSPENDED_SM3_STATE_LEN - 3 = 105 bytes. + let input: &[u8; 105] = check_lib_ver(&serialized_state, None)?.try_into().unwrap(); + + let mut v = Secret::<[u32; 8]>::new(); + for i in 0..8 { + // infallible: a 4-byte slice into a [u8; 4] + v[i] = u32::from_le_bytes(input[i * 4..(i * 4) + 4].try_into().unwrap()); + } + // infallible: an 8-byte slice into a [u8; 8] + let byte_count = u64::from_le_bytes(input[32..40].try_into().unwrap()); + + let mut x_buf = Secret::<[u8; 64]>::new(); + x_buf.copy_from_slice(&input[40..104]); + + let x_buf_off = input[104] as usize; + if x_buf_off >= 64 { + return Err(SuspendableError::InvalidData); + } + + Ok(SM3 { v, byte_count, x_buf, x_buf_off }) + } +} diff --git a/crypto/sm3/tests/sm3_tests.rs b/crypto/sm3/tests/sm3_tests.rs new file mode 100644 index 00000000..fa366732 --- /dev/null +++ b/crypto/sm3/tests/sm3_tests.rs @@ -0,0 +1,239 @@ +#[cfg(test)] +mod sm3_tests { + use bouncycastle_core::errors::{HashError, SuspendableError}; + use bouncycastle_core::traits::{ + Algorithm, AlgorithmOID, Hash, HashAlgParams, SecurityStrength, + }; + use bouncycastle_core_test_framework::DUMMY_SEED; + use bouncycastle_core_test_framework::hash::TestFrameworkHash; + use bouncycastle_hex as hex; + use bouncycastle_sm3::*; + + fn h(s: &str) -> Vec { + hex::decode(s).unwrap() + } + + /// Runs the shared Hash-trait conformance suite against known answers. + /// The first two are the standard vectors from GB/T 32905-2016 Appendix A; the rest are the + /// bc-java SM3DigestTest vectors and digests of DUMMY_SEED generated with openssl and confirmed + /// with bc-java's `SM3Digest`. + #[test] + fn core_test_framework_hash() { + let test_framework = TestFrameworkHash::new(); + + test_framework.test_hash::( + b"abc", + &h("66c7f0f462eeedd9d1f2d46bdc10e4e24167c4875cf2f7a2297da02b8f4ba8e0"), + ); + test_framework.test_hash::( + b"abcdabcdabcdabcdabcdabcdabcdabcdabcdabcdabcdabcdabcdabcdabcdabcd", + &h("debe9ff92275b8a138604889c18e5a4d6fdb70e5387e5765293dcba39c0c5732"), + ); + test_framework.test_hash::( + b"", + &h("1ab21d8355cfa17f8e61194831e81a8f22bec8c728fefb747ed035eb5082aa2b"), + ); + test_framework.test_hash::( + b"a", + &h("623476ac18f65a2909e43c7fec61b49c7e764a91a18ccb82f1917a29c86c5e88"), + ); + test_framework.test_hash::( + b"abcdefghijklmnopqrstuvwxyz", + &h("b80fe97a4da24afc277564f66a359ef440462ad28dcc6d63adb24d5c20a61595"), + ); + test_framework.test_hash::( + &DUMMY_SEED[..512], + &h("b21f830dca06be8b678cf987f26b9a436e1b427963b4450332f01270bd2df75c"), + ); + test_framework.test_hash::( + DUMMY_SEED, + &h("1f00bad6a72e851e0f6e94fd317f97b74d5fbc4c090aefb91e7554e3f9c8c7fb"), + ); + } + + /// bc-java SM3DigestTest "Additional vectors for GMSSL": the SM2 Z_A value from GM/T 0003.5 (also + /// checked against openssl `dgst -sm3`). + #[test] + fn bc_java_vectors() { + let msg = h(concat!( + "0090", + "414C494345313233405941484F4F2E434F4D", + "787968B4FA32C3FD2417842E73BBFEFF2F3C848B6831D7E0EC65228B3937E498", + "63E4C6D3B23B0C849CF84241484BFE48F61D59A5B16BA06E6E12D1DA27C5249A", + "421DEBD61B62EAB6746434EBC3CC315E32220B3BADD50BDC4C4E6C147FEDD43D", + "0680512BCBB42C07D47349D2153B70C4E5D7FDFCBFA36EA1A85841B9E46E09A2", + "0AE4C7798AA0F119471BEE11825BE46202BB79E2A5844495E97C04FF4DF2548A", + "7C0240F88F1CD4E16352A73C17B7F16F07353E53A176D684A9FE0C6BB798E857", + )); + assert_eq!( + SM3::new().hash(&msg), + h("f4a38489e32b45b6f876e3ac2168ca392362dc8f23459c1d1146fc3dbfb7bc9a") + ); + } + + /// Padding boundaries (GB/T 32905-2016 s. 5.2): message lengths around the 56- and 64-byte + /// points where the length field does / does not fit in the current block. Expected values + /// generated with openssl `dgst -sm3` over prefixes of DUMMY_SEED and confirmed with bc-java's + /// `SM3Digest`. + #[test] + fn padding_boundaries() { + for (len, expected) in [ + (55, "a79cf9dcee3404abf7f769698201647fd9d3ff61d629d0f58bb4b5579a427db8"), + (56, "62f7363b15f4de76dd925c493b9d6d00d4ba0ef2a1f334c1d0f13b293aeb40d1"), + (63, "6165e4cbb15cde01c6226e0015a47f710f8f8e1f2c296700033bb34d9212109c"), + (64, "93566f236d157aae078d1ddb5cebdbba1520b5142e22a8915564345ba2ae1d63"), + (65, "c886e6814be748285a10b28ae62ddacd85db830cd2cf3a2bfa2f729c15f63618"), + (119, "8f3ea392a89a7119982d6634660db1a95f35d68267a2235e3255998a857f4fbf"), + (128, "a9e7985473ca09df1510d83b572f72375430756c4a661b00724afeb8b75dd0a5"), + ] { + assert_eq!(SM3::new().hash(&DUMMY_SEED[..len]), h(expected), "len={len}"); + + // and the same via byte-at-a-time streaming, which exercises every x_buf_off value + let mut sm3 = SM3::new(); + for b in &DUMMY_SEED[..len] { + sm3.do_update(core::slice::from_ref(b)); + } + assert_eq!(sm3.do_final(), h(expected), "streaming len={len}"); + } + } + + #[test] + fn test_constants() { + assert_eq!(SM3::OUTPUT_LEN, 32); + assert_eq!(SM3::BLOCK_LEN, 64); + assert_eq!(SM3::new().block_bitlen(), 512); + assert_eq!(SM3::new().output_len(), 32); + } + + #[test] + fn test_algorithm() { + assert_eq!(SM3::ALG_NAME, SM3_NAME); + assert_eq!(SM3_NAME, "SM3"); + assert_eq!(SM3::OID, &[1, 2, 156, 10197, 1, 401]); + assert_eq!(SM3::OID_DER, &[0x06, 0x08, 0x2A, 0x81, 0x1C, 0xCF, 0x55, 0x01, 0x83, 0x11]); + } + + #[test] + fn test_security_strength() { + assert_eq!(SM3::MAX_SECURITY_STRENGTH, SecurityStrength::_128bit); + assert_eq!(SM3::default().max_security_strength(), SecurityStrength::_128bit); + } + + /// GB/T 32905-2016 s. 5.2: bit-oriented messages. Zero partial bits must equal the byte-oriented + /// digest; more than 7 partial bits is rejected; only the low bits of the partial byte matter; + /// and the pad byte spilling into a second block must not break. + #[test] + fn partial_bits() { + let mut a = SM3::new(); + a.do_update(b"abc"); + assert_eq!(a.do_final_partial_bits(0xFF, 0).unwrap(), SM3::new().hash(b"abc")); + + for bad in [8usize, 9, 16, 64, usize::MAX] { + let mut sm3 = SM3::new(); + sm3.do_update(b"abc"); + assert!( + matches!(sm3.do_final_partial_bits(0xFF, bad), Err(HashError::InvalidLength(_))), + "n={bad}" + ); + let mut out = [0u8; 32]; + assert!(matches!( + SM3::new().do_final_partial_bits_out(0xFF, bad, &mut out), + Err(HashError::InvalidLength(_)) + )); + } + + for n in 1..=7usize { + let mask = ((1u16 << n) - 1) as u8; + let x = SM3::new().do_final_partial_bits(0xA5, n).unwrap(); + let y = SM3::new().do_final_partial_bits(0xA5 & mask, n).unwrap(); + let z = SM3::new().do_final_partial_bits(0xA5 ^ 1, n).unwrap(); + assert_eq!(x, y, "n={n}"); + assert_ne!(x, z, "n={n}: low bit must change the digest"); + assert_ne!(x, SM3::new().hash(&[]), "n={n}"); + assert_ne!(x, SM3::new().hash(&[0xA5 & mask]), "n={n}"); + } + + for len in [55usize, 56, 63, 64, 119, 128] { + let mut sm3 = SM3::new(); + sm3.do_update(&vec![0x5Au8; len]); + let mut out = [0u8; 32]; + assert_eq!(sm3.do_final_partial_bits_out(0x03, 2, &mut out).unwrap(), 32, "len={len}"); + } + } + + /// Bit-oriented known answers. Neither openssl nor bc-java expose a bit-length SM3 API, so the + /// expected values come from an independent pure-Python implementation of GB/T 32905-2016 with + /// bit-length padding, itself checked against `openssl dgst -sm3` on byte-aligned inputs. + /// `(prefix, partial_byte, bits, digest)`. + #[test] + fn partial_bits_known_answers() { + let cases: [(&[u8], u8, usize, &str); 6] = [ + (b"", 0x01, 1, "985ffe9568be96328729b1c16631e9328d356432413d7556a646b9eefe479b9e"), + (b"", 0x15, 5, "469dd7b688a7b98d6362a8e2488a148cb4231bc196b796eee9652cb9044f3dcd"), + (b"abc", 0x7f, 7, "5ad9f5745671e4a49f6704fdadff8cc2ff8a9683d1c7c0810a5dd7db367e9d74"), + ( + &[0x5a; 55], + 0x03, + 2, + "65985be43230ee70a939d38e34a88198e0d63bb307081459d8d75541d54a382e", + ), + ( + &[0x5a; 111], + 0x05, + 3, + "8dfb4b90e5f899286782c9b192b67c5ebfbbab5a10d827d2518509307b7877c3", + ), + ( + &DUMMY_SEED[..64], + 0x0f, + 4, + "30e64a364406c1ac354ad17845b4df681de5bad9a1b41e996921a6f5effbf85b", + ), + ]; + for (prefix, partial_byte, bits, expected) in cases { + let mut sm3 = SM3::new(); + sm3.do_update(prefix); + assert_eq!( + sm3.do_final_partial_bits(partial_byte, bits).unwrap(), + h(expected), + "{}/{bits}", + prefix.len() + ); + } + } + + #[test] + fn suspendable_state() { + use bouncycastle_core::traits::Suspendable; + use bouncycastle_core_test_framework::suspendable_state::TestFrameworkSuspendableState; + + let str = "Colorless green ideas sleep furiously"; + + let mut sm3 = SM3::new(); + sm3.do_update(str.as_bytes()); + + // do the default tests + let test_framework = TestFrameworkSuspendableState::new(); + test_framework.test(&sm3); + + // now let's serialize the in-progress state + let serialized_state = sm3.clone().suspend(); + assert_eq!(serialized_state.len(), SUSPENDED_SM3_STATE_LEN); + + // finish the hash + let output = sm3.do_final(); + + // then load from state and finish the hash and make sure we get the same thing + let sm3_from_state = SM3::from_suspended(serialized_state).unwrap(); + let output2 = sm3_from_state.do_final(); + assert_eq!(output, output2); + + // also, give it a busted x_buf_off, just to satisfy mutants that that's been tested + let mut busted_state = serialized_state; + busted_state[3 + 104] = 65; + match SM3::from_suspended(busted_state) { + Err(SuspendableError::InvalidData) => { /* good */ } + _ => panic!("Expected an error"), + } + } +} diff --git a/src/lib.rs b/src/lib.rs index b46df8cd..8b2b81ab 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -11,3 +11,4 @@ pub use bouncycastle_mlkem_lowmemory as mlkem_lowmemory; pub use bouncycastle_rng as rng; pub use bouncycastle_sha2 as sha2; pub use bouncycastle_sha3 as sha3; +pub use bouncycastle_sm3 as sm3;