rtci-crypto 0.2.0

Provider-neutral cryptography interface of a sans-I/O WebRTC stack, with ring and aws-lc-rs providers
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
use std::sync::Arc;

use aws_lc_rs::rand::SystemRandom;
use aws_lc_rs::signature::{self, KeyPair};
use aws_lc_rs::{aead, agreement, digest, hmac};

use crate::common;
use crate::{
    ActiveKeyExchange, AeadAlgorithm, AeadCipher, BlockCipherAlgorithm, CbcAlgorithm, CbcCipher,
    CryptoAlgorithm, CryptoError, HEADER_MASK_LEN, HEADER_MASK_SAMPLE_LEN, HashAlgorithm,
    HeaderMask, HeaderMaskAlgorithm, HmacAlgorithm, KeyExchangeAlgorithm, Mac, PublicKey,
    PublicKeyEncoding, RTCCrypto, RTCCryptoProvider, RTCRandom, SecretVec, SignatureScheme,
    SigningKey, StreamCipher, StreamCipherAlgorithm, constant_time_eq,
};

/// The built-in AWS-LC-RS provider bundle.
#[derive(Default)]
pub struct AwsLcRsProvider {
    crypto: AwsLcRsCrypto,
    random: AwsLcRsRandom,
}

impl AwsLcRsProvider {
    /// Creates an AWS-LC-RS provider.
    #[must_use]
    pub const fn new() -> Self {
        Self {
            crypto: AwsLcRsCrypto,
            random: AwsLcRsRandom,
        }
    }
}

impl RTCCryptoProvider for AwsLcRsProvider {
    fn name(&self) -> &'static str {
        "aws-lc-rs"
    }

    fn crypto(&self) -> &dyn RTCCrypto {
        &self.crypto
    }

    fn random(&self) -> &dyn RTCRandom {
        &self.random
    }
}

/// AWS-LC-RS-backed operations, with RustCrypto fallbacks for primitives that are not exposed by
/// its stable high-level API: MD5, AES block/CTR/CBC, and AES-CCM.
#[derive(Default)]
pub struct AwsLcRsCrypto;

/// AWS-LC-RS's operating-system-backed secure random source.
#[derive(Default)]
pub struct AwsLcRsRandom;

impl RTCRandom for AwsLcRsRandom {
    fn fill(&self, output: &mut [u8]) -> Result<(), CryptoError> {
        common::fill_random(output)
    }

    fn fill_secret(&self, output: &mut [u8]) -> Result<(), CryptoError> {
        use aws_lc_rs::rand::SecureRandom;
        SystemRandom::new()
            .fill(output)
            .map_err(|_| CryptoError::RandomnessFailed)
    }
}

