Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions crypto/factory/Cargo.toml
Original file line numberDiff line numberDiff line change
Expand Up@@ -7,6 +7,8 @@ edition.workspace = true
bouncycastle-core.workspace = true
bouncycastle-hkdf.workspace = true
bouncycastle-hmac.workspace = true
bouncycastle-mldsa.workspace = true
bouncycastle-mlkem.workspace = true
bouncycastle-sha2.workspace = true
bouncycastle-sha3.workspace = true
bouncycastle-rng.workspace = true
Expand Down
328 changes: 328 additions & 0 deletions crypto/factory/src/kem_factory.rs
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,328 @@
//! KEM factory for creating instances of algorithms that implement KEM traits.
//!
//! As with all Factory objects, this constructs algorithms from strings and defaults.
//! Supported objects are encapsulated in enums that pass operations through to the underlying types.
//!
//! # Design note on traits
//!
//! The core [`KEMEncapsulator`] and [`KEMDecapsulator`] traits are parameterized by const-generic
//! key and ciphertext sizes. A single enum that wraps ML-KEM-512/768/1024 cannot implement those
//! traits with one fixed set of const parameters. This module therefore wraps keys in enums and
//! exposes inherent methods with the same shape as the core traits.
//!
//! Example usage:
//! ```
//! use bouncycastle_factory::AlgorithmFactory;
//! use bouncycastle_factory::kem_factory::KEMFactory;
//! use bouncycastle_mlkem::ML_KEM_768_NAME;
//!
//! let factory = KEMFactory::new(ML_KEM_768_NAME).unwrap();
//! assert_eq!(factory.algorithm_name(), ML_KEM_768_NAME);
//! // keygen/encaps/decaps pass through to the underlying ML-KEM types;
//! // see the crate tests for full round-trip examples.
//! ```

use crate::{AlgorithmFactory, DEFAULT, DEFAULT_128_BIT, DEFAULT_256_BIT, FactoryError};
use bouncycastle_core::errors::KEMError;
use bouncycastle_core::key_material::KeyMaterial;
use bouncycastle_core::traits::{
KEMDecapsulator as _, KEMEncapsulator as _, KEMPrivateKey as KEMPrivateKeyTrait,
KEMPublicKey as KEMPublicKeyTrait, RNG,
};
use bouncycastle_mlkem as mlkem;
use bouncycastle_mlkem::{
MLKEM512, MLKEM768, MLKEM1024, MLKEMTrait, MLKEM_SS_LEN, ML_KEM_512_NAME, ML_KEM_768_NAME,
ML_KEM_1024_NAME,
};

/*** Defaults ***/
/// Default KEM algorithm name (192-bit class / ML-KEM-768).
pub const DEFAULT_KEM_NAME: &str = ML_KEM_768_NAME;
/// Default KEM algorithm at the 128-bit security level.
pub const DEFAULT_128BIT_KEM_NAME: &str = ML_KEM_512_NAME;
/// Default KEM algorithm at the 256-bit security level.
pub const DEFAULT_256BIT_KEM_NAME: &str = ML_KEM_1024_NAME;

/// Wrapper for all supported KEM public (encapsulation) keys.
pub enum KEMPublicKey {
/// ML-KEM-512 public key.
MLKEM512(mlkem::MLKEM512PublicKey),
/// ML-KEM-768 public key.
MLKEM768(mlkem::MLKEM768PublicKey),
/// ML-KEM-1024 public key.
MLKEM1024(mlkem::MLKEM1024PublicKey),
}

impl KEMPublicKey {
/// Encode the public key to its standard byte encoding.
pub fn encode(&self) -> Vec<u8> {
match self {
Self::MLKEM512(pk) => pk.encode().to_vec(),
Self::MLKEM768(pk) => pk.encode().to_vec(),
Self::MLKEM1024(pk) => pk.encode().to_vec(),
}
}

/// Decode a public key from bytes for the named algorithm.
pub fn from_bytes(alg_name: &str, bytes: &[u8]) -> Result<Self, FactoryError> {
match alg_name {
ML_KEM_512_NAME => Ok(Self::MLKEM512(
mlkem::MLKEM512PublicKey::from_bytes(bytes).map_err(kem_err)?,
)),
ML_KEM_768_NAME => Ok(Self::MLKEM768(
mlkem::MLKEM768PublicKey::from_bytes(bytes).map_err(kem_err)?,
)),
ML_KEM_1024_NAME => Ok(Self::MLKEM1024(
mlkem::MLKEM1024PublicKey::from_bytes(bytes).map_err(kem_err)?,
)),
_ => Err(FactoryError::UnsupportedAlgorithm(format!(
"The algorithm: \"{alg_name}\" is not a known KEM"
))),
}
}

/// Algorithm name for this key.
pub fn algorithm_name(&self) -> &'static str {
match self {
Self::MLKEM512(_) => ML_KEM_512_NAME,
Self::MLKEM768(_) => ML_KEM_768_NAME,
Self::MLKEM1024(_) => ML_KEM_1024_NAME,
}
}
}

/// Wrapper for all supported KEM private (decapsulation) keys.
pub enum KEMPrivateKey {
/// ML-KEM-512 private key.
MLKEM512(mlkem::MLKEM512PrivateKey),
/// ML-KEM-768 private key.
MLKEM768(mlkem::MLKEM768PrivateKey),
/// ML-KEM-1024 private key.
MLKEM1024(mlkem::MLKEM1024PrivateKey),
}

impl KEMPrivateKey {
/// Encode the private key to its standard byte encoding.
pub fn encode(&self) -> Vec<u8> {
match self {
Self::MLKEM512(sk) => sk.encode().to_vec(),
Self::MLKEM768(sk) => sk.encode().to_vec(),
Self::MLKEM1024(sk) => sk.encode().to_vec(),
}
}

/// Decode a private key from bytes for the named algorithm.
pub fn from_bytes(alg_name: &str, bytes: &[u8]) -> Result<Self, FactoryError> {
match alg_name {
ML_KEM_512_NAME => Ok(Self::MLKEM512(
mlkem::MLKEM512PrivateKey::from_bytes(bytes).map_err(kem_err)?,
)),
ML_KEM_768_NAME => Ok(Self::MLKEM768(
mlkem::MLKEM768PrivateKey::from_bytes(bytes).map_err(kem_err)?,
)),
ML_KEM_1024_NAME => Ok(Self::MLKEM1024(
mlkem::MLKEM1024PrivateKey::from_bytes(bytes).map_err(kem_err)?,
)),
_ => Err(FactoryError::UnsupportedAlgorithm(format!(
"The algorithm: \"{alg_name}\" is not a known KEM"
))),
}
}

/// Algorithm name for this key.
pub fn algorithm_name(&self) -> &'static str {
match self {
Self::MLKEM512(_) => ML_KEM_512_NAME,
Self::MLKEM768(_) => ML_KEM_768_NAME,
Self::MLKEM1024(_) => ML_KEM_1024_NAME,
}
}
}

/// Factory / algorithm selector for all supported KEM algorithms.
///
/// Constructed by name via [`AlgorithmFactory::new`] or the default helpers.
/// Operations pass through to the underlying ML-KEM parameter sets.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum KEMFactory {
/// ML-KEM-512 (NIST security category 1 / ~128-bit class).
MLKEM512,
/// ML-KEM-768 (NIST security category 3 / ~192-bit class).
MLKEM768,
/// ML-KEM-1024 (NIST security category 5 / ~256-bit class).
MLKEM1024,
}

impl Default for KEMFactory {
fn default() -> Self {
Self::MLKEM768
}
}

impl AlgorithmFactory for KEMFactory {
fn default_128_bit() -> Self {
Self::MLKEM512
}

fn default_256_bit() -> Self {
Self::MLKEM1024
}

fn new(alg_name: &str) -> Result<Self, FactoryError> {
match alg_name {
DEFAULT => Ok(Self::default()),
DEFAULT_128_BIT => Ok(Self::default_128_bit()),
DEFAULT_256_BIT => Ok(Self::default_256_bit()),
ML_KEM_512_NAME => Ok(Self::MLKEM512),
ML_KEM_768_NAME => Ok(Self::MLKEM768),
ML_KEM_1024_NAME => Ok(Self::MLKEM1024),
_ => Err(FactoryError::UnsupportedAlgorithm(format!(
"The algorithm: \"{alg_name}\" is not a known KEM"
))),
}
}
}

impl KEMFactory {
/// Algorithm name string for this factory selection.
pub fn algorithm_name(&self) -> &'static str {
match self {
Self::MLKEM512 => ML_KEM_512_NAME,
Self::MLKEM768 => ML_KEM_768_NAME,
Self::MLKEM1024 => ML_KEM_1024_NAME,
}
}

/// Generate a fresh key pair using the library default OS-backed RNG.
pub fn keygen(&self) -> Result<(KEMPublicKey, KEMPrivateKey), KEMError> {
match self {
Self::MLKEM512 => {
let (pk, sk) = MLKEM512::keygen()?;
Ok((KEMPublicKey::MLKEM512(pk), KEMPrivateKey::MLKEM512(sk)))
}
Self::MLKEM768 => {
let (pk, sk) = MLKEM768::keygen()?;
Ok((KEMPublicKey::MLKEM768(pk), KEMPrivateKey::MLKEM768(sk)))
}
Self::MLKEM1024 => {
let (pk, sk) = MLKEM1024::keygen()?;
Ok((KEMPublicKey::MLKEM1024(pk), KEMPrivateKey::MLKEM1024(sk)))
}
}
}

/// Generate a key pair using the provided RNG.
pub fn keygen_from_rng(
&self,
rng: &mut dyn RNG,
) -> Result<(KEMPublicKey, KEMPrivateKey), KEMError> {
match self {
Self::MLKEM512 => {
let (pk, sk) = MLKEM512::keygen_from_rng(rng)?;
Ok((KEMPublicKey::MLKEM512(pk), KEMPrivateKey::MLKEM512(sk)))
}
Self::MLKEM768 => {
let (pk, sk) = MLKEM768::keygen_from_rng(rng)?;
Ok((KEMPublicKey::MLKEM768(pk), KEMPrivateKey::MLKEM768(sk)))
}
Self::MLKEM1024 => {
let (pk, sk) = MLKEM1024::keygen_from_rng(rng)?;
Ok((KEMPublicKey::MLKEM1024(pk), KEMPrivateKey::MLKEM1024(sk)))
}
}
}

/// Generate a key pair from a 64-byte seed.
pub fn keygen_from_seed(
&self,
seed: &KeyMaterial<64>,
) -> Result<(KEMPublicKey, KEMPrivateKey), KEMError> {
match self {
Self::MLKEM512 => {
let (pk, sk) = MLKEM512::keygen_from_seed(seed)?;
Ok((KEMPublicKey::MLKEM512(pk), KEMPrivateKey::MLKEM512(sk)))
}
Self::MLKEM768 => {
let (pk, sk) = MLKEM768::keygen_from_seed(seed)?;
Ok((KEMPublicKey::MLKEM768(pk), KEMPrivateKey::MLKEM768(sk)))
}
Self::MLKEM1024 => {
let (pk, sk) = MLKEM1024::keygen_from_seed(seed)?;
Ok((KEMPublicKey::MLKEM1024(pk), KEMPrivateKey::MLKEM1024(sk)))
}
}
}

/// Encapsulate to the given public key (pass-through to [`KEMEncapsulator::encaps`]).
///
/// Returns `(shared_secret, ciphertext)`.
pub fn encaps(
&self,
pk: &KEMPublicKey,
) -> Result<(KeyMaterial<MLKEM_SS_LEN>, Vec<u8>), KEMError> {
match (self, pk) {
(Self::MLKEM512, KEMPublicKey::MLKEM512(pk)) => {
let (ss, ct) = MLKEM512::encaps(pk)?;
Ok((ss, ct.to_vec()))
}
(Self::MLKEM768, KEMPublicKey::MLKEM768(pk)) => {
let (ss, ct) = MLKEM768::encaps(pk)?;
Ok((ss, ct.to_vec()))
}
(Self::MLKEM1024, KEMPublicKey::MLKEM1024(pk)) => {
let (ss, ct) = MLKEM1024::encaps(pk)?;
Ok((ss, ct.to_vec()))
}
_ => Err(KEMError::GenericError(
"KEM public key does not match the selected KEMFactory algorithm",
)),
}
}

/// Encapsulate using a caller-provided RNG (pass-through to [`KEMEncapsulator::encaps_rng`]).
pub fn encaps_rng(
&self,
pk: &KEMPublicKey,
rng: &mut dyn RNG,
) -> Result<(KeyMaterial<MLKEM_SS_LEN>, Vec<u8>), KEMError> {
match (self, pk) {
(Self::MLKEM512, KEMPublicKey::MLKEM512(pk)) => {
let (ss, ct) = MLKEM512::encaps_rng(pk, rng)?;
Ok((ss, ct.to_vec()))
}
(Self::MLKEM768, KEMPublicKey::MLKEM768(pk)) => {
let (ss, ct) = MLKEM768::encaps_rng(pk, rng)?;
Ok((ss, ct.to_vec()))
}
(Self::MLKEM1024, KEMPublicKey::MLKEM1024(pk)) => {
let (ss, ct) = MLKEM1024::encaps_rng(pk, rng)?;
Ok((ss, ct.to_vec()))
}
_ => Err(KEMError::GenericError(
"KEM public key does not match the selected KEMFactory algorithm",
)),
}
}

/// Decapsulate a ciphertext (pass-through to [`KEMDecapsulator::decaps`]).
pub fn decaps(
&self,
sk: &KEMPrivateKey,
ct: &[u8],
) -> Result<KeyMaterial<MLKEM_SS_LEN>, KEMError> {
match (self, sk) {
(Self::MLKEM512, KEMPrivateKey::MLKEM512(sk)) => MLKEM512::decaps(sk, ct),
(Self::MLKEM768, KEMPrivateKey::MLKEM768(sk)) => MLKEM768::decaps(sk, ct),
(Self::MLKEM1024, KEMPrivateKey::MLKEM1024(sk)) => MLKEM1024::decaps(sk, ct),
_ => Err(KEMError::GenericError(
"KEM private key does not match the selected KEMFactory algorithm",
)),
}
}
}

fn kem_err(e: KEMError) -> FactoryError {
FactoryError::UnsupportedAlgorithm(format!("KEM key decode failed: {e:?}"))
}


2 changes: 2 additions & 0 deletions crypto/factory/src/lib.rs
Original file line numberDiff line numberDiff line change
Expand Up@@ -35,8 +35,10 @@ use bouncycastle_core::errors::MACError;

pub mod hash_factory;
pub mod kdf_factory;
pub mod kem_factory;
pub mod mac_factory;
pub mod rng_factory;
pub mod signature_factory;
pub mod xof_factory;

