Skip to content

Commit

Permalink
ml-dsa: impl pkcs8::EncodePrivateKey
Browse files Browse the repository at this point in the history
  • Loading branch information
baloo committed Jan 25, 2025
1 parent d0b8684 commit 79ef8f1
Show file tree
Hide file tree
Showing 2 changed files with 28 additions and 3 deletions.
23 changes: 21 additions & 2 deletions ml-dsa/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -71,9 +71,9 @@ use {

#[cfg(all(feature = "alloc", feature = "pkcs8"))]
use pkcs8::{
der::asn1::{BitString, BitStringRef},
der::asn1::{BitString, BitStringRef, OctetStringRef},
spki::{SignatureBitStringEncoding, SubjectPublicKeyInfo},
EncodePublicKey,
EncodePrivateKey, EncodePublicKey,
};

use crate::algebra::{AlgebraExt, Elem, NttMatrix, NttVector, Truncate, Vector};
Expand Down Expand Up @@ -182,6 +182,9 @@ pub struct KeyPair<P: MlDsaParams> {

/// The verifying key of the key pair
verifying_key: VerifyingKey<P>,

/// The seed this signing key was derived from
seed: B32,
}

impl<P: MlDsaParams> KeyPair<P> {
Expand Down Expand Up @@ -241,6 +244,21 @@ where
Signature::<P>::ALGORITHM_IDENTIFIER;
}

#[cfg(all(feature = "alloc", feature = "pkcs8"))]
impl<P> EncodePrivateKey for KeyPair<P>
where
P: MlDsaParams,
P: AssociatedAlgorithmIdentifier<Params = AnyRef<'static>>,
{
fn to_pkcs8_der(&self) -> pkcs8::Result<der::SecretDocument> {
let pkcs8_key = pkcs8::PrivateKeyInfoRef::new(
P::ALGORITHM_IDENTIFIER,
OctetStringRef::new(&self.seed)?,
);
Ok(der::SecretDocument::encode_msg(&pkcs8_key)?)
}
}

/// An ML-DSA signing key
#[derive(Clone, PartialEq)]
pub struct SigningKey<P: MlDsaParams> {
Expand Down Expand Up @@ -800,6 +818,7 @@ where
KeyPair {
signing_key,
verifying_key,
seed: xi.clone(),
}
}
}
Expand Down
8 changes: 7 additions & 1 deletion ml-dsa/tests/pkcs8.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ use ml_dsa::{KeyPair, MlDsa44, MlDsa65, MlDsa87, MlDsaParams, SigningKey, Verify
use pkcs8::{
der::{pem::LineEnding, AnyRef},
spki::AssociatedAlgorithmIdentifier,
DecodePrivateKey, DecodePublicKey, EncodePublicKey,
DecodePrivateKey, DecodePublicKey, EncodePrivateKey, EncodePublicKey,
};
use signature::Keypair;

Expand All @@ -19,6 +19,12 @@ fn private_key_serialization() {
let sk = SigningKey::<P>::from_pkcs8_pem(private_bytes).expect("parse private key");
let kp = KeyPair::<P>::from_pkcs8_pem(private_bytes).expect("parse private key");
assert!(sk == *kp.signing_key());
assert_eq!(
kp.to_pkcs8_pem(LineEnding::LF)
.expect("serialize private seed")
.deref(),
private_bytes
);

let pk = VerifyingKey::<P>::from_public_key_pem(public_bytes).expect("parse public key");
assert_eq!(
Expand Down

0 comments on commit 79ef8f1

Please sign in to comment.