impl RTCCrypto for AwsLcRsCrypto {
    fn supports(&self, algorithm: CryptoAlgorithm) -> bool {
        matches!(
            algorithm,
            CryptoAlgorithm::Hash(
                HashAlgorithm::Md5
                    | HashAlgorithm::Sha256
                    | HashAlgorithm::Sha1
                    | HashAlgorithm::Sha224
                    | HashAlgorithm::Sha384
                    | HashAlgorithm::Sha512
            ) | CryptoAlgorithm::Hmac(
                HmacAlgorithm::Sha1
                    | HmacAlgorithm::Sha256
                    | HmacAlgorithm::Sha384
                    | HmacAlgorithm::Sha512
            ) | CryptoAlgorithm::HeaderMask(
                HeaderMaskAlgorithm::Aes128
                    | HeaderMaskAlgorithm::Aes256
                    | HeaderMaskAlgorithm::ChaCha20
            ) | CryptoAlgorithm::Aead(
                AeadAlgorithm::Aes128Gcm
                    | AeadAlgorithm::Aes256Gcm
                    | AeadAlgorithm::Aes128Ccm
                    | AeadAlgorithm::Aes128Ccm8
                    | AeadAlgorithm::ChaCha20Poly1305,
            ) | CryptoAlgorithm::StreamCipher(
                StreamCipherAlgorithm::Aes128Ctr
                    | StreamCipherAlgorithm::Aes256Ctr
                    | StreamCipherAlgorithm::Aes192Ctr,
            ) | CryptoAlgorithm::BlockCipher(
                BlockCipherAlgorithm::Aes128
                    | BlockCipherAlgorithm::Aes256
                    | BlockCipherAlgorithm::Aes192,
            ) | CryptoAlgorithm::Cbc(CbcAlgorithm::Aes256Cbc)
                | CryptoAlgorithm::KeyExchange(
                    KeyExchangeAlgorithm::P256
                        | KeyExchangeAlgorithm::P384
                        | KeyExchangeAlgorithm::X25519
                        | KeyExchangeAlgorithm::X25519MlKem768,
                )
                | CryptoAlgorithm::Signature(
                    SignatureScheme::Ed25519
                        | SignatureScheme::EcdsaP256Sha256
                        | SignatureScheme::EcdsaP384Sha256
                        | SignatureScheme::EcdsaP384Sha384
                        | SignatureScheme::RsaPkcs1Sha1
                        | SignatureScheme::RsaPkcs1Sha256
                        | SignatureScheme::RsaPkcs1Sha384
                        | SignatureScheme::RsaPkcs1Sha512
                        | SignatureScheme::RsaPssSha256
                        | SignatureScheme::RsaPssSha384
                        | SignatureScheme::RsaPssSha512,
                )
                | CryptoAlgorithm::SigningKeyGeneration(
                    SignatureScheme::Ed25519
                        | SignatureScheme::EcdsaP256Sha256
                        | SignatureScheme::RsaPkcs1Sha256,
                )
                | CryptoAlgorithm::SigningKeyImport(
                    SignatureScheme::Ed25519
                        | SignatureScheme::EcdsaP256Sha256
                        | SignatureScheme::RsaPkcs1Sha256,
                )
        )
    }

    fn hash(&self, algorithm: HashAlgorithm, data: &[u8]) -> Result<Vec<u8>, CryptoError> {
        match algorithm {
            HashAlgorithm::Md5 => Ok(common::md5(data)),
            HashAlgorithm::Sha256 => Ok(digest::digest(&digest::SHA256, data).as_ref().to_vec()),
            HashAlgorithm::Sha1 => Ok(digest::digest(&digest::SHA1_FOR_LEGACY_USE_ONLY, data)
                .as_ref()
                .to_vec()),
            HashAlgorithm::Sha224 => Ok(digest::digest(&digest::SHA224, data).as_ref().to_vec()),
            HashAlgorithm::Sha384 => Ok(digest::digest(&digest::SHA384, data).as_ref().to_vec()),
            HashAlgorithm::Sha512 => Ok(digest::digest(&digest::SHA512, data).as_ref().to_vec()),
        }
    }

    fn new_hmac(&self, algorithm: HmacAlgorithm, key: &[u8]) -> Result<Box<dyn Mac>, CryptoError> {
        Ok(Box::new(AwsLcRsHmac {
            key: hmac::Key::new(hmac_algorithm(algorithm), key),
            output_len: algorithm.output_len(),
        }))
    }

    fn block_encrypt(
        &self,
        algorithm: BlockCipherAlgorithm,
        key: &[u8],
        block: &mut [u8],
    ) -> Result<(), CryptoError> {
        common::block_encrypt(algorithm, key, block)
    }

    fn new_stream_cipher(
        &self,
        algorithm: StreamCipherAlgorithm,
        key: &[u8],
    ) -> Result<Box<dyn StreamCipher>, CryptoError> {
        common::new_stream_cipher(algorithm, key)
    }

    fn new_aead(
        &self,
        algorithm: AeadAlgorithm,
        key: &[u8],
    ) -> Result<Box<dyn AeadCipher>, CryptoError> {
        match algorithm {
            AeadAlgorithm::Aes128Ccm | AeadAlgorithm::Aes128Ccm8 => common::new_ccm(algorithm, key),
            AeadAlgorithm::Aes128Gcm => AwsLcRsAead::create(&aead::AES_128_GCM, key),
            AeadAlgorithm::Aes256Gcm => AwsLcRsAead::create(&aead::AES_256_GCM, key),
            AeadAlgorithm::ChaCha20Poly1305 => AwsLcRsAead::create(&aead::CHACHA20_POLY1305, key),
        }
    }