/*** String constants ***/
Expand Down
Loading
Loading
, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Add copy buttons to all
 blocks\n(function() {\n function addCopyButtons() {\n document.querySelectorAll('pre code').forEach(function(codeBlock) {\n if (codeBlock.parentElement.hasAttribute('data-copy-added')) return;\n codeBlock.parentElement.setAttribute('data-copy-added', 'true');\n \n var btn = document.createElement('button');\n btn.textContent = 'Copy';\n btn.style.cssText = 'position:absolute;top:4px;right:4px;padding:2px 8px;font-size:11px;background:#4ecdc4;border:none;border-radius:4px;color:#1a1a2e;cursor:pointer;opacity:0.7;transition:opacity 0.2s;';\n btn.onmouseover = function() { this.style.opacity = '1'; };\n btn.onmouseout = function() { this.style.opacity = '0.7'; };\n btn.onclick = function() {\n navigator.clipboard.writeText(codeBlock.textContent).then(function() {\n btn.textContent = 'Copied!';\n setTimeout(function() { btn.textContent = 'Copy'; }, 1500);\n });\n };\n codeBlock.parentElement.style.position = 'relative';\n codeBlock.parentElement.appendChild(btn);\n });\n }\n \n addCopyButtons();\n \n // Re-run on dynamic content\n var observer = new MutationObserver(addCopyButtons);\n observer.observe(document.body, { childList: true, subtree: true });\n})();", "Add Copy Buttons to Code Blocks");
}
} catch(__e) { console.warn('[Userscript:Add Copy Buttons to Code Blocks]', __e); }
})();
(function(){
try {
var __m = "github.com";
var __re = new RegExp('^' + "github\\.com" + '
Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions crypto/factory/Cargo.toml
Original file line numberDiff line numberDiff line change
Expand Up@@ -7,6 +7,8 @@ edition.workspace = true
bouncycastle-core.workspace = true
bouncycastle-hkdf.workspace = true
bouncycastle-hmac.workspace = true
bouncycastle-mldsa.workspace = true
bouncycastle-mlkem.workspace = true
bouncycastle-sha2.workspace = true
bouncycastle-sha3.workspace = true
bouncycastle-rng.workspace = true
Expand Down
328 changes: 328 additions & 0 deletions crypto/factory/src/kem_factory.rs
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,328 @@
//! KEM factory for creating instances of algorithms that implement KEM traits.
//!
//! As with all Factory objects, this constructs algorithms from strings and defaults.
//! Supported objects are encapsulated in enums that pass operations through to the underlying types.
//!
//! # Design note on traits
//!
//! The core [`KEMEncapsulator`] and [`KEMDecapsulator`] traits are parameterized by const-generic
//! key and ciphertext sizes. A single enum that wraps ML-KEM-512/768/1024 cannot implement those
//! traits with one fixed set of const parameters. This module therefore wraps keys in enums and
//! exposes inherent methods with the same shape as the core traits.
//!
//! Example usage:
//! ```
//! use bouncycastle_factory::AlgorithmFactory;
//! use bouncycastle_factory::kem_factory::KEMFactory;
//! use bouncycastle_mlkem::ML_KEM_768_NAME;
//!
//! let factory = KEMFactory::new(ML_KEM_768_NAME).unwrap();
//! assert_eq!(factory.algorithm_name(), ML_KEM_768_NAME);
//! // keygen/encaps/decaps pass through to the underlying ML-KEM types;
//! // see the crate tests for full round-trip examples.
//! ```

use crate::{AlgorithmFactory, DEFAULT, DEFAULT_128_BIT, DEFAULT_256_BIT, FactoryError};
use bouncycastle_core::errors::KEMError;
use bouncycastle_core::key_material::KeyMaterial;
use bouncycastle_core::traits::{
KEMDecapsulator as _, KEMEncapsulator as _, KEMPrivateKey as KEMPrivateKeyTrait,
KEMPublicKey as KEMPublicKeyTrait, RNG,
};
use bouncycastle_mlkem as mlkem;
use bouncycastle_mlkem::{
MLKEM512, MLKEM768, MLKEM1024, MLKEMTrait, MLKEM_SS_LEN, ML_KEM_512_NAME, ML_KEM_768_NAME,
ML_KEM_1024_NAME,
};

/*** Defaults ***/
/// Default KEM algorithm name (192-bit class / ML-KEM-768).
pub const DEFAULT_KEM_NAME: &str = ML_KEM_768_NAME;
/// Default KEM algorithm at the 128-bit security level.
pub const DEFAULT_128BIT_KEM_NAME: &str = ML_KEM_512_NAME;
/// Default KEM algorithm at the 256-bit security level.
pub const DEFAULT_256BIT_KEM_NAME: &str = ML_KEM_1024_NAME;

/// Wrapper for all supported KEM public (encapsulation) keys.
pub enum KEMPublicKey {
/// ML-KEM-512 public key.
MLKEM512(mlkem::MLKEM512PublicKey),
/// ML-KEM-768 public key.
MLKEM768(mlkem::MLKEM768PublicKey),
/// ML-KEM-1024 public key.
MLKEM1024(mlkem::MLKEM1024PublicKey),
}

impl KEMPublicKey {
/// Encode the public key to its standard byte encoding.
pub fn encode(&self) -> Vec<u8> {
match self {
Self::MLKEM512(pk) => pk.encode().to_vec(),
Self::MLKEM768(pk) => pk.encode().to_vec(),
Self::MLKEM1024(pk) => pk.encode().to_vec(),
}
}

/// Decode a public key from bytes for the named algorithm.
pub fn from_bytes(alg_name: &str, bytes: &[u8]) -> Result<Self, FactoryError> {
match alg_name {
ML_KEM_512_NAME => Ok(Self::MLKEM512(
mlkem::MLKEM512PublicKey::from_bytes(bytes).map_err(kem_err)?,
)),
ML_KEM_768_NAME => Ok(Self::MLKEM768(
mlkem::MLKEM768PublicKey::from_bytes(bytes).map_err(kem_err)?,
)),
ML_KEM_1024_NAME => Ok(Self::MLKEM1024(
mlkem::MLKEM1024PublicKey::from_bytes(bytes).map_err(kem_err)?,
)),
_ => Err(FactoryError::UnsupportedAlgorithm(format!(
"The algorithm: \"{alg_name}\" is not a known KEM"
))),
}
}

/// Algorithm name for this key.
pub fn algorithm_name(&self) -> &'static str {
match self {
Self::MLKEM512(_) => ML_KEM_512_NAME,
Self::MLKEM768(_) => ML_KEM_768_NAME,
Self::MLKEM1024(_) => ML_KEM_1024_NAME,
}
}
}

/// Wrapper for all supported KEM private (decapsulation) keys.
pub enum KEMPrivateKey {
/// ML-KEM-512 private key.
MLKEM512(mlkem::MLKEM512PrivateKey),
/// ML-KEM-768 private key.
MLKEM768(mlkem::MLKEM768PrivateKey),
/// ML-KEM-1024 private key.
MLKEM1024(mlkem::MLKEM1024PrivateKey),
}

impl KEMPrivateKey {
/// Encode the private key to its standard byte encoding.
pub fn encode(&self) -> Vec<u8> {
match self {
Self::MLKEM512(sk) => sk.encode().to_vec(),
Self::MLKEM768(sk) => sk.encode().to_vec(),
Self::MLKEM1024(sk) => sk.encode().to_vec(),
}
}

/// Decode a private key from bytes for the named algorithm.
pub fn from_bytes(alg_name: &str, bytes: &[u8]) -> Result<Self, FactoryError> {
match alg_name {
ML_KEM_512_NAME => Ok(Self::MLKEM512(
mlkem::MLKEM512PrivateKey::from_bytes(bytes).map_err(kem_err)?,
)),
ML_KEM_768_NAME => Ok(Self::MLKEM768(
mlkem::MLKEM768PrivateKey::from_bytes(bytes).map_err(kem_err)?,
)),
ML_KEM_1024_NAME => Ok(Self::MLKEM1024(
mlkem::MLKEM1024PrivateKey::from_bytes(bytes).map_err(kem_err)?,
)),
_ => Err(FactoryError::UnsupportedAlgorithm(format!(
"The algorithm: \"{alg_name}\" is not a known KEM"
))),
}
}

/// Algorithm name for this key.
pub fn algorithm_name(&self) -> &'static str {
match self {
Self::MLKEM512(_) => ML_KEM_512_NAME,
Self::MLKEM768(_) => ML_KEM_768_NAME,
Self::MLKEM1024(_) => ML_KEM_1024_NAME,
}
}
}

/// Factory / algorithm selector for all supported KEM algorithms.
///
/// Constructed by name via [`AlgorithmFactory::new`] or the default helpers.
/// Operations pass through to the underlying ML-KEM parameter sets.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum KEMFactory {
/// ML-KEM-512 (NIST security category 1 / ~128-bit class).
MLKEM512,
/// ML-KEM-768 (NIST security category 3 / ~192-bit class).
MLKEM768,
/// ML-KEM-1024 (NIST security category 5 / ~256-bit class).
MLKEM1024,
}

impl Default for KEMFactory {
fn default() -> Self {
Self::MLKEM768
}
}

impl AlgorithmFactory for KEMFactory {
fn default_128_bit() -> Self {
Self::MLKEM512
}

fn default_256_bit() -> Self {
Self::MLKEM1024
}

fn new(alg_name: &str) -> Result<Self, FactoryError> {
match alg_name {
DEFAULT => Ok(Self::default()),
DEFAULT_128_BIT => Ok(Self::default_128_bit()),
DEFAULT_256_BIT => Ok(Self::default_256_bit()),
ML_KEM_512_NAME => Ok(Self::MLKEM512),
ML_KEM_768_NAME => Ok(Self::MLKEM768),
ML_KEM_1024_NAME => Ok(Self::MLKEM1024),
_ => Err(FactoryError::UnsupportedAlgorithm(format!(
"The algorithm: \"{alg_name}\" is not a known KEM"
))),
}
}
}

impl KEMFactory {
/// Algorithm name string for this factory selection.
pub fn algorithm_name(&self) -> &'static str {
match self {
Self::MLKEM512 => ML_KEM_512_NAME,
Self::MLKEM768 => ML_KEM_768_NAME,
Self::MLKEM1024 => ML_KEM_1024_NAME,
}
}

/// Generate a fresh key pair using the library default OS-backed RNG.
pub fn keygen(&self) -> Result<(KEMPublicKey, KEMPrivateKey), KEMError> {
match self {
Self::MLKEM512 => {
let (pk, sk) = MLKEM512::keygen()?;
Ok((KEMPublicKey::MLKEM512(pk), KEMPrivateKey::MLKEM512(sk)))
}
Self::MLKEM768 => {
let (pk, sk) = MLKEM768::keygen()?;
Ok((KEMPublicKey::MLKEM768(pk), KEMPrivateKey::MLKEM768(sk)))
}
Self::MLKEM1024 => {
let (pk, sk) = MLKEM1024::keygen()?;
Ok((KEMPublicKey::MLKEM1024(pk), KEMPrivateKey::MLKEM1024(sk)))
}
}
}

/// Generate a key pair using the provided RNG.
pub fn keygen_from_rng(
&self,
rng: &mut dyn RNG,
) -> Result<(KEMPublicKey, KEMPrivateKey), KEMError> {
match self {
Self::MLKEM512 => {
let (pk, sk) = MLKEM512::keygen_from_rng(rng)?;
Ok((KEMPublicKey::MLKEM512(pk), KEMPrivateKey::MLKEM512(sk)))
}
Self::MLKEM768 => {
let (pk, sk) = MLKEM768::keygen_from_rng(rng)?;
Ok((KEMPublicKey::MLKEM768(pk), KEMPrivateKey::MLKEM768(sk)))
}
Self::MLKEM1024 => {
let (pk, sk) = MLKEM1024::keygen_from_rng(rng)?;
Ok((KEMPublicKey::MLKEM1024(pk), KEMPrivateKey::MLKEM1024(sk)))
}
}
}

/// Generate a key pair from a 64-byte seed.
pub fn keygen_from_seed(
&self,
seed: &KeyMaterial<64>,
) -> Result<(KEMPublicKey, KEMPrivateKey), KEMError> {
match self {
Self::MLKEM512 => {
let (pk, sk) = MLKEM512::keygen_from_seed(seed)?;
Ok((KEMPublicKey::MLKEM512(pk), KEMPrivateKey::MLKEM512(sk)))
}
Self::MLKEM768 => {
let (pk, sk) = MLKEM768::keygen_from_seed(seed)?;
Ok((KEMPublicKey::MLKEM768(pk), KEMPrivateKey::MLKEM768(sk)))
}
Self::MLKEM1024 => {
let (pk, sk) = MLKEM1024::keygen_from_seed(seed)?;
Ok((KEMPublicKey::MLKEM1024(pk), KEMPrivateKey::MLKEM1024(sk)))
}
}
}

/// Encapsulate to the given public key (pass-through to [`KEMEncapsulator::encaps`]).
///
/// Returns `(shared_secret, ciphertext)`.
pub fn encaps(
&self,
pk: &KEMPublicKey,
) -> Result<(KeyMaterial<MLKEM_SS_LEN>, Vec<u8>), KEMError> {
match (self, pk) {
(Self::MLKEM512, KEMPublicKey::MLKEM512(pk)) => {
let (ss, ct) = MLKEM512::encaps(pk)?;
Ok((ss, ct.to_vec()))
}
(Self::MLKEM768, KEMPublicKey::MLKEM768(pk)) => {
let (ss, ct) = MLKEM768::encaps(pk)?;
Ok((ss, ct.to_vec()))
}
(Self::MLKEM1024, KEMPublicKey::MLKEM1024(pk)) => {
let (ss, ct) = MLKEM1024::encaps(pk)?;
Ok((ss, ct.to_vec()))
}
_ => Err(KEMError::GenericError(
"KEM public key does not match the selected KEMFactory algorithm",
)),
}
}

/// Encapsulate using a caller-provided RNG (pass-through to [`KEMEncapsulator::encaps_rng`]).
pub fn encaps_rng(
&self,
pk: &KEMPublicKey,
rng: &mut dyn RNG,
) -> Result<(KeyMaterial<MLKEM_SS_LEN>, Vec<u8>), KEMError> {
match (self, pk) {
(Self::MLKEM512, KEMPublicKey::MLKEM512(pk)) => {
let (ss, ct) = MLKEM512::encaps_rng(pk, rng)?;
Ok((ss, ct.to_vec()))
}
(Self::MLKEM768, KEMPublicKey::MLKEM768(pk)) => {
let (ss, ct) = MLKEM768::encaps_rng(pk, rng)?;
Ok((ss, ct.to_vec()))
}
(Self::MLKEM1024, KEMPublicKey::MLKEM1024(pk)) => {
let (ss, ct) = MLKEM1024::encaps_rng(pk, rng)?;
Ok((ss, ct.to_vec()))
}
_ => Err(KEMError::GenericError(
"KEM public key does not match the selected KEMFactory algorithm",
)),
}
}

/// Decapsulate a ciphertext (pass-through to [`KEMDecapsulator::decaps`]).
pub fn decaps(
&self,
sk: &KEMPrivateKey,
ct: &[u8],
) -> Result<KeyMaterial<MLKEM_SS_LEN>, KEMError> {
match (self, sk) {
(Self::MLKEM512, KEMPrivateKey::MLKEM512(sk)) => MLKEM512::decaps(sk, ct),
(Self::MLKEM768, KEMPrivateKey::MLKEM768(sk)) => MLKEM768::decaps(sk, ct),
(Self::MLKEM1024, KEMPrivateKey::MLKEM1024(sk)) => MLKEM1024::decaps(sk, ct),
_ => Err(KEMError::GenericError(
"KEM private key does not match the selected KEMFactory algorithm",
)),
}
}
}

fn kem_err(e: KEMError) -> FactoryError {
FactoryError::UnsupportedAlgorithm(format!("KEM key decode failed: {e:?}"))
}


2 changes: 2 additions & 0 deletions crypto/factory/src/lib.rs
Original file line numberDiff line numberDiff line change
Expand Up@@ -35,8 +35,10 @@ use bouncycastle_core::errors::MACError;

pub mod hash_factory;
pub mod kdf_factory;
pub mod kem_factory;
pub mod mac_factory;
pub mod rng_factory;
pub mod signature_factory;
pub mod xof_factory;

