Skip to content

Commit

Permalink
ml-dsa: protect keypair components
Browse files Browse the repository at this point in the history
This ensure the keypair can only be constructed from a seed.
  • Loading branch information
baloo committed Jan 24, 2025
1 parent c374e3b commit 6af3701
Show file tree
Hide file tree
Showing 3 changed files with 16 additions and 8 deletions.
17 changes: 12 additions & 5 deletions ml-dsa/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -18,15 +18,15 @@
//!
//! ```
//! use ml_dsa::{MlDsa65, KeyGen};
//! use signature::{Signer, Verifier};
//! use signature::{Keypair, Signer, Verifier};
//!
//! let mut rng = rand::thread_rng();
//! let kp = MlDsa65::key_gen(&mut rng);
//!
//! let msg = b"Hello world";
//! let sig = kp.signing_key.sign(msg);
//! let sig = kp.signing_key().sign(msg);
//!
//! assert!(kp.verifying_key.verify(msg, &sig).is_ok());
//! assert!(kp.verifying_key().verify(msg, &sig).is_ok());
//! ```
mod algebra;
Expand Down Expand Up @@ -178,10 +178,17 @@ fn message_representative(tr: &[u8], Mp: &[&[u8]]) -> B64 {
/// An ML-DSA key pair
pub struct KeyPair<P: MlDsaParams> {
/// The signing key of the key pair
pub signing_key: SigningKey<P>,
signing_key: SigningKey<P>,

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

impl<P: MlDsaParams> KeyPair<P> {
/// The signing key of the key pair
pub fn signing_key(&self) -> &SigningKey<P> {
&self.signing_key
}
}

impl<P: MlDsaParams> AsRef<VerifyingKey<P>> for KeyPair<P> {
Expand Down
5 changes: 3 additions & 2 deletions ml-dsa/tests/key-gen.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
use ml_dsa::*;

use hybrid_array::Array;
use signature::Keypair;
use std::{fs::read_to_string, path::PathBuf};

#[test]
Expand Down Expand Up @@ -32,8 +33,8 @@ fn verify<P: MlDsaParams>(tc: &acvp::TestCase) {
let sk_bytes = EncodedSigningKey::<P>::try_from(tc.sk.as_slice()).unwrap();

let kp = P::key_gen_internal(&seed);
let sk = kp.signing_key;
let vk = kp.verifying_key;
let sk = kp.signing_key().clone();
let vk = kp.verifying_key().clone();

// Verify correctness via serialization
assert_eq!(sk.encode(), sk_bytes);
Expand Down
2 changes: 1 addition & 1 deletion ml-dsa/tests/pkcs8.rs
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@ 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!(sk == *kp.signing_key());

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

0 comments on commit 6af3701

Please sign in to comment.