    fn new_header_mask(
        &self,
        algorithm: HeaderMaskAlgorithm,
        key: &[u8],
    ) -> Result<Box<dyn HeaderMask>, CryptoError> {
        common::check_key_len(algorithm.key_len(), key.len())?;
        let backend_algorithm = match algorithm {
            HeaderMaskAlgorithm::Aes128 => &aead::quic::AES_128,
            HeaderMaskAlgorithm::Aes256 => &aead::quic::AES_256,
            HeaderMaskAlgorithm::ChaCha20 => &aead::quic::CHACHA20,
        };
        let key = aead::quic::HeaderProtectionKey::new(backend_algorithm, key)
            .map_err(|_| CryptoError::InvalidPrivateKey)?;
        Ok(Box::new(AwsLcRsHeaderMask { key }))
    }

    fn new_cbc(
        &self,
        algorithm: CbcAlgorithm,
        key: &[u8],
    ) -> Result<Box<dyn CbcCipher>, CryptoError> {
        common::new_cbc(algorithm, key)
    }

    fn start_key_exchange(
        &self,
        algorithm: KeyExchangeAlgorithm,
    ) -> Result<Box<dyn ActiveKeyExchange>, CryptoError> {
        if algorithm == KeyExchangeAlgorithm::X25519MlKem768 {
            return HybridKeyExchange::start();
        }
        AwsLcRsKeyExchange::start(algorithm)
    }

    fn key_exchange_respond(
        &self,
        algorithm: KeyExchangeAlgorithm,
        peer_share: &[u8],
    ) -> Result<(Vec<u8>, SecretVec), CryptoError> {
        if algorithm == KeyExchangeAlgorithm::X25519MlKem768 {
            return HybridKeyExchange::respond(peer_share);
        }
        let exchange = self.start_key_exchange(algorithm)?;
        let share = exchange.public_key().to_vec();
        let secret = exchange.complete(peer_share)?;
        Ok((share, secret))
    }

    fn generate_signing_key(
        &self,
        scheme: SignatureScheme,
    ) -> Result<Arc<dyn SigningKey>, CryptoError> {
        AwsLcRsSigningKey::generate(scheme)
    }

    fn import_signing_key(
        &self,
        scheme: SignatureScheme,
        pkcs8_der: &[u8],
    ) -> Result<Arc<dyn SigningKey>, CryptoError> {
        AwsLcRsSigningKey::import(scheme, pkcs8_der)
    }

    fn verify_signature(
        &self,
        scheme: SignatureScheme,
        public_key: PublicKey<'_>,
        message: &[u8],
        signature: &[u8],
    ) -> Result<(), CryptoError> {
        verify_public_key_encoding(scheme, public_key.encoding)?;
        signature::UnparsedPublicKey::new(verification_algorithm(scheme), public_key.bytes)
            .verify(message, signature)
            .map_err(|_| CryptoError::InvalidSignature)
    }
}

/// A keyed HMAC holding an `aws_lc_rs::hmac::Key`.
///
/// `Key::new` performs the ipad/opad derivation; `Context::with_key` only clones the resulting
/// state. Keeping the key here is what moves that derivation off the per-packet path.
struct AwsLcRsHmac {
    key: hmac::Key,
    output_len: usize,
}

impl Mac for AwsLcRsHmac {
    fn output_len(&self) -> usize {
        self.output_len
    }

    fn sign(&mut self, input: &[&[u8]], output: &mut [u8]) -> Result<(), CryptoError> {
        common::check_tag_len(self.output_len, output.len())?;
        let mut context = hmac::Context::with_key(&self.key);
        for part in input {
            context.update(part);
        }
        output.copy_from_slice(context.sign().as_ref());
        Ok(())
    }