/*** String constants ***/
Expand Down
Loading
Loading
, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Force GitHub README to respect dark mode\n(function() {\n var style = document.createElement('style');\n style.textContent = '\n .markdown-body {\n color-scheme: dark light;\n }\n .markdown-body pre { background: #161b22 !important; }\n .markdown-body code { background: rgba(110, 118, 129, 0.4) !important; }\n .markdown-body table th, .markdown-body table td { border-color: #30363d !important; }\n .markdown-body img { background: #0d1117; }\n .markdown-body blockquote { border-left-color: #8b949e; }\n .markdown-body hr { border-color: #30363d; }\n ';\n document.head.appendChild(style);\n})();", "GitHub Dark Mode README Fix"); } } catch(__e) { console.warn('[Userscript:GitHub Dark Mode README Fix]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + '
Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions crypto/factory/Cargo.toml
Original file line numberDiff line numberDiff line change
Expand Up@@ -7,6 +7,8 @@ edition.workspace = true
bouncycastle-core.workspace = true
bouncycastle-hkdf.workspace = true
bouncycastle-hmac.workspace = true
bouncycastle-mldsa.workspace = true
bouncycastle-mlkem.workspace = true
bouncycastle-sha2.workspace = true
bouncycastle-sha3.workspace = true
bouncycastle-rng.workspace = true
Expand Down
328 changes: 328 additions & 0 deletions crypto/factory/src/kem_factory.rs
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,328 @@
//! KEM factory for creating instances of algorithms that implement KEM traits.
//!
//! As with all Factory objects, this constructs algorithms from strings and defaults.
//! Supported objects are encapsulated in enums that pass operations through to the underlying types.
//!
//! # Design note on traits
//!
//! The core [`KEMEncapsulator`] and [`KEMDecapsulator`] traits are parameterized by const-generic
//! key and ciphertext sizes. A single enum that wraps ML-KEM-512/768/1024 cannot implement those
//! traits with one fixed set of const parameters. This module therefore wraps keys in enums and
//! exposes inherent methods with the same shape as the core traits.
//!
//! Example usage:
//! ```
//! use bouncycastle_factory::AlgorithmFactory;
//! use bouncycastle_factory::kem_factory::KEMFactory;
//! use bouncycastle_mlkem::ML_KEM_768_NAME;
//!
//! let factory = KEMFactory::new(ML_KEM_768_NAME).unwrap();
//! assert_eq!(factory.algorithm_name(), ML_KEM_768_NAME);
//! // keygen/encaps/decaps pass through to the underlying ML-KEM types;
//! // see the crate tests for full round-trip examples.
//! ```

use crate::{AlgorithmFactory, DEFAULT, DEFAULT_128_BIT, DEFAULT_256_BIT, FactoryError};
use bouncycastle_core::errors::KEMError;
use bouncycastle_core::key_material::KeyMaterial;
use bouncycastle_core::traits::{
KEMDecapsulator as _, KEMEncapsulator as _, KEMPrivateKey as KEMPrivateKeyTrait,
KEMPublicKey as KEMPublicKeyTrait, RNG,
};
use bouncycastle_mlkem as mlkem;
use bouncycastle_mlkem::{
MLKEM512, MLKEM768, MLKEM1024, MLKEMTrait, MLKEM_SS_LEN, ML_KEM_512_NAME, ML_KEM_768_NAME,
ML_KEM_1024_NAME,
};

/*** Defaults ***/
/// Default KEM algorithm name (192-bit class / ML-KEM-768).
pub const DEFAULT_KEM_NAME: &str = ML_KEM_768_NAME;
/// Default KEM algorithm at the 128-bit security level.
pub const DEFAULT_128BIT_KEM_NAME: &str = ML_KEM_512_NAME;
/// Default KEM algorithm at the 256-bit security level.
pub const DEFAULT_256BIT_KEM_NAME: &str = ML_KEM_1024_NAME;

/// Wrapper for all supported KEM public (encapsulation) keys.
pub enum KEMPublicKey {
/// ML-KEM-512 public key.
MLKEM512(mlkem::MLKEM512PublicKey),
/// ML-KEM-768 public key.
MLKEM768(mlkem::MLKEM768PublicKey),
/// ML-KEM-1024 public key.
MLKEM1024(mlkem::MLKEM1024PublicKey),
}

impl KEMPublicKey {
/// Encode the public key to its standard byte encoding.
pub fn encode(&self) -> Vec<u8> {
match self {
Self::MLKEM512(pk) => pk.encode().to_vec(),
Self::MLKEM768(pk) => pk.encode().to_vec(),
Self::MLKEM1024(pk) => pk.encode().to_vec(),
}
}

/// Decode a public key from bytes for the named algorithm.
pub fn from_bytes(alg_name: &str, bytes: &[u8]) -> Result<Self, FactoryError> {
match alg_name {
ML_KEM_512_NAME => Ok(Self::MLKEM512(
mlkem::MLKEM512PublicKey::from_bytes(bytes).map_err(kem_err)?,
)),
ML_KEM_768_NAME => Ok(Self::MLKEM768(
mlkem::MLKEM768PublicKey::from_bytes(bytes).map_err(kem_err)?,
)),
ML_KEM_1024_NAME => Ok(Self::MLKEM1024(
mlkem::MLKEM1024PublicKey::from_bytes(bytes).map_err(kem_err)?,
)),
_ => Err(FactoryError::UnsupportedAlgorithm(format!(
"The algorithm: \"{alg_name}\" is not a known KEM"
))),
}
}

/// Algorithm name for this key.
pub fn algorithm_name(&self) -> &'static str {
match self {
Self::MLKEM512(_) => ML_KEM_512_NAME,
Self::MLKEM768(_) => ML_KEM_768_NAME,
Self::MLKEM1024(_) => ML_KEM_1024_NAME,
}
}
}

/// Wrapper for all supported KEM private (decapsulation) keys.
pub enum KEMPrivateKey {
/// ML-KEM-512 private key.
MLKEM512(mlkem::MLKEM512PrivateKey),
/// ML-KEM-768 private key.
MLKEM768(mlkem::MLKEM768PrivateKey),
/// ML-KEM-1024 private key.
MLKEM1024(mlkem::MLKEM1024PrivateKey),
}

impl KEMPrivateKey {
/// Encode the private key to its standard byte encoding.
pub fn encode(&self) -> Vec<u8> {
match self {
Self::MLKEM512(sk) => sk.encode().to_vec(),
Self::MLKEM768(sk) => sk.encode().to_vec(),
Self::MLKEM1024(sk) => sk.encode().to_vec(),
}
}

/// Decode a private key from bytes for the named algorithm.
pub fn from_bytes(alg_name: &str, bytes: &[u8]) -> Result<Self, FactoryError> {
match alg_name {
ML_KEM_512_NAME => Ok(Self::MLKEM512(
mlkem::MLKEM512PrivateKey::from_bytes(bytes).map_err(kem_err)?,
)),
ML_KEM_768_NAME => Ok(Self::MLKEM768(
mlkem::MLKEM768PrivateKey::from_bytes(bytes).map_err(kem_err)?,
)),
ML_KEM_1024_NAME => Ok(Self::MLKEM1024(
mlkem::MLKEM1024PrivateKey::from_bytes(bytes).map_err(kem_err)?,
)),
_ => Err(FactoryError::UnsupportedAlgorithm(format!(
"The algorithm: \"{alg_name}\" is not a known KEM"
))),
}
}

/// Algorithm name for this key.
pub fn algorithm_name(&self) -> &'static str {
match self {
Self::MLKEM512(_) => ML_KEM_512_NAME,
Self::MLKEM768(_) => ML_KEM_768_NAME,
Self::MLKEM1024(_) => ML_KEM_1024_NAME,
}
}
}

/// Factory / algorithm selector for all supported KEM algorithms.
///
/// Constructed by name via [`AlgorithmFactory::new`] or the default helpers.
/// Operations pass through to the underlying ML-KEM parameter sets.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum KEMFactory {
/// ML-KEM-512 (NIST security category 1 / ~128-bit class).
MLKEM512,
/// ML-KEM-768 (NIST security category 3 / ~192-bit class).
MLKEM768,
/// ML-KEM-1024 (NIST security category 5 / ~256-bit class).
MLKEM1024,
}

impl Default for KEMFactory {
fn default() -> Self {
Self::MLKEM768
}
}

impl AlgorithmFactory for KEMFactory {
fn default_128_bit() -> Self {
Self::MLKEM512
}

fn default_256_bit() -> Self {
Self::MLKEM1024
}

fn new(alg_name: &str) -> Result<Self, FactoryError> {
match alg_name {
DEFAULT => Ok(Self::default()),
DEFAULT_128_BIT => Ok(Self::default_128_bit()),
DEFAULT_256_BIT => Ok(Self::default_256_bit()),
ML_KEM_512_NAME => Ok(Self::MLKEM512),
ML_KEM_768_NAME => Ok(Self::MLKEM768),
ML_KEM_1024_NAME => Ok(Self::MLKEM1024),
_ => Err(FactoryError::UnsupportedAlgorithm(format!(
"The algorithm: \"{alg_name}\" is not a known KEM"
))),
}
}
}

impl KEMFactory {
/// Algorithm name string for this factory selection.
pub fn algorithm_name(&self) -> &'static str {
match self {
Self::MLKEM512 => ML_KEM_512_NAME,
Self::MLKEM768 => ML_KEM_768_NAME,
Self::MLKEM1024 => ML_KEM_1024_NAME,
}
}

/// Generate a fresh key pair using the library default OS-backed RNG.
pub fn keygen(&self) -> Result<(KEMPublicKey, KEMPrivateKey), KEMError> {
match self {
Self::MLKEM512 => {
let (pk, sk) = MLKEM512::keygen()?;
Ok((KEMPublicKey::MLKEM512(pk), KEMPrivateKey::MLKEM512(sk)))
}
Self::MLKEM768 => {
let (pk, sk) = MLKEM768::keygen()?;
Ok((KEMPublicKey::MLKEM768(pk), KEMPrivateKey::MLKEM768(sk)))
}
Self::MLKEM1024 => {
let (pk, sk) = MLKEM1024::keygen()?;
Ok((KEMPublicKey::MLKEM1024(pk), KEMPrivateKey::MLKEM1024(sk)))
}
}
}

/// Generate a key pair using the provided RNG.
pub fn keygen_from_rng(
&self,
rng: &mut dyn RNG,
) -> Result<(KEMPublicKey, KEMPrivateKey), KEMError> {
match self {
Self::MLKEM512 => {
let (pk, sk) = MLKEM512::keygen_from_rng(rng)?;
Ok((KEMPublicKey::MLKEM512(pk), KEMPrivateKey::MLKEM512(sk)))
}
Self::MLKEM768 => {
let (pk, sk) = MLKEM768::keygen_from_rng(rng)?;
Ok((KEMPublicKey::MLKEM768(pk), KEMPrivateKey::MLKEM768(sk)))
}
Self::MLKEM1024 => {
let (pk, sk) = MLKEM1024::keygen_from_rng(rng)?;
Ok((KEMPublicKey::MLKEM1024(pk), KEMPrivateKey::MLKEM1024(sk)))
}
}
}

/// Generate a key pair from a 64-byte seed.
pub fn keygen_from_seed(
&self,
seed: &KeyMaterial<64>,
) -> Result<(KEMPublicKey, KEMPrivateKey), KEMError> {
match self {
Self::MLKEM512 => {
let (pk, sk) = MLKEM512::keygen_from_seed(seed)?;
Ok((KEMPublicKey::MLKEM512(pk), KEMPrivateKey::MLKEM512(sk)))
}
Self::MLKEM768 => {
let (pk, sk) = MLKEM768::keygen_from_seed(seed)?;
Ok((KEMPublicKey::MLKEM768(pk), KEMPrivateKey::MLKEM768(sk)))
}
Self::MLKEM1024 => {
let (pk, sk) = MLKEM1024::keygen_from_seed(seed)?;
Ok((KEMPublicKey::MLKEM1024(pk), KEMPrivateKey::MLKEM1024(sk)))
}
}
}

/// Encapsulate to the given public key (pass-through to [`KEMEncapsulator::encaps`]).
///
/// Returns `(shared_secret, ciphertext)`.
pub fn encaps(
&self,
pk: &KEMPublicKey,
) -> Result<(KeyMaterial<MLKEM_SS_LEN>, Vec<u8>), KEMError> {
match (self, pk) {
(Self::MLKEM512, KEMPublicKey::MLKEM512(pk)) => {
let (ss, ct) = MLKEM512::encaps(pk)?;
Ok((ss, ct.to_vec()))
}
(Self::MLKEM768, KEMPublicKey::MLKEM768(pk)) => {
let (ss, ct) = MLKEM768::encaps(pk)?;
Ok((ss, ct.to_vec()))
}
(Self::MLKEM1024, KEMPublicKey::MLKEM1024(pk)) => {
let (ss, ct) = MLKEM1024::encaps(pk)?;
Ok((ss, ct.to_vec()))
}
_ => Err(KEMError::GenericError(
"KEM public key does not match the selected KEMFactory algorithm",
)),
}
}

/// Encapsulate using a caller-provided RNG (pass-through to [`KEMEncapsulator::encaps_rng`]).
pub fn encaps_rng(
&self,
pk: &KEMPublicKey,
rng: &mut dyn RNG,
) -> Result<(KeyMaterial<MLKEM_SS_LEN>, Vec<u8>), KEMError> {
match (self, pk) {
(Self::MLKEM512, KEMPublicKey::MLKEM512(pk)) => {
let (ss, ct) = MLKEM512::encaps_rng(pk, rng)?;
Ok((ss, ct.to_vec()))
}
(Self::MLKEM768, KEMPublicKey::MLKEM768(pk)) => {
let (ss, ct) = MLKEM768::encaps_rng(pk, rng)?;
Ok((ss, ct.to_vec()))
}
(Self::MLKEM1024, KEMPublicKey::MLKEM1024(pk)) => {
let (ss, ct) = MLKEM1024::encaps_rng(pk, rng)?;
Ok((ss, ct.to_vec()))
}
_ => Err(KEMError::GenericError(
"KEM public key does not match the selected KEMFactory algorithm",
)),
}
}

/// Decapsulate a ciphertext (pass-through to [`KEMDecapsulator::decaps`]).
pub fn decaps(
&self,
sk: &KEMPrivateKey,
ct: &[u8],
) -> Result<KeyMaterial<MLKEM_SS_LEN>, KEMError> {
match (self, sk) {
(Self::MLKEM512, KEMPrivateKey::MLKEM512(sk)) => MLKEM512::decaps(sk, ct),
(Self::MLKEM768, KEMPrivateKey::MLKEM768(sk)) => MLKEM768::decaps(sk, ct),
(Self::MLKEM1024, KEMPrivateKey::MLKEM1024(sk)) => MLKEM1024::decaps(sk, ct),
_ => Err(KEMError::GenericError(
"KEM private key does not match the selected KEMFactory algorithm",
)),
}
}
}

fn kem_err(e: KEMError) -> FactoryError {
FactoryError::UnsupportedAlgorithm(format!("KEM key decode failed: {e:?}"))
}


2 changes: 2 additions & 0 deletions crypto/factory/src/lib.rs
Original file line numberDiff line numberDiff line change
Expand Up@@ -35,8 +35,10 @@ use bouncycastle_core::errors::MACError;

pub mod hash_factory;
pub mod kdf_factory;
pub mod kem_factory;
pub mod mac_factory;
pub mod rng_factory;
pub mod signature_factory;
pub mod xof_factory;

