aws_lc_rs/ec/
key_pair.rs

1// Copyright 2015-2016 Brian Smith.
2// SPDX-License-Identifier: ISC
3// Modifications copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
4// SPDX-License-Identifier: Apache-2.0 OR ISC
5
6use crate::aws_lc::{EVP_PKEY, EVP_PKEY_EC};
7use core::fmt;
8use core::fmt::{Debug, Formatter};
9
10use crate::ec::evp_key_generate;
11use crate::ec::signature::{EcdsaSignatureFormat, EcdsaSigningAlgorithm, PublicKey};
12#[cfg(feature = "fips")]
13use crate::ec::validate_evp_key;
14#[cfg(not(feature = "fips"))]
15use crate::ec::verify_evp_key_nid;
16
17use crate::ec;
18use crate::ec::encoding::rfc5915::{marshal_rfc5915_private_key, parse_rfc5915_private_key};
19use crate::ec::encoding::sec1::{
20    marshal_sec1_private_key, parse_sec1_private_bn, parse_sec1_public_point,
21};
22use crate::encoding::{AsBigEndian, AsDer, EcPrivateKeyBin, EcPrivateKeyRfc5915Der};
23use crate::error::{KeyRejected, Unspecified};
24use crate::evp_pkey::No_EVP_PKEY_CTX_consumer;
25use crate::pkcs8::{Document, Version};
26use crate::ptr::LcPtr;
27use crate::rand::SecureRandom;
28use crate::signature::{KeyPair, Signature};
29
30/// An ECDSA key pair, used for signing.
31#[allow(clippy::module_name_repetitions)]
32pub struct EcdsaKeyPair {
33    algorithm: &'static EcdsaSigningAlgorithm,
34    evp_pkey: LcPtr<EVP_PKEY>,
35    pubkey: PublicKey,
36}
37
38impl Debug for EcdsaKeyPair {
39    fn fmt(&self, f: &mut Formatter<'_>) -> Result<(), fmt::Error> {
40        f.write_str(&format!("EcdsaKeyPair {{ public_key: {:?} }}", self.pubkey))
41    }
42}
43
44unsafe impl Send for EcdsaKeyPair {}
45
46unsafe impl Sync for EcdsaKeyPair {}
47
48impl KeyPair for EcdsaKeyPair {
49    type PublicKey = PublicKey;
50
51    #[inline]
52    /// Provides the public key.
53    fn public_key(&self) -> &Self::PublicKey {
54        &self.pubkey
55    }
56}
57
58impl EcdsaKeyPair {
59    #[allow(clippy::needless_pass_by_value)]
60    fn new(
61        algorithm: &'static EcdsaSigningAlgorithm,
62        evp_pkey: LcPtr<EVP_PKEY>,
63    ) -> Result<Self, ()> {
64        let pubkey = ec::signature::public_key_from_evp_pkey(&evp_pkey, algorithm)?;
65
66        Ok(Self {
67            algorithm,
68            evp_pkey,
69            pubkey,
70        })
71    }
72
73    /// Generates a new key pair.
74    ///
75    /// # Errors
76    /// `error::Unspecified` on internal error.
77    ///
78    pub fn generate(alg: &'static EcdsaSigningAlgorithm) -> Result<Self, Unspecified> {
79        let evp_pkey = evp_key_generate(alg.0.id.nid())?;
80
81        Ok(Self::new(alg, evp_pkey)?)
82    }
83
84    /// Constructs an ECDSA key pair by parsing an unencrypted PKCS#8 v1
85    /// id-ecPublicKey `ECPrivateKey` key.
86    ///
87    /// # Errors
88    /// `error::KeyRejected` if bytes do not encode an ECDSA key pair or if the key is otherwise not
89    /// acceptable.
90    pub fn from_pkcs8(
91        alg: &'static EcdsaSigningAlgorithm,
92        pkcs8: &[u8],
93    ) -> Result<Self, KeyRejected> {
94        // Includes a call to `EC_KEY_check_key`
95        let evp_pkey = LcPtr::<EVP_PKEY>::parse_rfc5208_private_key(pkcs8, EVP_PKEY_EC)?;
96
97        #[cfg(not(feature = "fips"))]
98        verify_evp_key_nid(&evp_pkey.as_const(), alg.id.nid())?;
99        #[cfg(feature = "fips")]
100        validate_evp_key(&evp_pkey.as_const(), alg.id.nid())?;
101
102        let key_pair = Self::new(alg, evp_pkey)?;
103
104        Ok(key_pair)
105    }
106
107    /// Generates a new key pair and returns the key pair serialized as a
108    /// PKCS#8 v1 document.
109    ///
110    /// # *ring* Compatibility
111    /// Our implementation ignores the `SecureRandom` parameter.
112    ///
113    /// # Errors
114    /// `error::Unspecified` on internal error.
115    pub fn generate_pkcs8(
116        alg: &'static EcdsaSigningAlgorithm,
117        _rng: &dyn SecureRandom,
118    ) -> Result<Document, Unspecified> {
119        let key_pair = Self::generate(alg)?;
120
121        key_pair.to_pkcs8v1()
122    }
123
124    /// Serializes this `EcdsaKeyPair` into a PKCS#8 v1 document.
125    ///
126    /// # Errors
127    /// `error::Unspecified` on internal error.
128    ///
129    pub fn to_pkcs8v1(&self) -> Result<Document, Unspecified> {
130        Ok(Document::new(
131            self.evp_pkey.marshal_rfc5208_private_key(Version::V1)?,
132        ))
133    }
134
135    /// Constructs an ECDSA key pair from the private key and public key bytes
136    ///
137    /// The private key must encoded as a big-endian fixed-length integer. For
138    /// example, a P-256 private key must be 32 bytes prefixed with leading
139    /// zeros as needed.
140    ///
141    /// The public key is encoding in uncompressed form using the
142    /// Octet-String-to-Elliptic-Curve-Point algorithm in
143    /// [SEC 1: Elliptic Curve Cryptography, Version 2.0].
144    ///
145    /// This is intended for use by code that deserializes key pairs. It is
146    /// recommended to use `EcdsaKeyPair::from_pkcs8()` (with a PKCS#8-encoded
147    /// key) instead.
148    ///
149    /// [SEC 1: Elliptic Curve Cryptography, Version 2.0]:
150    ///     http://www.secg.org/sec1-v2.pdf
151    ///
152    /// # Errors
153    /// `error::KeyRejected` if parsing failed or key otherwise unacceptable.
154    pub fn from_private_key_and_public_key(
155        alg: &'static EcdsaSigningAlgorithm,
156        private_key: &[u8],
157        public_key: &[u8],
158    ) -> Result<Self, KeyRejected> {
159        let priv_evp_pkey = parse_sec1_private_bn(private_key, alg.id.nid())?;
160        let pub_evp_pkey = parse_sec1_public_point(public_key, alg.id.nid())?;
161        // EVP_PKEY_cmp only compares params and public key
162        if !priv_evp_pkey.eq(&pub_evp_pkey) {
163            return Err(KeyRejected::inconsistent_components());
164        }
165
166        let key_pair = Self::new(alg, priv_evp_pkey)?;
167        Ok(key_pair)
168    }
169
170    /// Deserializes a DER-encoded private key structure to produce a `EcdsaKeyPair`.
171    ///
172    /// This function is typically used to deserialize RFC 5915 encoded private keys, but it will
173    /// attempt to automatically detect other key formats. This function supports unencrypted
174    /// PKCS#8 `PrivateKeyInfo` structures as well as key type specific formats.
175    ///
176    /// See `EcdsaPrivateKey::as_der`.
177    ///
178    /// # Errors
179    /// `error::KeyRejected` if parsing failed or key otherwise unacceptable.
180    ///
181    /// # Panics
182    pub fn from_private_key_der(
183        alg: &'static EcdsaSigningAlgorithm,
184        private_key: &[u8],
185    ) -> Result<Self, KeyRejected> {
186        let evp_pkey = LcPtr::<EVP_PKEY>::parse_rfc5208_private_key(private_key, EVP_PKEY_EC)
187            .or(parse_rfc5915_private_key(private_key, alg.id.nid()))?;
188
189        Ok(Self::new(alg, evp_pkey)?)
190    }
191
192    /// Access functions related to the private key.
193    #[must_use]
194    pub fn private_key(&self) -> PrivateKey<'_> {
195        PrivateKey(self)
196    }
197
198    /// Returns the signature of the message using a random nonce.
199    ///
200    /// # *ring* Compatibility
201    /// Our implementation ignores the `SecureRandom` parameter.
202    ///
203    /// # Errors
204    /// `error::Unspecified` on internal error.
205    //
206    // # FIPS
207    // The following conditions must be met:
208    // * NIST Elliptic Curves: P256, P384, P521
209    // * Digest Algorithms: SHA256, SHA384, SHA512
210    #[inline]
211    pub fn sign(&self, _rng: &dyn SecureRandom, message: &[u8]) -> Result<Signature, Unspecified> {
212        let out_sig = self.evp_pkey.sign(
213            message,
214            Some(self.algorithm.digest),
215            No_EVP_PKEY_CTX_consumer,
216        )?;
217
218        Ok(match self.algorithm.sig_format {
219            EcdsaSignatureFormat::ASN1 => Signature::new(|slice| {
220                slice[..out_sig.len()].copy_from_slice(&out_sig);
221                out_sig.len()
222            }),
223            EcdsaSignatureFormat::Fixed => ec::ecdsa_asn1_to_fixed(self.algorithm.id, &out_sig)?,
224        })
225    }
226}
227
228/// Elliptic curve private key.
229pub struct PrivateKey<'a>(&'a EcdsaKeyPair);
230
231impl Debug for PrivateKey<'_> {
232    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
233        f.write_str(&format!("EcdsaPrivateKey({:?})", self.0.algorithm.id))
234    }
235}
236
237impl AsBigEndian<EcPrivateKeyBin<'static>> for PrivateKey<'_> {
238    /// Exposes the private key encoded as a big-endian fixed-length integer.
239    ///
240    /// For most use-cases, `EcdsaKeyPair::to_pkcs8()` should be preferred.
241    ///
242    /// # Errors
243    /// `error::Unspecified` if serialization failed.
244    fn as_be_bytes(&self) -> Result<EcPrivateKeyBin<'static>, Unspecified> {
245        let buffer = marshal_sec1_private_key(&self.0.evp_pkey)?;
246        Ok(EcPrivateKeyBin::new(buffer))
247    }
248}
249
250impl AsDer<EcPrivateKeyRfc5915Der<'static>> for PrivateKey<'_> {
251    /// Serializes the key as a DER-encoded `ECPrivateKey` (RFC 5915) structure.
252    ///
253    /// # Errors
254    /// `error::Unspecified`  if serialization failed.
255    fn as_der(&self) -> Result<EcPrivateKeyRfc5915Der<'static>, Unspecified> {
256        let bytes = marshal_rfc5915_private_key(&self.0.evp_pkey)?;
257        Ok(EcPrivateKeyRfc5915Der::new(bytes))
258    }
259}
260
261#[cfg(test)]
262mod tests {
263    use crate::encoding::AsDer;
264    use crate::signature::{EcdsaKeyPair, ECDSA_P256_SHA256_FIXED_SIGNING};
265
266    #[test]
267    fn test_from_private_key_der() {
268        let key_pair = EcdsaKeyPair::generate(&ECDSA_P256_SHA256_FIXED_SIGNING).unwrap();
269
270        let bytes_5208 = key_pair.to_pkcs8v1().unwrap();
271        let bytes_5915 = key_pair.private_key().as_der().unwrap();
272
273        let key_pair_5208 = EcdsaKeyPair::from_private_key_der(
274            &ECDSA_P256_SHA256_FIXED_SIGNING,
275            bytes_5208.as_ref(),
276        )
277        .unwrap();
278        let key_pair_5915 = EcdsaKeyPair::from_private_key_der(
279            &ECDSA_P256_SHA256_FIXED_SIGNING,
280            bytes_5915.as_ref(),
281        )
282        .unwrap();
283
284        assert_eq!(key_pair.evp_pkey, key_pair_5208.evp_pkey);
285        assert_eq!(key_pair.evp_pkey, key_pair_5915.evp_pkey);
286        assert_eq!(key_pair_5208.evp_pkey, key_pair_5915.evp_pkey);
287    }
288}