    fn verify(&mut self, input: &[&[u8]], expected: &[u8]) -> Result<(), CryptoError> {
        common::check_tag_len(self.output_len, expected.len())?;
        let mut actual = vec![0; self.output_len];
        self.sign(input, &mut actual)?;
        if constant_time_eq(&actual, expected) {
            Ok(())
        } else {
            Err(CryptoError::AuthenticationFailed)
        }
    }
}

fn hmac_algorithm(algorithm: HmacAlgorithm) -> hmac::Algorithm {
    match algorithm {
        HmacAlgorithm::Sha1 => hmac::HMAC_SHA1_FOR_LEGACY_USE_ONLY,
        HmacAlgorithm::Sha256 => hmac::HMAC_SHA256,
        HmacAlgorithm::Sha512 => hmac::HMAC_SHA512,
        HmacAlgorithm::Sha384 => hmac::HMAC_SHA384,
    }
}

/// A record-number mask generator on the backend's QUIC header-protection key, which is the
/// computation RFC 9147 section 4.2.3 defines (AES-ECB of the sample, or the ChaCha20 block
/// function keyed by it).
struct AwsLcRsHeaderMask {
    key: aead::quic::HeaderProtectionKey,
}

impl HeaderMask for AwsLcRsHeaderMask {
    fn mask(
        &mut self,
        sample: &[u8; HEADER_MASK_SAMPLE_LEN],
    ) -> Result<[u8; HEADER_MASK_LEN], CryptoError> {
        self.key
            .new_mask(sample)
            .map_err(|_| CryptoError::Provider("header mask generation failed".into()))
    }
}

struct AwsLcRsAead {
    key: aead::LessSafeKey,
}

impl AwsLcRsAead {
    fn create(
        algorithm: &'static aead::Algorithm,
        key: &[u8],
    ) -> Result<Box<dyn AeadCipher>, CryptoError> {
        common::check_key_len(algorithm.key_len(), key.len())?;
        let key = aead::UnboundKey::new(algorithm, key)
            .map(aead::LessSafeKey::new)
            .map_err(|_| CryptoError::InvalidPrivateKey)?;
        Ok(Box::new(Self { key }))
    }
}

impl AeadCipher for AwsLcRsAead {
    fn tag_len(&self) -> usize {
        16
    }

    fn seal_in_place(
        &mut self,
        nonce: &[u8],
        aad: &[u8],
        plaintext_and_ciphertext: &mut [u8],
        tag_out: &mut [u8],
    ) -> Result<(), CryptoError> {
        common::check_nonce_len(12, nonce.len())?;
        common::check_tag_len(self.tag_len(), tag_out.len())?;
        let nonce = aead::Nonce::try_assume_unique_for_key(nonce).map_err(|_| {
            CryptoError::InvalidNonceLength {
                expected: 12,
                actual: nonce.len(),
            }
        })?;
        let tag = self
            .key
            .seal_in_place_separate_tag(nonce, aead::Aad::from(aad), plaintext_and_ciphertext)
            .map_err(|_| CryptoError::AuthenticationFailed)?;
        tag_out.copy_from_slice(tag.as_ref());
        Ok(())
    }

    fn open_in_place(
        &mut self,
        nonce: &[u8],
        aad: &[u8],
        ciphertext_and_plaintext: &mut [u8],
        tag: &[u8],
    ) -> Result<(), CryptoError> {
        common::check_nonce_len(12, nonce.len())?;
        common::check_tag_len(self.tag_len(), tag.len())?;
        let nonce = aead::Nonce::try_assume_unique_for_key(nonce).map_err(|_| {
            CryptoError::InvalidNonceLength {
                expected: 12,
                actual: nonce.len(),
            }
        })?;
        self.key
            .open_in_place_separate_tag(nonce, aead::Aad::from(aad), tag, ciphertext_and_plaintext)
            .map(|_| ())
            .map_err(|_| CryptoError::AuthenticationFailed)
    }
}