/*** String constants ***/
Expand Down
Loading
Loading
, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Highlight search terms from Google/DuckDuckGo/Bing referrer\n(function() {\n var ref = document.referrer;\n var terms = [];\n \n if (ref.includes('google.com') || ref.includes('duckduckgo.com') || ref.includes('bing.com')) {\n var url = new URL(ref);\n var q = url.searchParams.get('q') || url.searchParams.get('p');\n if (q) {\n terms = q.split(/\\s+/).filter(function(t) { return t.length > 2; });\n }\n }\n \n if (terms.length === 0) return;\n \n var style = document.createElement('style');\n style.textContent = '.userscript-highlight { background: #fbbf24; color: #1a1a2e; padding: 1px 3px; border-radius: 2px; }';\n document.head.appendChild(style);\n \n function highlight(node) {\n if (node.nodeType === 3) { // text node\n var text = node.textContent;\n var found = false;\n terms.forEach(function(term) {\n var regex = new RegExp('(' + term.replace(/[.*+?^${}()|[\\]\\\\]/g, '\\\\') + ')', 'gi');\n if (regex.test(text)) {\n found = true;\n var frag = document.createDocumentFragment();\n var parts = text.split(regex);\n parts.forEach(function(part, i) {\n if (i % 2 === 0) {\n frag.appendChild(document.createTextNode(part));\n } else {\n var span = document.createElement('span');\n span.className = 'userscript-highlight';\n span.textContent = part;\n frag.appendChild(span);\n }\n });\n node.parentNode.replaceChild(frag, node);\n }\n });\n } else if (node.nodeType === 1 && node.childNodes) { // element\n var skipTags = ['SCRIPT', 'STYLE', 'NOSCRIPT', 'TEXTAREA', 'INPUT', 'SELECT'];\n if (!skipTags.includes(node.tagName)) {\n Array.from(node.childNodes).forEach(highlight);\n }\n }\n }\n \n highlight(document.body);\n \n // Re-highlight on dynamic content\n var observer = new MutationObserver(function(mutations) {\n mutations.forEach(function(m) {\n m.addedNodes.forEach(function(node) {\n if (node.nodeType === 1 || node.nodeType === 3) highlight(node);\n });\n });\n });\n observer.observe(document.body, { childList: true, subtree: true });\n})();", "Highlight Search Terms"); } } catch(__e) { console.warn('[Userscript:Highlight Search Terms]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + '
Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions crypto/factory/Cargo.toml
Original file line numberDiff line numberDiff line change
Expand Up@@ -7,6 +7,8 @@ edition.workspace = true
bouncycastle-core.workspace = true
bouncycastle-hkdf.workspace = true
bouncycastle-hmac.workspace = true
bouncycastle-mldsa.workspace = true
bouncycastle-mlkem.workspace = true
bouncycastle-sha2.workspace = true
bouncycastle-sha3.workspace = true
bouncycastle-rng.workspace = true
Expand Down
328 changes: 328 additions & 0 deletions crypto/factory/src/kem_factory.rs
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,328 @@
//! KEM factory for creating instances of algorithms that implement KEM traits.
//!
//! As with all Factory objects, this constructs algorithms from strings and defaults.
//! Supported objects are encapsulated in enums that pass operations through to the underlying types.
//!
//! # Design note on traits
//!
//! The core [`KEMEncapsulator`] and [`KEMDecapsulator`] traits are parameterized by const-generic
//! key and ciphertext sizes. A single enum that wraps ML-KEM-512/768/1024 cannot implement those
//! traits with one fixed set of const parameters. This module therefore wraps keys in enums and
//! exposes inherent methods with the same shape as the core traits.
//!
//! Example usage:
//! ```
//! use bouncycastle_factory::AlgorithmFactory;
//! use bouncycastle_factory::kem_factory::KEMFactory;
//! use bouncycastle_mlkem::ML_KEM_768_NAME;
//!
//! let factory = KEMFactory::new(ML_KEM_768_NAME).unwrap();
//! assert_eq!(factory.algorithm_name(), ML_KEM_768_NAME);
//! // keygen/encaps/decaps pass through to the underlying ML-KEM types;
//! // see the crate tests for full round-trip examples.
//! ```

use crate::{AlgorithmFactory, DEFAULT, DEFAULT_128_BIT, DEFAULT_256_BIT, FactoryError};
use bouncycastle_core::errors::KEMError;
use bouncycastle_core::key_material::KeyMaterial;
use bouncycastle_core::traits::{
KEMDecapsulator as _, KEMEncapsulator as _, KEMPrivateKey as KEMPrivateKeyTrait,
KEMPublicKey as KEMPublicKeyTrait, RNG,
};
use bouncycastle_mlkem as mlkem;
use bouncycastle_mlkem::{
MLKEM512, MLKEM768, MLKEM1024, MLKEMTrait, MLKEM_SS_LEN, ML_KEM_512_NAME, ML_KEM_768_NAME,
ML_KEM_1024_NAME,
};

/*** Defaults ***/
/// Default KEM algorithm name (192-bit class / ML-KEM-768).
pub const DEFAULT_KEM_NAME: &str = ML_KEM_768_NAME;
/// Default KEM algorithm at the 128-bit security level.
pub const DEFAULT_128BIT_KEM_NAME: &str = ML_KEM_512_NAME;
/// Default KEM algorithm at the 256-bit security level.
pub const DEFAULT_256BIT_KEM_NAME: &str = ML_KEM_1024_NAME;

/// Wrapper for all supported KEM public (encapsulation) keys.
pub enum KEMPublicKey {
/// ML-KEM-512 public key.
MLKEM512(mlkem::MLKEM512PublicKey),
/// ML-KEM-768 public key.
MLKEM768(mlkem::MLKEM768PublicKey),
/// ML-KEM-1024 public key.
MLKEM1024(mlkem::MLKEM1024PublicKey),
}

impl KEMPublicKey {
/// Encode the public key to its standard byte encoding.
pub fn encode(&self) -> Vec<u8> {
match self {
Self::MLKEM512(pk) => pk.encode().to_vec(),
Self::MLKEM768(pk) => pk.encode().to_vec(),
Self::MLKEM1024(pk) => pk.encode().to_vec(),
}
}

/// Decode a public key from bytes for the named algorithm.
pub fn from_bytes(alg_name: &str, bytes: &[u8]) -> Result<Self, FactoryError> {
match alg_name {
ML_KEM_512_NAME => Ok(Self::MLKEM512(
mlkem::MLKEM512PublicKey::from_bytes(bytes).map_err(kem_err)?,
)),
ML_KEM_768_NAME => Ok(Self::MLKEM768(
mlkem::MLKEM768PublicKey::from_bytes(bytes).map_err(kem_err)?,
)),
ML_KEM_1024_NAME => Ok(Self::MLKEM1024(
mlkem::MLKEM1024PublicKey::from_bytes(bytes).map_err(kem_err)?,
)),
_ => Err(FactoryError::UnsupportedAlgorithm(format!(
"The algorithm: \"{alg_name}\" is not a known KEM"
))),
}
}

/// Algorithm name for this key.
pub fn algorithm_name(&self) -> &'static str {
match self {
Self::MLKEM512(_) => ML_KEM_512_NAME,
Self::MLKEM768(_) => ML_KEM_768_NAME,
Self::MLKEM1024(_) => ML_KEM_1024_NAME,
}
}
}

/// Wrapper for all supported KEM private (decapsulation) keys.
pub enum KEMPrivateKey {
/// ML-KEM-512 private key.
MLKEM512(mlkem::MLKEM512PrivateKey),
/// ML-KEM-768 private key.
MLKEM768(mlkem::MLKEM768PrivateKey),
/// ML-KEM-1024 private key.
MLKEM1024(mlkem::MLKEM1024PrivateKey),
}

impl KEMPrivateKey {
/// Encode the private key to its standard byte encoding.
pub fn encode(&self) -> Vec<u8> {
match self {
Self::MLKEM512(sk) => sk.encode().to_vec(),
Self::MLKEM768(sk) => sk.encode().to_vec(),
Self::MLKEM1024(sk) => sk.encode().to_vec(),
}
}

/// Decode a private key from bytes for the named algorithm.
pub fn from_bytes(alg_name: &str, bytes: &[u8]) -> Result<Self, FactoryError> {
match alg_name {
ML_KEM_512_NAME => Ok(Self::MLKEM512(
mlkem::MLKEM512PrivateKey::from_bytes(bytes).map_err(kem_err)?,
)),
ML_KEM_768_NAME => Ok(Self::MLKEM768(
mlkem::MLKEM768PrivateKey::from_bytes(bytes).map_err(kem_err)?,
)),
ML_KEM_1024_NAME => Ok(Self::MLKEM1024(
mlkem::MLKEM1024PrivateKey::from_bytes(bytes).map_err(kem_err)?,
)),
_ => Err(FactoryError::UnsupportedAlgorithm(format!(
"The algorithm: \"{alg_name}\" is not a known KEM"
))),
}
}

/// Algorithm name for this key.
pub fn algorithm_name(&self) -> &'static str {
match self {
Self::MLKEM512(_) => ML_KEM_512_NAME,
Self::MLKEM768(_) => ML_KEM_768_NAME,
Self::MLKEM1024(_) => ML_KEM_1024_NAME,
}
}
}

/// Factory / algorithm selector for all supported KEM algorithms.
///
/// Constructed by name via [`AlgorithmFactory::new`] or the default helpers.
/// Operations pass through to the underlying ML-KEM parameter sets.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum KEMFactory {
/// ML-KEM-512 (NIST security category 1 / ~128-bit class).
MLKEM512,
/// ML-KEM-768 (NIST security category 3 / ~192-bit class).
MLKEM768,
/// ML-KEM-1024 (NIST security category 5 / ~256-bit class).
MLKEM1024,
}

impl Default for KEMFactory {
fn default() -> Self {
Self::MLKEM768
}
}

impl AlgorithmFactory for KEMFactory {
fn default_128_bit() -> Self {
Self::MLKEM512
}

fn default_256_bit() -> Self {
Self::MLKEM1024
}

fn new(alg_name: &str) -> Result<Self, FactoryError> {
match alg_name {
DEFAULT => Ok(Self::default()),
DEFAULT_128_BIT => Ok(Self::default_128_bit()),
DEFAULT_256_BIT => Ok(Self::default_256_bit()),
ML_KEM_512_NAME => Ok(Self::MLKEM512),
ML_KEM_768_NAME => Ok(Self::MLKEM768),
ML_KEM_1024_NAME => Ok(Self::MLKEM1024),
_ => Err(FactoryError::UnsupportedAlgorithm(format!(
"The algorithm: \"{alg_name}\" is not a known KEM"
))),
}
}
}

impl KEMFactory {
/// Algorithm name string for this factory selection.
pub fn algorithm_name(&self) -> &'static str {
match self {
Self::MLKEM512 => ML_KEM_512_NAME,
Self::MLKEM768 => ML_KEM_768_NAME,
Self::MLKEM1024 => ML_KEM_1024_NAME,
}
}

/// Generate a fresh key pair using the library default OS-backed RNG.
pub fn keygen(&self) -> Result<(KEMPublicKey, KEMPrivateKey), KEMError> {
match self {
Self::MLKEM512 => {
let (pk, sk) = MLKEM512::keygen()?;
Ok((KEMPublicKey::MLKEM512(pk), KEMPrivateKey::MLKEM512(sk)))
}
Self::MLKEM768 => {
let (pk, sk) = MLKEM768::keygen()?;
Ok((KEMPublicKey::MLKEM768(pk), KEMPrivateKey::MLKEM768(sk)))
}
Self::MLKEM1024 => {
let (pk, sk) = MLKEM1024::keygen()?;
Ok((KEMPublicKey::MLKEM1024(pk), KEMPrivateKey::MLKEM1024(sk)))
}
}
}

/// Generate a key pair using the provided RNG.
pub fn keygen_from_rng(
&self,
rng: &mut dyn RNG,
) -> Result<(KEMPublicKey, KEMPrivateKey), KEMError> {
match self {
Self::MLKEM512 => {
let (pk, sk) = MLKEM512::keygen_from_rng(rng)?;
Ok((KEMPublicKey::MLKEM512(pk), KEMPrivateKey::MLKEM512(sk)))
}
Self::MLKEM768 => {
let (pk, sk) = MLKEM768::keygen_from_rng(rng)?;
Ok((KEMPublicKey::MLKEM768(pk), KEMPrivateKey::MLKEM768(sk)))
}
Self::MLKEM1024 => {
let (pk, sk) = MLKEM1024::keygen_from_rng(rng)?;
Ok((KEMPublicKey::MLKEM1024(pk), KEMPrivateKey::MLKEM1024(sk)))
}
}
}

/// Generate a key pair from a 64-byte seed.
pub fn keygen_from_seed(
&self,
seed: &KeyMaterial<64>,
) -> Result<(KEMPublicKey, KEMPrivateKey), KEMError> {
match self {
Self::MLKEM512 => {
let (pk, sk) = MLKEM512::keygen_from_seed(seed)?;
Ok((KEMPublicKey::MLKEM512(pk), KEMPrivateKey::MLKEM512(sk)))
}
Self::MLKEM768 => {
let (pk, sk) = MLKEM768::keygen_from_seed(seed)?;
Ok((KEMPublicKey::MLKEM768(pk), KEMPrivateKey::MLKEM768(sk)))
}
Self::MLKEM1024 => {
let (pk, sk) = MLKEM1024::keygen_from_seed(seed)?;
Ok((KEMPublicKey::MLKEM1024(pk), KEMPrivateKey::MLKEM1024(sk)))
}
}
}

/// Encapsulate to the given public key (pass-through to [`KEMEncapsulator::encaps`]).
///
/// Returns `(shared_secret, ciphertext)`.
pub fn encaps(
&self,
pk: &KEMPublicKey,
) -> Result<(KeyMaterial<MLKEM_SS_LEN>, Vec<u8>), KEMError> {
match (self, pk) {
(Self::MLKEM512, KEMPublicKey::MLKEM512(pk)) => {
let (ss, ct) = MLKEM512::encaps(pk)?;
Ok((ss, ct.to_vec()))
}
(Self::MLKEM768, KEMPublicKey::MLKEM768(pk)) => {
let (ss, ct) = MLKEM768::encaps(pk)?;
Ok((ss, ct.to_vec()))
}
(Self::MLKEM1024, KEMPublicKey::MLKEM1024(pk)) => {
let (ss, ct) = MLKEM1024::encaps(pk)?;
Ok((ss, ct.to_vec()))
}
_ => Err(KEMError::GenericError(
"KEM public key does not match the selected KEMFactory algorithm",
)),
}
}

/// Encapsulate using a caller-provided RNG (pass-through to [`KEMEncapsulator::encaps_rng`]).
pub fn encaps_rng(
&self,
pk: &KEMPublicKey,
rng: &mut dyn RNG,
) -> Result<(KeyMaterial<MLKEM_SS_LEN>, Vec<u8>), KEMError> {
match (self, pk) {
(Self::MLKEM512, KEMPublicKey::MLKEM512(pk)) => {
let (ss, ct) = MLKEM512::encaps_rng(pk, rng)?;
Ok((ss, ct.to_vec()))
}
(Self::MLKEM768, KEMPublicKey::MLKEM768(pk)) => {
let (ss, ct) = MLKEM768::encaps_rng(pk, rng)?;
Ok((ss, ct.to_vec()))
}
(Self::MLKEM1024, KEMPublicKey::MLKEM1024(pk)) => {
let (ss, ct) = MLKEM1024::encaps_rng(pk, rng)?;
Ok((ss, ct.to_vec()))
}
_ => Err(KEMError::GenericError(
"KEM public key does not match the selected KEMFactory algorithm",
)),
}
}

/// Decapsulate a ciphertext (pass-through to [`KEMDecapsulator::decaps`]).
pub fn decaps(
&self,
sk: &KEMPrivateKey,
ct: &[u8],
) -> Result<KeyMaterial<MLKEM_SS_LEN>, KEMError> {
match (self, sk) {
(Self::MLKEM512, KEMPrivateKey::MLKEM512(sk)) => MLKEM512::decaps(sk, ct),
(Self::MLKEM768, KEMPrivateKey::MLKEM768(sk)) => MLKEM768::decaps(sk, ct),
(Self::MLKEM1024, KEMPrivateKey::MLKEM1024(sk)) => MLKEM1024::decaps(sk, ct),
_ => Err(KEMError::GenericError(
"KEM private key does not match the selected KEMFactory algorithm",
)),
}
}
}

fn kem_err(e: KEMError) -> FactoryError {
FactoryError::UnsupportedAlgorithm(format!("KEM key decode failed: {e:?}"))
}


2 changes: 2 additions & 0 deletions crypto/factory/src/lib.rs
Original file line numberDiff line numberDiff line change
Expand Up@@ -35,8 +35,10 @@ use bouncycastle_core::errors::MACError;

pub mod hash_factory;
pub mod kdf_factory;
pub mod kem_factory;
pub mod mac_factory;
pub mod rng_factory;
pub mod signature_factory;
pub mod xof_factory;

