Skip to main content

crypto_glue/
lib.rs

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