/// The lengths of X25519MLKEM768 (draft-ietf-tls-ecdhe-mlkem section 4.2).
const ML_KEM_768_ENCAPSULATION_KEY_LEN: usize = 1184;
const ML_KEM_768_CIPHERTEXT_LEN: usize = 1088;
const X25519_LEN: usize = 32;

/// The initiator's half of X25519MLKEM768: an ML-KEM-768 decapsulation key and an X25519
/// private key. Its share is the encapsulation key followed by the X25519 public key.
struct HybridKeyExchange {
    decapsulation_key: aws_lc_rs::kem::DecapsulationKey,
    x25519: agreement::PrivateKey,
    share: Vec<u8>,
}

impl HybridKeyExchange {
    fn failure(what: &'static str) -> CryptoError {
        CryptoError::Provider(what.into())
    }

    fn start() -> Result<Box<dyn ActiveKeyExchange>, CryptoError> {
        let decapsulation_key =
            aws_lc_rs::kem::DecapsulationKey::generate(&aws_lc_rs::kem::ML_KEM_768)
                .map_err(|_| CryptoError::RandomnessFailed)?;
        let encapsulation_key = decapsulation_key
            .encapsulation_key()
            .and_then(|key| key.key_bytes())
            .map_err(|_| Self::failure("ML-KEM key generation failed"))?;
        let x25519 = agreement::PrivateKey::generate(&agreement::X25519)
            .map_err(|_| CryptoError::RandomnessFailed)?;
        let x25519_public = x25519
            .compute_public_key()
            .map_err(|_| Self::failure("key exchange public-key generation failed"))?;
        let mut share = encapsulation_key.as_ref().to_vec();
        share.extend_from_slice(x25519_public.as_ref());
        Ok(Box::new(Self {
            decapsulation_key,
            x25519,
            share,
        }))
    }

    /// The responder's half: encapsulates to the initiator's ML-KEM key and agrees with its
    /// X25519 key. The share is the ciphertext followed by an X25519 public key, the secret
    /// the ML-KEM shared secret followed by the X25519 one.
    fn respond(peer_share: &[u8]) -> Result<(Vec<u8>, SecretVec), CryptoError> {
        if peer_share.len() != ML_KEM_768_ENCAPSULATION_KEY_LEN + X25519_LEN {
            return Err(CryptoError::InvalidPublicKey);
        }
        let (encapsulation_key, peer_x25519) =
            peer_share.split_at(ML_KEM_768_ENCAPSULATION_KEY_LEN);
        let encapsulation_key =
            aws_lc_rs::kem::EncapsulationKey::new(&aws_lc_rs::kem::ML_KEM_768, encapsulation_key)
                .map_err(|_| CryptoError::InvalidPublicKey)?;
        let (ciphertext, kem_secret) = encapsulation_key
            .encapsulate()
            .map_err(|_| CryptoError::InvalidPublicKey)?;
        let x25519 = agreement::PrivateKey::generate(&agreement::X25519)
            .map_err(|_| CryptoError::RandomnessFailed)?;
        let x25519_public = x25519
            .compute_public_key()
            .map_err(|_| Self::failure("key exchange public-key generation failed"))?;
        let mut secret = kem_secret.as_ref().to_vec();
        agreement::agree(
            &x25519,
            agreement::UnparsedPublicKey::new(&agreement::X25519, peer_x25519),
            CryptoError::InvalidPublicKey,
            |x25519_secret| {
                secret.extend_from_slice(x25519_secret);
                Ok(())
            },
        )?;
        let mut share = ciphertext.as_ref().to_vec();
        share.extend_from_slice(x25519_public.as_ref());
        Ok((share, SecretVec::new(secret)))
    }
}

impl ActiveKeyExchange for HybridKeyExchange {
    fn algorithm(&self) -> KeyExchangeAlgorithm {
        KeyExchangeAlgorithm::X25519MlKem768
    }

    fn public_key(&self) -> &[u8] {
        &self.share
    }

