1use crate::common;
2use crate::common::check_tag_len;
3use crate::{
4 ActiveKeyExchange, AeadAlgorithm, AeadCipher, BlockCipherAlgorithm, CbcAlgorithm, CbcCipher,
5 CryptoAlgorithm, CryptoError, HEADER_MASK_LEN, HEADER_MASK_SAMPLE_LEN, HashAlgorithm,
6 HeaderMask, HeaderMaskAlgorithm, HmacAlgorithm, KeyExchangeAlgorithm, Mac, PublicKey,
7 PublicKeyEncoding, RTCCrypto, RTCCryptoProvider, RTCRandom, SecretVec, SignatureScheme,
8 SigningKey, StreamCipher, StreamCipherAlgorithm, constant_time_eq,
9};
10use ::hmac::Mac as RustCryptoMac;
11use ring::aead;
12use ring::agreement;
13use ring::digest;
14use ring::hmac;
15use ring::rand::SystemRandom;
16use ring::signature::{self, KeyPair};
17use sha1::Sha1;
18use std::mem::MaybeUninit;
19use std::sync::Arc;
20use std::sync::atomic::{Ordering, compiler_fence};
21
22#[derive(Default)]
24pub struct RingProvider {
25 crypto: RingCrypto,
26 random: RingRandom,
27}
28
29impl RingProvider {
30 #[must_use]
32 pub const fn new() -> Self {
33 Self {
34 crypto: RingCrypto,
35 random: RingRandom,
36 }
37 }
38}
39
40impl RTCCryptoProvider for RingProvider {
41 fn name(&self) -> &'static str {
42 "ring"
43 }
44
45 fn crypto(&self) -> &dyn RTCCrypto {
46 &self.crypto
47 }
48
49 fn random(&self) -> &dyn RTCRandom {
50 &self.random
51 }
52}
53
54#[derive(Default)]
57pub struct RingCrypto;
58
59#[derive(Default)]
61pub struct RingRandom;
62
63impl RTCRandom for RingRandom {
64 fn fill(&self, output: &mut [u8]) -> Result<(), CryptoError> {
65 common::fill_random(output)
66 }
67
68 fn fill_secret(&self, output: &mut [u8]) -> Result<(), CryptoError> {
69 use ring::rand::SecureRandom;
70 SystemRandom::new()
71 .fill(output)
72 .map_err(|_| CryptoError::RandomnessFailed)
73 }
74}
75
76impl RTCCrypto for RingCrypto {
77 fn supports(&self, algorithm: CryptoAlgorithm) -> bool {
78 matches!(
79 algorithm,
80 CryptoAlgorithm::Hash(
81 HashAlgorithm::Md5
82 | HashAlgorithm::Sha256
83 | HashAlgorithm::Sha1
84 | HashAlgorithm::Sha224
85 | HashAlgorithm::Sha384
86 | HashAlgorithm::Sha512
87 ) | CryptoAlgorithm::Hmac(
88 HmacAlgorithm::Sha1
89 | HmacAlgorithm::Sha256
90 | HmacAlgorithm::Sha384
91 | HmacAlgorithm::Sha512
92 ) | CryptoAlgorithm::HeaderMask(
93 HeaderMaskAlgorithm::Aes128
94 | HeaderMaskAlgorithm::Aes256
95 | HeaderMaskAlgorithm::ChaCha20
96 ) | CryptoAlgorithm::Aead(
97 AeadAlgorithm::Aes128Gcm
98 | AeadAlgorithm::Aes256Gcm
99 | AeadAlgorithm::Aes128Ccm
100 | AeadAlgorithm::Aes128Ccm8
101 | AeadAlgorithm::ChaCha20Poly1305,
102 ) | CryptoAlgorithm::StreamCipher(
103 StreamCipherAlgorithm::Aes128Ctr
104 | StreamCipherAlgorithm::Aes256Ctr
105 | StreamCipherAlgorithm::Aes192Ctr,
106 ) | CryptoAlgorithm::BlockCipher(
107 BlockCipherAlgorithm::Aes128
108 | BlockCipherAlgorithm::Aes256
109 | BlockCipherAlgorithm::Aes192,
110 ) | CryptoAlgorithm::Cbc(CbcAlgorithm::Aes256Cbc)
111 | CryptoAlgorithm::KeyExchange(
112 KeyExchangeAlgorithm::P256
113 | KeyExchangeAlgorithm::P384
114 | KeyExchangeAlgorithm::X25519,
115 )
116 | CryptoAlgorithm::Signature(
117 SignatureScheme::Ed25519
118 | SignatureScheme::EcdsaP256Sha256
119 | SignatureScheme::EcdsaP384Sha256
120 | SignatureScheme::EcdsaP384Sha384
121 | SignatureScheme::RsaPkcs1Sha1
122 | SignatureScheme::RsaPkcs1Sha256
123 | SignatureScheme::RsaPkcs1Sha384
124 | SignatureScheme::RsaPkcs1Sha512
125 | SignatureScheme::RsaPssSha256
126 | SignatureScheme::RsaPssSha384
127 | SignatureScheme::RsaPssSha512,
128 )
129 | CryptoAlgorithm::SigningKeyGeneration(
130 SignatureScheme::Ed25519 | SignatureScheme::EcdsaP256Sha256,
131 )
132 | CryptoAlgorithm::SigningKeyImport(
133 SignatureScheme::Ed25519
134 | SignatureScheme::EcdsaP256Sha256
135 | SignatureScheme::RsaPkcs1Sha256,
136 )
137 )
138 }
139
140 fn hash(&self, algorithm: HashAlgorithm, data: &[u8]) -> Result<Vec<u8>, CryptoError> {
141 match algorithm {
142 HashAlgorithm::Md5 => Ok(common::md5(data)),
143 HashAlgorithm::Sha256 => Ok(digest::digest(&digest::SHA256, data).as_ref().to_vec()),
144 HashAlgorithm::Sha1 => Ok(digest::digest(&digest::SHA1_FOR_LEGACY_USE_ONLY, data)
145 .as_ref()
146 .to_vec()),
147 HashAlgorithm::Sha224 => Ok(common::sha224(data)),
149 HashAlgorithm::Sha384 => Ok(digest::digest(&digest::SHA384, data).as_ref().to_vec()),
150 HashAlgorithm::Sha512 => Ok(digest::digest(&digest::SHA512, data).as_ref().to_vec()),
151 }
152 }
153
154 fn new_hmac(&self, algorithm: HmacAlgorithm, key: &[u8]) -> Result<Box<dyn Mac>, CryptoError> {
155 match algorithm {
156 HmacAlgorithm::Sha1 => Ok(Box::new(RustCryptoHmacSha1::new(key))),
160 HmacAlgorithm::Sha256 | HmacAlgorithm::Sha384 | HmacAlgorithm::Sha512 => {
161 Ok(Box::new(RingHmac {
162 key: ErasedOnDrop::new(hmac::Key::new(hmac_algorithm(algorithm), key)),
163 output_len: algorithm.output_len(),
164 }))
165 }
166 }
167 }
168
169 fn block_encrypt(
170 &self,
171 algorithm: BlockCipherAlgorithm,
172 key: &[u8],
173 block: &mut [u8],
174 ) -> Result<(), CryptoError> {
175 common::block_encrypt(algorithm, key, block)
176 }
177
178 fn new_stream_cipher(
179 &self,
180 algorithm: StreamCipherAlgorithm,
181 key: &[u8],
182 ) -> Result<Box<dyn StreamCipher>, CryptoError> {
183 common::new_stream_cipher(algorithm, key)
184 }
185
186 fn new_aead(
187 &self,
188 algorithm: AeadAlgorithm,
189 key: &[u8],
190 ) -> Result<Box<dyn AeadCipher>, CryptoError> {
191 match algorithm {
192 AeadAlgorithm::Aes128Ccm | AeadAlgorithm::Aes128Ccm8 => common::new_ccm(algorithm, key),
193 AeadAlgorithm::Aes128Gcm => RingAead::create(&aead::AES_128_GCM, key),
194 AeadAlgorithm::Aes256Gcm => RingAead::create(&aead::AES_256_GCM, key),
195 AeadAlgorithm::ChaCha20Poly1305 => RingAead::create(&aead::CHACHA20_POLY1305, key),
196 }
197 }
198
199 fn new_header_mask(
200 &self,
201 algorithm: HeaderMaskAlgorithm,
202 key: &[u8],
203 ) -> Result<Box<dyn HeaderMask>, CryptoError> {
204 common::check_key_len(algorithm.key_len(), key.len())?;
205 let backend_algorithm = match algorithm {
206 HeaderMaskAlgorithm::Aes128 => &aead::quic::AES_128,
207 HeaderMaskAlgorithm::Aes256 => &aead::quic::AES_256,
208 HeaderMaskAlgorithm::ChaCha20 => &aead::quic::CHACHA20,
209 };
210 let key = aead::quic::HeaderProtectionKey::new(backend_algorithm, key)
211 .map_err(|_| CryptoError::InvalidPrivateKey)?;
212 Ok(Box::new(RingHeaderMask {
213 key: ErasedOnDrop::new(key),
214 }))
215 }
216
217 fn new_cbc(
218 &self,
219 algorithm: CbcAlgorithm,
220 key: &[u8],
221 ) -> Result<Box<dyn CbcCipher>, CryptoError> {
222 common::new_cbc(algorithm, key)
223 }
224
225 fn start_key_exchange(
226 &self,
227 algorithm: KeyExchangeAlgorithm,
228 ) -> Result<Box<dyn ActiveKeyExchange>, CryptoError> {
229 RingKeyExchange::start(algorithm)
230 }
231
232 fn generate_signing_key(
233 &self,
234 scheme: SignatureScheme,
235 ) -> Result<Arc<dyn SigningKey>, CryptoError> {
236 RingSigningKey::generate(scheme)
237 }
238
239 fn import_signing_key(
240 &self,
241 scheme: SignatureScheme,
242 pkcs8_der: &[u8],
243 ) -> Result<Arc<dyn SigningKey>, CryptoError> {
244 RingSigningKey::import(scheme, pkcs8_der)
245 }
246
247 fn verify_signature(
248 &self,
249 scheme: SignatureScheme,
250 public_key: PublicKey<'_>,
251 message: &[u8],
252 signature: &[u8],
253 ) -> Result<(), CryptoError> {
254 verify_public_key_encoding(scheme, public_key.encoding)?;
255 signature::UnparsedPublicKey::new(verification_algorithm(scheme), public_key.bytes)
256 .verify(message, signature)
257 .map_err(|_| CryptoError::InvalidSignature)
258 }
259}
260
261struct ErasedOnDrop<T> {
288 slot: Box<MaybeUninit<T>>,
289}
290
291impl<T> ErasedOnDrop<T> {
292 fn new(value: T) -> Self {
293 let mut slot = Box::<T>::new_uninit();
294 MaybeUninit::write(&mut *slot, value);
295 Self { slot }
296 }
297
298 fn get(&self) -> &T {
299 unsafe { self.slot.assume_init_ref() }
301 }
302
303 fn into_inner(mut self) -> T {
308 let value = unsafe { self.slot.assume_init_read() };
311 self.overwrite();
312 let slot = unsafe { std::ptr::read(&self.slot) };
315 std::mem::forget(self);
316 drop(slot);
317 value
318 }
319
320 fn overwrite(&mut self) {
322 let bytes = self.slot.as_mut_ptr().cast::<u8>();
323 for offset in 0..size_of::<T>() {
324 unsafe { std::ptr::write_volatile(bytes.add(offset), 0) };
327 }
328 compiler_fence(Ordering::SeqCst);
329 }
330}
331
332impl<T> Drop for ErasedOnDrop<T> {
333 fn drop(&mut self) {
334 unsafe { self.slot.assume_init_drop() };
337 self.overwrite();
338 }
339}
340
341struct RingHmac {
346 key: ErasedOnDrop<hmac::Key>,
347 output_len: usize,
348}
349
350impl Mac for RingHmac {
351 fn output_len(&self) -> usize {
352 self.output_len
353 }
354
355 fn sign(&mut self, input: &[&[u8]], output: &mut [u8]) -> Result<(), CryptoError> {
356 common::check_tag_len(self.output_len, output.len())?;
357 let mut context = hmac::Context::with_key(self.key.get());
358 for part in input {
359 context.update(part);
360 }
361 output.copy_from_slice(context.sign().as_ref());
362 Ok(())
363 }
364
365 fn verify(&mut self, input: &[&[u8]], expected: &[u8]) -> Result<(), CryptoError> {
366 common::check_tag_len(self.output_len, expected.len())?;
367 let mut actual = vec![0; self.output_len];
368 self.sign(input, &mut actual)?;
369 if constant_time_eq(&actual, expected) {
370 Ok(())
371 } else {
372 Err(CryptoError::AuthenticationFailed)
373 }
374 }
375}
376
377fn hmac_algorithm(algorithm: HmacAlgorithm) -> hmac::Algorithm {
378 match algorithm {
379 HmacAlgorithm::Sha1 => hmac::HMAC_SHA1_FOR_LEGACY_USE_ONLY,
380 HmacAlgorithm::Sha256 => hmac::HMAC_SHA256,
381 HmacAlgorithm::Sha512 => hmac::HMAC_SHA512,
382 HmacAlgorithm::Sha384 => hmac::HMAC_SHA384,
383 }
384}
385
386struct RingHeaderMask {
390 key: ErasedOnDrop<aead::quic::HeaderProtectionKey>,
391}
392
393impl HeaderMask for RingHeaderMask {
394 fn mask(
395 &mut self,
396 sample: &[u8; HEADER_MASK_SAMPLE_LEN],
397 ) -> Result<[u8; HEADER_MASK_LEN], CryptoError> {
398 self.key
399 .get()
400 .new_mask(sample)
401 .map_err(|_| CryptoError::Provider("header mask generation failed".into()))
402 }
403}
404
405struct RingAead {
406 key: ErasedOnDrop<aead::LessSafeKey>,
407}
408
409impl RingAead {
410 fn create(
411 algorithm: &'static aead::Algorithm,
412 key: &[u8],
413 ) -> Result<Box<dyn AeadCipher>, CryptoError> {
414 common::check_key_len(algorithm.key_len(), key.len())?;
415 let key = aead::UnboundKey::new(algorithm, key)
416 .map(aead::LessSafeKey::new)
417 .map_err(|_| CryptoError::InvalidPrivateKey)?;
418 Ok(Box::new(Self {
419 key: ErasedOnDrop::new(key),
420 }))
421 }
422}
423
424impl AeadCipher for RingAead {
425 fn tag_len(&self) -> usize {
426 16
427 }
428
429 fn seal_in_place(
430 &mut self,
431 nonce: &[u8],
432 aad: &[u8],
433 plaintext_and_ciphertext: &mut [u8],
434 tag_out: &mut [u8],
435 ) -> Result<(), CryptoError> {
436 common::check_nonce_len(12, nonce.len())?;
437 common::check_tag_len(self.tag_len(), tag_out.len())?;
438 let nonce = aead::Nonce::try_assume_unique_for_key(nonce).map_err(|_| {
439 CryptoError::InvalidNonceLength {
440 expected: 12,
441 actual: nonce.len(),
442 }
443 })?;
444 let key = self.key.get();
445 record_call(key, || {
446 let tag = key
447 .seal_in_place_separate_tag(nonce, aead::Aad::from(aad), plaintext_and_ciphertext)
448 .map_err(|_| CryptoError::AuthenticationFailed)?;
449 tag_out.copy_from_slice(tag.as_ref());
450 Ok(())
451 })
452 }
453
454 fn open_in_place(
455 &mut self,
456 nonce: &[u8],
457 aad: &[u8],
458 ciphertext_and_plaintext: &mut [u8],
459 tag: &[u8],
460 ) -> Result<(), CryptoError> {
461 common::check_nonce_len(12, nonce.len())?;
462 common::check_tag_len(self.tag_len(), tag.len())?;
463 let nonce = aead::Nonce::try_assume_unique_for_key(nonce).map_err(|_| {
464 CryptoError::InvalidNonceLength {
465 expected: 12,
466 actual: nonce.len(),
467 }
468 })?;
469 let tag = aead::Tag::try_from(tag).map_err(|_| CryptoError::InvalidTagLength {
470 expected: self.tag_len(),
471 actual: tag.len(),
472 })?;
473 let key = self.key.get();
474 record_call(key, || {
475 key.open_in_place_separate_tag(
476 nonce,
477 aead::Aad::from(aad),
478 tag,
479 ciphertext_and_plaintext,
480 0..,
481 )
482 .map(|_| ())
483 .map_err(|_| CryptoError::AuthenticationFailed)
484 })
485 }
486}
487
488#[inline(always)]
498fn record_call<R>(key: &aead::LessSafeKey, work: impl FnOnce() -> R) -> R {
499 if key.algorithm() == &aead::CHACHA20_POLY1305 {
500 crate::secret::erased_record_call::<{ crate::secret::record_depth::RING_CHACHA20 }, _>(work)
501 } else if !ring_aes_gcm_hardware() {
502 crate::secret::erased_record_call::<{ crate::secret::record_depth::RING_AES_GCM_PORTABLE }, _>(
503 work,
504 )
505 } else {
506 work()
507 }
508}
509
510fn ring_aes_gcm_hardware() -> bool {
516 #[cfg(any(target_arch = "x86", target_arch = "x86_64"))]
517 {
518 std::arch::is_x86_feature_detected!("aes")
519 && std::arch::is_x86_feature_detected!("pclmulqdq")
520 && std::arch::is_x86_feature_detected!("ssse3")
521 }
522 #[cfg(target_arch = "aarch64")]
523 {
524 std::arch::is_aarch64_feature_detected!("aes")
525 && std::arch::is_aarch64_feature_detected!("pmull")
526 }
527 #[cfg(not(any(target_arch = "x86", target_arch = "x86_64", target_arch = "aarch64")))]
528 {
529 false
530 }
531}
532
533struct RingKeyExchange {
534 algorithm: KeyExchangeAlgorithm,
535 backend_algorithm: &'static agreement::Algorithm,
536 private_key: ErasedOnDrop<agreement::EphemeralPrivateKey>,
539 public_key: Vec<u8>,
540}
541
542impl RingKeyExchange {
543 fn start(algorithm: KeyExchangeAlgorithm) -> Result<Box<dyn ActiveKeyExchange>, CryptoError> {
544 Self::start_with(algorithm, &SystemRandom::new())
545 }
546
547 fn start_with(
548 algorithm: KeyExchangeAlgorithm,
549 rng: &dyn ring::rand::SecureRandom,
550 ) -> Result<Box<dyn ActiveKeyExchange>, CryptoError> {
551 let backend_algorithm = agreement_algorithm(algorithm)?;
552 let private_key = agreement::EphemeralPrivateKey::generate(backend_algorithm, rng)
553 .map_err(|_| CryptoError::RandomnessFailed)?;
554 let public_key = private_key
555 .compute_public_key()
556 .map_err(|_| CryptoError::Provider("key exchange public-key generation failed".into()))?
557 .as_ref()
558 .to_vec();
559 Ok(Box::new(Self {
560 algorithm,
561 backend_algorithm,
562 private_key: ErasedOnDrop::new(private_key),
563 public_key,
564 }))
565 }
566}
567
568impl ActiveKeyExchange for RingKeyExchange {
569 fn algorithm(&self) -> KeyExchangeAlgorithm {
570 self.algorithm
571 }
572
573 fn public_key(&self) -> &[u8] {
574 &self.public_key
575 }
576
577 fn complete(self: Box<Self>, peer_public_key: &[u8]) -> Result<SecretVec, CryptoError> {
578 let this = *self;
579 let peer = agreement::UnparsedPublicKey::new(this.backend_algorithm, peer_public_key);
580 agreement::agree_ephemeral(this.private_key.into_inner(), &peer, |secret| {
581 SecretVec::new(secret.to_vec())
582 })
583 .map_err(|_| CryptoError::InvalidPublicKey)
584 }
585}
586
587enum RingSigningKeyKind {
588 Ed25519(signature::Ed25519KeyPair),
589 EcdsaP256(signature::EcdsaKeyPair),
590 Rsa(signature::RsaKeyPair),
591}
592
593struct RingSigningKey {
594 scheme: SignatureScheme,
595 kind: ErasedOnDrop<RingSigningKeyKind>,
598 public_key: Vec<u8>,
599 public_key_encoding: PublicKeyEncoding,
600 pkcs8_der: SecretVec,
601}
602
603impl RingSigningKey {
604 fn generate(scheme: SignatureScheme) -> Result<Arc<dyn SigningKey>, CryptoError> {
605 let rng = SystemRandom::new();
606 let pkcs8 = match scheme {
607 SignatureScheme::Ed25519 => signature::Ed25519KeyPair::generate_pkcs8(&rng),
608 SignatureScheme::EcdsaP256Sha256 => signature::EcdsaKeyPair::generate_pkcs8(
609 &signature::ECDSA_P256_SHA256_ASN1_SIGNING,
610 &rng,
611 ),
612 _ => {
613 return Err(CryptoError::UnsupportedAlgorithm(
614 CryptoAlgorithm::SigningKeyGeneration(scheme),
615 ));
616 }
617 }
618 .map_err(|_| CryptoError::RandomnessFailed)?;
619 Self::import(scheme, pkcs8.as_ref())
620 }
621
622 fn import(
623 scheme: SignatureScheme,
624 pkcs8_der: &[u8],
625 ) -> Result<Arc<dyn SigningKey>, CryptoError> {
626 let rng = SystemRandom::new();
627 let (kind, public_key, public_key_encoding) = match scheme {
628 SignatureScheme::Ed25519 => {
629 let key = signature::Ed25519KeyPair::from_pkcs8_maybe_unchecked(pkcs8_der)
630 .map_err(|_| CryptoError::InvalidPrivateKey)?;
631 let public = key.public_key().as_ref().to_vec();
632 (
633 RingSigningKeyKind::Ed25519(key),
634 public,
635 PublicKeyEncoding::Ed25519Raw,
636 )
637 }
638 SignatureScheme::EcdsaP256Sha256 => {
639 let key = signature::EcdsaKeyPair::from_pkcs8(
640 &signature::ECDSA_P256_SHA256_ASN1_SIGNING,
641 pkcs8_der,
642 &rng,
643 )
644 .map_err(|_| CryptoError::InvalidPrivateKey)?;
645 let public = key.public_key().as_ref().to_vec();
646 (
647 RingSigningKeyKind::EcdsaP256(key),
648 public,
649 PublicKeyEncoding::EcUncompressedPoint,
650 )
651 }
652 SignatureScheme::RsaPkcs1Sha256 => {
653 let key = signature::RsaKeyPair::from_pkcs8(pkcs8_der)
654 .map_err(|_| CryptoError::InvalidPrivateKey)?;
655 let public = key.public().as_ref().to_vec();
656 (
657 RingSigningKeyKind::Rsa(key),
658 public,
659 PublicKeyEncoding::RsaPkcs1Der,
660 )
661 }
662 _ => {
663 return Err(CryptoError::UnsupportedAlgorithm(
664 CryptoAlgorithm::SigningKeyImport(scheme),
665 ));
666 }
667 };
668 Ok(Arc::new(Self {
669 scheme,
670 kind: ErasedOnDrop::new(kind),
671 public_key,
672 public_key_encoding,
673 pkcs8_der: SecretVec::new(pkcs8_der.to_vec()),
674 }))
675 }
676}
677
678impl SigningKey for RingSigningKey {
679 fn supports(&self, scheme: SignatureScheme) -> bool {
680 self.scheme == scheme
683 || (matches!(self.kind.get(), RingSigningKeyKind::Rsa(_))
684 && matches!(
685 scheme,
686 SignatureScheme::RsaPssSha256
687 | SignatureScheme::RsaPssSha384
688 | SignatureScheme::RsaPssSha512
689 ))
690 }
691
692 fn public_key(&self) -> PublicKey<'_> {
693 PublicKey {
694 encoding: self.public_key_encoding,
695 bytes: &self.public_key,
696 }
697 }
698
699 fn sign(&self, scheme: SignatureScheme, message: &[u8]) -> Result<Vec<u8>, CryptoError> {
700 if !self.supports(scheme) {
701 return Err(CryptoError::UnsupportedAlgorithm(
702 CryptoAlgorithm::Signature(scheme),
703 ));
704 }
705 match self.kind.get() {
706 RingSigningKeyKind::Ed25519(key) => Ok(key.sign(message).as_ref().to_vec()),
707 RingSigningKeyKind::EcdsaP256(key) => key
708 .sign(&SystemRandom::new(), message)
709 .map(|signature| signature.as_ref().to_vec())
710 .map_err(|_| CryptoError::Provider("signature generation failed".into())),
711 RingSigningKeyKind::Rsa(key) => {
712 let encoding: &'static dyn signature::RsaEncoding = match scheme {
713 SignatureScheme::RsaPssSha256 => &signature::RSA_PSS_SHA256,
714 SignatureScheme::RsaPssSha384 => &signature::RSA_PSS_SHA384,
715 SignatureScheme::RsaPssSha512 => &signature::RSA_PSS_SHA512,
716 _ => &signature::RSA_PKCS1_SHA256,
717 };
718 let mut signature = vec![0; key.public().modulus_len()];
719 key.sign(encoding, &SystemRandom::new(), message, &mut signature)
720 .map_err(|_| CryptoError::Provider("signature generation failed".into()))?;
721 Ok(signature)
722 }
723 }
724 }
725
726 fn to_pkcs8_der(&self) -> Result<Option<SecretVec>, CryptoError> {
727 Ok(Some(self.pkcs8_der.clone()))
728 }
729}
730
731fn agreement_algorithm(
732 algorithm: KeyExchangeAlgorithm,
733) -> Result<&'static agreement::Algorithm, CryptoError> {
734 match algorithm {
735 KeyExchangeAlgorithm::P256 => Ok(&agreement::ECDH_P256),
736 KeyExchangeAlgorithm::P384 => Ok(&agreement::ECDH_P384),
737 KeyExchangeAlgorithm::X25519 => Ok(&agreement::X25519),
738 KeyExchangeAlgorithm::X25519MlKem768 => Err(CryptoError::UnsupportedAlgorithm(
740 CryptoAlgorithm::KeyExchange(algorithm),
741 )),
742 }
743}
744
745fn verification_algorithm(
746 scheme: SignatureScheme,
747) -> &'static dyn signature::VerificationAlgorithm {
748 match scheme {
749 SignatureScheme::Ed25519 => &signature::ED25519,
750 SignatureScheme::EcdsaP256Sha256 => &signature::ECDSA_P256_SHA256_ASN1,
751 SignatureScheme::EcdsaP384Sha256 => &signature::ECDSA_P384_SHA256_ASN1,
752 SignatureScheme::EcdsaP384Sha384 => &signature::ECDSA_P384_SHA384_ASN1,
753 SignatureScheme::RsaPkcs1Sha1 => &signature::RSA_PKCS1_1024_8192_SHA1_FOR_LEGACY_USE_ONLY,
754 SignatureScheme::RsaPkcs1Sha256 => {
755 &signature::RSA_PKCS1_1024_8192_SHA256_FOR_LEGACY_USE_ONLY
756 }
757 SignatureScheme::RsaPkcs1Sha384 => &signature::RSA_PKCS1_2048_8192_SHA384,
758 SignatureScheme::RsaPkcs1Sha512 => {
759 &signature::RSA_PKCS1_1024_8192_SHA512_FOR_LEGACY_USE_ONLY
760 }
761 SignatureScheme::RsaPssSha256 => &signature::RSA_PSS_2048_8192_SHA256,
762 SignatureScheme::RsaPssSha384 => &signature::RSA_PSS_2048_8192_SHA384,
763 SignatureScheme::RsaPssSha512 => &signature::RSA_PSS_2048_8192_SHA512,
764 }
765}
766
767fn verify_public_key_encoding(
768 scheme: SignatureScheme,
769 encoding: PublicKeyEncoding,
770) -> Result<(), CryptoError> {
771 let valid = matches!(
772 (scheme, encoding),
773 (SignatureScheme::Ed25519, PublicKeyEncoding::Ed25519Raw)
774 | (
775 SignatureScheme::EcdsaP256Sha256
776 | SignatureScheme::EcdsaP384Sha256
777 | SignatureScheme::EcdsaP384Sha384,
778 PublicKeyEncoding::EcUncompressedPoint
779 )
780 | (
781 SignatureScheme::RsaPkcs1Sha1
782 | SignatureScheme::RsaPkcs1Sha256
783 | SignatureScheme::RsaPkcs1Sha384
784 | SignatureScheme::RsaPkcs1Sha512
785 | SignatureScheme::RsaPssSha256
786 | SignatureScheme::RsaPssSha384
787 | SignatureScheme::RsaPssSha512,
788 PublicKeyEncoding::RsaPkcs1Der
789 )
790 );
791 if valid {
792 Ok(())
793 } else {
794 Err(CryptoError::InvalidPublicKey)
795 }
796}
797
798type HmacSha1 = ::hmac::HmacReset<Sha1>;
799
800pub(crate) struct RustCryptoHmacSha1 {
822 keyed: HmacSha1,
823}
824
825impl RustCryptoHmacSha1 {
826 pub(crate) fn new(key: &[u8]) -> Self {
827 Self {
828 keyed: <HmacSha1 as ::hmac::KeyInit>::new_from_slice(key)
830 .expect("HMAC accepts keys of any length"),
831 }
832 }
833}
834
835impl Mac for RustCryptoHmacSha1 {
836 fn output_len(&self) -> usize {
837 20
838 }
839
840 fn sign(&mut self, input: &[&[u8]], output: &mut [u8]) -> Result<(), CryptoError> {
841 check_tag_len(20, output.len())?;
842 let keyed = &mut self.keyed;
843 let mut mac = || {
844 for part in input {
845 keyed.update(part);
846 }
847 output.copy_from_slice(&keyed.finalize_reset().into_bytes());
848 };
849 if crate::secret::rustcrypto_sha1_hardware() {
852 mac();
853 } else {
854 crate::secret::erased_record_call::<
855 { crate::secret::record_depth::RUSTCRYPTO_SHA1_PORTABLE },
856 _,
857 >(mac);
858 }
859 Ok(())
860 }
861
862 fn verify(&mut self, input: &[&[u8]], expected: &[u8]) -> Result<(), CryptoError> {
863 check_tag_len(20, expected.len())?;
864 let mut actual = [0u8; 20];
865 self.sign(input, &mut actual)?;
866 if crate::constant_time_eq(&actual, expected) {
867 Ok(())
868 } else {
869 Err(CryptoError::AuthenticationFailed)
870 }
871 }
872}
873
874#[cfg(feature = "test-support")]
878#[doc(hidden)]
879#[allow(deprecated)]
880pub fn ring_key_exchange_with_seed(
881 algorithm: KeyExchangeAlgorithm,
882 seed: &[u8],
883) -> Result<Box<dyn ActiveKeyExchange>, CryptoError> {
884 RingKeyExchange::start_with(
885 algorithm,
886 &ring::test::rand::FixedSliceRandom { bytes: seed },
887 )
888}