1#![deny(warnings)]
2#![allow(dead_code)]
3#![warn(unused_extern_crates)]
4#![deny(clippy::suspicious)]
6#![deny(clippy::perf)]
7#![deny(clippy::todo)]
9#![deny(clippy::unimplemented)]
10#![deny(clippy::unwrap_used)]
11#![deny(clippy::expect_used)]
12#![deny(clippy::panic)]
13#![deny(clippy::await_holding_lock)]
14#![deny(clippy::needless_pass_by_value)]
15#![deny(clippy::trivially_copy_pass_by_ref)]
16#![deny(clippy::disallowed_types)]
17#![deny(clippy::manual_let_else)]
18#![allow(clippy::unreachable)]
19
20pub use argon2;
21pub use cipher::block_padding;
22pub use der;
23pub use hex;
24pub use pbkdf2;
25pub use rand;
26pub use spki;
27pub use zeroize;
28
29pub mod prelude {}
30
31#[cfg(test)]
32mod test_ca;
33
34pub mod traits {
35 pub use aes_gcm::aead::AeadInPlace;
36 pub use crypto_common::KeyInit;
37 pub use crypto_common::OutputSizeUser;
38 pub use der::{
39 pem::LineEnding as LineEndingPem, referenced::OwnedToRef, Decode as DecodeDer, DecodePem,
40 Encode as EncodeDer, EncodePem,
41 };
42 pub use elliptic_curve::sec1::{FromEncodedPoint, ToEncodedPoint};
43 pub use hmac::{Hmac, Mac};
44 pub use pkcs8::{
45 DecodePrivateKey as Pkcs8DecodePrivateKey, EncodePrivateKey as Pkcs8EncodePrivateKey,
46 };
47 pub use rsa::pkcs1::{
48 DecodeRsaPrivateKey as Pkcs1DecodeRsaPrivateKey,
49 EncodeRsaPrivateKey as Pkcs1EncodeRsaPrivateKey,
50 };
51 pub use rsa::signature::{
52 DigestSigner, DigestVerifier, Keypair, RandomizedSigner, SignatureEncoding, Signer,
53 Verifier,
54 };
55 pub use rsa::traits::PublicKeyParts;
56 pub use sha2::Digest;
57 pub use spki::{
58 DecodePublicKey as SpkiDecodePublicKey, DynSignatureAlgorithmIdentifier,
59 EncodePublicKey as SpkiEncodePublicKey,
60 };
61 pub use zeroize::Zeroizing;
62 pub mod hazmat {
63 pub use rsa::signature::hazmat::PrehashVerifier;
66 }
67}
68
69pub mod x509;
70
71pub mod sha1 {
72 use generic_array::GenericArray;
73 use sha1::digest::consts::U20;
74
75 pub use sha1::Sha1;
76
77 pub type Sha1Output = GenericArray<u8, U20>;
78}
79
80pub mod s256 {
81 use generic_array::GenericArray;
82 use sha2::digest::consts::U32;
83
84 pub use sha2::Sha256;
85
86 pub type Sha256Output = GenericArray<u8, U32>;
87}
88
89pub mod s384 {
90 use generic_array::GenericArray;
91 use sha2::digest::consts::U48;
92
93 pub use sha2::Sha384;
94
95 pub type Sha384Output = GenericArray<u8, U48>;
96}
97
98pub mod s512 {
99 use generic_array::GenericArray;
100 use sha2::digest::consts::U64;
101
102 pub use sha2::Sha512;
103
104 pub type Sha512Output = GenericArray<u8, U64>;
105}
106
107pub mod hkdf_s256 {
108 use hkdf::Hkdf;
109 use sha2::Sha256;
110
111 pub type HkdfSha256 = Hkdf<Sha256>;
112}
113
114pub mod hmac_s1 {
115 use crypto_common::Key;
116 use crypto_common::Output;
117
118 use hmac::Hmac;
119 use hmac::Mac;
120 use sha1::digest::CtOutput;
121 use sha1::Sha1;
122 use zeroize::Zeroizing;
123
124 pub type HmacSha1 = Hmac<Sha1>;
125
126 pub type HmacSha1Key = Zeroizing<Key<Hmac<Sha1>>>;
127
128 pub type HmacSha1Output = CtOutput<HmacSha1>;
129
130 pub type HmacSha1Bytes = Output<HmacSha1>;
131
132 pub fn new_key() -> HmacSha1Key {
133 use crypto_common::KeyInit;
134
135 let mut rng = rand::thread_rng();
136 HmacSha1::generate_key(&mut rng).into()
137 }
138
139 pub fn oneshot(key: &HmacSha1Key, data: &[u8]) -> HmacSha1Output {
140 let mut hmac = HmacSha1::new(key);
141 hmac.update(data);
142 hmac.finalize()
143 }
144
145 pub fn key_from_vec(bytes: Vec<u8>) -> Option<HmacSha1Key> {
146 key_from_slice(&bytes)
147 }
148
149 pub fn key_from_slice(bytes: &[u8]) -> Option<HmacSha1Key> {
150 use crypto_common::KeySizeUser;
151 if bytes.len() < 16 || bytes.len() > Hmac::<Sha1>::key_size() {
153 None
154 } else {
155 let mut key = Key::<Hmac<Sha1>>::default();
156 let key_ref = &mut key.as_mut_slice()[..bytes.len()];
157 key_ref.copy_from_slice(bytes);
158 Some(key.into())
159 }
160 }
161
162 pub fn key_from_bytes(bytes: [u8; 64]) -> HmacSha1Key {
163 Key::<Hmac<Sha1>>::from(bytes).into()
164 }
165
166 pub fn key_size() -> usize {
167 use crypto_common::KeySizeUser;
168 Hmac::<Sha1>::key_size()
169 }
170}
171
172pub mod hmac_s256 {
173 use crypto_common::Key;
174 use crypto_common::Output;
175
176 use hmac::Hmac;
177 use hmac::Mac;
178 use sha2::digest::CtOutput;
179 use sha2::Sha256;
180 use zeroize::Zeroizing;
181
182 pub type HmacSha256 = Hmac<Sha256>;
183
184 pub type HmacSha256Key = Zeroizing<Key<Hmac<Sha256>>>;
185
186 pub type HmacSha256Output = CtOutput<HmacSha256>;
187
188 pub type HmacSha256Bytes = Output<HmacSha256>;
189
190 pub fn new_key() -> HmacSha256Key {
191 use crypto_common::KeyInit;
192
193 let mut rng = rand::thread_rng();
194 HmacSha256::generate_key(&mut rng).into()
195 }
196
197 pub fn oneshot(key: &HmacSha256Key, data: &[u8]) -> HmacSha256Output {
198 let mut hmac = HmacSha256::new(key);
199 hmac.update(data);
200 hmac.finalize()
201 }
202
203 pub fn key_from_vec(bytes: Vec<u8>) -> Option<HmacSha256Key> {
204 key_from_slice(&bytes)
205 }
206
207 pub fn key_from_slice(bytes: &[u8]) -> Option<HmacSha256Key> {
208 use crypto_common::KeySizeUser;
209 if bytes.len() < 16 || bytes.len() > Hmac::<Sha256>::key_size() {
211 None
212 } else {
213 let mut key = Key::<Hmac<Sha256>>::default();
214 let key_ref = &mut key.as_mut_slice()[..bytes.len()];
215 key_ref.copy_from_slice(bytes);
216 Some(key.into())
217 }
218 }
219
220 pub fn key_from_bytes(bytes: [u8; 64]) -> HmacSha256Key {
221 Key::<Hmac<Sha256>>::from(bytes).into()
222 }
223
224 pub fn key_size() -> usize {
225 use crypto_common::KeySizeUser;
226 Hmac::<Sha256>::key_size()
227 }
228}
229
230pub mod hmac_s512 {
231 use crypto_common::Key;
232 use crypto_common::Output;
233
234 use hmac::Hmac;
235 use sha2::digest::CtOutput;
236 use sha2::Sha512;
237 use zeroize::Zeroizing;
238
239 pub use hmac::Mac;
240
241 pub type HmacSha512 = Hmac<Sha512>;
242
243 pub type HmacSha512Key = Zeroizing<Key<Hmac<Sha512>>>;
244
245 pub type HmacSha512Output = CtOutput<HmacSha512>;
246
247 pub type HmacSha512Bytes = Output<HmacSha512>;
248
249 pub fn new_hmac_sha512_key() -> HmacSha512Key {
250 use crypto_common::KeyInit;
251
252 let mut rng = rand::thread_rng();
253 HmacSha512::generate_key(&mut rng).into()
254 }
255
256 pub fn oneshot(key: &HmacSha512Key, data: &[u8]) -> HmacSha512Output {
257 let mut hmac = HmacSha512::new(key);
258 hmac.update(data);
259 hmac.finalize()
260 }
261
262 pub fn key_from_slice(bytes: &[u8]) -> Option<HmacSha512Key> {
263 use crypto_common::KeySizeUser;
264 if bytes.len() < 16 || bytes.len() > Hmac::<Sha512>::key_size() {
266 None
267 } else {
268 let mut key = Key::<Hmac<Sha512>>::default();
269 let key_ref = &mut key.as_mut_slice()[..bytes.len()];
270 key_ref.copy_from_slice(bytes);
271 Some(key.into())
272 }
273 }
274
275 pub fn key_size() -> usize {
276 use crypto_common::KeySizeUser;
277 Hmac::<Sha512>::key_size()
278 }
279}
280
281pub mod aes128 {
282 use aes;
283 use crypto_common::Key;
284 use crypto_common::KeyInit;
285 use zeroize::Zeroizing;
286
287 pub type Aes128Key = Zeroizing<Key<aes::Aes128>>;
288
289 pub fn key_size() -> usize {
290 use crypto_common::KeySizeUser;
291 aes::Aes128::key_size()
292 }
293
294 pub fn key_from_slice(bytes: &[u8]) -> Option<Aes128Key> {
295 Key::<aes::Aes128>::from_exact_iter(bytes.iter().copied()).map(|key| key.into())
296 }
297
298 pub fn key_from_bytes(bytes: [u8; 16]) -> Aes128Key {
299 Key::<aes::Aes128>::from(bytes).into()
300 }
301
302 pub fn new_key() -> Aes128Key {
303 let mut rng = rand::thread_rng();
304 aes::Aes128::generate_key(&mut rng).into()
305 }
306}
307
308pub mod aes128gcm {
309 use aes::cipher::consts::{U12, U16};
310 use aes_gcm::aead::AeadCore;
312 use generic_array::GenericArray;
314
315 pub use aes_gcm::aead::{Aead, AeadInPlace, Payload};
316 pub use crypto_common::KeyInit;
317
318 pub use crate::aes128::Aes128Key;
319
320 pub type Aes128Gcm = aes_gcm::Aes128Gcm;
322
323 pub type Aes128GcmNonce = GenericArray<u8, U12>;
324 pub type Aes128GcmTag = GenericArray<u8, U16>;
325
326 pub fn new_nonce() -> Aes128GcmNonce {
327 let mut rng = rand::thread_rng();
328 Aes128Gcm::generate_nonce(&mut rng)
329 }
330}
331
332pub mod aes128kw {
333 use aes::cipher::consts::U24;
334 use generic_array::GenericArray;
335
336 pub use crypto_common::KeyInit;
337
338 pub type Aes128Kw = aes_kw::KekAes128;
339
340 pub type Aes128KwWrapped = GenericArray<u8, U24>;
341}
342
343pub mod aes256 {
344 use aes;
345 use crypto_common::Key;
346 use crypto_common::KeyInit;
347 use zeroize::Zeroizing;
348
349 pub type Aes256Key = Zeroizing<Key<aes::Aes256>>;
350
351 pub fn key_size() -> usize {
352 use crypto_common::KeySizeUser;
353 aes::Aes256::key_size()
354 }
355
356 pub fn key_from_slice(bytes: &[u8]) -> Option<Aes256Key> {
357 Key::<aes::Aes256>::from_exact_iter(bytes.iter().copied()).map(|key| key.into())
358 }
359
360 pub fn key_from_vec(bytes: Vec<u8>) -> Option<Aes256Key> {
361 Key::<aes::Aes256>::from_exact_iter(bytes).map(|key| key.into())
362 }
363
364 pub fn key_from_bytes(bytes: [u8; 32]) -> Aes256Key {
365 Key::<aes::Aes256>::from(bytes).into()
366 }
367
368 pub fn new_key() -> Aes256Key {
369 let mut rng = rand::thread_rng();
370 aes::Aes256::generate_key(&mut rng).into()
371 }
372}
373
374pub mod aes256gcm {
375 use aes::cipher::consts::{U12, U16};
376 use aes::Aes256;
377 use aes_gcm::aead::AeadCore;
378 use aes_gcm::AesGcm;
379 use generic_array::GenericArray;
380
381 pub use aes_gcm::aead::{Aead, AeadInPlace, Payload};
382 pub use crypto_common::KeyInit;
383
384 pub use crate::aes256::Aes256Key;
385
386 pub type Aes256Gcm = aes_gcm::Aes256Gcm;
388
389 pub type Aes256GcmN16 = AesGcm<Aes256, U16, U16>;
390 pub type Aes256GcmNonce16 = GenericArray<u8, U16>;
391
392 pub type Aes256GcmNonce = GenericArray<u8, U12>;
393
394 pub type Aes256GcmTag = GenericArray<u8, U16>;
395
396 pub fn new_nonce() -> Aes256GcmNonce {
397 let mut rng = rand::thread_rng();
398
399 Aes256Gcm::generate_nonce(&mut rng)
400 }
401}
402
403pub mod aes256cbc {
404 use crate::hmac_s256::HmacSha256;
405 use crate::hmac_s256::HmacSha256Output;
406 use aes::cipher::consts::U16;
407 use generic_array::GenericArray;
408
409 pub use crate::aes256::Aes256Key;
410
411 pub use aes::cipher::{block_padding, BlockDecryptMut, BlockEncryptMut, KeyIvInit};
412
413 pub type Aes256CbcEnc = cbc::Encryptor<aes::Aes256>;
414 pub type Aes256CbcDec = cbc::Decryptor<aes::Aes256>;
415
416 pub type Aes256CbcIv = GenericArray<u8, U16>;
417
418 pub fn new_iv() -> Aes256CbcIv {
419 let mut rng = rand::thread_rng();
420 Aes256CbcEnc::generate_iv(&mut rng)
421 }
422
423 pub fn enc<P>(
424 key: &Aes256Key,
425 data: &[u8],
426 ) -> Result<(HmacSha256Output, Aes256CbcIv, Vec<u8>), crypto_common::InvalidLength>
427 where
428 P: block_padding::Padding<<aes::Aes256 as crypto_common::BlockSizeUser>::BlockSize>,
429 {
430 use hmac::Mac;
431
432 let iv = new_iv();
433 let enc = Aes256CbcEnc::new(key, &iv);
434
435 let ciphertext = enc.encrypt_padded_vec_mut::<P>(data);
436
437 let mut hmac = HmacSha256::new_from_slice(key.as_slice())?;
438 hmac.update(&ciphertext);
439 let mac = hmac.finalize();
440
441 Ok((mac, iv, ciphertext))
442 }
443
444 pub fn dec<P>(
445 key: &Aes256Key,
446 mac: &HmacSha256Output,
447 iv: &Aes256CbcIv,
448 ciphertext: &[u8],
449 ) -> Option<Vec<u8>>
450 where
451 P: block_padding::Padding<<aes::Aes256 as crypto_common::BlockSizeUser>::BlockSize>,
452 {
453 use hmac::Mac;
454
455 let mut hmac = HmacSha256::new_from_slice(key.as_slice()).ok()?;
456 hmac.update(ciphertext);
457 let check_mac = hmac.finalize();
458
459 if check_mac != *mac {
460 return None;
461 }
462
463 let dec = Aes256CbcDec::new(key, iv);
464
465 let plaintext = dec.decrypt_padded_vec_mut::<P>(ciphertext).ok()?;
466
467 Some(plaintext)
468 }
469}
470
471pub mod aes256kw {
472 use aes::cipher::consts::U40;
473 use generic_array::GenericArray;
474
475 pub use crypto_common::KeyInit;
476
477 pub type Aes256Kw = aes_kw::KekAes256;
478
479 pub type Aes256KwWrapped = GenericArray<u8, U40>;
480}
481
482pub mod rsa {
483 use rsa::pkcs1v15::{Signature, SigningKey, VerifyingKey};
484 use rsa::{RsaPrivateKey, RsaPublicKey};
485
486 pub use rand;
487 pub use rsa::BigUint;
488 pub use rsa::{pkcs1v15, Oaep};
489 pub use sha2::Sha256;
490
491 pub const MIN_BITS: usize = 2048;
492
493 pub type RS256PrivateKey = RsaPrivateKey;
494 pub type RS256PublicKey = RsaPublicKey;
495 pub type RS256Signature = Signature;
496 pub type RS256Digest = Sha256;
497 pub type RS256VerifyingKey = VerifyingKey<Sha256>;
498 pub type RS256SigningKey = SigningKey<Sha256>;
499
500 pub fn new_key(bits: usize) -> rsa::errors::Result<RsaPrivateKey> {
501 let bits = std::cmp::max(bits, MIN_BITS);
502 let mut rng = rand::thread_rng();
503 RsaPrivateKey::new(&mut rng, bits)
504 }
505
506 pub fn oaep_sha256_encrypt(
507 public_key: &RsaPublicKey,
508 data: &[u8],
509 ) -> rsa::errors::Result<Vec<u8>> {
510 let mut rng = rand::thread_rng();
511 let padding = Oaep::new::<Sha256>();
512 public_key.encrypt(&mut rng, padding, data)
513 }
514
515 pub fn oaep_sha256_decrypt(
516 private_key: &RsaPrivateKey,
517 ciphertext: &[u8],
518 ) -> rsa::errors::Result<Vec<u8>> {
519 let padding = Oaep::new::<Sha256>();
520 private_key.decrypt(padding, ciphertext)
521 }
522}
523
524pub mod ec {
525 pub use sec1::EcPrivateKey;
526}
527
528pub mod ecdh {
529 pub use elliptic_curve::ecdh::diffie_hellman;
530}
531
532pub mod ecdh_p256 {
533 use elliptic_curve::ecdh::{EphemeralSecret, SharedSecret};
534 use elliptic_curve::sec1::EncodedPoint;
535 use elliptic_curve::{FieldBytes, PublicKey};
536 use hkdf::Hkdf;
537 use hmac::SimpleHmac;
538 use p256::NistP256;
539 use sha2::Sha256;
540
541 pub type EcdhP256EphemeralSecret = EphemeralSecret<NistP256>;
542 pub type EcdhP256SharedSecret = SharedSecret<NistP256>;
543 pub type EcdhP256PublicKey = PublicKey<NistP256>;
544 pub type EcdhP256PublicEncodedPoint = EncodedPoint<NistP256>;
545 pub type EcdhP256FieldBytes = FieldBytes<NistP256>;
546
547 pub type EcdhP256Hkdf = Hkdf<Sha256, SimpleHmac<Sha256>>;
548
549 pub type EcdhP256Digest = Sha256;
550
551 pub fn new_secret() -> EcdhP256EphemeralSecret {
552 let mut rng = rand::thread_rng();
553 EcdhP256EphemeralSecret::random(&mut rng)
554 }
555}
556
557pub mod ecdsa_p256 {
558 use ecdsa::hazmat::DigestPrimitive;
559 use ecdsa::{Signature, SignatureBytes, SigningKey, VerifyingKey};
560 use elliptic_curve::point::AffinePoint;
561 use elliptic_curve::scalar::{NonZeroScalar, ScalarPrimitive};
562 use elliptic_curve::sec1::EncodedPoint;
563 use elliptic_curve::sec1::FromEncodedPoint;
564 use elliptic_curve::{FieldBytes, PublicKey, SecretKey};
565 use generic_array::GenericArray;
566 use p256::{ecdsa::DerSignature, NistP256};
567 use sha2::digest::consts::U32;
568
569 pub type EcdsaP256Digest = <NistP256 as DigestPrimitive>::Digest;
570
571 pub type EcdsaP256PrivateKey = SecretKey<NistP256>;
572 pub type EcdsaP256NonZeroScalar = NonZeroScalar<NistP256>;
573 pub type EcdsaP256ScalarPrimitive = ScalarPrimitive<NistP256>;
574
575 pub type EcdsaP256FieldBytes = FieldBytes<NistP256>;
576 pub type EcdsaP256AffinePoint = AffinePoint<NistP256>;
577
578 pub type EcdsaP256PublicKey = PublicKey<NistP256>;
579
580 pub type EcdsaP256PublicCoordinate = GenericArray<u8, U32>;
581 pub type EcdsaP256PublicEncodedPoint = EncodedPoint<NistP256>;
582
583 pub type EcdsaP256SigningKey = SigningKey<NistP256>;
584 pub type EcdsaP256VerifyingKey = VerifyingKey<NistP256>;
585
586 pub type EcdsaP256Signature = Signature<NistP256>;
587 pub type EcdsaP256DerSignature = DerSignature;
588 pub type EcdsaP256SignatureBytes = SignatureBytes<NistP256>;
589
590 pub fn new_key() -> EcdsaP256PrivateKey {
591 let mut rng = rand::thread_rng();
592 EcdsaP256PrivateKey::random(&mut rng)
593 }
594
595 pub fn from_coords_raw(x: &[u8], y: &[u8]) -> Option<EcdsaP256PublicKey> {
596 let mut field_x = EcdsaP256FieldBytes::default();
597 if x.len() != field_x.len() {
598 return None;
599 }
600
601 let mut field_y = EcdsaP256FieldBytes::default();
602 if y.len() != field_y.len() {
603 return None;
604 }
605
606 field_x.copy_from_slice(x);
607 field_y.copy_from_slice(y);
608
609 let ep = EcdsaP256PublicEncodedPoint::from_affine_coordinates(&field_x, &field_y, false);
610
611 EcdsaP256PublicKey::from_encoded_point(&ep).into_option()
612 }
613}
614
615pub mod ecdsa_p384 {
616 use ecdsa::hazmat::DigestPrimitive;
617 use ecdsa::{Signature, SignatureBytes, SigningKey, VerifyingKey};
618 use elliptic_curve::point::AffinePoint;
619 use elliptic_curve::sec1::EncodedPoint;
620 use elliptic_curve::sec1::FromEncodedPoint;
621 use elliptic_curve::{FieldBytes, PublicKey, SecretKey};
622 use p384::{ecdsa::DerSignature, NistP384};
624 pub type EcdsaP384Digest = <NistP384 as DigestPrimitive>::Digest;
627
628 pub type EcdsaP384PrivateKey = SecretKey<NistP384>;
629
630 pub type EcdsaP384FieldBytes = FieldBytes<NistP384>;
631 pub type EcdsaP384AffinePoint = AffinePoint<NistP384>;
632
633 pub type EcdsaP384PublicKey = PublicKey<NistP384>;
634
635 pub type EcdsaP384PublicEncodedPoint = EncodedPoint<NistP384>;
637
638 pub type EcdsaP384SigningKey = SigningKey<NistP384>;
639 pub type EcdsaP384VerifyingKey = VerifyingKey<NistP384>;
640
641 pub type EcdsaP384Signature = Signature<NistP384>;
642 pub type EcdsaP384DerSignature = DerSignature;
643 pub type EcdsaP384SignatureBytes = SignatureBytes<NistP384>;
644
645 pub fn new_key() -> EcdsaP384PrivateKey {
646 let mut rng = rand::thread_rng();
647 EcdsaP384PrivateKey::random(&mut rng)
648 }
649
650 pub fn from_coords_raw(x: &[u8], y: &[u8]) -> Option<EcdsaP384PublicKey> {
651 let mut field_x = EcdsaP384FieldBytes::default();
652 if x.len() != field_x.len() {
653 return None;
654 }
655
656 let mut field_y = EcdsaP384FieldBytes::default();
657 if y.len() != field_y.len() {
658 return None;
659 }
660
661 field_x.copy_from_slice(x);
662 field_y.copy_from_slice(y);
663
664 let ep = EcdsaP384PublicEncodedPoint::from_affine_coordinates(&field_x, &field_y, false);
665
666 EcdsaP384PublicKey::from_encoded_point(&ep).into_option()
667 }
668}
669
670pub mod ecdsa_p521 {
671 use ecdsa::hazmat::DigestPrimitive;
672 use ecdsa::{Signature, SignatureBytes, SigningKey, VerifyingKey};
673 use elliptic_curve::point::AffinePoint;
674 use elliptic_curve::sec1::EncodedPoint;
675 use elliptic_curve::sec1::FromEncodedPoint;
676 use elliptic_curve::{FieldBytes, PublicKey, SecretKey};
677 use p521::{ecdsa::DerSignature, NistP521};
679 pub type EcdsaP521Digest = <NistP521 as DigestPrimitive>::Digest;
682
683 pub type EcdsaP521PrivateKey = SecretKey<NistP521>;
684
685 pub type EcdsaP521FieldBytes = FieldBytes<NistP521>;
686 pub type EcdsaP521AffinePoint = AffinePoint<NistP521>;
687
688 pub type EcdsaP521PublicKey = PublicKey<NistP521>;
689
690 pub type EcdsaP521PublicEncodedPoint = EncodedPoint<NistP521>;
692
693 pub type EcdsaP521SigningKey = SigningKey<NistP521>;
694 pub type EcdsaP521VerifyingKey = VerifyingKey<NistP521>;
695
696 pub type EcdsaP521Signature = Signature<NistP521>;
697 pub type EcdsaP521DerSignature = DerSignature;
698 pub type EcdsaP521SignatureBytes = SignatureBytes<NistP521>;
699
700 pub fn new_key() -> EcdsaP521PrivateKey {
701 let mut rng = rand::thread_rng();
702 EcdsaP521PrivateKey::random(&mut rng)
703 }
704
705 pub fn from_coords_raw(x: &[u8], y: &[u8]) -> Option<EcdsaP521PublicKey> {
706 let mut field_x = EcdsaP521FieldBytes::default();
707 if x.len() != field_x.len() {
708 return None;
709 }
710
711 let mut field_y = EcdsaP521FieldBytes::default();
712 if y.len() != field_y.len() {
713 return None;
714 }
715
716 field_x.copy_from_slice(x);
717 field_y.copy_from_slice(y);
718
719 let ep = EcdsaP521PublicEncodedPoint::from_affine_coordinates(&field_x, &field_y, false);
720
721 EcdsaP521PublicKey::from_encoded_point(&ep).into_option()
722 }
723}
724
725pub mod nist_sp800_108_kdf_hmac_sha256 {
726 use crate::traits::Zeroizing;
727 use crypto_common_pre::KeySizeUser;
728 use digest_pre::consts::*;
729 use hmac_pre::Hmac;
730 use kbkdf::{Counter, Kbkdf, Params};
731 use sha2_pre::Sha256;
732
733 struct MockOutput;
734
735 impl KeySizeUser for MockOutput {
736 type KeySize = U32;
737 }
738
739 type HmacSha256 = Hmac<Sha256>;
740
741 pub fn derive_key_aes256(
742 key_in: &[u8],
743 label: &[u8],
744 context: &[u8],
745 ) -> Option<Zeroizing<Vec<u8>>> {
746 let counter = Counter::<HmacSha256, MockOutput>::default();
747 let params = Params::builder(key_in)
748 .with_label(label)
749 .with_context(context)
750 .use_l(true)
751 .use_separator(true)
752 .use_counter(true)
753 .build();
754 let key = counter.derive(params).ok()?;
755
756 let mut output = Zeroizing::new(vec![0; MockOutput::key_size()]);
757 output.copy_from_slice(key.as_slice());
758 Some(output)
759 }
760}
761
762pub mod pkcs8 {
763 pub use pkcs8::PrivateKeyInfo;
764}
765
766#[cfg(test)]
767mod tests {
768 #[test]
769 fn sha256_basic() {
770 use crate::s256::*;
771 use crate::traits::*;
772
773 let mut hasher = Sha256::new();
774 hasher.update([0, 1, 2, 3]);
775 let out: Sha256Output = hasher.finalize();
776
777 eprintln!("{:?}", out.as_slice());
778 }
779
780 #[test]
781 fn hmac_256_basic() {
782 use crate::hmac_s256::*;
783 use crate::traits::Mac;
784
785 let hmac_key = new_key();
786
787 let mut hmac = HmacSha256::new(&hmac_key);
788 hmac.update(&[0, 1, 2, 3]);
789 let out = hmac.finalize();
790
791 eprintln!("{:?}", out.into_bytes());
792 }
793
794 #[test]
795 fn hmac_512_basic() {
796 use crate::hmac_s512::*;
797
798 let hmac_key = new_hmac_sha512_key();
799
800 let mut hmac = HmacSha512::new(&hmac_key);
801 hmac.update(&[0, 1, 2, 3]);
802 let out = hmac.finalize();
803
804 eprintln!("{:?}", out.into_bytes());
805 }
806
807 #[test]
808 fn aes256gcm_basic() {
809 use crate::aes256;
810 use crate::aes256gcm::*;
811
812 let aes256gcm_key = aes256::new_key();
813
814 let cipher = Aes256Gcm::new(&aes256gcm_key);
815
816 let nonce = new_nonce();
817
818 let ciphertext = cipher
820 .encrypt(&nonce, b"plaintext message".as_ref())
821 .unwrap();
822 let plaintext = cipher.decrypt(&nonce, ciphertext.as_ref()).unwrap();
823
824 assert_eq!(&plaintext, b"plaintext message");
825
826 let nonce = new_nonce();
830
831 let mut buffer = Vec::from(b"test message, super cool");
832
833 let associated_data = b"";
835
836 let tag = cipher
837 .encrypt_in_place_detached(&nonce, associated_data, buffer.as_mut_slice())
838 .unwrap();
839
840 cipher
841 .decrypt_in_place_detached(&nonce, associated_data, &mut buffer, &tag)
842 .unwrap();
843
844 assert_eq!(buffer, b"test message, super cool");
845 }
846
847 #[test]
848 fn aes256cbc_basic() {
849 use crate::aes256;
850 use crate::aes256cbc::{self, *};
851
852 let key = aes256::new_key();
853 let iv = aes256cbc::new_iv();
854
855 let enc = aes256cbc::Aes256CbcEnc::new(&key, &iv);
856
857 let ciphertext = enc.encrypt_padded_vec_mut::<block_padding::Pkcs7>(b"plaintext message");
858
859 let dec = aes256cbc::Aes256CbcDec::new(&key, &iv);
860
861 let plaintext = dec
862 .decrypt_padded_vec_mut::<block_padding::Pkcs7>(&ciphertext)
863 .expect("Unpadding Failed");
864
865 assert_eq!(plaintext, b"plaintext message");
866 }
867
868 #[test]
869 fn aes256cbc_hmac_basic() {
870 use crate::aes256;
871 use crate::aes256cbc::{self, block_padding};
872
873 let key = aes256::new_key();
874
875 let (mac, iv, ciphertext) =
876 aes256cbc::enc::<block_padding::Pkcs7>(&key, b"plaintext message").unwrap();
877
878 let plaintext =
879 aes256cbc::dec::<block_padding::Pkcs7>(&key, &mac, &iv, &ciphertext).unwrap();
880
881 assert_eq!(plaintext, b"plaintext message");
882 }
883
884 #[test]
885 fn aes256kw_basic() {
886 use crate::aes256;
887 use crate::aes256kw::*;
888
889 let key_wrap_key = aes256::new_key();
890 let key_wrap = Aes256Kw::new(&key_wrap_key);
891
892 let key_to_wrap = aes256::new_key();
893 let mut wrapped_key = Aes256KwWrapped::default();
894
895 key_wrap.wrap(&key_to_wrap, &mut wrapped_key).unwrap();
897 let mut key_unwrapped = aes256::Aes256Key::default();
900
901 key_wrap.unwrap(&wrapped_key, &mut key_unwrapped).unwrap();
902
903 assert_eq!(key_to_wrap, key_unwrapped);
904 }
905
906 #[test]
907 fn rsa_basic() {
908 use crate::rsa::*;
909 use crate::traits::*;
910
911 let pkey = new_key(MIN_BITS).unwrap();
912
913 let pubkey = RS256PublicKey::from(&pkey);
914
915 let ciphertext = oaep_sha256_encrypt(&pubkey, b"this is a message").unwrap();
918
919 let plaintext = oaep_sha256_decrypt(&pkey, &ciphertext).unwrap();
920
921 assert_eq!(plaintext, b"this is a message");
922
923 let signing_key = RS256SigningKey::new(pkey);
925 let verifying_key = RS256VerifyingKey::new(pubkey);
926
927 let mut rng = rand::thread_rng();
928
929 let data = b"Fully sick data to sign mate.";
930
931 let signature = signing_key.sign_with_rng(&mut rng, data);
932 assert!(verifying_key.verify(data, &signature).is_ok());
933
934 let signature = signing_key.sign(data);
935 assert!(verifying_key.verify(data, &signature).is_ok());
936 }
937
938 #[test]
939 fn ecdsa_p256_basic() {
940 use crate::ecdsa_p256::*;
941 use crate::traits::*;
942
943 let priv_key = new_key();
944
945 let pub_key = priv_key.public_key();
946
947 let signer = EcdsaP256SigningKey::from(&priv_key);
948 let verifier = EcdsaP256VerifyingKey::from(&pub_key);
949
950 let data = [0, 1, 2, 3, 4, 5, 6, 7];
952
953 let sig: EcdsaP256Signature = signer.try_sign(&data).unwrap();
954
955 assert!(verifier.verify(&data, &sig).is_ok());
956
957 let mut digest = EcdsaP256Digest::new();
960 digest.update(data);
961
962 let sig: EcdsaP256Signature = signer.try_sign_digest(digest).unwrap();
963 assert!(verifier.verify(&data, &sig).is_ok());
964 }
965
966 #[test]
967 fn ecdh_p256_basic() {
968 use crate::ecdh_p256::*;
969
970 let secret_a = new_secret();
971 let secret_b = new_secret();
972
973 let public_a = secret_a.public_key();
974 let public_b = secret_b.public_key();
975
976 let derived_secret_a = secret_a.diffie_hellman(&public_b);
977 let derived_secret_b = secret_b.diffie_hellman(&public_a);
978
979 assert_eq!(
980 derived_secret_a.raw_secret_bytes(),
981 derived_secret_b.raw_secret_bytes()
982 );
983 }
984
985 #[test]
986 fn pkcs8_handling_test() {
987 use crate::ecdsa_p256;
988 use crate::traits::Pkcs8EncodePrivateKey;
989
990 use pkcs8::PrivateKeyInfo;
992
993 let ecdsa_priv_key = ecdsa_p256::new_key();
994 let ecdsa_priv_key_der = ecdsa_priv_key.to_pkcs8_der().unwrap();
995
996 let priv_key_info = PrivateKeyInfo::try_from(ecdsa_priv_key_der.as_bytes()).unwrap();
997
998 eprintln!("{:?}", priv_key_info);
999 }
1000
1001 #[test]
1002 fn rustls_mtls_basic() {
1003 use crate::test_ca::*;
1004 use crate::x509::X509Display;
1005 use elliptic_curve::SecretKey;
1006 use rustls::{
1007 self,
1008 client::{ClientConfig, ClientConnection},
1009 pki_types::{CertificateDer, PrivateKeyDer, PrivatePkcs8KeyDer, ServerName},
1010 server::{ServerConfig, ServerConnection},
1011 RootCertStore,
1012 };
1013 use std::io::Read;
1014 use std::io::Write;
1015 use std::os::unix::net::UnixStream;
1016 use std::str::FromStr;
1017 use std::sync::atomic::{AtomicU16, Ordering};
1018 use std::sync::Arc;
1019 use std::time::Duration;
1020 use std::time::SystemTime;
1021 use x509_cert::der::Encode;
1022 use x509_cert::name::Name;
1023 use x509_cert::time::Time;
1024
1025 let now = SystemTime::now();
1029 let not_before = Time::try_from(now).unwrap();
1030 let not_after = Time::try_from(now + Duration::new(3600, 0)).unwrap();
1031
1032 let (root_signing_key, root_ca_cert) = build_test_ca_root(not_before, not_after);
1033
1034 eprintln!("{}", X509Display::from(&root_ca_cert));
1035
1036 let subject = Name::from_str("CN=localhost").unwrap();
1037
1038 let (server_key, server_csr) = build_test_csr(&subject);
1039
1040 let server_cert = test_ca_sign_server_csr(
1041 not_before,
1042 not_after,
1043 &server_csr,
1044 &root_signing_key,
1045 &root_ca_cert,
1046 );
1047
1048 eprintln!("{}", X509Display::from(&server_cert));
1049
1050 use p384::pkcs8::EncodePrivateKey;
1052 let server_private_key_pkcs8_der = SecretKey::from(server_key).to_pkcs8_der().unwrap();
1053
1054 let root_ca_cert_der = root_ca_cert.to_der().unwrap();
1055 let server_cert_der = server_cert.to_der().unwrap();
1056
1057 let mut ca_roots = RootCertStore::empty();
1058
1059 ca_roots
1060 .add(CertificateDer::from(root_ca_cert_der.clone()))
1061 .unwrap();
1062
1063 let server_chain = vec![
1064 CertificateDer::from(server_cert_der),
1065 CertificateDer::from(root_ca_cert_der),
1066 ];
1067
1068 let server_private_key: PrivateKeyDer =
1069 PrivatePkcs8KeyDer::from(server_private_key_pkcs8_der.as_bytes().to_vec()).into();
1070
1071 let provider = Arc::new(rustls_rustcrypto::provider());
1072
1073 let client_tls_config: Arc<_> = ClientConfig::builder_with_provider(provider.clone())
1074 .with_safe_default_protocol_versions()
1075 .unwrap()
1076 .with_root_certificates(ca_roots)
1077 .with_no_client_auth()
1078 .into();
1079
1080 let server_tls_config: Arc<_> = ServerConfig::builder_with_provider(provider)
1081 .with_safe_default_protocol_versions()
1082 .unwrap()
1083 .with_no_client_auth()
1084 .with_single_cert(server_chain, server_private_key)
1085 .map(Arc::new)
1086 .expect("bad certificate/key");
1087
1088 let server_name = ServerName::try_from("localhost").expect("invalid DNS name");
1089
1090 let (mut server_unix_stream, mut client_unix_stream) = UnixStream::pair().unwrap();
1091
1092 let atomic = Arc::new(AtomicU16::new(0));
1093
1094 let atomic_t = atomic.clone();
1095
1096 let handle = std::thread::spawn(move || {
1097 let mut client_connection =
1098 ClientConnection::new(client_tls_config, server_name).unwrap();
1099
1100 let mut client = rustls::Stream::new(&mut client_connection, &mut client_unix_stream);
1101
1102 client.write_all(b"hello").unwrap();
1103
1104 while atomic_t.load(Ordering::Relaxed) != 1 {
1105 std::thread::sleep(std::time::Duration::from_millis(1));
1106 }
1107
1108 println!("THREAD DONE");
1109 });
1110
1111 let mut server_connection = ServerConnection::new(server_tls_config).unwrap();
1112
1113 server_connection
1114 .complete_io(&mut server_unix_stream)
1115 .unwrap();
1116
1117 server_connection
1118 .complete_io(&mut server_unix_stream)
1119 .unwrap();
1120
1121 let mut buf: [u8; 5] = [0; 5];
1122 server_connection.reader().read(&mut buf).unwrap();
1123
1124 assert_eq!(&buf, b"hello");
1125
1126 atomic.store(1, Ordering::Relaxed);
1127
1128 handle.join().unwrap();
1130 }
1131}