    fn complete(self: Box<Self>, peer_share: &[u8]) -> Result<SecretVec, CryptoError> {
        if peer_share.len() != ML_KEM_768_CIPHERTEXT_LEN + X25519_LEN {
            return Err(CryptoError::InvalidPublicKey);
        }
        let (ciphertext, peer_x25519) = peer_share.split_at(ML_KEM_768_CIPHERTEXT_LEN);
        let kem_secret = self
            .decapsulation_key
            .decapsulate(ciphertext.into())
            .map_err(|_| CryptoError::InvalidPublicKey)?;
        let mut secret = kem_secret.as_ref().to_vec();
        agreement::agree(
            &self.x25519,
            agreement::UnparsedPublicKey::new(&agreement::X25519, peer_x25519),
            CryptoError::InvalidPublicKey,
            |x25519_secret| {
                secret.extend_from_slice(x25519_secret);
                Ok(())
            },
        )?;
        Ok(SecretVec::new(secret))
    }
}

struct AwsLcRsKeyExchange {
    algorithm: KeyExchangeAlgorithm,
    backend_algorithm: &'static agreement::Algorithm,
    private_key: agreement::PrivateKey,
    public_key: Vec<u8>,
}

impl AwsLcRsKeyExchange {
    fn start(algorithm: KeyExchangeAlgorithm) -> Result<Box<dyn ActiveKeyExchange>, CryptoError> {
        let backend_algorithm = agreement_algorithm(algorithm);
        let private_key = agreement::PrivateKey::generate(backend_algorithm)
            .map_err(|_| CryptoError::RandomnessFailed)?;
        let public_key = private_key
            .compute_public_key()
            .map_err(|_| CryptoError::Provider("key exchange public-key generation failed".into()))?
            .as_ref()
            .to_vec();
        Ok(Box::new(Self {
            algorithm,
            backend_algorithm,
            private_key,
            public_key,
        }))
    }
}

impl ActiveKeyExchange for AwsLcRsKeyExchange {
    fn algorithm(&self) -> KeyExchangeAlgorithm {
        self.algorithm
    }

    fn public_key(&self) -> &[u8] {
        &self.public_key
    }

    fn complete(self: Box<Self>, peer_public_key: &[u8]) -> Result<SecretVec, CryptoError> {
        let peer = agreement::UnparsedPublicKey::new(self.backend_algorithm, peer_public_key);
        agreement::agree(
            &self.private_key,
            peer,
            CryptoError::InvalidPublicKey,
            |secret| Ok(SecretVec::new(secret.to_vec())),
        )
    }
}

enum AwsLcRsSigningKeyKind {
    Ed25519(signature::Ed25519KeyPair),
    EcdsaP256(signature::EcdsaKeyPair),
    Rsa(signature::RsaKeyPair),
}

struct AwsLcRsSigningKey {
    scheme: SignatureScheme,
    kind: AwsLcRsSigningKeyKind,
    public_key: Vec<u8>,
    public_key_encoding: PublicKeyEncoding,
    pkcs8_der: SecretVec,
}

impl AwsLcRsSigningKey {
    fn generate(scheme: SignatureScheme) -> Result<Arc<dyn SigningKey>, CryptoError> {
        let rng = SystemRandom::new();
        let pkcs8 = match scheme {
            SignatureScheme::Ed25519 => signature::Ed25519KeyPair::generate_pkcs8(&rng),
            SignatureScheme::EcdsaP256Sha256 => signature::EcdsaKeyPair::generate_pkcs8(
                &signature::ECDSA_P256_SHA256_ASN1_SIGNING,
                &rng,
            ),
            // W3C webrtc-pc 4.9 generateCertificate: RSASSA-PKCS1-v1_5 with a 2048-bit
            // modulus, public exponent 65537 (AWS-LC's key generation default), SHA-256.
            SignatureScheme::RsaPkcs1Sha256 => {
                use aws_lc_rs::encoding::AsDer;
                let key = aws_lc_rs::rsa::KeyPair::generate(aws_lc_rs::rsa::KeySize::Rsa2048)
                    .map_err(|_| CryptoError::RandomnessFailed)?;
                let pkcs8 = key.as_der().map_err(|_| CryptoError::RandomnessFailed)?;
                return Self::import(scheme, pkcs8.as_ref());
            }
            _ => {
                return Err(CryptoError::UnsupportedAlgorithm(
                    CryptoAlgorithm::SigningKeyGeneration(scheme),
                ));
            }
        }
        .map_err(|_| CryptoError::RandomnessFailed)?;
        Self::import(scheme, pkcs8.as_ref())
    }