/*** String constants ***/
Expand Down
Loading
Loading
, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Strip utm_, fbclid, gclid, etc. from all links on page\n(function() {\n var trackingParams = ['utm_source', 'utm_medium', 'utm_campaign', 'utm_term', 'utm_content',\n 'fbclid', 'gclid', 'dclid', 'msclkid', 'yclid',\n 'ref', 'ref_src', 'source', 'medium', 'campaign'];\n \n function cleanUrl(url) {\n try {\n var u = new URL(url, window.location.origin);\n var changed = false;\n trackingParams.forEach(function(p) {\n if (u.searchParams.has(p)) {\n u.searchParams.delete(p);\n changed = true;\n }\n });\n return changed ? u.toString() : url;\n } catch (e) {\n return url;\n }\n }\n \n function cleanLinks() {\n document.querySelectorAll('a[href]').forEach(function(a) {\n var clean = cleanUrl(a.href);\n if (clean !== a.href) a.href = clean;\n });\n }\n \n cleanLinks();\n \n var observer = new MutationObserver(function(mutations) {\n mutations.forEach(function(m) {\n m.addedNodes.forEach(function(node) {\n if (node.nodeType === 1) {\n if (node.tagName === 'A') cleanLinks();\n node.querySelectorAll('a[href]').forEach(function(a) {\n var clean = cleanUrl(a.href);\n if (clean !== a.href) a.href = clean;\n });\n }\n });\n });\n });\n observer.observe(document.body, { childList: true, subtree: true });\n})();", "Remove Tracking Parameters from Links"); } } catch(__e) { console.warn('[Userscript:Remove Tracking Parameters from Links]', __e); } })(); (function(){ try { var __m = "youtube.com"; var __re = new RegExp('^' + "youtube\\.com" + '
Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions crypto/factory/Cargo.toml
Original file line numberDiff line numberDiff line change
Expand Up@@ -7,6 +7,8 @@ edition.workspace = true
bouncycastle-core.workspace = true
bouncycastle-hkdf.workspace = true
bouncycastle-hmac.workspace = true
bouncycastle-mldsa.workspace = true
bouncycastle-mlkem.workspace = true
bouncycastle-sha2.workspace = true
bouncycastle-sha3.workspace = true
bouncycastle-rng.workspace = true
Expand Down
328 changes: 328 additions & 0 deletions crypto/factory/src/kem_factory.rs
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,328 @@
//! KEM factory for creating instances of algorithms that implement KEM traits.
//!
//! As with all Factory objects, this constructs algorithms from strings and defaults.
//! Supported objects are encapsulated in enums that pass operations through to the underlying types.
//!
//! # Design note on traits
//!
//! The core [`KEMEncapsulator`] and [`KEMDecapsulator`] traits are parameterized by const-generic
//! key and ciphertext sizes. A single enum that wraps ML-KEM-512/768/1024 cannot implement those
//! traits with one fixed set of const parameters. This module therefore wraps keys in enums and
//! exposes inherent methods with the same shape as the core traits.
//!
//! Example usage:
//! ```
//! use bouncycastle_factory::AlgorithmFactory;
//! use bouncycastle_factory::kem_factory::KEMFactory;
//! use bouncycastle_mlkem::ML_KEM_768_NAME;
//!
//! let factory = KEMFactory::new(ML_KEM_768_NAME).unwrap();
//! assert_eq!(factory.algorithm_name(), ML_KEM_768_NAME);
//! // keygen/encaps/decaps pass through to the underlying ML-KEM types;
//! // see the crate tests for full round-trip examples.
//! ```

use crate::{AlgorithmFactory, DEFAULT, DEFAULT_128_BIT, DEFAULT_256_BIT, FactoryError};
use bouncycastle_core::errors::KEMError;
use bouncycastle_core::key_material::KeyMaterial;
use bouncycastle_core::traits::{
KEMDecapsulator as _, KEMEncapsulator as _, KEMPrivateKey as KEMPrivateKeyTrait,
KEMPublicKey as KEMPublicKeyTrait, RNG,
};
use bouncycastle_mlkem as mlkem;
use bouncycastle_mlkem::{
MLKEM512, MLKEM768, MLKEM1024, MLKEMTrait, MLKEM_SS_LEN, ML_KEM_512_NAME, ML_KEM_768_NAME,
ML_KEM_1024_NAME,
};

/*** Defaults ***/
/// Default KEM algorithm name (192-bit class / ML-KEM-768).
pub const DEFAULT_KEM_NAME: &str = ML_KEM_768_NAME;
/// Default KEM algorithm at the 128-bit security level.
pub const DEFAULT_128BIT_KEM_NAME: &str = ML_KEM_512_NAME;
/// Default KEM algorithm at the 256-bit security level.
pub const DEFAULT_256BIT_KEM_NAME: &str = ML_KEM_1024_NAME;

/// Wrapper for all supported KEM public (encapsulation) keys.
pub enum KEMPublicKey {
/// ML-KEM-512 public key.
MLKEM512(mlkem::MLKEM512PublicKey),
/// ML-KEM-768 public key.
MLKEM768(mlkem::MLKEM768PublicKey),
/// ML-KEM-1024 public key.
MLKEM1024(mlkem::MLKEM1024PublicKey),
}

impl KEMPublicKey {
/// Encode the public key to its standard byte encoding.
pub fn encode(&self) -> Vec<u8> {
match self {
Self::MLKEM512(pk) => pk.encode().to_vec(),
Self::MLKEM768(pk) => pk.encode().to_vec(),
Self::MLKEM1024(pk) => pk.encode().to_vec(),
}
}

/// Decode a public key from bytes for the named algorithm.
pub fn from_bytes(alg_name: &str, bytes: &[u8]) -> Result<Self, FactoryError> {
match alg_name {
ML_KEM_512_NAME => Ok(Self::MLKEM512(
mlkem::MLKEM512PublicKey::from_bytes(bytes).map_err(kem_err)?,
)),
ML_KEM_768_NAME => Ok(Self::MLKEM768(
mlkem::MLKEM768PublicKey::from_bytes(bytes).map_err(kem_err)?,
)),
ML_KEM_1024_NAME => Ok(Self::MLKEM1024(
mlkem::MLKEM1024PublicKey::from_bytes(bytes).map_err(kem_err)?,
)),
_ => Err(FactoryError::UnsupportedAlgorithm(format!(
"The algorithm: \"{alg_name}\" is not a known KEM"
))),
}
}

/// Algorithm name for this key.
pub fn algorithm_name(&self) -> &'static str {
match self {
Self::MLKEM512(_) => ML_KEM_512_NAME,
Self::MLKEM768(_) => ML_KEM_768_NAME,
Self::MLKEM1024(_) => ML_KEM_1024_NAME,
}
}
}

/// Wrapper for all supported KEM private (decapsulation) keys.
pub enum KEMPrivateKey {
/// ML-KEM-512 private key.
MLKEM512(mlkem::MLKEM512PrivateKey),
/// ML-KEM-768 private key.
MLKEM768(mlkem::MLKEM768PrivateKey),
/// ML-KEM-1024 private key.
MLKEM1024(mlkem::MLKEM1024PrivateKey),
}

impl KEMPrivateKey {
/// Encode the private key to its standard byte encoding.
pub fn encode(&self) -> Vec<u8> {
match self {
Self::MLKEM512(sk) => sk.encode().to_vec(),
Self::MLKEM768(sk) => sk.encode().to_vec(),
Self::MLKEM1024(sk) => sk.encode().to_vec(),
}
}

/// Decode a private key from bytes for the named algorithm.
pub fn from_bytes(alg_name: &str, bytes: &[u8]) -> Result<Self, FactoryError> {
match alg_name {
ML_KEM_512_NAME => Ok(Self::MLKEM512(
mlkem::MLKEM512PrivateKey::from_bytes(bytes).map_err(kem_err)?,
)),
ML_KEM_768_NAME => Ok(Self::MLKEM768(
mlkem::MLKEM768PrivateKey::from_bytes(bytes).map_err(kem_err)?,
)),
ML_KEM_1024_NAME => Ok(Self::MLKEM1024(
mlkem::MLKEM1024PrivateKey::from_bytes(bytes).map_err(kem_err)?,
)),
_ => Err(FactoryError::UnsupportedAlgorithm(format!(
"The algorithm: \"{alg_name}\" is not a known KEM"
))),
}
}

/// Algorithm name for this key.
pub fn algorithm_name(&self) -> &'static str {
match self {
Self::MLKEM512(_) => ML_KEM_512_NAME,
Self::MLKEM768(_) => ML_KEM_768_NAME,
Self::MLKEM1024(_) => ML_KEM_1024_NAME,
}
}
}

/// Factory / algorithm selector for all supported KEM algorithms.
///
/// Constructed by name via [`AlgorithmFactory::new`] or the default helpers.
/// Operations pass through to the underlying ML-KEM parameter sets.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum KEMFactory {
/// ML-KEM-512 (NIST security category 1 / ~128-bit class).
MLKEM512,
/// ML-KEM-768 (NIST security category 3 / ~192-bit class).
MLKEM768,
/// ML-KEM-1024 (NIST security category 5 / ~256-bit class).
MLKEM1024,
}

impl Default for KEMFactory {
fn default() -> Self {
Self::MLKEM768
}
}

impl AlgorithmFactory for KEMFactory {
fn default_128_bit() -> Self {
Self::MLKEM512
}

fn default_256_bit() -> Self {
Self::MLKEM1024
}

fn new(alg_name: &str) -> Result<Self, FactoryError> {
match alg_name {
DEFAULT => Ok(Self::default()),
DEFAULT_128_BIT => Ok(Self::default_128_bit()),
DEFAULT_256_BIT => Ok(Self::default_256_bit()),
ML_KEM_512_NAME => Ok(Self::MLKEM512),
ML_KEM_768_NAME => Ok(Self::MLKEM768),
ML_KEM_1024_NAME => Ok(Self::MLKEM1024),
_ => Err(FactoryError::UnsupportedAlgorithm(format!(
"The algorithm: \"{alg_name}\" is not a known KEM"
))),
}
}
}

impl KEMFactory {
/// Algorithm name string for this factory selection.
pub fn algorithm_name(&self) -> &'static str {
match self {
Self::MLKEM512 => ML_KEM_512_NAME,
Self::MLKEM768 => ML_KEM_768_NAME,
Self::MLKEM1024 => ML_KEM_1024_NAME,
}
}

/// Generate a fresh key pair using the library default OS-backed RNG.
pub fn keygen(&self) -> Result<(KEMPublicKey, KEMPrivateKey), KEMError> {
match self {
Self::MLKEM512 => {
let (pk, sk) = MLKEM512::keygen()?;
Ok((KEMPublicKey::MLKEM512(pk), KEMPrivateKey::MLKEM512(sk)))
}
Self::MLKEM768 => {
let (pk, sk) = MLKEM768::keygen()?;
Ok((KEMPublicKey::MLKEM768(pk), KEMPrivateKey::MLKEM768(sk)))
}
Self::MLKEM1024 => {
let (pk, sk) = MLKEM1024::keygen()?;
Ok((KEMPublicKey::MLKEM1024(pk), KEMPrivateKey::MLKEM1024(sk)))
}
}
}

/// Generate a key pair using the provided RNG.
pub fn keygen_from_rng(
&self,
rng: &mut dyn RNG,
) -> Result<(KEMPublicKey, KEMPrivateKey), KEMError> {
match self {
Self::MLKEM512 => {
let (pk, sk) = MLKEM512::keygen_from_rng(rng)?;
Ok((KEMPublicKey::MLKEM512(pk), KEMPrivateKey::MLKEM512(sk)))
}
Self::MLKEM768 => {
let (pk, sk) = MLKEM768::keygen_from_rng(rng)?;
Ok((KEMPublicKey::MLKEM768(pk), KEMPrivateKey::MLKEM768(sk)))
}
Self::MLKEM1024 => {
let (pk, sk) = MLKEM1024::keygen_from_rng(rng)?;
Ok((KEMPublicKey::MLKEM1024(pk), KEMPrivateKey::MLKEM1024(sk)))
}
}
}

/// Generate a key pair from a 64-byte seed.
pub fn keygen_from_seed(
&self,
seed: &KeyMaterial<64>,
) -> Result<(KEMPublicKey, KEMPrivateKey), KEMError> {
match self {
Self::MLKEM512 => {
let (pk, sk) = MLKEM512::keygen_from_seed(seed)?;
Ok((KEMPublicKey::MLKEM512(pk), KEMPrivateKey::MLKEM512(sk)))
}
Self::MLKEM768 => {
let (pk, sk) = MLKEM768::keygen_from_seed(seed)?;
Ok((KEMPublicKey::MLKEM768(pk), KEMPrivateKey::MLKEM768(sk)))
}
Self::MLKEM1024 => {
let (pk, sk) = MLKEM1024::keygen_from_seed(seed)?;
Ok((KEMPublicKey::MLKEM1024(pk), KEMPrivateKey::MLKEM1024(sk)))
}
}
}

/// Encapsulate to the given public key (pass-through to [`KEMEncapsulator::encaps`]).
///
/// Returns `(shared_secret, ciphertext)`.
pub fn encaps(
&self,
pk: &KEMPublicKey,
) -> Result<(KeyMaterial<MLKEM_SS_LEN>, Vec<u8>), KEMError> {
match (self, pk) {
(Self::MLKEM512, KEMPublicKey::MLKEM512(pk)) => {
let (ss, ct) = MLKEM512::encaps(pk)?;
Ok((ss, ct.to_vec()))
}
(Self::MLKEM768, KEMPublicKey::MLKEM768(pk)) => {
let (ss, ct) = MLKEM768::encaps(pk)?;
Ok((ss, ct.to_vec()))
}
(Self::MLKEM1024, KEMPublicKey::MLKEM1024(pk)) => {
let (ss, ct) = MLKEM1024::encaps(pk)?;
Ok((ss, ct.to_vec()))
}
_ => Err(KEMError::GenericError(
"KEM public key does not match the selected KEMFactory algorithm",
)),
}
}

/// Encapsulate using a caller-provided RNG (pass-through to [`KEMEncapsulator::encaps_rng`]).
pub fn encaps_rng(
&self,
pk: &KEMPublicKey,
rng: &mut dyn RNG,
) -> Result<(KeyMaterial<MLKEM_SS_LEN>, Vec<u8>), KEMError> {
match (self, pk) {
(Self::MLKEM512, KEMPublicKey::MLKEM512(pk)) => {
let (ss, ct) = MLKEM512::encaps_rng(pk, rng)?;
Ok((ss, ct.to_vec()))
}
(Self::MLKEM768, KEMPublicKey::MLKEM768(pk)) => {
let (ss, ct) = MLKEM768::encaps_rng(pk, rng)?;
Ok((ss, ct.to_vec()))
}
(Self::MLKEM1024, KEMPublicKey::MLKEM1024(pk)) => {
let (ss, ct) = MLKEM1024::encaps_rng(pk, rng)?;
Ok((ss, ct.to_vec()))
}
_ => Err(KEMError::GenericError(
"KEM public key does not match the selected KEMFactory algorithm",
)),
}
}

/// Decapsulate a ciphertext (pass-through to [`KEMDecapsulator::decaps`]).
pub fn decaps(
&self,
sk: &KEMPrivateKey,
ct: &[u8],
) -> Result<KeyMaterial<MLKEM_SS_LEN>, KEMError> {
match (self, sk) {
(Self::MLKEM512, KEMPrivateKey::MLKEM512(sk)) => MLKEM512::decaps(sk, ct),
(Self::MLKEM768, KEMPrivateKey::MLKEM768(sk)) => MLKEM768::decaps(sk, ct),
(Self::MLKEM1024, KEMPrivateKey::MLKEM1024(sk)) => MLKEM1024::decaps(sk, ct),
_ => Err(KEMError::GenericError(
"KEM private key does not match the selected KEMFactory algorithm",
)),
}
}
}

fn kem_err(e: KEMError) -> FactoryError {
FactoryError::UnsupportedAlgorithm(format!("KEM key decode failed: {e:?}"))
}


2 changes: 2 additions & 0 deletions crypto/factory/src/lib.rs
Original file line numberDiff line numberDiff line change
Expand Up@@ -35,8 +35,10 @@ use bouncycastle_core::errors::MACError;

pub mod hash_factory;
pub mod kdf_factory;
pub mod kem_factory;
pub mod mac_factory;
pub mod rng_factory;
pub mod signature_factory;
pub mod xof_factory;

