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::{EVP_PKEY_CTX_pqdsa_set_params, EVP_PKEY, EVP_PKEY_PQDSA};
5use crate::encoding::{AsDer, AsRawBytes, Pkcs8V1Der, PqdsaPrivateKeyRaw};
6use crate::error::{KeyRejected, Unspecified};
7use crate::evp_pkey::No_EVP_PKEY_CTX_consumer;
8use crate::pkcs8;
9use crate::pkcs8::{Document, Version};
10use crate::pqdsa::signature::{PqdsaSigningAlgorithm, PublicKey};
11use crate::pqdsa::validate_pqdsa_evp_key;
12use crate::ptr::LcPtr;
13use crate::signature::KeyPair;
14use core::fmt::{Debug, Formatter};
15use std::ffi::c_int;
16
17/// A PQDSA (Post-Quantum Digital Signature Algorithm) key pair, used for signing and verification.
18#[allow(clippy::module_name_repetitions)]
19pub struct PqdsaKeyPair {
20    algorithm: &'static PqdsaSigningAlgorithm,
21    evp_pkey: LcPtr<EVP_PKEY>,
22    pubkey: PublicKey,
23}
24
25#[allow(clippy::missing_fields_in_debug)]
26impl Debug for PqdsaKeyPair {
27    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
28        f.debug_struct("PqdsaKeyPair")
29            .field("algorithm", &self.algorithm)
30            .finish()
31    }
32}
33
34impl KeyPair for PqdsaKeyPair {
35    type PublicKey = PublicKey;
36
37    fn public_key(&self) -> &Self::PublicKey {
38        &self.pubkey
39    }
40}
41
42/// A PQDSA private key.
43pub struct PqdsaPrivateKey<'a>(pub(crate) &'a PqdsaKeyPair);
44
45impl AsDer<Pkcs8V1Der<'static>> for PqdsaPrivateKey<'_> {
46    /// Serializes the key to PKCS#8 v1 DER.
47    ///
48    /// # Errors
49    /// Returns `Unspecified` if serialization fails.
50    fn as_der(&self) -> Result<Pkcs8V1Der<'static>, Unspecified> {
51        Ok(Pkcs8V1Der::new(
52            self.0
53                .evp_pkey
54                .marshal_rfc5208_private_key(pkcs8::Version::V1)?,
55        ))
56    }
57}
58
59impl AsRawBytes<PqdsaPrivateKeyRaw<'static>> for PqdsaPrivateKey<'_> {
60    fn as_raw_bytes(&self) -> Result<PqdsaPrivateKeyRaw<'static>, Unspecified> {
61        Ok(PqdsaPrivateKeyRaw::new(
62            self.0.evp_pkey.marshal_raw_private_key()?,
63        ))
64    }
65}
66
67impl PqdsaKeyPair {
68    /// Generates a new PQDSA key pair for the specified algorithm.
69    ///
70    /// # Errors
71    /// Returns `Unspecified` is the key generation fails.
72    pub fn generate(algorithm: &'static PqdsaSigningAlgorithm) -> Result<Self, Unspecified> {
73        let evp_pkey = evp_key_pqdsa_generate(algorithm.0.id.nid())?;
74        let pubkey = PublicKey::from_private_evp_pkey(&evp_pkey)?;
75        Ok(Self {
76            algorithm,
77            evp_pkey,
78            pubkey,
79        })
80    }
81
82    /// Constructs a key pair from the parsing of PKCS#8.
83    ///
84    /// # Errors
85    /// Returns `Unspecified` if the key is not valid for the specified signing algorithm.
86    pub fn from_pkcs8(
87        algorithm: &'static PqdsaSigningAlgorithm,
88        pkcs8: &[u8],
89    ) -> Result<Self, KeyRejected> {
90        let evp_pkey = LcPtr::<EVP_PKEY>::parse_rfc5208_private_key(pkcs8, EVP_PKEY_PQDSA)?;
91        validate_pqdsa_evp_key(&evp_pkey, algorithm.0.id)?;
92        let pubkey = PublicKey::from_private_evp_pkey(&evp_pkey)?;
93        Ok(Self {
94            algorithm,
95            evp_pkey,
96            pubkey,
97        })
98    }
99
100    /// Constructs a key pair from raw private key bytes.
101    ///
102    /// # Errors
103    /// Returns `Unspecified` if the key is not valid for the specified signing algorithm.
104    pub fn from_raw_private_key(
105        algorithm: &'static PqdsaSigningAlgorithm,
106        raw_private_key: &[u8],
107    ) -> Result<Self, KeyRejected> {
108        let evp_pkey = LcPtr::<EVP_PKEY>::parse_raw_private_key(raw_private_key, EVP_PKEY_PQDSA)?;
109        validate_pqdsa_evp_key(&evp_pkey, algorithm.0.id)?;
110        let pubkey = PublicKey::from_private_evp_pkey(&evp_pkey)?;
111        Ok(Self {
112            algorithm,
113            evp_pkey,
114            pubkey,
115        })
116    }
117
118    /// Serializes the private key to PKCS#8 v1 DER.
119    ///
120    /// # Errors
121    /// Returns `Unspecified` if serialization fails.
122    pub fn to_pkcs8(&self) -> Result<Document, Unspecified> {
123        Ok(Document::new(
124            self.evp_pkey.marshal_rfc5208_private_key(Version::V1)?,
125        ))
126    }
127
128    /// Uses this key to sign the message provided. The signature is written to the `signature`
129    /// slice provided. It returns the length of the signature on success.
130    ///
131    /// # Errors
132    /// Returns `Unspecified` if signing fails.
133    pub fn sign(&self, msg: &[u8], signature: &mut [u8]) -> Result<usize, Unspecified> {
134        let sig_length = self.algorithm.signature_len();
135        if signature.len() < sig_length {
136            return Err(Unspecified);
137        }
138        let sig_bytes = self.evp_pkey.sign(msg, None, No_EVP_PKEY_CTX_consumer)?;
139        signature[0..sig_length].copy_from_slice(&sig_bytes);
140        Ok(sig_length)
141    }
142
143    /// Returns the signing algorithm associated with this key pair.
144    #[must_use]
145    pub fn algorithm(&self) -> &'static PqdsaSigningAlgorithm {
146        self.algorithm
147    }
148
149    /// Returns the private key associated with this key pair.
150    #[must_use]
151    pub fn private_key(&self) -> PqdsaPrivateKey {
152        PqdsaPrivateKey(self)
153    }
154}
155
156unsafe impl Send for PqdsaKeyPair {}
157
158unsafe impl Sync for PqdsaKeyPair {}
159
160pub(crate) fn evp_key_pqdsa_generate(nid: c_int) -> Result<LcPtr<EVP_PKEY>, Unspecified> {
161    let params_fn = |ctx| {
162        if 1 == unsafe { EVP_PKEY_CTX_pqdsa_set_params(ctx, nid) } {
163            Ok(())
164        } else {
165            Err(())
166        }
167    };
168    LcPtr::<EVP_PKEY>::generate(EVP_PKEY_PQDSA, Some(params_fn))
169}
170
171#[cfg(all(test, feature = "unstable"))]
172mod tests {
173    use super::*;
174
175    use crate::signature::{UnparsedPublicKey, VerificationAlgorithm};
176    use crate::unstable::signature::{MLDSA_44_SIGNING, MLDSA_65_SIGNING, MLDSA_87_SIGNING};
177
178    const TEST_ALGORITHMS: &[&PqdsaSigningAlgorithm] =
179        &[&MLDSA_44_SIGNING, &MLDSA_65_SIGNING, &MLDSA_87_SIGNING];
180
181    #[test]
182    fn test_public_key_serialization() {
183        for &alg in TEST_ALGORITHMS {
184            // Generate a new key pair
185            let keypair = PqdsaKeyPair::generate(alg).unwrap();
186            let message = b"Test message";
187            let different_message = b"Different message";
188            let mut signature = vec![0; alg.signature_len()];
189            assert!(keypair
190                .sign(message, &mut signature[0..(alg.signature_len() - 1)])
191                .is_err());
192            let sig_len = keypair.sign(message, &mut signature).unwrap();
193            assert_eq!(sig_len, alg.signature_len());
194            let invalid_signature = vec![0u8; alg.signature_len()];
195
196            let original_public_key = keypair.public_key();
197
198            let x509_der = original_public_key.as_der().unwrap();
199            let x509_public_key = UnparsedPublicKey::new(alg.0, x509_der.as_ref());
200            assert!(x509_public_key.verify(message, signature.as_ref()).is_ok());
201            assert!(x509_public_key
202                .verify(different_message, signature.as_ref())
203                .is_err());
204            assert!(x509_public_key.verify(message, &invalid_signature).is_err());
205
206            let raw = original_public_key.as_ref();
207            let raw_public_key = UnparsedPublicKey::new(alg.0, raw);
208            assert!(raw_public_key.verify(message, signature.as_ref()).is_ok());
209            assert!(raw_public_key
210                .verify(different_message, signature.as_ref())
211                .is_err());
212            assert!(raw_public_key
213                .verify(different_message, &invalid_signature)
214                .is_err());
215
216            #[cfg(feature = "ring-sig-verify")]
217            #[allow(deprecated)]
218            {
219                assert!(alg
220                    .0
221                    .verify(
222                        raw.into(),
223                        message.as_ref().into(),
224                        signature.as_slice().into()
225                    )
226                    .is_ok());
227            }
228        }
229    }
230
231    #[test]
232    fn test_private_key_serialization() {
233        for &alg in TEST_ALGORITHMS {
234            // Generate a new key pair
235            let keypair = PqdsaKeyPair::generate(alg).unwrap();
236            let message = b"Test message";
237            let mut original_signature = vec![0; alg.signature_len()];
238            let sig_len = keypair.sign(message, &mut original_signature).unwrap();
239            assert_eq!(sig_len, alg.signature_len());
240
241            let public_key = keypair.public_key();
242            let unparsed_public_key = UnparsedPublicKey::new(alg.0, public_key.as_ref());
243            unparsed_public_key
244                .verify(message, original_signature.as_ref())
245                .unwrap();
246
247            let pkcs8_1 = keypair.to_pkcs8().unwrap();
248            let pkcs8_2 = keypair.private_key().as_der().unwrap();
249            let raw = keypair.private_key().as_raw_bytes().unwrap();
250
251            assert_eq!(pkcs8_1.as_ref(), pkcs8_2.as_ref());
252
253            let pkcs8_keypair = PqdsaKeyPair::from_pkcs8(alg, pkcs8_1.as_ref()).unwrap();
254            let raw_keypair = PqdsaKeyPair::from_raw_private_key(alg, raw.as_ref()).unwrap();
255
256            assert_eq!(pkcs8_keypair.evp_pkey, raw_keypair.evp_pkey);
257        }
258    }
259
260    // Additional test for the algorithm getter
261    #[test]
262    fn test_algorithm_getter() {
263        for &alg in TEST_ALGORITHMS {
264            let keypair = PqdsaKeyPair::generate(alg).unwrap();
265            assert_eq!(keypair.algorithm(), alg);
266        }
267    }
268
269    // Additional test for the algorithm getter
270    #[test]
271    fn test_debug() {
272        for &alg in TEST_ALGORITHMS {
273            let keypair = PqdsaKeyPair::generate(alg).unwrap();
274            assert!(
275                format!("{keypair:?}").starts_with("PqdsaKeyPair { algorithm: PqdsaSigningAlgorithm(PqdsaVerificationAlgorithm { id:"),
276                "{keypair:?}"
277            );
278            let pubkey = keypair.public_key();
279            assert!(
280                format!("{pubkey:?}").starts_with("PqdsaPublicKey("),
281                "{pubkey:?}"
282            );
283        }
284    }
285}