    fn import(
        scheme: SignatureScheme,
        pkcs8_der: &[u8],
    ) -> Result<Arc<dyn SigningKey>, CryptoError> {
        let (kind, public_key, public_key_encoding) = match scheme {
            SignatureScheme::Ed25519 => {
                let key = signature::Ed25519KeyPair::from_pkcs8_maybe_unchecked(pkcs8_der)
                    .map_err(|_| CryptoError::InvalidPrivateKey)?;
                let public = key.public_key().as_ref().to_vec();
                (
                    AwsLcRsSigningKeyKind::Ed25519(key),
                    public,
                    PublicKeyEncoding::Ed25519Raw,
                )
            }
            SignatureScheme::EcdsaP256Sha256 => {
                let key = signature::EcdsaKeyPair::from_pkcs8(
                    &signature::ECDSA_P256_SHA256_ASN1_SIGNING,
                    pkcs8_der,
                )
                .map_err(|_| CryptoError::InvalidPrivateKey)?;
                let public = key.public_key().as_ref().to_vec();
                (
                    AwsLcRsSigningKeyKind::EcdsaP256(key),
                    public,
                    PublicKeyEncoding::EcUncompressedPoint,
                )
            }
            SignatureScheme::RsaPkcs1Sha256 => {
                let key = signature::RsaKeyPair::from_pkcs8(pkcs8_der)
                    .map_err(|_| CryptoError::InvalidPrivateKey)?;
                let public = key.public_key().as_ref().to_vec();
                (
                    AwsLcRsSigningKeyKind::Rsa(key),
                    public,
                    PublicKeyEncoding::RsaPkcs1Der,
                )
            }
            _ => {
                return Err(CryptoError::UnsupportedAlgorithm(
                    CryptoAlgorithm::SigningKeyImport(scheme),
                ));
            }
        };
        Ok(Arc::new(Self {
            scheme,
            kind,
            public_key,
            public_key_encoding,
            pkcs8_der: SecretVec::new(pkcs8_der.to_vec()),
        }))
    }
}

impl SigningKey for AwsLcRsSigningKey {
    fn supports(&self, scheme: SignatureScheme) -> bool {
        // An RSA key with the rsaEncryption OID signs PKCS#1 v1.5 and RSASSA-PSS alike
        // (RFC 8446 section 4.2.3, the rsa_pss_rsae schemes).
        self.scheme == scheme
            || (matches!(self.kind, AwsLcRsSigningKeyKind::Rsa(_))
                && matches!(
                    scheme,
                    SignatureScheme::RsaPssSha256
                        | SignatureScheme::RsaPssSha384
                        | SignatureScheme::RsaPssSha512
                ))
    }

    fn public_key(&self) -> PublicKey<'_> {
        PublicKey {
            encoding: self.public_key_encoding,
            bytes: &self.public_key,
        }
    }

    fn sign(&self, scheme: SignatureScheme, message: &[u8]) -> Result<Vec<u8>, CryptoError> {
        if !self.supports(scheme) {
            return Err(CryptoError::UnsupportedAlgorithm(
                CryptoAlgorithm::Signature(scheme),
            ));
        }
        match &self.kind {
            AwsLcRsSigningKeyKind::Ed25519(key) => Ok(key.sign(message).as_ref().to_vec()),
            AwsLcRsSigningKeyKind::EcdsaP256(key) => key
                .sign(&SystemRandom::new(), message)
                .map(|signature| signature.as_ref().to_vec())
                .map_err(|_| CryptoError::Provider("signature generation failed".into())),
            AwsLcRsSigningKeyKind::Rsa(key) => {
                let encoding: &'static dyn signature::RsaEncoding = match scheme {
                    SignatureScheme::RsaPssSha256 => &signature::RSA_PSS_SHA256,
                    SignatureScheme::RsaPssSha384 => &signature::RSA_PSS_SHA384,
                    SignatureScheme::RsaPssSha512 => &signature::RSA_PSS_SHA512,
                    _ => &signature::RSA_PKCS1_SHA256,
                };
                let mut signature = vec![0; key.public_modulus_len()];
                key.sign(encoding, &SystemRandom::new(), message, &mut signature)
                    .map_err(|_| CryptoError::Provider("signature generation failed".into()))?;
                Ok(signature)
            }
        }
    }

    fn to_pkcs8_der(&self) -> Result<Option<SecretVec>, CryptoError> {
        Ok(Some(self.pkcs8_der.clone()))
    }
}