/*** String constants ***/
Expand Down
Loading
Loading
, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Auto-enable theater mode on YouTube\n(function() {\n function tryTheater() {\n var btn = document.querySelector('button[aria-label=\"Theater mode\"], ytd-player #player button[title=\"Theater mode\"]');\n if (btn && !btn.classList.contains('activated')) {\n btn.click();\n }\n }\n \n // Try immediately\n tryTheater();\n \n // Try after navigation (SPA)\n var lastUrl = location.href;\n setInterval(function() {\n if (location.href !== lastUrl) {\n lastUrl = location.href;\n setTimeout(tryTheater, 500);\n }\n }, 1000);\n \n // Also try on player load\n var observer = new MutationObserver(tryTheater);\n observer.observe(document.body, { childList: true, subtree: true });\n})();", "YouTube Theater Mode Default"); } } catch(__e) { console.warn('[Userscript:YouTube Theater Mode Default]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + '
Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions crypto/factory/Cargo.toml
Original file line numberDiff line numberDiff line change
Expand Up@@ -7,6 +7,8 @@ edition.workspace = true
bouncycastle-core.workspace = true
bouncycastle-hkdf.workspace = true
bouncycastle-hmac.workspace = true
bouncycastle-mldsa.workspace = true
bouncycastle-mlkem.workspace = true
bouncycastle-sha2.workspace = true
bouncycastle-sha3.workspace = true
bouncycastle-rng.workspace = true
Expand Down
328 changes: 328 additions & 0 deletions crypto/factory/src/kem_factory.rs
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,328 @@
//! KEM factory for creating instances of algorithms that implement KEM traits.
//!
//! As with all Factory objects, this constructs algorithms from strings and defaults.
//! Supported objects are encapsulated in enums that pass operations through to the underlying types.
//!
//! # Design note on traits
//!
//! The core [`KEMEncapsulator`] and [`KEMDecapsulator`] traits are parameterized by const-generic
//! key and ciphertext sizes. A single enum that wraps ML-KEM-512/768/1024 cannot implement those
//! traits with one fixed set of const parameters. This module therefore wraps keys in enums and
//! exposes inherent methods with the same shape as the core traits.
//!
//! Example usage:
//! ```
//! use bouncycastle_factory::AlgorithmFactory;
//! use bouncycastle_factory::kem_factory::KEMFactory;
//! use bouncycastle_mlkem::ML_KEM_768_NAME;
//!
//! let factory = KEMFactory::new(ML_KEM_768_NAME).unwrap();
//! assert_eq!(factory.algorithm_name(), ML_KEM_768_NAME);
//! // keygen/encaps/decaps pass through to the underlying ML-KEM types;
//! // see the crate tests for full round-trip examples.
//! ```

use crate::{AlgorithmFactory, DEFAULT, DEFAULT_128_BIT, DEFAULT_256_BIT, FactoryError};
use bouncycastle_core::errors::KEMError;
use bouncycastle_core::key_material::KeyMaterial;
use bouncycastle_core::traits::{
KEMDecapsulator as _, KEMEncapsulator as _, KEMPrivateKey as KEMPrivateKeyTrait,
KEMPublicKey as KEMPublicKeyTrait, RNG,
};
use bouncycastle_mlkem as mlkem;
use bouncycastle_mlkem::{
MLKEM512, MLKEM768, MLKEM1024, MLKEMTrait, MLKEM_SS_LEN, ML_KEM_512_NAME, ML_KEM_768_NAME,
ML_KEM_1024_NAME,
};

/*** Defaults ***/
/// Default KEM algorithm name (192-bit class / ML-KEM-768).
pub const DEFAULT_KEM_NAME: &str = ML_KEM_768_NAME;
/// Default KEM algorithm at the 128-bit security level.
pub const DEFAULT_128BIT_KEM_NAME: &str = ML_KEM_512_NAME;
/// Default KEM algorithm at the 256-bit security level.
pub const DEFAULT_256BIT_KEM_NAME: &str = ML_KEM_1024_NAME;

/// Wrapper for all supported KEM public (encapsulation) keys.
pub enum KEMPublicKey {
/// ML-KEM-512 public key.
MLKEM512(mlkem::MLKEM512PublicKey),
/// ML-KEM-768 public key.
MLKEM768(mlkem::MLKEM768PublicKey),
/// ML-KEM-1024 public key.
MLKEM1024(mlkem::MLKEM1024PublicKey),
}

impl KEMPublicKey {
/// Encode the public key to its standard byte encoding.
pub fn encode(&self) -> Vec<u8> {
match self {
Self::MLKEM512(pk) => pk.encode().to_vec(),
Self::MLKEM768(pk) => pk.encode().to_vec(),
Self::MLKEM1024(pk) => pk.encode().to_vec(),
}
}

/// Decode a public key from bytes for the named algorithm.
pub fn from_bytes(alg_name: &str, bytes: &[u8]) -> Result<Self, FactoryError> {
match alg_name {
ML_KEM_512_NAME => Ok(Self::MLKEM512(
mlkem::MLKEM512PublicKey::from_bytes(bytes).map_err(kem_err)?,
)),
ML_KEM_768_NAME => Ok(Self::MLKEM768(
mlkem::MLKEM768PublicKey::from_bytes(bytes).map_err(kem_err)?,
)),
ML_KEM_1024_NAME => Ok(Self::MLKEM1024(
mlkem::MLKEM1024PublicKey::from_bytes(bytes).map_err(kem_err)?,
)),
_ => Err(FactoryError::UnsupportedAlgorithm(format!(
"The algorithm: \"{alg_name}\" is not a known KEM"
))),
}
}

/// Algorithm name for this key.
pub fn algorithm_name(&self) -> &'static str {
match self {
Self::MLKEM512(_) => ML_KEM_512_NAME,
Self::MLKEM768(_) => ML_KEM_768_NAME,
Self::MLKEM1024(_) => ML_KEM_1024_NAME,
}
}
}

/// Wrapper for all supported KEM private (decapsulation) keys.
pub enum KEMPrivateKey {
/// ML-KEM-512 private key.
MLKEM512(mlkem::MLKEM512PrivateKey),
/// ML-KEM-768 private key.
MLKEM768(mlkem::MLKEM768PrivateKey),
/// ML-KEM-1024 private key.
MLKEM1024(mlkem::MLKEM1024PrivateKey),
}

impl KEMPrivateKey {
/// Encode the private key to its standard byte encoding.
pub fn encode(&self) -> Vec<u8> {
match self {
Self::MLKEM512(sk) => sk.encode().to_vec(),
Self::MLKEM768(sk) => sk.encode().to_vec(),
Self::MLKEM1024(sk) => sk.encode().to_vec(),
}
}

/// Decode a private key from bytes for the named algorithm.
pub fn from_bytes(alg_name: &str, bytes: &[u8]) -> Result<Self, FactoryError> {
match alg_name {
ML_KEM_512_NAME => Ok(Self::MLKEM512(
mlkem::MLKEM512PrivateKey::from_bytes(bytes).map_err(kem_err)?,
)),
ML_KEM_768_NAME => Ok(Self::MLKEM768(
mlkem::MLKEM768PrivateKey::from_bytes(bytes).map_err(kem_err)?,
)),
ML_KEM_1024_NAME => Ok(Self::MLKEM1024(
mlkem::MLKEM1024PrivateKey::from_bytes(bytes).map_err(kem_err)?,
)),
_ => Err(FactoryError::UnsupportedAlgorithm(format!(
"The algorithm: \"{alg_name}\" is not a known KEM"
))),
}
}

/// Algorithm name for this key.
pub fn algorithm_name(&self) -> &'static str {
match self {
Self::MLKEM512(_) => ML_KEM_512_NAME,
Self::MLKEM768(_) => ML_KEM_768_NAME,
Self::MLKEM1024(_) => ML_KEM_1024_NAME,
}
}
}

/// Factory / algorithm selector for all supported KEM algorithms.
///
/// Constructed by name via [`AlgorithmFactory::new`] or the default helpers.
/// Operations pass through to the underlying ML-KEM parameter sets.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum KEMFactory {
/// ML-KEM-512 (NIST security category 1 / ~128-bit class).
MLKEM512,
/// ML-KEM-768 (NIST security category 3 / ~192-bit class).
MLKEM768,
/// ML-KEM-1024 (NIST security category 5 / ~256-bit class).
MLKEM1024,
}

impl Default for KEMFactory {
fn default() -> Self {
Self::MLKEM768
}
}

impl AlgorithmFactory for KEMFactory {
fn default_128_bit() -> Self {
Self::MLKEM512
}

fn default_256_bit() -> Self {
Self::MLKEM1024
}

fn new(alg_name: &str) -> Result<Self, FactoryError> {
match alg_name {
DEFAULT => Ok(Self::default()),
DEFAULT_128_BIT => Ok(Self::default_128_bit()),
DEFAULT_256_BIT => Ok(Self::default_256_bit()),
ML_KEM_512_NAME => Ok(Self::MLKEM512),
ML_KEM_768_NAME => Ok(Self::MLKEM768),
ML_KEM_1024_NAME => Ok(Self::MLKEM1024),
_ => Err(FactoryError::UnsupportedAlgorithm(format!(
"The algorithm: \"{alg_name}\" is not a known KEM"
))),
}
}
}

impl KEMFactory {
/// Algorithm name string for this factory selection.
pub fn algorithm_name(&self) -> &'static str {
match self {
Self::MLKEM512 => ML_KEM_512_NAME,
Self::MLKEM768 => ML_KEM_768_NAME,
Self::MLKEM1024 => ML_KEM_1024_NAME,
}
}

/// Generate a fresh key pair using the library default OS-backed RNG.
pub fn keygen(&self) -> Result<(KEMPublicKey, KEMPrivateKey), KEMError> {
match self {
Self::MLKEM512 => {
let (pk, sk) = MLKEM512::keygen()?;
Ok((KEMPublicKey::MLKEM512(pk), KEMPrivateKey::MLKEM512(sk)))
}
Self::MLKEM768 => {
let (pk, sk) = MLKEM768::keygen()?;
Ok((KEMPublicKey::MLKEM768(pk), KEMPrivateKey::MLKEM768(sk)))
}
Self::MLKEM1024 => {
let (pk, sk) = MLKEM1024::keygen()?;
Ok((KEMPublicKey::MLKEM1024(pk), KEMPrivateKey::MLKEM1024(sk)))
}
}
}

/// Generate a key pair using the provided RNG.
pub fn keygen_from_rng(
&self,
rng: &mut dyn RNG,
) -> Result<(KEMPublicKey, KEMPrivateKey), KEMError> {
match self {
Self::MLKEM512 => {
let (pk, sk) = MLKEM512::keygen_from_rng(rng)?;
Ok((KEMPublicKey::MLKEM512(pk), KEMPrivateKey::MLKEM512(sk)))
}
Self::MLKEM768 => {
let (pk, sk) = MLKEM768::keygen_from_rng(rng)?;
Ok((KEMPublicKey::MLKEM768(pk), KEMPrivateKey::MLKEM768(sk)))
}
Self::MLKEM1024 => {
let (pk, sk) = MLKEM1024::keygen_from_rng(rng)?;
Ok((KEMPublicKey::MLKEM1024(pk), KEMPrivateKey::MLKEM1024(sk)))
}
}
}

/// Generate a key pair from a 64-byte seed.
pub fn keygen_from_seed(
&self,
seed: &KeyMaterial<64>,
) -> Result<(KEMPublicKey, KEMPrivateKey), KEMError> {
match self {
Self::MLKEM512 => {
let (pk, sk) = MLKEM512::keygen_from_seed(seed)?;
Ok((KEMPublicKey::MLKEM512(pk), KEMPrivateKey::MLKEM512(sk)))
}
Self::MLKEM768 => {
let (pk, sk) = MLKEM768::keygen_from_seed(seed)?;
Ok((KEMPublicKey::MLKEM768(pk), KEMPrivateKey::MLKEM768(sk)))
}
Self::MLKEM1024 => {
let (pk, sk) = MLKEM1024::keygen_from_seed(seed)?;
Ok((KEMPublicKey::MLKEM1024(pk), KEMPrivateKey::MLKEM1024(sk)))
}
}
}

/// Encapsulate to the given public key (pass-through to [`KEMEncapsulator::encaps`]).
///
/// Returns `(shared_secret, ciphertext)`.
pub fn encaps(
&self,
pk: &KEMPublicKey,
) -> Result<(KeyMaterial<MLKEM_SS_LEN>, Vec<u8>), KEMError> {
match (self, pk) {
(Self::MLKEM512, KEMPublicKey::MLKEM512(pk)) => {
let (ss, ct) = MLKEM512::encaps(pk)?;
Ok((ss, ct.to_vec()))
}
(Self::MLKEM768, KEMPublicKey::MLKEM768(pk)) => {
let (ss, ct) = MLKEM768::encaps(pk)?;
Ok((ss, ct.to_vec()))
}
(Self::MLKEM1024, KEMPublicKey::MLKEM1024(pk)) => {
let (ss, ct) = MLKEM1024::encaps(pk)?;
Ok((ss, ct.to_vec()))
}
_ => Err(KEMError::GenericError(
"KEM public key does not match the selected KEMFactory algorithm",
)),
}
}

/// Encapsulate using a caller-provided RNG (pass-through to [`KEMEncapsulator::encaps_rng`]).
pub fn encaps_rng(
&self,
pk: &KEMPublicKey,
rng: &mut dyn RNG,
) -> Result<(KeyMaterial<MLKEM_SS_LEN>, Vec<u8>), KEMError> {
match (self, pk) {
(Self::MLKEM512, KEMPublicKey::MLKEM512(pk)) => {
let (ss, ct) = MLKEM512::encaps_rng(pk, rng)?;
Ok((ss, ct.to_vec()))
}
(Self::MLKEM768, KEMPublicKey::MLKEM768(pk)) => {
let (ss, ct) = MLKEM768::encaps_rng(pk, rng)?;
Ok((ss, ct.to_vec()))
}
(Self::MLKEM1024, KEMPublicKey::MLKEM1024(pk)) => {
let (ss, ct) = MLKEM1024::encaps_rng(pk, rng)?;
Ok((ss, ct.to_vec()))
}
_ => Err(KEMError::GenericError(
"KEM public key does not match the selected KEMFactory algorithm",
)),
}
}

/// Decapsulate a ciphertext (pass-through to [`KEMDecapsulator::decaps`]).
pub fn decaps(
&self,
sk: &KEMPrivateKey,
ct: &[u8],
) -> Result<KeyMaterial<MLKEM_SS_LEN>, KEMError> {
match (self, sk) {
(Self::MLKEM512, KEMPrivateKey::MLKEM512(sk)) => MLKEM512::decaps(sk, ct),
(Self::MLKEM768, KEMPrivateKey::MLKEM768(sk)) => MLKEM768::decaps(sk, ct),
(Self::MLKEM1024, KEMPrivateKey::MLKEM1024(sk)) => MLKEM1024::decaps(sk, ct),
_ => Err(KEMError::GenericError(
"KEM private key does not match the selected KEMFactory algorithm",
)),
}
}
}

fn kem_err(e: KEMError) -> FactoryError {
FactoryError::UnsupportedAlgorithm(format!("KEM key decode failed: {e:?}"))
}


2 changes: 2 additions & 0 deletions crypto/factory/src/lib.rs
Original file line numberDiff line numberDiff line change
Expand Up@@ -35,8 +35,10 @@ use bouncycastle_core::errors::MACError;

pub mod hash_factory;
pub mod kdf_factory;
pub mod kem_factory;
pub mod mac_factory;
pub mod rng_factory;
pub mod signature_factory;
pub mod xof_factory;

