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