Skip to main content

rtci_crypto/providers/
aws_lc_rs.rs

1use std::sync::Arc;
2
3use aws_lc_rs::rand::SystemRandom;
4use aws_lc_rs::signature::{self, KeyPair};
5use aws_lc_rs::{aead, agreement, digest, hmac};
6
7use crate::common;
8use crate::{
9    ActiveKeyExchange, AeadAlgorithm, AeadCipher, BlockCipherAlgorithm, CbcAlgorithm, CbcCipher,
10    CryptoAlgorithm, CryptoError, HEADER_MASK_LEN, HEADER_MASK_SAMPLE_LEN, HashAlgorithm,
11    HeaderMask, HeaderMaskAlgorithm, HmacAlgorithm, KeyExchangeAlgorithm, Mac, PublicKey,
12    PublicKeyEncoding, RTCCrypto, RTCCryptoProvider, RTCRandom, SecretVec, SignatureScheme,
13    SigningKey, StreamCipher, StreamCipherAlgorithm, constant_time_eq,
14};
15
16/// The built-in AWS-LC-RS provider bundle.
17#[derive(Default)]
18pub struct AwsLcRsProvider {
19    crypto: AwsLcRsCrypto,
20    random: AwsLcRsRandom,
21}
22
23impl AwsLcRsProvider {
24    /// Creates an AWS-LC-RS provider.
25    #[must_use]
26    pub const fn new() -> Self {
27        Self {
28            crypto: AwsLcRsCrypto,
29            random: AwsLcRsRandom,
30        }
31    }
32}
33
34impl RTCCryptoProvider for AwsLcRsProvider {
35    fn name(&self) -> &'static str {
36        "aws-lc-rs"
37    }
38
39    fn crypto(&self) -> &dyn RTCCrypto {
40        &self.crypto
41    }
42
43    fn random(&self) -> &dyn RTCRandom {
44        &self.random
45    }
46}
47
48/// AWS-LC-RS-backed operations, with RustCrypto fallbacks for primitives that are not exposed by
49/// its stable high-level API: MD5, AES block/CTR/CBC, and AES-CCM.
50#[derive(Default)]
51pub struct AwsLcRsCrypto;
52
53/// AWS-LC-RS's operating-system-backed secure random source.
54#[derive(Default)]
55pub struct AwsLcRsRandom;
56
57impl RTCRandom for AwsLcRsRandom {
58    fn fill(&self, output: &mut [u8]) -> Result<(), CryptoError> {
59        common::fill_random(output)
60    }
61}
62
63impl RTCCrypto for AwsLcRsCrypto {
64    fn supports(&self, algorithm: CryptoAlgorithm) -> bool {
65        matches!(
66            algorithm,
67            CryptoAlgorithm::Hash(
68                HashAlgorithm::Md5
69                    | HashAlgorithm::Sha256
70                    | HashAlgorithm::Sha1
71                    | HashAlgorithm::Sha224
72                    | HashAlgorithm::Sha384
73                    | HashAlgorithm::Sha512
74            ) | CryptoAlgorithm::Hmac(
75                HmacAlgorithm::Sha1
76                    | HmacAlgorithm::Sha256
77                    | HmacAlgorithm::Sha384
78                    | HmacAlgorithm::Sha512
79            ) | CryptoAlgorithm::HeaderMask(
80                HeaderMaskAlgorithm::Aes128
81                    | HeaderMaskAlgorithm::Aes256
82                    | HeaderMaskAlgorithm::ChaCha20
83            ) | CryptoAlgorithm::Aead(
84                AeadAlgorithm::Aes128Gcm
85                    | AeadAlgorithm::Aes256Gcm
86                    | AeadAlgorithm::Aes128Ccm
87                    | AeadAlgorithm::Aes128Ccm8
88                    | AeadAlgorithm::ChaCha20Poly1305,
89            ) | CryptoAlgorithm::StreamCipher(
90                StreamCipherAlgorithm::Aes128Ctr
91                    | StreamCipherAlgorithm::Aes256Ctr
92                    | StreamCipherAlgorithm::Aes192Ctr,
93            ) | CryptoAlgorithm::BlockCipher(
94                BlockCipherAlgorithm::Aes128
95                    | BlockCipherAlgorithm::Aes256
96                    | BlockCipherAlgorithm::Aes192,
97            ) | CryptoAlgorithm::Cbc(CbcAlgorithm::Aes256Cbc)
98                | CryptoAlgorithm::KeyExchange(
99                    KeyExchangeAlgorithm::P256
100                        | KeyExchangeAlgorithm::P384
101                        | KeyExchangeAlgorithm::X25519
102                        | KeyExchangeAlgorithm::X25519MlKem768,
103                )
104                | CryptoAlgorithm::Signature(
105                    SignatureScheme::Ed25519
106                        | SignatureScheme::EcdsaP256Sha256
107                        | SignatureScheme::EcdsaP384Sha256
108                        | SignatureScheme::EcdsaP384Sha384
109                        | SignatureScheme::RsaPkcs1Sha1
110                        | SignatureScheme::RsaPkcs1Sha256
111                        | SignatureScheme::RsaPkcs1Sha384
112                        | SignatureScheme::RsaPkcs1Sha512
113                        | SignatureScheme::RsaPssSha256
114                        | SignatureScheme::RsaPssSha384
115                        | SignatureScheme::RsaPssSha512,
116                )
117                | CryptoAlgorithm::SigningKeyGeneration(
118                    SignatureScheme::Ed25519
119                        | SignatureScheme::EcdsaP256Sha256
120                        | SignatureScheme::RsaPkcs1Sha256,
121                )
122                | CryptoAlgorithm::SigningKeyImport(
123                    SignatureScheme::Ed25519
124                        | SignatureScheme::EcdsaP256Sha256
125                        | SignatureScheme::RsaPkcs1Sha256,
126                )
127        )
128    }
129
130    fn hash(&self, algorithm: HashAlgorithm, data: &[u8]) -> Result<Vec<u8>, CryptoError> {
131        match algorithm {
132            HashAlgorithm::Md5 => Ok(common::md5(data)),
133            HashAlgorithm::Sha256 => Ok(digest::digest(&digest::SHA256, data).as_ref().to_vec()),
134            HashAlgorithm::Sha1 => Ok(digest::digest(&digest::SHA1_FOR_LEGACY_USE_ONLY, data)
135                .as_ref()
136                .to_vec()),
137            HashAlgorithm::Sha224 => Ok(digest::digest(&digest::SHA224, data).as_ref().to_vec()),
138            HashAlgorithm::Sha384 => Ok(digest::digest(&digest::SHA384, data).as_ref().to_vec()),
139            HashAlgorithm::Sha512 => Ok(digest::digest(&digest::SHA512, data).as_ref().to_vec()),
140        }
141    }
142
143    fn new_hmac(&self, algorithm: HmacAlgorithm, key: &[u8]) -> Result<Box<dyn Mac>, CryptoError> {
144        Ok(Box::new(AwsLcRsHmac {
145            key: hmac::Key::new(hmac_algorithm(algorithm), key),
146            output_len: algorithm.output_len(),
147        }))
148    }
149
150    fn block_encrypt(
151        &self,
152        algorithm: BlockCipherAlgorithm,
153        key: &[u8],
154        block: &mut [u8],
155    ) -> Result<(), CryptoError> {
156        common::block_encrypt(algorithm, key, block)
157    }
158
159    fn new_stream_cipher(
160        &self,
161        algorithm: StreamCipherAlgorithm,
162        key: &[u8],
163    ) -> Result<Box<dyn StreamCipher>, CryptoError> {
164        common::new_stream_cipher(algorithm, key)
165    }
166
167    fn new_aead(
168        &self,
169        algorithm: AeadAlgorithm,
170        key: &[u8],
171    ) -> Result<Box<dyn AeadCipher>, CryptoError> {
172        match algorithm {
173            AeadAlgorithm::Aes128Ccm | AeadAlgorithm::Aes128Ccm8 => common::new_ccm(algorithm, key),
174            AeadAlgorithm::Aes128Gcm => AwsLcRsAead::create(&aead::AES_128_GCM, key),
175            AeadAlgorithm::Aes256Gcm => AwsLcRsAead::create(&aead::AES_256_GCM, key),
176            AeadAlgorithm::ChaCha20Poly1305 => AwsLcRsAead::create(&aead::CHACHA20_POLY1305, key),
177        }
178    }
179
180    fn new_header_mask(
181        &self,
182        algorithm: HeaderMaskAlgorithm,
183        key: &[u8],
184    ) -> Result<Box<dyn HeaderMask>, CryptoError> {
185        common::check_key_len(algorithm.key_len(), key.len())?;
186        let backend_algorithm = match algorithm {
187            HeaderMaskAlgorithm::Aes128 => &aead::quic::AES_128,
188            HeaderMaskAlgorithm::Aes256 => &aead::quic::AES_256,
189            HeaderMaskAlgorithm::ChaCha20 => &aead::quic::CHACHA20,
190        };
191        let key = aead::quic::HeaderProtectionKey::new(backend_algorithm, key)
192            .map_err(|_| CryptoError::InvalidPrivateKey)?;
193        Ok(Box::new(AwsLcRsHeaderMask { key }))
194    }
195
196    fn new_cbc(
197        &self,
198        algorithm: CbcAlgorithm,
199        key: &[u8],
200    ) -> Result<Box<dyn CbcCipher>, CryptoError> {
201        common::new_cbc(algorithm, key)
202    }
203
204    fn start_key_exchange(
205        &self,
206        algorithm: KeyExchangeAlgorithm,
207    ) -> Result<Box<dyn ActiveKeyExchange>, CryptoError> {
208        if algorithm == KeyExchangeAlgorithm::X25519MlKem768 {
209            return HybridKeyExchange::start();
210        }
211        AwsLcRsKeyExchange::start(algorithm)
212    }
213
214    fn key_exchange_respond(
215        &self,
216        algorithm: KeyExchangeAlgorithm,
217        peer_share: &[u8],
218    ) -> Result<(Vec<u8>, SecretVec), CryptoError> {
219        if algorithm == KeyExchangeAlgorithm::X25519MlKem768 {
220            return HybridKeyExchange::respond(peer_share);
221        }
222        let exchange = self.start_key_exchange(algorithm)?;
223        let share = exchange.public_key().to_vec();
224        let secret = exchange.complete(peer_share)?;
225        Ok((share, secret))
226    }
227
228    fn generate_signing_key(
229        &self,
230        scheme: SignatureScheme,
231    ) -> Result<Arc<dyn SigningKey>, CryptoError> {
232        AwsLcRsSigningKey::generate(scheme)
233    }
234
235    fn import_signing_key(
236        &self,
237        scheme: SignatureScheme,
238        pkcs8_der: &[u8],
239    ) -> Result<Arc<dyn SigningKey>, CryptoError> {
240        AwsLcRsSigningKey::import(scheme, pkcs8_der)
241    }
242
243    fn verify_signature(
244        &self,
245        scheme: SignatureScheme,
246        public_key: PublicKey<'_>,
247        message: &[u8],
248        signature: &[u8],
249    ) -> Result<(), CryptoError> {
250        verify_public_key_encoding(scheme, public_key.encoding)?;
251        signature::UnparsedPublicKey::new(verification_algorithm(scheme), public_key.bytes)
252            .verify(message, signature)
253            .map_err(|_| CryptoError::InvalidSignature)
254    }
255}
256
257/// A keyed HMAC holding an `aws_lc_rs::hmac::Key`.
258///
259/// `Key::new` performs the ipad/opad derivation; `Context::with_key` only clones the resulting
260/// state. Keeping the key here is what moves that derivation off the per-packet path.
261struct AwsLcRsHmac {
262    key: hmac::Key,
263    output_len: usize,
264}
265
266impl Mac for AwsLcRsHmac {
267    fn output_len(&self) -> usize {
268        self.output_len
269    }
270
271    fn sign(&mut self, input: &[&[u8]], output: &mut [u8]) -> Result<(), CryptoError> {
272        common::check_tag_len(self.output_len, output.len())?;
273        let mut context = hmac::Context::with_key(&self.key);
274        for part in input {
275            context.update(part);
276        }
277        output.copy_from_slice(context.sign().as_ref());
278        Ok(())
279    }
280
281    fn verify(&mut self, input: &[&[u8]], expected: &[u8]) -> Result<(), CryptoError> {
282        common::check_tag_len(self.output_len, expected.len())?;
283        let mut actual = vec![0; self.output_len];
284        self.sign(input, &mut actual)?;
285        if constant_time_eq(&actual, expected) {
286            Ok(())
287        } else {
288            Err(CryptoError::AuthenticationFailed)
289        }
290    }
291}
292
293fn hmac_algorithm(algorithm: HmacAlgorithm) -> hmac::Algorithm {
294    match algorithm {
295        HmacAlgorithm::Sha1 => hmac::HMAC_SHA1_FOR_LEGACY_USE_ONLY,
296        HmacAlgorithm::Sha256 => hmac::HMAC_SHA256,
297        HmacAlgorithm::Sha512 => hmac::HMAC_SHA512,
298        HmacAlgorithm::Sha384 => hmac::HMAC_SHA384,
299    }
300}
301
302/// A record-number mask generator on the backend's QUIC header-protection key, which is the
303/// computation RFC 9147 section 4.2.3 defines (AES-ECB of the sample, or the ChaCha20 block
304/// function keyed by it).
305struct AwsLcRsHeaderMask {
306    key: aead::quic::HeaderProtectionKey,
307}
308
309impl HeaderMask for AwsLcRsHeaderMask {
310    fn mask(
311        &mut self,
312        sample: &[u8; HEADER_MASK_SAMPLE_LEN],
313    ) -> Result<[u8; HEADER_MASK_LEN], CryptoError> {
314        self.key
315            .new_mask(sample)
316            .map_err(|_| CryptoError::Provider("header mask generation failed".into()))
317    }
318}
319
320struct AwsLcRsAead {
321    key: aead::LessSafeKey,
322}
323
324impl AwsLcRsAead {
325    fn create(
326        algorithm: &'static aead::Algorithm,
327        key: &[u8],
328    ) -> Result<Box<dyn AeadCipher>, CryptoError> {
329        common::check_key_len(algorithm.key_len(), key.len())?;
330        let key = aead::UnboundKey::new(algorithm, key)
331            .map(aead::LessSafeKey::new)
332            .map_err(|_| CryptoError::InvalidPrivateKey)?;
333        Ok(Box::new(Self { key }))
334    }
335}
336
337impl AeadCipher for AwsLcRsAead {
338    fn tag_len(&self) -> usize {
339        16
340    }
341
342    fn seal_in_place(
343        &mut self,
344        nonce: &[u8],
345        aad: &[u8],
346        plaintext_and_ciphertext: &mut [u8],
347        tag_out: &mut [u8],
348    ) -> Result<(), CryptoError> {
349        common::check_nonce_len(12, nonce.len())?;
350        common::check_tag_len(self.tag_len(), tag_out.len())?;
351        let nonce = aead::Nonce::try_assume_unique_for_key(nonce).map_err(|_| {
352            CryptoError::InvalidNonceLength {
353                expected: 12,
354                actual: nonce.len(),
355            }
356        })?;
357        let tag = self
358            .key
359            .seal_in_place_separate_tag(nonce, aead::Aad::from(aad), plaintext_and_ciphertext)
360            .map_err(|_| CryptoError::AuthenticationFailed)?;
361        tag_out.copy_from_slice(tag.as_ref());
362        Ok(())
363    }
364
365    fn open_in_place(
366        &mut self,
367        nonce: &[u8],
368        aad: &[u8],
369        ciphertext_and_plaintext: &mut [u8],
370        tag: &[u8],
371    ) -> Result<(), CryptoError> {
372        common::check_nonce_len(12, nonce.len())?;
373        common::check_tag_len(self.tag_len(), tag.len())?;
374        let nonce = aead::Nonce::try_assume_unique_for_key(nonce).map_err(|_| {
375            CryptoError::InvalidNonceLength {
376                expected: 12,
377                actual: nonce.len(),
378            }
379        })?;
380        self.key
381            .open_in_place_separate_tag(nonce, aead::Aad::from(aad), tag, ciphertext_and_plaintext)
382            .map(|_| ())
383            .map_err(|_| CryptoError::AuthenticationFailed)
384    }
385}
386
387/// The lengths of X25519MLKEM768 (draft-ietf-tls-ecdhe-mlkem section 4.2).
388const ML_KEM_768_ENCAPSULATION_KEY_LEN: usize = 1184;
389const ML_KEM_768_CIPHERTEXT_LEN: usize = 1088;
390const X25519_LEN: usize = 32;
391
392/// The initiator's half of X25519MLKEM768: an ML-KEM-768 decapsulation key and an X25519
393/// private key. Its share is the encapsulation key followed by the X25519 public key.
394struct HybridKeyExchange {
395    decapsulation_key: aws_lc_rs::kem::DecapsulationKey,
396    x25519: agreement::PrivateKey,
397    share: Vec<u8>,
398}
399
400impl HybridKeyExchange {
401    fn failure(what: &'static str) -> CryptoError {
402        CryptoError::Provider(what.into())
403    }
404
405    fn start() -> Result<Box<dyn ActiveKeyExchange>, CryptoError> {
406        let decapsulation_key =
407            aws_lc_rs::kem::DecapsulationKey::generate(&aws_lc_rs::kem::ML_KEM_768)
408                .map_err(|_| CryptoError::RandomnessFailed)?;
409        let encapsulation_key = decapsulation_key
410            .encapsulation_key()
411            .and_then(|key| key.key_bytes())
412            .map_err(|_| Self::failure("ML-KEM key generation failed"))?;
413        let x25519 = agreement::PrivateKey::generate(&agreement::X25519)
414            .map_err(|_| CryptoError::RandomnessFailed)?;
415        let x25519_public = x25519
416            .compute_public_key()
417            .map_err(|_| Self::failure("key exchange public-key generation failed"))?;
418        let mut share = encapsulation_key.as_ref().to_vec();
419        share.extend_from_slice(x25519_public.as_ref());
420        Ok(Box::new(Self {
421            decapsulation_key,
422            x25519,
423            share,
424        }))
425    }
426
427    /// The responder's half: encapsulates to the initiator's ML-KEM key and agrees with its
428    /// X25519 key. The share is the ciphertext followed by an X25519 public key, the secret
429    /// the ML-KEM shared secret followed by the X25519 one.
430    fn respond(peer_share: &[u8]) -> Result<(Vec<u8>, SecretVec), CryptoError> {
431        if peer_share.len() != ML_KEM_768_ENCAPSULATION_KEY_LEN + X25519_LEN {
432            return Err(CryptoError::InvalidPublicKey);
433        }
434        let (encapsulation_key, peer_x25519) =
435            peer_share.split_at(ML_KEM_768_ENCAPSULATION_KEY_LEN);
436        let encapsulation_key =
437            aws_lc_rs::kem::EncapsulationKey::new(&aws_lc_rs::kem::ML_KEM_768, encapsulation_key)
438                .map_err(|_| CryptoError::InvalidPublicKey)?;
439        let (ciphertext, kem_secret) = encapsulation_key
440            .encapsulate()
441            .map_err(|_| CryptoError::InvalidPublicKey)?;
442        let x25519 = agreement::PrivateKey::generate(&agreement::X25519)
443            .map_err(|_| CryptoError::RandomnessFailed)?;
444        let x25519_public = x25519
445            .compute_public_key()
446            .map_err(|_| Self::failure("key exchange public-key generation failed"))?;
447        let mut secret = kem_secret.as_ref().to_vec();
448        agreement::agree(
449            &x25519,
450            agreement::UnparsedPublicKey::new(&agreement::X25519, peer_x25519),
451            CryptoError::InvalidPublicKey,
452            |x25519_secret| {
453                secret.extend_from_slice(x25519_secret);
454                Ok(())
455            },
456        )?;
457        let mut share = ciphertext.as_ref().to_vec();
458        share.extend_from_slice(x25519_public.as_ref());
459        Ok((share, SecretVec::new(secret)))
460    }
461}
462
463impl ActiveKeyExchange for HybridKeyExchange {
464    fn algorithm(&self) -> KeyExchangeAlgorithm {
465        KeyExchangeAlgorithm::X25519MlKem768
466    }
467
468    fn public_key(&self) -> &[u8] {
469        &self.share
470    }
471
472    fn complete(self: Box<Self>, peer_share: &[u8]) -> Result<SecretVec, CryptoError> {
473        if peer_share.len() != ML_KEM_768_CIPHERTEXT_LEN + X25519_LEN {
474            return Err(CryptoError::InvalidPublicKey);
475        }
476        let (ciphertext, peer_x25519) = peer_share.split_at(ML_KEM_768_CIPHERTEXT_LEN);
477        let kem_secret = self
478            .decapsulation_key
479            .decapsulate(ciphertext.into())
480            .map_err(|_| CryptoError::InvalidPublicKey)?;
481        let mut secret = kem_secret.as_ref().to_vec();
482        agreement::agree(
483            &self.x25519,
484            agreement::UnparsedPublicKey::new(&agreement::X25519, peer_x25519),
485            CryptoError::InvalidPublicKey,
486            |x25519_secret| {
487                secret.extend_from_slice(x25519_secret);
488                Ok(())
489            },
490        )?;
491        Ok(SecretVec::new(secret))
492    }
493}
494
495struct AwsLcRsKeyExchange {
496    algorithm: KeyExchangeAlgorithm,
497    backend_algorithm: &'static agreement::Algorithm,
498    private_key: agreement::PrivateKey,
499    public_key: Vec<u8>,
500}
501
502impl AwsLcRsKeyExchange {
503    fn start(algorithm: KeyExchangeAlgorithm) -> Result<Box<dyn ActiveKeyExchange>, CryptoError> {
504        let backend_algorithm = agreement_algorithm(algorithm);
505        let private_key = agreement::PrivateKey::generate(backend_algorithm)
506            .map_err(|_| CryptoError::RandomnessFailed)?;
507        let public_key = private_key
508            .compute_public_key()
509            .map_err(|_| CryptoError::Provider("key exchange public-key generation failed".into()))?
510            .as_ref()
511            .to_vec();
512        Ok(Box::new(Self {
513            algorithm,
514            backend_algorithm,
515            private_key,
516            public_key,
517        }))
518    }
519}
520
521impl ActiveKeyExchange for AwsLcRsKeyExchange {
522    fn algorithm(&self) -> KeyExchangeAlgorithm {
523        self.algorithm
524    }
525
526    fn public_key(&self) -> &[u8] {
527        &self.public_key
528    }
529
530    fn complete(self: Box<Self>, peer_public_key: &[u8]) -> Result<SecretVec, CryptoError> {
531        let peer = agreement::UnparsedPublicKey::new(self.backend_algorithm, peer_public_key);
532        agreement::agree(
533            &self.private_key,
534            peer,
535            CryptoError::InvalidPublicKey,
536            |secret| Ok(SecretVec::new(secret.to_vec())),
537        )
538    }
539}
540
541enum AwsLcRsSigningKeyKind {
542    Ed25519(signature::Ed25519KeyPair),
543    EcdsaP256(signature::EcdsaKeyPair),
544    Rsa(signature::RsaKeyPair),
545}
546
547struct AwsLcRsSigningKey {
548    scheme: SignatureScheme,
549    kind: AwsLcRsSigningKeyKind,
550    public_key: Vec<u8>,
551    public_key_encoding: PublicKeyEncoding,
552    pkcs8_der: SecretVec,
553}
554
555impl AwsLcRsSigningKey {
556    fn generate(scheme: SignatureScheme) -> Result<Arc<dyn SigningKey>, CryptoError> {
557        let rng = SystemRandom::new();
558        let pkcs8 = match scheme {
559            SignatureScheme::Ed25519 => signature::Ed25519KeyPair::generate_pkcs8(&rng),
560            SignatureScheme::EcdsaP256Sha256 => signature::EcdsaKeyPair::generate_pkcs8(
561                &signature::ECDSA_P256_SHA256_ASN1_SIGNING,
562                &rng,
563            ),
564            // W3C webrtc-pc 4.9 generateCertificate: RSASSA-PKCS1-v1_5 with a 2048-bit
565            // modulus, public exponent 65537 (AWS-LC's key generation default), SHA-256.
566            SignatureScheme::RsaPkcs1Sha256 => {
567                use aws_lc_rs::encoding::AsDer;
568                let key = aws_lc_rs::rsa::KeyPair::generate(aws_lc_rs::rsa::KeySize::Rsa2048)
569                    .map_err(|_| CryptoError::RandomnessFailed)?;
570                let pkcs8 = key.as_der().map_err(|_| CryptoError::RandomnessFailed)?;
571                return Self::import(scheme, pkcs8.as_ref());
572            }
573            _ => {
574                return Err(CryptoError::UnsupportedAlgorithm(
575                    CryptoAlgorithm::SigningKeyGeneration(scheme),
576                ));
577            }
578        }
579        .map_err(|_| CryptoError::RandomnessFailed)?;
580        Self::import(scheme, pkcs8.as_ref())
581    }
582
583    fn import(
584        scheme: SignatureScheme,
585        pkcs8_der: &[u8],
586    ) -> Result<Arc<dyn SigningKey>, CryptoError> {
587        let (kind, public_key, public_key_encoding) = match scheme {
588            SignatureScheme::Ed25519 => {
589                let key = signature::Ed25519KeyPair::from_pkcs8_maybe_unchecked(pkcs8_der)
590                    .map_err(|_| CryptoError::InvalidPrivateKey)?;
591                let public = key.public_key().as_ref().to_vec();
592                (
593                    AwsLcRsSigningKeyKind::Ed25519(key),
594                    public,
595                    PublicKeyEncoding::Ed25519Raw,
596                )
597            }
598            SignatureScheme::EcdsaP256Sha256 => {
599                let key = signature::EcdsaKeyPair::from_pkcs8(
600                    &signature::ECDSA_P256_SHA256_ASN1_SIGNING,
601                    pkcs8_der,
602                )
603                .map_err(|_| CryptoError::InvalidPrivateKey)?;
604                let public = key.public_key().as_ref().to_vec();
605                (
606                    AwsLcRsSigningKeyKind::EcdsaP256(key),
607                    public,
608                    PublicKeyEncoding::EcUncompressedPoint,
609                )
610            }
611            SignatureScheme::RsaPkcs1Sha256 => {
612                let key = signature::RsaKeyPair::from_pkcs8(pkcs8_der)
613                    .map_err(|_| CryptoError::InvalidPrivateKey)?;
614                let public = key.public_key().as_ref().to_vec();
615                (
616                    AwsLcRsSigningKeyKind::Rsa(key),
617                    public,
618                    PublicKeyEncoding::RsaPkcs1Der,
619                )
620            }
621            _ => {
622                return Err(CryptoError::UnsupportedAlgorithm(
623                    CryptoAlgorithm::SigningKeyImport(scheme),
624                ));
625            }
626        };
627        Ok(Arc::new(Self {
628            scheme,
629            kind,
630            public_key,
631            public_key_encoding,
632            pkcs8_der: SecretVec::new(pkcs8_der.to_vec()),
633        }))
634    }
635}
636
637impl SigningKey for AwsLcRsSigningKey {
638    fn supports(&self, scheme: SignatureScheme) -> bool {
639        // An RSA key with the rsaEncryption OID signs PKCS#1 v1.5 and RSASSA-PSS alike
640        // (RFC 8446 section 4.2.3, the rsa_pss_rsae schemes).
641        self.scheme == scheme
642            || (matches!(self.kind, AwsLcRsSigningKeyKind::Rsa(_))
643                && matches!(
644                    scheme,
645                    SignatureScheme::RsaPssSha256
646                        | SignatureScheme::RsaPssSha384
647                        | SignatureScheme::RsaPssSha512
648                ))
649    }
650
651    fn public_key(&self) -> PublicKey<'_> {
652        PublicKey {
653            encoding: self.public_key_encoding,
654            bytes: &self.public_key,
655        }
656    }
657
658    fn sign(&self, scheme: SignatureScheme, message: &[u8]) -> Result<Vec<u8>, CryptoError> {
659        if !self.supports(scheme) {
660            return Err(CryptoError::UnsupportedAlgorithm(
661                CryptoAlgorithm::Signature(scheme),
662            ));
663        }
664        match &self.kind {
665            AwsLcRsSigningKeyKind::Ed25519(key) => Ok(key.sign(message).as_ref().to_vec()),
666            AwsLcRsSigningKeyKind::EcdsaP256(key) => key
667                .sign(&SystemRandom::new(), message)
668                .map(|signature| signature.as_ref().to_vec())
669                .map_err(|_| CryptoError::Provider("signature generation failed".into())),
670            AwsLcRsSigningKeyKind::Rsa(key) => {
671                let encoding: &'static dyn signature::RsaEncoding = match scheme {
672                    SignatureScheme::RsaPssSha256 => &signature::RSA_PSS_SHA256,
673                    SignatureScheme::RsaPssSha384 => &signature::RSA_PSS_SHA384,
674                    SignatureScheme::RsaPssSha512 => &signature::RSA_PSS_SHA512,
675                    _ => &signature::RSA_PKCS1_SHA256,
676                };
677                let mut signature = vec![0; key.public_modulus_len()];
678                key.sign(encoding, &SystemRandom::new(), message, &mut signature)
679                    .map_err(|_| CryptoError::Provider("signature generation failed".into()))?;
680                Ok(signature)
681            }
682        }
683    }
684
685    fn to_pkcs8_der(&self) -> Result<Option<SecretVec>, CryptoError> {
686        Ok(Some(self.pkcs8_der.clone()))
687    }
688}
689
690fn agreement_algorithm(algorithm: KeyExchangeAlgorithm) -> &'static agreement::Algorithm {
691    match algorithm {
692        KeyExchangeAlgorithm::P256 => &agreement::ECDH_P256,
693        KeyExchangeAlgorithm::P384 => &agreement::ECDH_P384,
694        // The hybrid has its own type (`HybridKeyExchange`); its Diffie-Hellman half is
695        // X25519.
696        KeyExchangeAlgorithm::X25519 | KeyExchangeAlgorithm::X25519MlKem768 => &agreement::X25519,
697    }
698}
699
700fn verification_algorithm(
701    scheme: SignatureScheme,
702) -> &'static dyn signature::VerificationAlgorithm {
703    match scheme {
704        SignatureScheme::Ed25519 => &signature::ED25519,
705        SignatureScheme::EcdsaP256Sha256 => &signature::ECDSA_P256_SHA256_ASN1,
706        SignatureScheme::EcdsaP384Sha256 => &signature::ECDSA_P384_SHA256_ASN1,
707        SignatureScheme::EcdsaP384Sha384 => &signature::ECDSA_P384_SHA384_ASN1,
708        SignatureScheme::RsaPkcs1Sha1 => &signature::RSA_PKCS1_1024_8192_SHA1_FOR_LEGACY_USE_ONLY,
709        SignatureScheme::RsaPkcs1Sha256 => {
710            &signature::RSA_PKCS1_1024_8192_SHA256_FOR_LEGACY_USE_ONLY
711        }
712        SignatureScheme::RsaPkcs1Sha384 => &signature::RSA_PKCS1_2048_8192_SHA384,
713        SignatureScheme::RsaPkcs1Sha512 => {
714            &signature::RSA_PKCS1_1024_8192_SHA512_FOR_LEGACY_USE_ONLY
715        }
716        SignatureScheme::RsaPssSha256 => &signature::RSA_PSS_2048_8192_SHA256,
717        SignatureScheme::RsaPssSha384 => &signature::RSA_PSS_2048_8192_SHA384,
718        SignatureScheme::RsaPssSha512 => &signature::RSA_PSS_2048_8192_SHA512,
719    }
720}
721
722fn verify_public_key_encoding(
723    scheme: SignatureScheme,
724    encoding: PublicKeyEncoding,
725) -> Result<(), CryptoError> {
726    let valid = matches!(
727        (scheme, encoding),
728        (SignatureScheme::Ed25519, PublicKeyEncoding::Ed25519Raw)
729            | (
730                SignatureScheme::EcdsaP256Sha256
731                    | SignatureScheme::EcdsaP384Sha256
732                    | SignatureScheme::EcdsaP384Sha384,
733                PublicKeyEncoding::EcUncompressedPoint
734            )
735            | (
736                SignatureScheme::RsaPkcs1Sha1
737                    | SignatureScheme::RsaPkcs1Sha256
738                    | SignatureScheme::RsaPkcs1Sha384
739                    | SignatureScheme::RsaPkcs1Sha512
740                    | SignatureScheme::RsaPssSha256
741                    | SignatureScheme::RsaPssSha384
742                    | SignatureScheme::RsaPssSha512,
743                PublicKeyEncoding::RsaPkcs1Der
744            )
745    );
746    if valid {
747        Ok(())
748    } else {
749        Err(CryptoError::InvalidPublicKey)
750    }
751}