/*** String constants ***/
Expand Down
Loading
Loading
, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Remove or un-stick sticky/fixed headers that block content\n(function() {\n function unstick() {\n document.querySelectorAll('header, nav, [role=\"banner\"], .header, .navbar, .sticky, .fixed-top, [style*=\"position: fixed\"], [style*=\"position:sticky\"]').forEach(function(el) {\n if (el.style.position === 'fixed' || el.style.position === 'sticky' || \n getComputedStyle(el).position === 'fixed' || getComputedStyle(el).position === 'sticky') {\n el.style.position = 'static';\n el.style.top = 'auto';\n el.style.zIndex = 'auto';\n }\n });\n }\n \n unstick();\n \n var observer = new MutationObserver(unstick);\n observer.observe(document.body, { childList: true, subtree: true, attributes: true, attributeFilter: ['style', 'class'] });\n})();", "Kill Sticky Headers"); } } catch(__e) { console.warn('[Userscript:Kill Sticky Headers]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + '
Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions crypto/factory/Cargo.toml
Original file line numberDiff line numberDiff line change
Expand Up@@ -7,6 +7,8 @@ edition.workspace = true
bouncycastle-core.workspace = true
bouncycastle-hkdf.workspace = true
bouncycastle-hmac.workspace = true
bouncycastle-mldsa.workspace = true
bouncycastle-mlkem.workspace = true
bouncycastle-sha2.workspace = true
bouncycastle-sha3.workspace = true
bouncycastle-rng.workspace = true
Expand Down
328 changes: 328 additions & 0 deletions crypto/factory/src/kem_factory.rs
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,328 @@
//! KEM factory for creating instances of algorithms that implement KEM traits.
//!
//! As with all Factory objects, this constructs algorithms from strings and defaults.
//! Supported objects are encapsulated in enums that pass operations through to the underlying types.
//!
//! # Design note on traits
//!
//! The core [`KEMEncapsulator`] and [`KEMDecapsulator`] traits are parameterized by const-generic
//! key and ciphertext sizes. A single enum that wraps ML-KEM-512/768/1024 cannot implement those
//! traits with one fixed set of const parameters. This module therefore wraps keys in enums and
//! exposes inherent methods with the same shape as the core traits.
//!
//! Example usage:
//! ```
//! use bouncycastle_factory::AlgorithmFactory;
//! use bouncycastle_factory::kem_factory::KEMFactory;
//! use bouncycastle_mlkem::ML_KEM_768_NAME;
//!
//! let factory = KEMFactory::new(ML_KEM_768_NAME).unwrap();
//! assert_eq!(factory.algorithm_name(), ML_KEM_768_NAME);
//! // keygen/encaps/decaps pass through to the underlying ML-KEM types;
//! // see the crate tests for full round-trip examples.
//! ```

use crate::{AlgorithmFactory, DEFAULT, DEFAULT_128_BIT, DEFAULT_256_BIT, FactoryError};
use bouncycastle_core::errors::KEMError;
use bouncycastle_core::key_material::KeyMaterial;
use bouncycastle_core::traits::{
KEMDecapsulator as _, KEMEncapsulator as _, KEMPrivateKey as KEMPrivateKeyTrait,
KEMPublicKey as KEMPublicKeyTrait, RNG,
};
use bouncycastle_mlkem as mlkem;
use bouncycastle_mlkem::{
MLKEM512, MLKEM768, MLKEM1024, MLKEMTrait, MLKEM_SS_LEN, ML_KEM_512_NAME, ML_KEM_768_NAME,
ML_KEM_1024_NAME,
};

/*** Defaults ***/
/// Default KEM algorithm name (192-bit class / ML-KEM-768).
pub const DEFAULT_KEM_NAME: &str = ML_KEM_768_NAME;
/// Default KEM algorithm at the 128-bit security level.
pub const DEFAULT_128BIT_KEM_NAME: &str = ML_KEM_512_NAME;
/// Default KEM algorithm at the 256-bit security level.
pub const DEFAULT_256BIT_KEM_NAME: &str = ML_KEM_1024_NAME;

/// Wrapper for all supported KEM public (encapsulation) keys.
pub enum KEMPublicKey {
/// ML-KEM-512 public key.
MLKEM512(mlkem::MLKEM512PublicKey),
/// ML-KEM-768 public key.
MLKEM768(mlkem::MLKEM768PublicKey),
/// ML-KEM-1024 public key.
MLKEM1024(mlkem::MLKEM1024PublicKey),
}

impl KEMPublicKey {
/// Encode the public key to its standard byte encoding.
pub fn encode(&self) -> Vec<u8> {
match self {
Self::MLKEM512(pk) => pk.encode().to_vec(),
Self::MLKEM768(pk) => pk.encode().to_vec(),
Self::MLKEM1024(pk) => pk.encode().to_vec(),
}
}

/// Decode a public key from bytes for the named algorithm.
pub fn from_bytes(alg_name: &str, bytes: &[u8]) -> Result<Self, FactoryError> {
match alg_name {
ML_KEM_512_NAME => Ok(Self::MLKEM512(
mlkem::MLKEM512PublicKey::from_bytes(bytes).map_err(kem_err)?,
)),
ML_KEM_768_NAME => Ok(Self::MLKEM768(
mlkem::MLKEM768PublicKey::from_bytes(bytes).map_err(kem_err)?,
)),
ML_KEM_1024_NAME => Ok(Self::MLKEM1024(
mlkem::MLKEM1024PublicKey::from_bytes(bytes).map_err(kem_err)?,
)),
_ => Err(FactoryError::UnsupportedAlgorithm(format!(
"The algorithm: \"{alg_name}\" is not a known KEM"
))),
}
}

/// Algorithm name for this key.
pub fn algorithm_name(&self) -> &'static str {
match self {
Self::MLKEM512(_) => ML_KEM_512_NAME,
Self::MLKEM768(_) => ML_KEM_768_NAME,
Self::MLKEM1024(_) => ML_KEM_1024_NAME,
}
}
}

/// Wrapper for all supported KEM private (decapsulation) keys.
pub enum KEMPrivateKey {
/// ML-KEM-512 private key.
MLKEM512(mlkem::MLKEM512PrivateKey),
/// ML-KEM-768 private key.
MLKEM768(mlkem::MLKEM768PrivateKey),
/// ML-KEM-1024 private key.
MLKEM1024(mlkem::MLKEM1024PrivateKey),
}

impl KEMPrivateKey {
/// Encode the private key to its standard byte encoding.
pub fn encode(&self) -> Vec<u8> {
match self {
Self::MLKEM512(sk) => sk.encode().to_vec(),
Self::MLKEM768(sk) => sk.encode().to_vec(),
Self::MLKEM1024(sk) => sk.encode().to_vec(),
}
}

/// Decode a private key from bytes for the named algorithm.
pub fn from_bytes(alg_name: &str, bytes: &[u8]) -> Result<Self, FactoryError> {
match alg_name {
ML_KEM_512_NAME => Ok(Self::MLKEM512(
mlkem::MLKEM512PrivateKey::from_bytes(bytes).map_err(kem_err)?,
)),
ML_KEM_768_NAME => Ok(Self::MLKEM768(
mlkem::MLKEM768PrivateKey::from_bytes(bytes).map_err(kem_err)?,
)),
ML_KEM_1024_NAME => Ok(Self::MLKEM1024(
mlkem::MLKEM1024PrivateKey::from_bytes(bytes).map_err(kem_err)?,
)),
_ => Err(FactoryError::UnsupportedAlgorithm(format!(
"The algorithm: \"{alg_name}\" is not a known KEM"
))),
}
}

/// Algorithm name for this key.
pub fn algorithm_name(&self) -> &'static str {
match self {
Self::MLKEM512(_) => ML_KEM_512_NAME,
Self::MLKEM768(_) => ML_KEM_768_NAME,
Self::MLKEM1024(_) => ML_KEM_1024_NAME,
}
}
}

/// Factory / algorithm selector for all supported KEM algorithms.
///
/// Constructed by name via [`AlgorithmFactory::new`] or the default helpers.
/// Operations pass through to the underlying ML-KEM parameter sets.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum KEMFactory {
/// ML-KEM-512 (NIST security category 1 / ~128-bit class).
MLKEM512,
/// ML-KEM-768 (NIST security category 3 / ~192-bit class).
MLKEM768,
/// ML-KEM-1024 (NIST security category 5 / ~256-bit class).
MLKEM1024,
}

impl Default for KEMFactory {
fn default() -> Self {
Self::MLKEM768
}
}

impl AlgorithmFactory for KEMFactory {
fn default_128_bit() -> Self {
Self::MLKEM512
}

fn default_256_bit() -> Self {
Self::MLKEM1024
}

fn new(alg_name: &str) -> Result<Self, FactoryError> {
match alg_name {
DEFAULT => Ok(Self::default()),
DEFAULT_128_BIT => Ok(Self::default_128_bit()),
DEFAULT_256_BIT => Ok(Self::default_256_bit()),
ML_KEM_512_NAME => Ok(Self::MLKEM512),
ML_KEM_768_NAME => Ok(Self::MLKEM768),
ML_KEM_1024_NAME => Ok(Self::MLKEM1024),
_ => Err(FactoryError::UnsupportedAlgorithm(format!(
"The algorithm: \"{alg_name}\" is not a known KEM"
))),
}
}
}

impl KEMFactory {
/// Algorithm name string for this factory selection.
pub fn algorithm_name(&self) -> &'static str {
match self {
Self::MLKEM512 => ML_KEM_512_NAME,
Self::MLKEM768 => ML_KEM_768_NAME,
Self::MLKEM1024 => ML_KEM_1024_NAME,
}
}

/// Generate a fresh key pair using the library default OS-backed RNG.
pub fn keygen(&self) -> Result<(KEMPublicKey, KEMPrivateKey), KEMError> {
match self {
Self::MLKEM512 => {
let (pk, sk) = MLKEM512::keygen()?;
Ok((KEMPublicKey::MLKEM512(pk), KEMPrivateKey::MLKEM512(sk)))
}
Self::MLKEM768 => {
let (pk, sk) = MLKEM768::keygen()?;
Ok((KEMPublicKey::MLKEM768(pk), KEMPrivateKey::MLKEM768(sk)))
}
Self::MLKEM1024 => {
let (pk, sk) = MLKEM1024::keygen()?;
Ok((KEMPublicKey::MLKEM1024(pk), KEMPrivateKey::MLKEM1024(sk)))
}
}
}

/// Generate a key pair using the provided RNG.
pub fn keygen_from_rng(
&self,
rng: &mut dyn RNG,
) -> Result<(KEMPublicKey, KEMPrivateKey), KEMError> {
match self {
Self::MLKEM512 => {
let (pk, sk) = MLKEM512::keygen_from_rng(rng)?;
Ok((KEMPublicKey::MLKEM512(pk), KEMPrivateKey::MLKEM512(sk)))
}
Self::MLKEM768 => {
let (pk, sk) = MLKEM768::keygen_from_rng(rng)?;
Ok((KEMPublicKey::MLKEM768(pk), KEMPrivateKey::MLKEM768(sk)))
}
Self::MLKEM1024 => {
let (pk, sk) = MLKEM1024::keygen_from_rng(rng)?;
Ok((KEMPublicKey::MLKEM1024(pk), KEMPrivateKey::MLKEM1024(sk)))
}
}
}

/// Generate a key pair from a 64-byte seed.
pub fn keygen_from_seed(
&self,
seed: &KeyMaterial<64>,
) -> Result<(KEMPublicKey, KEMPrivateKey), KEMError> {
match self {
Self::MLKEM512 => {
let (pk, sk) = MLKEM512::keygen_from_seed(seed)?;
Ok((KEMPublicKey::MLKEM512(pk), KEMPrivateKey::MLKEM512(sk)))
}
Self::MLKEM768 => {
let (pk, sk) = MLKEM768::keygen_from_seed(seed)?;
Ok((KEMPublicKey::MLKEM768(pk), KEMPrivateKey::MLKEM768(sk)))
}
Self::MLKEM1024 => {
let (pk, sk) = MLKEM1024::keygen_from_seed(seed)?;
Ok((KEMPublicKey::MLKEM1024(pk), KEMPrivateKey::MLKEM1024(sk)))
}
}
}

/// Encapsulate to the given public key (pass-through to [`KEMEncapsulator::encaps`]).
///
/// Returns `(shared_secret, ciphertext)`.
pub fn encaps(
&self,
pk: &KEMPublicKey,
) -> Result<(KeyMaterial<MLKEM_SS_LEN>, Vec<u8>), KEMError> {
match (self, pk) {
(Self::MLKEM512, KEMPublicKey::MLKEM512(pk)) => {
let (ss, ct) = MLKEM512::encaps(pk)?;
Ok((ss, ct.to_vec()))
}
(Self::MLKEM768, KEMPublicKey::MLKEM768(pk)) => {
let (ss, ct) = MLKEM768::encaps(pk)?;
Ok((ss, ct.to_vec()))
}
(Self::MLKEM1024, KEMPublicKey::MLKEM1024(pk)) => {
let (ss, ct) = MLKEM1024::encaps(pk)?;
Ok((ss, ct.to_vec()))
}
_ => Err(KEMError::GenericError(
"KEM public key does not match the selected KEMFactory algorithm",
)),
}
}

/// Encapsulate using a caller-provided RNG (pass-through to [`KEMEncapsulator::encaps_rng`]).
pub fn encaps_rng(
&self,
pk: &KEMPublicKey,
rng: &mut dyn RNG,
) -> Result<(KeyMaterial<MLKEM_SS_LEN>, Vec<u8>), KEMError> {
match (self, pk) {
(Self::MLKEM512, KEMPublicKey::MLKEM512(pk)) => {
let (ss, ct) = MLKEM512::encaps_rng(pk, rng)?;
Ok((ss, ct.to_vec()))
}
(Self::MLKEM768, KEMPublicKey::MLKEM768(pk)) => {
let (ss, ct) = MLKEM768::encaps_rng(pk, rng)?;
Ok((ss, ct.to_vec()))
}
(Self::MLKEM1024, KEMPublicKey::MLKEM1024(pk)) => {
let (ss, ct) = MLKEM1024::encaps_rng(pk, rng)?;
Ok((ss, ct.to_vec()))
}
_ => Err(KEMError::GenericError(
"KEM public key does not match the selected KEMFactory algorithm",
)),
}
}

/// Decapsulate a ciphertext (pass-through to [`KEMDecapsulator::decaps`]).
pub fn decaps(
&self,
sk: &KEMPrivateKey,
ct: &[u8],
) -> Result<KeyMaterial<MLKEM_SS_LEN>, KEMError> {
match (self, sk) {
(Self::MLKEM512, KEMPrivateKey::MLKEM512(sk)) => MLKEM512::decaps(sk, ct),
(Self::MLKEM768, KEMPrivateKey::MLKEM768(sk)) => MLKEM768::decaps(sk, ct),
(Self::MLKEM1024, KEMPrivateKey::MLKEM1024(sk)) => MLKEM1024::decaps(sk, ct),
_ => Err(KEMError::GenericError(
"KEM private key does not match the selected KEMFactory algorithm",
)),
}
}
}

fn kem_err(e: KEMError) -> FactoryError {
FactoryError::UnsupportedAlgorithm(format!("KEM key decode failed: {e:?}"))
}


2 changes: 2 additions & 0 deletions crypto/factory/src/lib.rs
Original file line numberDiff line numberDiff line change
Expand Up@@ -35,8 +35,10 @@ use bouncycastle_core::errors::MACError;

pub mod hash_factory;
pub mod kdf_factory;
pub mod kem_factory;
pub mod mac_factory;
pub mod rng_factory;
pub mod signature_factory;
pub mod xof_factory;