fn agreement_algorithm(algorithm: KeyExchangeAlgorithm) -> &'static agreement::Algorithm {
    match algorithm {
        KeyExchangeAlgorithm::P256 => &agreement::ECDH_P256,
        KeyExchangeAlgorithm::P384 => &agreement::ECDH_P384,
        // The hybrid has its own type (`HybridKeyExchange`); its Diffie-Hellman half is
        // X25519.
        KeyExchangeAlgorithm::X25519 | KeyExchangeAlgorithm::X25519MlKem768 => &agreement::X25519,
    }
}

fn verification_algorithm(
    scheme: SignatureScheme,
) -> &'static dyn signature::VerificationAlgorithm {
    match scheme {
        SignatureScheme::Ed25519 => &signature::ED25519,
        SignatureScheme::EcdsaP256Sha256 => &signature::ECDSA_P256_SHA256_ASN1,
        SignatureScheme::EcdsaP384Sha256 => &signature::ECDSA_P384_SHA256_ASN1,
        SignatureScheme::EcdsaP384Sha384 => &signature::ECDSA_P384_SHA384_ASN1,
        SignatureScheme::RsaPkcs1Sha1 => &signature::RSA_PKCS1_1024_8192_SHA1_FOR_LEGACY_USE_ONLY,
        SignatureScheme::RsaPkcs1Sha256 => {
            &signature::RSA_PKCS1_1024_8192_SHA256_FOR_LEGACY_USE_ONLY
        }
        SignatureScheme::RsaPkcs1Sha384 => &signature::RSA_PKCS1_2048_8192_SHA384,
        SignatureScheme::RsaPkcs1Sha512 => {
            &signature::RSA_PKCS1_1024_8192_SHA512_FOR_LEGACY_USE_ONLY
        }
        SignatureScheme::RsaPssSha256 => &signature::RSA_PSS_2048_8192_SHA256,
        SignatureScheme::RsaPssSha384 => &signature::RSA_PSS_2048_8192_SHA384,
        SignatureScheme::RsaPssSha512 => &signature::RSA_PSS_2048_8192_SHA512,
    }
}

fn verify_public_key_encoding(
    scheme: SignatureScheme,
    encoding: PublicKeyEncoding,
) -> Result<(), CryptoError> {
    let valid = matches!(
        (scheme, encoding),
        (SignatureScheme::Ed25519, PublicKeyEncoding::Ed25519Raw)
            | (
                SignatureScheme::EcdsaP256Sha256
                    | SignatureScheme::EcdsaP384Sha256
                    | SignatureScheme::EcdsaP384Sha384,
                PublicKeyEncoding::EcUncompressedPoint
            )
            | (
                SignatureScheme::RsaPkcs1Sha1
                    | SignatureScheme::RsaPkcs1Sha256
                    | SignatureScheme::RsaPkcs1Sha384
                    | SignatureScheme::RsaPkcs1Sha512
                    | SignatureScheme::RsaPssSha256
                    | SignatureScheme::RsaPssSha384
                    | SignatureScheme::RsaPssSha512,
                PublicKeyEncoding::RsaPkcs1Der
            )
    );
    if valid {
        Ok(())
    } else {
        Err(CryptoError::InvalidPublicKey)
    }
}