Skip to main content

aws_lc_rs/pqdsa/
key_pair.rs

1// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
2// SPDX-License-Identifier: Apache-2.0 OR ISC
3
4use crate::aws_lc::{
5    EVP_PKEY_CTX_pqdsa_set_params, EVP_PKEY_pqdsa_new_raw_private_key, EVP_PKEY, EVP_PKEY_PQDSA,
6};
7use crate::encoding::{AsDer, AsRawBytes, Pkcs8V1Der, PqdsaPrivateKeyRaw};
8use crate::error::{KeyRejected, Unspecified};
9use crate::evp_pkey::No_EVP_PKEY_CTX_consumer;
10use crate::pkcs8;
11use crate::pkcs8::{Document, Version};
12use crate::pqdsa::signature::{PqdsaSigningAlgorithm, PublicKey};
13use crate::pqdsa::validate_pqdsa_evp_key;
14use crate::ptr::LcPtr;
15use crate::signature::KeyPair;
16use core::fmt::{Debug, Formatter};
17use std::ffi::c_int;
18
19/// A PQDSA (Post-Quantum Digital Signature Algorithm) key pair, used for signing and verification.
20#[allow(clippy::module_name_repetitions)]
21pub struct PqdsaKeyPair {
22    algorithm: &'static PqdsaSigningAlgorithm,
23    evp_pkey: LcPtr<EVP_PKEY>,
24    pubkey: PublicKey,
25}
26
27#[allow(clippy::missing_fields_in_debug)]
28impl Debug for PqdsaKeyPair {
29    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
30        f.debug_struct("PqdsaKeyPair")
31            .field("algorithm", &self.algorithm)
32            .finish()
33    }
34}
35
36impl KeyPair for PqdsaKeyPair {
37    type PublicKey = PublicKey;
38
39    fn public_key(&self) -> &Self::PublicKey {
40        &self.pubkey
41    }
42}
43
44/// A PQDSA private key.
45pub struct PqdsaPrivateKey<'a>(pub(crate) &'a PqdsaKeyPair);
46
47impl AsDer<Pkcs8V1Der<'static>> for PqdsaPrivateKey<'_> {
48    /// Serializes the key to PKCS#8 v1 DER.
49    ///
50    /// See [`PqdsaKeyPair::to_pkcs8`] for the chosen representation of the private key.
51    ///
52    /// # Errors
53    /// Returns `Unspecified` if serialization fails.
54    fn as_der(&self) -> Result<Pkcs8V1Der<'static>, Unspecified> {
55        Ok(Pkcs8V1Der::new(
56            self.0
57                .evp_pkey
58                .as_const()
59                .marshal_rfc5208_private_key(pkcs8::Version::V1)?,
60        ))
61    }
62}
63
64impl AsRawBytes<PqdsaPrivateKeyRaw<'static>> for PqdsaPrivateKey<'_> {
65    /// Serializes the expanded raw private key.
66    ///
67    /// This can be passed back to [`PqdsaKeyPair::from_raw_private_key`].
68    fn as_raw_bytes(&self) -> Result<PqdsaPrivateKeyRaw<'static>, Unspecified> {
69        Ok(PqdsaPrivateKeyRaw::new(
70            self.0.evp_pkey.as_const().marshal_raw_private_key()?,
71        ))
72    }
73}
74
75impl PqdsaKeyPair {
76    /// Generates a new PQDSA key pair for the specified algorithm.
77    ///
78    /// # Errors
79    /// Returns `Unspecified` is the key generation fails.
80    pub fn generate(algorithm: &'static PqdsaSigningAlgorithm) -> Result<Self, Unspecified> {
81        let evp_pkey = evp_key_pqdsa_generate(algorithm.0.id.nid())?;
82        let pubkey = PublicKey::from_private_evp_pkey(&evp_pkey)?;
83        Ok(Self {
84            algorithm,
85            evp_pkey,
86            pubkey,
87        })
88    }
89
90    /// Constructs a key pair from the parsing of PKCS#8.
91    ///
92    /// This accepts either the seed or expanded private key encodings. If both are present in the
93    /// input, they are validated to agree with each other.
94    ///
95    /// # Errors
96    /// Returns `Unspecified` if the key is not valid for the specified signing algorithm.
97    pub fn from_pkcs8(
98        algorithm: &'static PqdsaSigningAlgorithm,
99        pkcs8: &[u8],
100    ) -> Result<Self, KeyRejected> {
101        let evp_pkey = LcPtr::<EVP_PKEY>::parse_rfc5208_private_key(pkcs8, EVP_PKEY_PQDSA)?;
102        validate_pqdsa_evp_key(&evp_pkey, algorithm.0.id)?;
103        let pubkey = PublicKey::from_private_evp_pkey(&evp_pkey)?;
104        Ok(Self {
105            algorithm,
106            evp_pkey,
107            pubkey,
108        })
109    }
110
111    /// Constructs a key pair from raw private key bytes.
112    ///
113    /// This expects the expanded form of the raw private key bytes.
114    ///
115    /// # Errors
116    /// Returns `Unspecified` if the key is not valid for the specified signing algorithm.
117    pub fn from_raw_private_key(
118        algorithm: &'static PqdsaSigningAlgorithm,
119        raw_private_key: &[u8],
120    ) -> Result<Self, KeyRejected> {
121        let evp_pkey = LcPtr::<EVP_PKEY>::parse_raw_private_key(raw_private_key, EVP_PKEY_PQDSA)?;
122        validate_pqdsa_evp_key(&evp_pkey, algorithm.0.id)?;
123        let pubkey = PublicKey::from_private_evp_pkey(&evp_pkey)?;
124        Ok(Self {
125            algorithm,
126            evp_pkey,
127            pubkey,
128        })
129    }
130
131    /// Constructs a key pair deterministically from a 32-byte seed.
132    ///
133    /// Per FIPS 204, the same seed always produces the same key pair. This enables
134    /// reproducible key generation for testing, ACVP validation, and interoperability
135    /// with implementations that store seeds rather than expanded private keys.
136    ///
137    /// `algorithm` is the [`PqdsaSigningAlgorithm`] to be associated with the key pair.
138    ///
139    /// `seed` is the 32-byte seed from which the key pair is deterministically derived.
140    /// All ML-DSA variants (ML-DSA-44, ML-DSA-65, ML-DSA-87) use 32-byte seeds.
141    ///
142    /// # Security Considerations
143    ///
144    /// The seed is the root secret. Compromise of the seed is equivalent to compromise
145    /// of the private key. Callers are responsible for generating seeds from a
146    /// cryptographically secure random source and protecting them accordingly.
147    ///
148    /// The seed should be produced from random entropy such as through [`crate::rand::fill`].
149    /// However, for users requiring FIPS, the seed must be produced from
150    /// [`Self::generate`]. The [`Self::to_pkcs8`] method serializes the private key in seed form.
151    /// AWS-LC keeps the seed in the internal representation when possible, but if [`PqdsaKeyPair`]
152    /// is constructed from the expanded form (via [`Self::from_raw_private_key`]) the seed cannot
153    /// be obtained and [`Self::to_pkcs8`] will fail.
154    ///
155    /// This method expands the seed into the full private key internally. The expanded private key
156    /// can be retrieved via [`Self::private_key`] and serialized via
157    /// [`PqdsaPrivateKey::as_raw_bytes`].
158    ///
159    /// # Errors
160    ///
161    /// Returns `KeyRejected::too_small()` if `seed.len() < 32`.
162    ///
163    /// Returns `KeyRejected::too_large()` if `seed.len() > 32`.
164    ///
165    /// Returns `KeyRejected::unspecified()` if the underlying cryptographic operation fails.
166    pub fn from_seed(
167        algorithm: &'static PqdsaSigningAlgorithm,
168        seed: &[u8],
169    ) -> Result<Self, KeyRejected> {
170        let expected_seed_len = algorithm.0.id.seed_size_bytes();
171        match seed.len().cmp(&expected_seed_len) {
172            core::cmp::Ordering::Less => return Err(KeyRejected::too_small()),
173            core::cmp::Ordering::Greater => return Err(KeyRejected::too_large()),
174            core::cmp::Ordering::Equal => {}
175        }
176        let nid = algorithm.0.id.nid();
177        let evp_pkey = LcPtr::new(unsafe {
178            EVP_PKEY_pqdsa_new_raw_private_key(nid, seed.as_ptr(), seed.len())
179        })
180        .map_err(|()| KeyRejected::unspecified())?;
181        validate_pqdsa_evp_key(&evp_pkey, algorithm.0.id)?;
182        let pubkey =
183            PublicKey::from_private_evp_pkey(&evp_pkey).map_err(|_| KeyRejected::unspecified())?;
184        Ok(Self {
185            algorithm,
186            evp_pkey,
187            pubkey,
188        })
189    }
190
191    /// Serializes the private key to PKCS#8 v1 DER.
192    ///
193    /// This currently serializes the seed. If the seed is not available (for example when this
194    /// [`PqdsaKeyPair`] was constructed from the expanded private key via
195    /// [`Self::from_raw_private_key`]), serialization fails and this currently returns an error. A
196    /// future implementation may encode the expanded form of the key instead.
197    ///
198    /// # Errors
199    /// Returns `Unspecified` if serialization fails.
200    pub fn to_pkcs8(&self) -> Result<Document, Unspecified> {
201        Ok(Document::new(
202            self.evp_pkey
203                .as_const()
204                .marshal_rfc5208_private_key(Version::V1)?,
205        ))
206    }
207
208    /// Uses this key to sign the message provided. The signature is written to the `signature`
209    /// slice provided. It returns the length of the signature on success.
210    ///
211    /// # Errors
212    /// Returns `Unspecified` if signing fails.
213    pub fn sign(&self, msg: &[u8], signature: &mut [u8]) -> Result<usize, Unspecified> {
214        let sig_length = self.algorithm.signature_len();
215        if signature.len() < sig_length {
216            return Err(Unspecified);
217        }
218        let sig_bytes = self.evp_pkey.sign(msg, None, No_EVP_PKEY_CTX_consumer)?;
219        signature[0..sig_length].copy_from_slice(&sig_bytes);
220        Ok(sig_length)
221    }
222
223    /// Returns the signing algorithm associated with this key pair.
224    #[must_use]
225    pub fn algorithm(&self) -> &'static PqdsaSigningAlgorithm {
226        self.algorithm
227    }
228
229    /// Returns the private key associated with this key pair.
230    #[must_use]
231    pub fn private_key(&self) -> PqdsaPrivateKey<'_> {
232        PqdsaPrivateKey(self)
233    }
234}
235
236unsafe impl Send for PqdsaKeyPair {}
237
238unsafe impl Sync for PqdsaKeyPair {}
239
240pub(crate) fn evp_key_pqdsa_generate(nid: c_int) -> Result<LcPtr<EVP_PKEY>, Unspecified> {
241    let params_fn = |ctx| {
242        if 1 == unsafe { EVP_PKEY_CTX_pqdsa_set_params(ctx, nid) } {
243            Ok(())
244        } else {
245            Err(())
246        }
247    };
248    LcPtr::<EVP_PKEY>::generate(EVP_PKEY_PQDSA, Some(params_fn))
249}
250
251#[cfg(all(test, feature = "unstable"))]
252mod tests {
253    use super::*;
254
255    use crate::signature::UnparsedPublicKey;
256    use crate::unstable::signature::{ML_DSA_44_SIGNING, ML_DSA_65_SIGNING, ML_DSA_87_SIGNING};
257
258    const TEST_ALGORITHMS: &[&PqdsaSigningAlgorithm] =
259        &[&ML_DSA_44_SIGNING, &ML_DSA_65_SIGNING, &ML_DSA_87_SIGNING];
260
261    #[test]
262    fn test_public_key_serialization() {
263        for &alg in TEST_ALGORITHMS {
264            // Generate a new key pair
265            let keypair = PqdsaKeyPair::generate(alg).unwrap();
266            let message = b"Test message";
267            let different_message = b"Different message";
268            let mut signature = vec![0; alg.signature_len()];
269            assert!(keypair
270                .sign(message, &mut signature[0..(alg.signature_len() - 1)])
271                .is_err());
272            let sig_len = keypair.sign(message, &mut signature).unwrap();
273            assert_eq!(sig_len, alg.signature_len());
274            let invalid_signature = vec![0u8; alg.signature_len()];
275
276            let original_public_key = keypair.public_key();
277
278            let x509_der = original_public_key.as_der().unwrap();
279            let x509_public_key = UnparsedPublicKey::new(alg.0, x509_der.as_ref());
280            assert!(x509_public_key.verify(message, signature.as_ref()).is_ok());
281            assert!(x509_public_key
282                .verify(different_message, signature.as_ref())
283                .is_err());
284            assert!(x509_public_key.verify(message, &invalid_signature).is_err());
285
286            let raw = original_public_key.as_ref();
287            let raw_public_key = UnparsedPublicKey::new(alg.0, raw);
288            assert!(raw_public_key.verify(message, signature.as_ref()).is_ok());
289            assert!(raw_public_key
290                .verify(different_message, signature.as_ref())
291                .is_err());
292            assert!(raw_public_key
293                .verify(different_message, &invalid_signature)
294                .is_err());
295
296            #[cfg(feature = "ring-sig-verify")]
297            #[allow(deprecated)]
298            {
299                use crate::signature::VerificationAlgorithm;
300                assert!(alg
301                    .0
302                    .verify(
303                        raw.into(),
304                        message.as_ref().into(),
305                        signature.as_slice().into()
306                    )
307                    .is_ok());
308            }
309        }
310    }
311
312    #[test]
313    fn test_private_key_serialization() {
314        for &alg in TEST_ALGORITHMS {
315            // Generate a new key pair
316            let keypair = PqdsaKeyPair::generate(alg).unwrap();
317            let message = b"Test message";
318            let mut original_signature = vec![0; alg.signature_len()];
319            let sig_len = keypair.sign(message, &mut original_signature).unwrap();
320            assert_eq!(sig_len, alg.signature_len());
321
322            let public_key = keypair.public_key();
323            let unparsed_public_key = UnparsedPublicKey::new(alg.0, public_key.as_ref());
324            unparsed_public_key
325                .verify(message, original_signature.as_ref())
326                .unwrap();
327
328            let pkcs8_1 = keypair.to_pkcs8().unwrap();
329            let pkcs8_2 = keypair.private_key().as_der().unwrap();
330            let raw = keypair.private_key().as_raw_bytes().unwrap();
331
332            assert_eq!(pkcs8_1.as_ref(), pkcs8_2.as_ref());
333
334            let pkcs8_keypair = PqdsaKeyPair::from_pkcs8(alg, pkcs8_1.as_ref()).unwrap();
335            let raw_keypair = PqdsaKeyPair::from_raw_private_key(alg, raw.as_ref()).unwrap();
336
337            assert_eq!(pkcs8_keypair.evp_pkey, raw_keypair.evp_pkey);
338        }
339    }
340
341    #[test]
342    fn test_from_seed() {
343        for &alg in TEST_ALGORITHMS {
344            let seed = [1u8; 32];
345            let kp = PqdsaKeyPair::from_seed(alg, &seed).unwrap();
346            assert_eq!(kp.algorithm(), alg);
347            // Verify key works for signing
348            let msg = b"seed test";
349            let mut sig = vec![0; alg.signature_len()];
350            let sig_len = kp.sign(msg, &mut sig).unwrap();
351            assert_eq!(sig_len, alg.signature_len());
352        }
353    }
354
355    #[test]
356    fn test_from_seed_deterministic() {
357        for &alg in TEST_ALGORITHMS {
358            let seed = [42u8; 32];
359            let kp1 = PqdsaKeyPair::from_seed(alg, &seed).unwrap();
360            let kp2 = PqdsaKeyPair::from_seed(alg, &seed).unwrap();
361            assert_eq!(kp1.public_key().as_ref(), kp2.public_key().as_ref());
362        }
363    }
364
365    #[test]
366    fn test_from_seed_wrong_size() {
367        use crate::error::KeyRejected;
368        for &alg in TEST_ALGORITHMS {
369            assert_eq!(
370                PqdsaKeyPair::from_seed(alg, &[0u8; 31]).err(),
371                Some(KeyRejected::too_small())
372            );
373            assert_eq!(
374                PqdsaKeyPair::from_seed(alg, &[0u8; 33]).err(),
375                Some(KeyRejected::too_large())
376            );
377            assert_eq!(
378                PqdsaKeyPair::from_seed(alg, &[]).err(),
379                Some(KeyRejected::too_small())
380            );
381        }
382    }
383
384    #[test]
385    fn test_from_seed_different_seeds_different_keys() {
386        for &alg in TEST_ALGORITHMS {
387            let kp1 = PqdsaKeyPair::from_seed(alg, &[1u8; 32]).unwrap();
388            let kp2 = PqdsaKeyPair::from_seed(alg, &[2u8; 32]).unwrap();
389            assert_ne!(kp1.public_key().as_ref(), kp2.public_key().as_ref());
390        }
391    }
392
393    #[test]
394    fn test_from_seed_raw_private_key_roundtrip() {
395        use crate::encoding::AsRawBytes;
396        for &alg in TEST_ALGORITHMS {
397            let seed = [55u8; 32];
398            let kp = PqdsaKeyPair::from_seed(alg, &seed).unwrap();
399            let raw_bytes = kp.private_key().as_raw_bytes().unwrap();
400            let kp2 = PqdsaKeyPair::from_raw_private_key(alg, raw_bytes.as_ref()).unwrap();
401            assert_eq!(kp.public_key().as_ref(), kp2.public_key().as_ref());
402        }
403    }
404
405    #[test]
406    fn test_from_seed_pkcs8_roundtrip() {
407        for &alg in TEST_ALGORITHMS {
408            let seed = [77u8; 32];
409            let kp = PqdsaKeyPair::from_seed(alg, &seed).unwrap();
410            let pkcs8 = kp.to_pkcs8().unwrap();
411            let kp2 = PqdsaKeyPair::from_pkcs8(alg, pkcs8.as_ref()).unwrap();
412            assert_eq!(kp.public_key().as_ref(), kp2.public_key().as_ref());
413        }
414    }
415
416    #[test]
417    fn test_from_seed_same_seed_different_algorithms() {
418        // Same seed with different algorithms should produce different keys
419        let seed = [42u8; 32];
420        let kp_44 = PqdsaKeyPair::from_seed(&ML_DSA_44_SIGNING, &seed).unwrap();
421        let kp_65 = PqdsaKeyPair::from_seed(&ML_DSA_65_SIGNING, &seed).unwrap();
422        let kp_87 = PqdsaKeyPair::from_seed(&ML_DSA_87_SIGNING, &seed).unwrap();
423        // Public keys have different sizes across algorithms, so they must differ
424        assert_ne!(
425            kp_44.public_key().as_ref().len(),
426            kp_65.public_key().as_ref().len()
427        );
428        assert_ne!(
429            kp_65.public_key().as_ref().len(),
430            kp_87.public_key().as_ref().len()
431        );
432    }
433
434    // `from_raw_private_key` documents that it expects the *expanded* form of the
435    // raw private key bytes, not the 32-byte seed. Feeding it a seed-sized input
436    // must be rejected rather than silently misinterpreted.
437    #[test]
438    fn test_from_raw_private_key_rejects_seed() {
439        for &alg in TEST_ALGORITHMS {
440            // A 32-byte seed is far smaller than any expanded private key, so it
441            // must not be accepted as an expanded key.
442            assert!(PqdsaKeyPair::from_raw_private_key(alg, &[7u8; 32]).is_err());
443        }
444    }
445
446    // `to_pkcs8` documents that it prefers serializing just the seed. When a key
447    // pair is created from a seed, the PKCS#8 output must therefore be the compact
448    // seed encoding, which is dramatically smaller than the expanded private key.
449    #[test]
450    fn test_from_seed_pkcs8_is_seed_form() {
451        for &alg in TEST_ALGORITHMS {
452            let kp = PqdsaKeyPair::from_seed(alg, &[3u8; 32]).unwrap();
453            let pkcs8 = kp.to_pkcs8().unwrap();
454            let raw_expanded = kp.private_key().as_raw_bytes().unwrap();
455            // The seed-form PKCS#8 wraps only the 32-byte seed (plus ASN.1
456            // framing), so it is far smaller than the expanded private key.
457            assert!(
458                pkcs8.as_ref().len() < raw_expanded.as_ref().len(),
459                "seed-form pkcs8 ({}) should be smaller than expanded key ({})",
460                pkcs8.as_ref().len(),
461                raw_expanded.as_ref().len(),
462            );
463            assert!(
464                pkcs8.as_ref().len() < 128,
465                "seed-form pkcs8 should be compact, got {}",
466                pkcs8.as_ref().len(),
467            );
468        }
469    }
470
471    // `from_seed` documents that if a `PqdsaKeyPair` is constructed from the
472    // expanded form the seed cannot be obtained. AWS-LC's PKCS#8 encoding only
473    // emits the seed, so a key pair with no seed available cannot be serialized to
474    // PKCS#8 at all -- `to_pkcs8` returns an error rather than falling back to the
475    // expanded encoding.
476    #[test]
477    fn test_expanded_key_pkcs8_unavailable() {
478        for &alg in TEST_ALGORITHMS {
479            // Round-trip through the raw (expanded) encoding to drop the seed.
480            let seed_kp = PqdsaKeyPair::from_seed(alg, &[4u8; 32]).unwrap();
481            let raw = seed_kp.private_key().as_raw_bytes().unwrap();
482            let expanded_kp = PqdsaKeyPair::from_raw_private_key(alg, raw.as_ref()).unwrap();
483
484            // The expanded-form key pair still signs and exposes the expanded raw
485            // bytes...
486            assert!(expanded_kp.private_key().as_raw_bytes().is_ok());
487            // ...but the seed is gone, so PKCS#8 serialization is unavailable.
488            assert!(
489                expanded_kp.to_pkcs8().is_err(),
490                "expanded-only key unexpectedly serialized to PKCS#8",
491            );
492        }
493    }
494
495    // `from_pkcs8` documents that it accepts the seed encoding, and `to_pkcs8`
496    // documents that it prefers the seed. A seed -> PKCS#8 -> key pair -> PKCS#8
497    // round-trip must therefore preserve the seed form byte-for-byte.
498    #[test]
499    fn test_from_seed_pkcs8_roundtrip_preserves_seed_form() {
500        for &alg in TEST_ALGORITHMS {
501            let kp = PqdsaKeyPair::from_seed(alg, &[8u8; 32]).unwrap();
502            let pkcs8 = kp.to_pkcs8().unwrap();
503            let reparsed = PqdsaKeyPair::from_pkcs8(alg, pkcs8.as_ref()).unwrap();
504            let pkcs8_again = reparsed.to_pkcs8().unwrap();
505            // Seed is retained through parsing, so re-serialization is identical.
506            assert_eq!(pkcs8.as_ref(), pkcs8_again.as_ref());
507            // And the reconstructed key pair is the same key.
508            assert_eq!(kp.public_key().as_ref(), reparsed.public_key().as_ref());
509        }
510    }
511
512    // `PqdsaPrivateKey::as_der` documents that it uses the representation chosen by
513    // `to_pkcs8`. For a seed-derived key that representation is the seed form, so
514    // `as_der` and `to_pkcs8` must agree.
515    #[test]
516    fn test_from_seed_as_der_matches_to_pkcs8() {
517        for &alg in TEST_ALGORITHMS {
518            let kp = PqdsaKeyPair::from_seed(alg, &[11u8; 32]).unwrap();
519            let pkcs8 = kp.to_pkcs8().unwrap();
520            let der = kp.private_key().as_der().unwrap();
521            assert_eq!(pkcs8.as_ref(), der.as_ref());
522        }
523    }
524
525    // Additional test for the algorithm getter
526    #[test]
527    fn test_algorithm_getter() {
528        for &alg in TEST_ALGORITHMS {
529            let keypair = PqdsaKeyPair::generate(alg).unwrap();
530            assert_eq!(keypair.algorithm(), alg);
531        }
532    }
533
534    // Additional test for the algorithm getter
535    #[test]
536    fn test_debug() {
537        for &alg in TEST_ALGORITHMS {
538            let keypair = PqdsaKeyPair::generate(alg).unwrap();
539            assert!(
540                format!("{keypair:?}").starts_with("PqdsaKeyPair { algorithm: PqdsaSigningAlgorithm(PqdsaVerificationAlgorithm { id:"),
541                "{keypair:?}"
542            );
543            let pubkey = keypair.public_key();
544            assert!(
545                format!("{pubkey:?}").starts_with("PqdsaPublicKey("),
546                "{pubkey:?}"
547            );
548        }
549    }
550}