/*** String constants ***/
Expand Down
Loading
Loading
, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Universal Dark Mode - works on any site\n(function() {\n var enabled = true;\n \n function applyDarkMode() {\n if (!enabled) return;\n \n // Create style element if it doesn't exist\n var style = document.getElementById('universal-dark-mode-style');\n if (!style) {\n style = document.createElement('style');\n style.id = 'universal-dark-mode-style';\n document.head.appendChild(style);\n }\n \n // Dark mode CSS - inverts colors but preserves images/video\n style.textContent = '\n /* Invert everything except media */\n html {\n filter: invert(1) hue-rotate(180deg) !important;\n background: #1a1a2e !important;\n }\n \n /* Restore images, videos, iframes, canvas */\n img, video, iframe, canvas, svg, picture, [style*=\"background-image\"] {\n filter: invert(1) hue-rotate(180deg) !important;\n }\n \n /* Preserve specific elements that should not be inverted */\n .no-dark-mode, .no-dark-mode *,\n [data-theme=\"light\"], [data-theme=\"light\"],\n .ace_editor, .ace_editor *,\n .CodeMirror, .CodeMirror *,\n .monaco-editor, .monaco-editor *,\n .markdown-body pre, .markdown-body pre *,\n .highlight, .highlight *,\n pre code, pre code * {\n filter: none !important;\n }\n \n /* Fix common UI elements */\n .modal, .popup, .dropdown-menu, .tooltip, .popover {\n filter: invert(1) hue-rotate(180deg) !important;\n background: #2d2d44 !important;\n border-color: #444 !important;\n }\n \n /* Scrollbars */\n ::-webkit-scrollbar { background: #1a1a2e !important; }\n ::-webkit-scrollbar-thumb { background: #444 !important; }\n ::-webkit-scrollbar-thumb:hover { background: #555 !important; }\n \n /* Selection */\n ::selection { background: #4ecdc4 !important; color: #1a1a2e !important; }\n ::-moz-selection { background: #4ecdc4 !important; color: #1a1a2e !important; }\n ';\n }\n \n function removeDarkMode() {\n var style = document.getElementById('universal-dark-mode-style');\n if (style) style.remove();\n }\n \n // Toggle with Alt+Shift+D\n document.addEventListener('keydown', function(e) {\n if (e.altKey && e.shiftKey && e.key === 'D') {\n e.preventDefault();\n enabled = !enabled;\n if (enabled) {\n applyDarkMode();\n console.log('[Universal Dark Mode] Enabled');\n } else {\n removeDarkMode();\n console.log('[Universal Dark Mode] Disabled');\n }\n }\n });\n \n // Apply on load\n applyDarkMode();\n \n // Re-apply on dynamic content\n var observer = new MutationObserver(function(mutations) {\n if (enabled && !document.getElementById('universal-dark-mode-style')) {\n applyDarkMode();\n }\n });\n observer.observe(document.head, { childList: true });\n \n console.log('[Universal Dark Mode] Loaded - Press Alt+Shift+D to toggle');\n})();", "Universal Dark Mode"); } } catch(__e) { console.warn('[Userscript:Universal Dark Mode]', __e); } })(); })();
Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions crypto/factory/Cargo.toml
Original file line numberDiff line numberDiff line change
Expand Up@@ -7,6 +7,8 @@ edition.workspace = true
bouncycastle-core.workspace = true
bouncycastle-hkdf.workspace = true
bouncycastle-hmac.workspace = true
bouncycastle-mldsa.workspace = true
bouncycastle-mlkem.workspace = true
bouncycastle-sha2.workspace = true
bouncycastle-sha3.workspace = true
bouncycastle-rng.workspace = true
Expand Down
328 changes: 328 additions & 0 deletions crypto/factory/src/kem_factory.rs
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,328 @@
//! KEM factory for creating instances of algorithms that implement KEM traits.
//!
//! As with all Factory objects, this constructs algorithms from strings and defaults.
//! Supported objects are encapsulated in enums that pass operations through to the underlying types.
//!
//! # Design note on traits
//!
//! The core [`KEMEncapsulator`] and [`KEMDecapsulator`] traits are parameterized by const-generic
//! key and ciphertext sizes. A single enum that wraps ML-KEM-512/768/1024 cannot implement those
//! traits with one fixed set of const parameters. This module therefore wraps keys in enums and
//! exposes inherent methods with the same shape as the core traits.
//!
//! Example usage:
//! ```
//! use bouncycastle_factory::AlgorithmFactory;
//! use bouncycastle_factory::kem_factory::KEMFactory;
//! use bouncycastle_mlkem::ML_KEM_768_NAME;
//!
//! let factory = KEMFactory::new(ML_KEM_768_NAME).unwrap();
//! assert_eq!(factory.algorithm_name(), ML_KEM_768_NAME);
//! // keygen/encaps/decaps pass through to the underlying ML-KEM types;
//! // see the crate tests for full round-trip examples.
//! ```

use crate::{AlgorithmFactory, DEFAULT, DEFAULT_128_BIT, DEFAULT_256_BIT, FactoryError};
use bouncycastle_core::errors::KEMError;
use bouncycastle_core::key_material::KeyMaterial;
use bouncycastle_core::traits::{
KEMDecapsulator as _, KEMEncapsulator as _, KEMPrivateKey as KEMPrivateKeyTrait,
KEMPublicKey as KEMPublicKeyTrait, RNG,
};
use bouncycastle_mlkem as mlkem;
use bouncycastle_mlkem::{
MLKEM512, MLKEM768, MLKEM1024, MLKEMTrait, MLKEM_SS_LEN, ML_KEM_512_NAME, ML_KEM_768_NAME,
ML_KEM_1024_NAME,
};

/*** Defaults ***/
/// Default KEM algorithm name (192-bit class / ML-KEM-768).
pub const DEFAULT_KEM_NAME: &str = ML_KEM_768_NAME;
/// Default KEM algorithm at the 128-bit security level.
pub const DEFAULT_128BIT_KEM_NAME: &str = ML_KEM_512_NAME;
/// Default KEM algorithm at the 256-bit security level.
pub const DEFAULT_256BIT_KEM_NAME: &str = ML_KEM_1024_NAME;

/// Wrapper for all supported KEM public (encapsulation) keys.
pub enum KEMPublicKey {
/// ML-KEM-512 public key.
MLKEM512(mlkem::MLKEM512PublicKey),
/// ML-KEM-768 public key.
MLKEM768(mlkem::MLKEM768PublicKey),
/// ML-KEM-1024 public key.
MLKEM1024(mlkem::MLKEM1024PublicKey),
}

impl KEMPublicKey {
/// Encode the public key to its standard byte encoding.
pub fn encode(&self) -> Vec<u8> {
match self {
Self::MLKEM512(pk) => pk.encode().to_vec(),
Self::MLKEM768(pk) => pk.encode().to_vec(),
Self::MLKEM1024(pk) => pk.encode().to_vec(),
}
}

/// Decode a public key from bytes for the named algorithm.
pub fn from_bytes(alg_name: &str, bytes: &[u8]) -> Result<Self, FactoryError> {
match alg_name {
ML_KEM_512_NAME => Ok(Self::MLKEM512(
mlkem::MLKEM512PublicKey::from_bytes(bytes).map_err(kem_err)?,
)),
ML_KEM_768_NAME => Ok(Self::MLKEM768(
mlkem::MLKEM768PublicKey::from_bytes(bytes).map_err(kem_err)?,
)),
ML_KEM_1024_NAME => Ok(Self::MLKEM1024(
mlkem::MLKEM1024PublicKey::from_bytes(bytes).map_err(kem_err)?,
)),
_ => Err(FactoryError::UnsupportedAlgorithm(format!(
"The algorithm: \"{alg_name}\" is not a known KEM"
))),
}
}

/// Algorithm name for this key.
pub fn algorithm_name(&self) -> &'static str {
match self {
Self::MLKEM512(_) => ML_KEM_512_NAME,
Self::MLKEM768(_) => ML_KEM_768_NAME,
Self::MLKEM1024(_) => ML_KEM_1024_NAME,
}
}
}

/// Wrapper for all supported KEM private (decapsulation) keys.
pub enum KEMPrivateKey {
/// ML-KEM-512 private key.
MLKEM512(mlkem::MLKEM512PrivateKey),
/// ML-KEM-768 private key.
MLKEM768(mlkem::MLKEM768PrivateKey),
/// ML-KEM-1024 private key.
MLKEM1024(mlkem::MLKEM1024PrivateKey),
}

impl KEMPrivateKey {
/// Encode the private key to its standard byte encoding.
pub fn encode(&self) -> Vec<u8> {
match self {
Self::MLKEM512(sk) => sk.encode().to_vec(),
Self::MLKEM768(sk) => sk.encode().to_vec(),
Self::MLKEM1024(sk) => sk.encode().to_vec(),
}
}

/// Decode a private key from bytes for the named algorithm.
pub fn from_bytes(alg_name: &str, bytes: &[u8]) -> Result<Self, FactoryError> {
match alg_name {
ML_KEM_512_NAME => Ok(Self::MLKEM512(
mlkem::MLKEM512PrivateKey::from_bytes(bytes).map_err(kem_err)?,
)),
ML_KEM_768_NAME => Ok(Self::MLKEM768(
mlkem::MLKEM768PrivateKey::from_bytes(bytes).map_err(kem_err)?,
)),
ML_KEM_1024_NAME => Ok(Self::MLKEM1024(
mlkem::MLKEM1024PrivateKey::from_bytes(bytes).map_err(kem_err)?,
)),
_ => Err(FactoryError::UnsupportedAlgorithm(format!(
"The algorithm: \"{alg_name}\" is not a known KEM"
))),
}
}

/// Algorithm name for this key.
pub fn algorithm_name(&self) -> &'static str {
match self {
Self::MLKEM512(_) => ML_KEM_512_NAME,
Self::MLKEM768(_) => ML_KEM_768_NAME,
Self::MLKEM1024(_) => ML_KEM_1024_NAME,
}
}
}

/// Factory / algorithm selector for all supported KEM algorithms.
///
/// Constructed by name via [`AlgorithmFactory::new`] or the default helpers.
/// Operations pass through to the underlying ML-KEM parameter sets.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum KEMFactory {
/// ML-KEM-512 (NIST security category 1 / ~128-bit class).
MLKEM512,
/// ML-KEM-768 (NIST security category 3 / ~192-bit class).
MLKEM768,
/// ML-KEM-1024 (NIST security category 5 / ~256-bit class).
MLKEM1024,
}

impl Default for KEMFactory {
fn default() -> Self {
Self::MLKEM768
}
}

impl AlgorithmFactory for KEMFactory {
fn default_128_bit() -> Self {
Self::MLKEM512
}

fn default_256_bit() -> Self {
Self::MLKEM1024
}

fn new(alg_name: &str) -> Result<Self, FactoryError> {
match alg_name {
DEFAULT => Ok(Self::default()),
DEFAULT_128_BIT => Ok(Self::default_128_bit()),
DEFAULT_256_BIT => Ok(Self::default_256_bit()),
ML_KEM_512_NAME => Ok(Self::MLKEM512),
ML_KEM_768_NAME => Ok(Self::MLKEM768),
ML_KEM_1024_NAME => Ok(Self::MLKEM1024),
_ => Err(FactoryError::UnsupportedAlgorithm(format!(
"The algorithm: \"{alg_name}\" is not a known KEM"
))),
}
}
}

impl KEMFactory {
/// Algorithm name string for this factory selection.
pub fn algorithm_name(&self) -> &'static str {
match self {
Self::MLKEM512 => ML_KEM_512_NAME,
Self::MLKEM768 => ML_KEM_768_NAME,
Self::MLKEM1024 => ML_KEM_1024_NAME,
}
}

/// Generate a fresh key pair using the library default OS-backed RNG.
pub fn keygen(&self) -> Result<(KEMPublicKey, KEMPrivateKey), KEMError> {
match self {
Self::MLKEM512 => {
let (pk, sk) = MLKEM512::keygen()?;
Ok((KEMPublicKey::MLKEM512(pk), KEMPrivateKey::MLKEM512(sk)))
}
Self::MLKEM768 => {
let (pk, sk) = MLKEM768::keygen()?;
Ok((KEMPublicKey::MLKEM768(pk), KEMPrivateKey::MLKEM768(sk)))
}
Self::MLKEM1024 => {
let (pk, sk) = MLKEM1024::keygen()?;
Ok((KEMPublicKey::MLKEM1024(pk), KEMPrivateKey::MLKEM1024(sk)))
}
}
}

/// Generate a key pair using the provided RNG.
pub fn keygen_from_rng(
&self,
rng: &mut dyn RNG,
) -> Result<(KEMPublicKey, KEMPrivateKey), KEMError> {
match self {
Self::MLKEM512 => {
let (pk, sk) = MLKEM512::keygen_from_rng(rng)?;
Ok((KEMPublicKey::MLKEM512(pk), KEMPrivateKey::MLKEM512(sk)))
}
Self::MLKEM768 => {
let (pk, sk) = MLKEM768::keygen_from_rng(rng)?;
Ok((KEMPublicKey::MLKEM768(pk), KEMPrivateKey::MLKEM768(sk)))
}
Self::MLKEM1024 => {
let (pk, sk) = MLKEM1024::keygen_from_rng(rng)?;
Ok((KEMPublicKey::MLKEM1024(pk), KEMPrivateKey::MLKEM1024(sk)))
}
}
}

/// Generate a key pair from a 64-byte seed.
pub fn keygen_from_seed(
&self,
seed: &KeyMaterial<64>,
) -> Result<(KEMPublicKey, KEMPrivateKey), KEMError> {
match self {
Self::MLKEM512 => {
let (pk, sk) = MLKEM512::keygen_from_seed(seed)?;
Ok((KEMPublicKey::MLKEM512(pk), KEMPrivateKey::MLKEM512(sk)))
}
Self::MLKEM768 => {
let (pk, sk) = MLKEM768::keygen_from_seed(seed)?;
Ok((KEMPublicKey::MLKEM768(pk), KEMPrivateKey::MLKEM768(sk)))
}
Self::MLKEM1024 => {
let (pk, sk) = MLKEM1024::keygen_from_seed(seed)?;
Ok((KEMPublicKey::MLKEM1024(pk), KEMPrivateKey::MLKEM1024(sk)))
}
}
}

/// Encapsulate to the given public key (pass-through to [`KEMEncapsulator::encaps`]).
///
/// Returns `(shared_secret, ciphertext)`.
pub fn encaps(
&self,
pk: &KEMPublicKey,
) -> Result<(KeyMaterial<MLKEM_SS_LEN>, Vec<u8>), KEMError> {
match (self, pk) {
(Self::MLKEM512, KEMPublicKey::MLKEM512(pk)) => {
let (ss, ct) = MLKEM512::encaps(pk)?;
Ok((ss, ct.to_vec()))
}
(Self::MLKEM768, KEMPublicKey::MLKEM768(pk)) => {
let (ss, ct) = MLKEM768::encaps(pk)?;
Ok((ss, ct.to_vec()))
}
(Self::MLKEM1024, KEMPublicKey::MLKEM1024(pk)) => {
let (ss, ct) = MLKEM1024::encaps(pk)?;
Ok((ss, ct.to_vec()))
}
_ => Err(KEMError::GenericError(
"KEM public key does not match the selected KEMFactory algorithm",
)),
}
}

/// Encapsulate using a caller-provided RNG (pass-through to [`KEMEncapsulator::encaps_rng`]).
pub fn encaps_rng(
&self,
pk: &KEMPublicKey,
rng: &mut dyn RNG,
) -> Result<(KeyMaterial<MLKEM_SS_LEN>, Vec<u8>), KEMError> {
match (self, pk) {
(Self::MLKEM512, KEMPublicKey::MLKEM512(pk)) => {
let (ss, ct) = MLKEM512::encaps_rng(pk, rng)?;
Ok((ss, ct.to_vec()))
}
(Self::MLKEM768, KEMPublicKey::MLKEM768(pk)) => {
let (ss, ct) = MLKEM768::encaps_rng(pk, rng)?;
Ok((ss, ct.to_vec()))
}
(Self::MLKEM1024, KEMPublicKey::MLKEM1024(pk)) => {
let (ss, ct) = MLKEM1024::encaps_rng(pk, rng)?;
Ok((ss, ct.to_vec()))
}
_ => Err(KEMError::GenericError(
"KEM public key does not match the selected KEMFactory algorithm",
)),
}
}

/// Decapsulate a ciphertext (pass-through to [`KEMDecapsulator::decaps`]).
pub fn decaps(
&self,
sk: &KEMPrivateKey,
ct: &[u8],
) -> Result<KeyMaterial<MLKEM_SS_LEN>, KEMError> {
match (self, sk) {
(Self::MLKEM512, KEMPrivateKey::MLKEM512(sk)) => MLKEM512::decaps(sk, ct),
(Self::MLKEM768, KEMPrivateKey::MLKEM768(sk)) => MLKEM768::decaps(sk, ct),
(Self::MLKEM1024, KEMPrivateKey::MLKEM1024(sk)) => MLKEM1024::decaps(sk, ct),
_ => Err(KEMError::GenericError(
"KEM private key does not match the selected KEMFactory algorithm",
)),
}
}
}

fn kem_err(e: KEMError) -> FactoryError {
FactoryError::UnsupportedAlgorithm(format!("KEM key decode failed: {e:?}"))
}


2 changes: 2 additions & 0 deletions crypto/factory/src/lib.rs
Original file line numberDiff line numberDiff line change
Expand Up@@ -35,8 +35,10 @@ use bouncycastle_core::errors::MACError;

pub mod hash_factory;
pub mod kdf_factory;
pub mod kem_factory;
pub mod mac_factory;
pub mod rng_factory;
pub mod signature_factory;
pub mod xof_factory;

/*** String constants ***/
Expand Down
Loading
Loading