superboring 0.1.4

A reimplementation of the 'boring' crate in pure Rust.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
use hmac_sha256::Hash as Sha256;
use hmac_sha512::sha384::Hash as Sha384;
use hmac_sha512::Hash as Sha512;
use std::ffi::c_int;

#[allow(unused_imports)]
use rrsa::pkcs1::{
    DecodeRsaPrivateKey as _, DecodeRsaPublicKey as _, EncodeRsaPrivateKey as _,
    EncodeRsaPublicKey as _,
};
#[allow(unused_imports)]
use rrsa::pkcs8::{
    AssociatedOid as _, DecodePrivateKey as _, DecodePublicKey as _, EncodePrivateKey as _,
    EncodePublicKey as _,
};
#[allow(unused_imports)]
use rrsa::signature::{
    DigestSigner as _, DigestVerifier as _, Keypair as _, KeypairRef as _, PrehashSignature as _,
    RandomizedDigestSigner as _, RandomizedSigner as _, SignatureEncoding as _, Signer as _,
    SignerMut as _, Verifier as _,
};
#[allow(unused_imports)]
use rrsa::traits::{
    Decryptor as _, EncryptingKeypair as _, PaddingScheme as _, PrivateKeyParts as _,
    PublicKeyParts as _, RandomizedDecryptor as _, RandomizedEncryptor as _, SignatureScheme as _,
};

pub mod reexports {
    pub use hmac_sha256;
    pub use hmac_sha512;
    pub use rand;
    pub use rrsa as rsa;
}

#[allow(unused_imports)]
use rsa::*;
pub mod rsa {
    use rrsa::pkcs8::EncodePrivateKey;

    #[allow(unused_imports)]
    use super::*;

    #[allow(clippy::large_enum_variant)]
    #[derive(Debug, Clone, PartialEq, Eq, Default)]
    pub enum RsaKey {
        #[default]
        None,
        Public(rrsa::RsaPublicKey),
        Private(rrsa::RsaPrivateKey),
    }

    #[derive(Debug, Clone, Default, PartialEq, Eq)]
    pub struct Rsa<T> {
        pub rsa_key: RsaKey,
        pub _marker: std::marker::PhantomData<T>,
    }

    #[derive(Debug, Default, Copy, Clone, PartialEq, Eq)]
    pub enum PaddingId {
        #[default]
        None,
        Pkcs1,
        Pkcs1Pss,
    }

    #[derive(Debug, Copy, Clone, PartialEq, Eq)]
    pub struct Padding {
        id: PaddingId,
    }

    impl Padding {
        pub const NONE: Padding = Padding {
            id: PaddingId::None,
        };

        pub const PKCS1: Padding = Padding {
            id: PaddingId::Pkcs1,
        };

        pub const PKCS1_PSS: Padding = Padding {
            id: PaddingId::Pkcs1Pss,
        };
    }

    impl Rsa<Public> {
        pub fn new() -> Self {
            Rsa {
                rsa_key: RsaKey::None,
                _marker: std::marker::PhantomData,
            }
        }

        pub fn bits(&self) -> usize {
            let rsa_key = if let RsaKey::Public(x) = &self.rsa_key {
                x
            } else {
                unreachable!();
            };
            rsa_key.size() * 8
        }

        pub fn check_key(&self) -> Result<bool, ErrorStack> {
            match self.bits() {
                2048 | 3072 | 4096 => Ok(true),
                _ => Ok(false),
            }
        }

        pub fn public_key_from_der(der: &[u8]) -> Result<Rsa<Public>, ErrorStack> {
            let rsa_public_key = rrsa::RsaPublicKey::from_public_key_der(der)
                .map_err(|_| ErrorStack::InvalidPublicKey)?;
            let rsa_key = RsaKey::Public(rsa_public_key);
            Ok(Rsa {
                rsa_key,
                _marker: std::marker::PhantomData,
            })
        }

        pub fn public_key_from_der_pkcs1(der: &[u8]) -> Result<Rsa<Public>, ErrorStack> {
            let rsa_public_key = rrsa::RsaPublicKey::from_pkcs1_der(der)
                .map_err(|_| ErrorStack::InvalidPublicKey)?;
            let rsa_key = RsaKey::Public(rsa_public_key);
            Ok(Rsa {
                rsa_key,
                _marker: std::marker::PhantomData,
            })
        }

        pub fn public_key_from_pem(pem: &[u8]) -> Result<Rsa<Public>, ErrorStack> {
            let rsa_pem = std::str::from_utf8(pem).map_err(|_| ErrorStack::InvalidPublicKey)?;
            let rsa_public_key = rrsa::RsaPublicKey::from_public_key_pem(rsa_pem)
                .map_err(|_| ErrorStack::InvalidPublicKey)?;
            let rsa_key = RsaKey::Public(rsa_public_key);
            Ok(Rsa {
                rsa_key,
                _marker: std::marker::PhantomData,
            })
        }

        pub fn public_key_from_pem_pkcs1(pem: &[u8]) -> Result<Rsa<Public>, ErrorStack> {
            let rsa_pem = std::str::from_utf8(pem).map_err(|_| ErrorStack::InvalidPublicKey)?;
            let rsa_public_key = rrsa::RsaPublicKey::from_pkcs1_pem(rsa_pem)
                .map_err(|_| ErrorStack::InvalidPublicKey)?;
            let rsa_key = RsaKey::Public(rsa_public_key);
            Ok(Rsa {
                rsa_key,
                _marker: std::marker::PhantomData,
            })
        }

        pub fn from_public_components(n: BigNum, e: BigNum) -> Result<Rsa<Public>, ErrorStack> {
            let rsa_public_key = rrsa::RsaPublicKey::new(n.rsa_bn, e.rsa_bn)
                .map_err(|_| ErrorStack::InvalidPublicKey)?;
            let rsa_key = RsaKey::Public(rsa_public_key);
            Ok(Rsa {
                rsa_key,
                _marker: std::marker::PhantomData,
            })
        }

        pub fn n(&self) -> BigNum {
            let rsa_key = if let RsaKey::Public(x) = &self.rsa_key {
                x
            } else {
                unreachable!();
            };
            BigNum {
                rsa_bn: rsa_key.n().clone(),
            }
        }

        pub fn e(&self) -> BigNum {
            let rsa_key = if let RsaKey::Public(x) = &self.rsa_key {
                x
            } else {
                unreachable!();
            };
            BigNum {
                rsa_bn: rsa_key.e().clone(),
            }
        }

        pub fn public_key_to_der(&self) -> Result<Vec<u8>, ErrorStack> {
            let rsa_key = if let RsaKey::Public(x) = &self.rsa_key {
                x
            } else {
                unreachable!();
            };
            Ok(rsa_key
                .to_public_key_der()
                .map_err(|_| ErrorStack::InvalidPublicKey)?
                .into_vec())
        }

        pub fn public_key_to_der_pkcs1(&self) -> Result<Vec<u8>, ErrorStack> {
            let rsa_key = if let RsaKey::Public(x) = &self.rsa_key {
                x
            } else {
                unreachable!();
            };
            Ok(rsa_key
                .to_pkcs1_der()
                .map_err(|_| ErrorStack::InvalidPublicKey)?
                .into_vec())
        }

        pub fn public_key_to_pem(&self) -> Result<Vec<u8>, ErrorStack> {
            let rsa_key = if let RsaKey::Public(x) = &self.rsa_key {
                x
            } else {
                unreachable!();
            };
            Ok(rsa_key
                .to_public_key_pem(Default::default())
                .map_err(|_| ErrorStack::InvalidPublicKey)?
                .into_bytes())
        }

        pub fn public_key_to_pem_pkcs1(&self) -> Result<Vec<u8>, ErrorStack> {
            let rsa_key = if let RsaKey::Public(x) = &self.rsa_key {
                x
            } else {
                unreachable!();
            };
            Ok(rsa_key
                .to_pkcs1_pem(Default::default())
                .map_err(|_| ErrorStack::InvalidPublicKey)?
                .into_bytes())
        }

        pub fn public_encrypt(
            &self,
            from: &[u8],
            to: &mut [u8],
            padding: Padding,
        ) -> Result<usize, ErrorStack> {
            let rsa_key = if let RsaKey::Public(x) = &self.rsa_key {
                x
            } else {
                unreachable!();
            };
            let padding = match padding {
                Padding::NONE => panic!("Padding not set"),
                Padding::PKCS1 => rrsa::Pkcs1v15Encrypt,
                Padding::PKCS1_PSS => panic!("Invalid padding for encryption"),
            };
            let mut rng = rand::thread_rng();
            let c = rsa_key
                .encrypt(&mut rng, padding, from)
                .map_err(|_| ErrorStack::InvalidPublicKey)?;
            let len = c.len();
            to.fill(0);
            to[0..len].copy_from_slice(&c);
            Ok(len)
        }
    }

    impl Rsa<Private> {
        pub fn generate(bits: u32) -> Result<Rsa<Private>, ErrorStack> {
            match bits {
                2048 | 3072 | 4096 => {}
                _ => return Err(ErrorStack::UnsupportedModulus),
            };
            let mut rng = rand::thread_rng();
            let rsa_key = rrsa::RsaPrivateKey::new(&mut rng, bits as _)
                .map_err(|_| ErrorStack::InternalError)?;
            let rsa_key = RsaKey::Private(rsa_key);
            Ok(Rsa {
                rsa_key,
                _marker: std::marker::PhantomData,
            })
        }

        pub fn bits(&self) -> usize {
            let rsa_key = if let RsaKey::Private(x) = &self.rsa_key {
                x
            } else {
                unreachable!();
            };
            rsa_key.size() * 8
        }

        pub fn check_key(&self) -> Result<bool, ErrorStack> {
            let rsa_key = if let RsaKey::Private(x) = &self.rsa_key {
                x
            } else {
                unreachable!();
            };
            match self.bits() {
                2048 | 3072 | 4096 => {}
                _ => return Ok(false),
            };
            if rsa_key.validate().is_err() {
                return Ok(false);
            }
            Ok(true)
        }

        pub fn public_key(&self) -> Result<Rsa<Public>, ErrorStack> {
            let n = self.n();
            let e = self.e();
            Rsa::from_public_components(n, e)
        }

        pub fn private_key_from_pem(pem: &[u8]) -> Result<Rsa<Private>, ErrorStack> {
            let rsa_pem = std::str::from_utf8(pem).map_err(|_| ErrorStack::InvalidPrivateKey)?;
            let rsa_pem = rsa_pem.trim();
            let mut rsa_key = rrsa::RsaPrivateKey::from_pkcs8_pem(rsa_pem)
                .or_else(|_| rrsa::RsaPrivateKey::from_pkcs1_pem(rsa_pem))
                .map_err(|_| ErrorStack::InvalidPrivateKey)?;
            rsa_key
                .validate()
                .map_err(|_| ErrorStack::InvalidPrivateKey)?;
            rsa_key
                .precompute()
                .map_err(|_| ErrorStack::InvalidPrivateKey)?;
            let rsa_key = RsaKey::Private(rsa_key);
            Ok(Rsa {
                rsa_key,
                _marker: std::marker::PhantomData,
            })
        }

        pub fn private_key_from_der(der: &[u8]) -> Result<Rsa<Private>, ErrorStack> {
            let rsa_key = rrsa::RsaPrivateKey::from_pkcs8_der(der)
                .or_else(|_| rrsa::RsaPrivateKey::from_pkcs1_der(der))
                .map_err(|_| ErrorStack::InvalidPrivateKey)?;
            let rsa_key = RsaKey::Private(rsa_key);
            Ok(Rsa {
                rsa_key,
                _marker: std::marker::PhantomData,
            })
        }

        pub fn private_key_to_pem(&self) -> Result<Vec<u8>, ErrorStack> {
            let rsa_key = if let RsaKey::Private(x) = &self.rsa_key {
                x
            } else {
                unreachable!();
            };
            let bytes = rsa_key
                .to_pkcs8_pem(Default::default())
                .map_err(|_| ErrorStack::InvalidPrivateKey)?
                .as_bytes()
                .to_vec();
            Ok(bytes)
        }

        pub fn private_key_to_der(&self) -> Result<Vec<u8>, ErrorStack> {
            let rsa_key = if let RsaKey::Private(x) = &self.rsa_key {
                x
            } else {
                unreachable!();
            };
            let bytes = rsa_key
                .to_pkcs8_der()
                .map_err(|_| ErrorStack::InvalidPrivateKey)?
                .as_bytes()
                .to_vec();
            Ok(bytes)
        }

        pub fn n(&self) -> BigNum {
            let rsa_key = if let RsaKey::Private(x) = &self.rsa_key {
                x
            } else {
                unreachable!();
            };
            BigNum {
                rsa_bn: rsa_key.n().clone(),
            }
        }

        pub fn d(&self) -> BigNum {
            let rsa_key = if let RsaKey::Private(x) = &self.rsa_key {
                x
            } else {
                unreachable!();
            };
            BigNum {
                rsa_bn: rsa_key.d().clone(),
            }
        }

        pub fn e(&self) -> BigNum {
            let rsa_key = if let RsaKey::Private(x) = &self.rsa_key {
                x
            } else {
                unreachable!();
            };
            BigNum {
                rsa_bn: rsa_key.e().clone(),
            }
        }

        pub fn p(&self) -> BigNum {
            let rsa_key = if let RsaKey::Private(x) = &self.rsa_key {
                x
            } else {
                unreachable!();
            };
            BigNum {
                rsa_bn: rsa_key.primes()[0].clone(),
            }
        }

        pub fn q(&self) -> BigNum {
            let rsa_key = if let RsaKey::Private(x) = &self.rsa_key {
                x
            } else {
                unreachable!();
            };
            BigNum {
                rsa_bn: rsa_key.primes()[1].clone(),
            }
        }

        pub fn private_decrypt(
            &self,
            from: &[u8],
            to: &mut [u8],
            padding: Padding,
        ) -> Result<usize, ErrorStack> {
            let rsa_key = if let RsaKey::Private(x) = &self.rsa_key {
                x
            } else {
                unreachable!();
            };
            let padding = match padding {
                Padding::NONE => panic!("Padding not set"),
                Padding::PKCS1 => rrsa::Pkcs1v15Encrypt,
                Padding::PKCS1_PSS => panic!("Invalid padding for encryption"),
            };
            let mut rng = rand::thread_rng();
            let m = rsa_key
                .decrypt_blinded(&mut rng, padding, from)
                .map_err(|_| ErrorStack::InvalidPrivateKey)?;
            let len = m.len();
            to.fill(0);
            to[0..len].copy_from_slice(&m);
            Ok(len)
        }
    }
}

#[allow(unused_imports)]
use error::*;
pub mod error {
    #[allow(unused_imports)]
    use super::*;

    pub enum ErrorStack {
        InternalError,
        InvalidPrivateKey,
        InvalidPublicKey,
        Overflow,
        UnsupportedModulus,
    }

    impl std::fmt::Display for ErrorStack {
        fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
            match self {
                ErrorStack::InternalError => write!(f, "Internal error"),
                ErrorStack::InvalidPrivateKey => write!(f, "Invalid private key"),
                ErrorStack::InvalidPublicKey => write!(f, "Invalid public key"),
                ErrorStack::Overflow => write!(f, "Overflow"),
                ErrorStack::UnsupportedModulus => write!(f, "Unsupported modulus"),
            }
        }
    }

    impl std::fmt::Debug for ErrorStack {
        fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
            write!(f, "Superboring error: {}", self)
        }
    }

    impl std::error::Error for ErrorStack {}
}

#[allow(unused_imports)]
use bn::*;
pub mod bn {
    #[allow(unused_imports)]
    use super::*;

    #[derive(Debug, Clone, PartialEq, Eq)]
    pub struct BigNum {
        pub rsa_bn: rrsa::BigUint,
    }

    pub type BigNumRef<'a> = BigNum;

    impl BigNum {
        pub fn from_slice(slice: &[u8]) -> Result<Self, ErrorStack> {
            let rsa_bn = rrsa::BigUint::from_bytes_be(slice);
            Ok(BigNum { rsa_bn })
        }

        pub fn to_vec(&self) -> Vec<u8> {
            self.rsa_bn.to_bytes_be()
        }

        pub fn to_owned(&self) -> Result<BigNum, ErrorStack> {
            Ok(self.clone())
        }
    }
}

#[allow(unused_imports)]
use hash::*;
pub mod hash {
    #[allow(unused_imports)]
    use super::*;

    #[derive(Debug, Clone, PartialEq, Eq)]
    pub enum MessageDigest {
        Sha256,
        Sha384,
        Sha512,
    }

    impl MessageDigest {
        pub fn sha256() -> MessageDigest {
            MessageDigest::Sha256
        }

        pub fn sha384() -> MessageDigest {
            MessageDigest::Sha384
        }

        pub fn sha512() -> MessageDigest {
            MessageDigest::Sha512
        }
    }
}

#[allow(unused_imports)]
use pkey::*;
pub mod pkey {
    #[allow(unused_imports)]
    use super::*;

    #[derive(Debug, Copy, Clone, PartialEq, Eq)]
    pub enum Public {}

    #[derive(Debug, Copy, Clone, PartialEq, Eq)]
    pub enum Private {}

    pub trait HasPublic {}

    impl HasPublic for Public {}

    pub trait HasPrivate {}

    impl HasPrivate for Private {}

    #[allow(clippy::large_enum_variant)]
    #[derive(Debug, Clone, Default, PartialEq, Eq)]
    pub enum PKey<T> {
        #[default]
        None,
        Rsa(Rsa<T>),
    }

    impl<T> PKey<T> {
        pub fn from_rsa(rsa: Rsa<T>) -> Result<PKey<T>, ErrorStack> {
            Ok(PKey::Rsa(rsa))
        }
    }
}

#[allow(unused_imports)]
use sign::*;
pub mod sign {
    #[allow(unused_imports)]
    use super::*;

    #[derive(Debug, Copy, Clone, PartialEq, Eq)]
    pub struct RsaPssSaltlen {
        pub len: c_int,
    }

    impl Default for RsaPssSaltlen {
        fn default() -> Self {
            RsaPssSaltlen { len: -1 }
        }
    }

    impl RsaPssSaltlen {
        pub fn custom(len: c_int) -> Self {
            RsaPssSaltlen { len }
        }

        pub const DIGEST_LENGTH: RsaPssSaltlen = RsaPssSaltlen { len: -1 };
        pub const MAXIMUM_LENGTH: RsaPssSaltlen = RsaPssSaltlen { len: -2 };
    }

    #[derive(Clone, Default)]
    pub enum AnyHash {
        #[default]
        None,
        Sha256(Sha256),
        Sha384(Sha384),
        Sha512(Sha512),
    }

    #[derive(Clone)]
    pub struct Signer<'t, T> {
        pub message_digest: MessageDigest,
        pub pkey_ref: &'t PKey<T>,
        pub padding: Padding,
        pub salt_len: RsaPssSaltlen,
        pub any_hash: AnyHash,
    }

    impl<'t, T> Signer<'t, T> {
        pub fn new(type_: MessageDigest, pkey: &'t PKey<T>) -> Result<Signer<'t, T>, ErrorStack>
        where
            T: HasPrivate,
        {
            let any_hash = match type_ {
                MessageDigest::Sha256 => AnyHash::Sha256(Sha256::new()),
                MessageDigest::Sha384 => AnyHash::Sha384(Sha384::new()),
                MessageDigest::Sha512 => AnyHash::Sha512(Sha512::new()),
            };
            Ok(Signer {
                message_digest: type_,
                pkey_ref: pkey,
                padding: Padding::NONE,
                salt_len: RsaPssSaltlen::default(),
                any_hash,
            })
        }

        pub fn set_rsa_padding(&mut self, padding: Padding) -> Result<(), ErrorStack> {
            self.padding = padding;
            Ok(())
        }

        pub fn rsa_padding(&self) -> Result<Padding, ErrorStack> {
            Ok(self.padding)
        }

        pub fn set_rsa_pss_saltlen(&mut self, len: RsaPssSaltlen) -> Result<(), ErrorStack> {
            self.salt_len = len;
            Ok(())
        }

        pub fn rsa_pss_saltlen(&self) -> Result<RsaPssSaltlen, ErrorStack> {
            Ok(self.salt_len)
        }

        pub fn update(&mut self, buf: &[u8]) -> Result<(), ErrorStack> {
            match &mut self.any_hash {
                AnyHash::None => unreachable!("AnyHash::None"),
                AnyHash::Sha256(x) => x.update(buf),
                AnyHash::Sha384(x) => x.update(buf),
                AnyHash::Sha512(x) => x.update(buf),
            };
            Ok(())
        }

        #[allow(clippy::len_without_is_empty)]
        pub fn len(&self) -> Result<usize, ErrorStack> {
            let rsa_key = if let PKey::Rsa(x) = self.pkey_ref {
                x
            } else {
                unreachable!();
            };
            let rsa_key = if let RsaKey::Private(x) = &rsa_key.rsa_key {
                x
            } else {
                unreachable!();
            };
            Ok(rsa_key.size())
        }

        pub fn sign(&self, buf: &mut [u8]) -> Result<usize, ErrorStack> {
            let sig = self.sign_to_vec()?;
            if buf.len() < sig.len() {
                return Err(ErrorStack::Overflow);
            }
            buf.copy_from_slice(&sig);
            Ok(sig.len())
        }

        pub fn sign_to_vec(&self) -> Result<Vec<u8>, ErrorStack> {
            let rsa_key = if let PKey::Rsa(x) = self.pkey_ref {
                x
            } else {
                unreachable!();
            };
            let rsa_key = if let RsaKey::Private(x) = &rsa_key.rsa_key {
                x
            } else {
                unreachable!();
            };
            let mut rng = rand::thread_rng();
            let rsa_key = rsa_key.clone();
            match self.padding {
                Padding::NONE => panic!("Padding not set"),
                Padding::PKCS1 => match self.any_hash {
                    AnyHash::None => unreachable!("AnyHash::None"),
                    AnyHash::Sha256(x) => {
                        let signing_key = rrsa::pkcs1v15::SigningKey::<Sha256>::new(rsa_key);
                        Ok(signing_key
                            .sign_digest_with_rng(&mut rng, x)
                            .to_bytes()
                            .into_vec())
                    }
                    AnyHash::Sha384(x) => {
                        let signing_key = rrsa::pkcs1v15::SigningKey::<Sha384>::new(rsa_key);
                        Ok(signing_key
                            .sign_digest_with_rng(&mut rng, x)
                            .to_bytes()
                            .into_vec())
                    }
                    AnyHash::Sha512(x) => {
                        let signing_key = rrsa::pkcs1v15::SigningKey::<Sha512>::new(rsa_key);
                        Ok(signing_key
                            .sign_digest_with_rng(&mut rng, x)
                            .to_bytes()
                            .into_vec())
                    }
                },
                Padding::PKCS1_PSS => {
                    let hash_len = match self.message_digest {
                        MessageDigest::Sha256 => 32,
                        MessageDigest::Sha384 => 48,
                        MessageDigest::Sha512 => 64,
                    };
                    let salt_len = match self.salt_len.len {
                        -1 => hash_len,
                        -2 => rsa_key.size() - hash_len - 2,
                        x => x as _,
                    };
                    match self.any_hash {
                        AnyHash::None => unreachable!("AnyHash::None"),
                        AnyHash::Sha256(x) => {
                            let signing_key =
                                rrsa::pss::BlindedSigningKey::<Sha256>::new_with_salt_len(
                                    rsa_key, salt_len,
                                );
                            Ok(signing_key
                                .sign_digest_with_rng(&mut rng, x)
                                .to_bytes()
                                .into_vec())
                        }
                        AnyHash::Sha384(x) => {
                            let signing_key =
                                rrsa::pss::BlindedSigningKey::<Sha384>::new_with_salt_len(
                                    rsa_key, salt_len,
                                );
                            Ok(signing_key
                                .sign_digest_with_rng(&mut rng, x)
                                .to_bytes()
                                .into_vec())
                        }
                        AnyHash::Sha512(x) => {
                            let signing_key =
                                rrsa::pss::BlindedSigningKey::<Sha512>::new_with_salt_len(
                                    rsa_key, salt_len,
                                );
                            Ok(signing_key
                                .sign_digest_with_rng(&mut rng, x)
                                .to_bytes()
                                .into_vec())
                        }
                    }
                }
            }
        }
    }

    #[derive(Clone)]
    pub struct Verifier<'t, T> {
        pub message_digest: MessageDigest,
        pub pkey_ref: &'t PKey<T>,
        pub padding: Padding,
        pub salt_len: RsaPssSaltlen,
        pub any_hash: AnyHash,
    }

    impl<'t, T> Verifier<'t, T> {
        pub fn new(type_: MessageDigest, pkey: &'t PKey<T>) -> Result<Verifier<'t, T>, ErrorStack>
        where
            T: HasPublic,
        {
            let any_hash = match type_ {
                MessageDigest::Sha256 => AnyHash::Sha256(Sha256::new()),
                MessageDigest::Sha384 => AnyHash::Sha384(Sha384::new()),
                MessageDigest::Sha512 => AnyHash::Sha512(Sha512::new()),
            };
            Ok(Verifier {
                message_digest: type_,
                pkey_ref: pkey,
                padding: Padding::NONE,
                salt_len: RsaPssSaltlen::default(),
                any_hash,
            })
        }

        pub fn set_rsa_padding(&mut self, padding: Padding) -> Result<(), ErrorStack> {
            self.padding = padding;
            Ok(())
        }

        pub fn rsa_padding(&self) -> Result<Padding, ErrorStack> {
            Ok(self.padding)
        }

        pub fn set_rsa_pss_saltlen(&mut self, len: RsaPssSaltlen) -> Result<(), ErrorStack> {
            self.salt_len = len;
            Ok(())
        }

        pub fn rsa_pss_saltlen(&self) -> Result<RsaPssSaltlen, ErrorStack> {
            Ok(self.salt_len)
        }

        pub fn update(&mut self, buf: &[u8]) -> Result<(), ErrorStack> {
            match &mut self.any_hash {
                AnyHash::None => unreachable!("AnyHash::None"),
                AnyHash::Sha256(x) => x.update(buf),
                AnyHash::Sha384(x) => x.update(buf),
                AnyHash::Sha512(x) => x.update(buf),
            };
            Ok(())
        }

        pub fn verify(&self, signature: &[u8]) -> Result<bool, ErrorStack> {
            let rsa_key = if let PKey::Rsa(x) = self.pkey_ref {
                x
            } else {
                unreachable!();
            };
            let rsa_key = if let RsaKey::Public(x) = &rsa_key.rsa_key {
                x
            } else {
                unreachable!();
            };
            let rsa_key = rsa_key.clone();
            match self.padding {
                Padding::NONE => panic!("Padding not set"),
                Padding::PKCS1 => {
                    let rsa_signature = match rrsa::pkcs1v15::Signature::try_from(signature) {
                        Ok(x) => x,
                        Err(_) => return Ok(false),
                    };
                    match self.any_hash {
                        AnyHash::None => unreachable!("AnyHash::None"),
                        AnyHash::Sha256(x) => {
                            let verifying_key =
                                rrsa::pkcs1v15::VerifyingKey::<Sha256>::new(rsa_key);
                            Ok(verifying_key.verify_digest(x, &rsa_signature).is_ok())
                        }
                        AnyHash::Sha384(x) => {
                            let verifying_key =
                                rrsa::pkcs1v15::VerifyingKey::<Sha384>::new(rsa_key);
                            Ok(verifying_key.verify_digest(x, &rsa_signature).is_ok())
                        }
                        AnyHash::Sha512(x) => {
                            let verifying_key =
                                rrsa::pkcs1v15::VerifyingKey::<Sha512>::new(rsa_key);
                            Ok(verifying_key.verify_digest(x, &rsa_signature).is_ok())
                        }
                    }
                }
                Padding::PKCS1_PSS => {
                    let hash_len = match self.message_digest {
                        MessageDigest::Sha256 => 32,
                        MessageDigest::Sha384 => 48,
                        MessageDigest::Sha512 => 64,
                    };
                    let salt_len = match self.salt_len.len {
                        -1 => hash_len,
                        -2 => rsa_key.size() - hash_len - 2,
                        x => x as _,
                    };
                    let rsa_signature = match rrsa::pss::Signature::try_from(signature) {
                        Ok(x) => x,
                        Err(_) => return Ok(false),
                    };
                    match self.any_hash {
                        AnyHash::None => unreachable!("AnyHash::None"),
                        AnyHash::Sha256(x) => {
                            let verifying_key =
                                rrsa::pss::VerifyingKey::<Sha256>::new_with_salt_len(
                                    rsa_key, salt_len,
                                );
                            Ok(verifying_key.verify_digest(x, &rsa_signature).is_ok())
                        }
                        AnyHash::Sha384(x) => {
                            let verifying_key =
                                rrsa::pss::VerifyingKey::<Sha384>::new_with_salt_len(
                                    rsa_key, salt_len,
                                );
                            Ok(verifying_key.verify_digest(x, &rsa_signature).is_ok())
                        }
                        AnyHash::Sha512(x) => {
                            let verifying_key =
                                rrsa::pss::VerifyingKey::<Sha512>::new_with_salt_len(
                                    rsa_key, salt_len,
                                );
                            Ok(verifying_key.verify_digest(x, &rsa_signature).is_ok())
                        }
                    }
                }
            }
        }

        pub fn verify_oneshot(&mut self, signature: &[u8], buf: &[u8]) -> Result<bool, ErrorStack> {
            self.update(buf)?;
            self.verify(signature)
        }
    }
}

#[test]
fn test_rsa_pkcs1() {
    let sk = Rsa::generate(2048).unwrap();
    let pk = sk.public_key().unwrap();

    let sk = PKey::from_rsa(sk).unwrap();
    let pk = PKey::from_rsa(pk).unwrap();

    let mut signer = Signer::new(MessageDigest::Sha256, &sk).unwrap();
    let mut verifier = Verifier::new(MessageDigest::Sha256, &pk).unwrap();

    signer.set_rsa_padding(Padding::PKCS1).unwrap();
    verifier.set_rsa_padding(Padding::PKCS1).unwrap();

    signer.update(b"hello").unwrap();
    let signature = signer.sign_to_vec().unwrap();

    verifier.update(b"hello").unwrap();
    let res = verifier.verify(&signature).unwrap();
    assert!(res);
}

#[test]
fn test_rsa_pss() {
    let sk = Rsa::generate(2048).unwrap();
    let pk = sk.public_key().unwrap();

    let sk = PKey::from_rsa(sk).unwrap();
    let pk = PKey::from_rsa(pk).unwrap();

    let mut signer = Signer::new(MessageDigest::Sha384, &sk).unwrap();
    let mut verifier = Verifier::new(MessageDigest::Sha384, &pk).unwrap();

    signer.set_rsa_padding(Padding::PKCS1_PSS).unwrap();
    verifier.set_rsa_padding(Padding::PKCS1_PSS).unwrap();

    signer.update(b"hello").unwrap();
    let signature = signer.sign_to_vec().unwrap();

    verifier.update(b"hello").unwrap();
    let res = verifier.verify(&signature).unwrap();
    assert!(res);
}

#[test]
fn test_rsa_encrypt_decrypt() {
    let sk = Rsa::generate(2048).unwrap();
    let pk = sk.public_key().unwrap();

    let mut ciphertext = [0u8; 256];
    let mut recovered_plaintext = [0u8; 256];

    let len = pk
        .public_encrypt(b"hello", &mut ciphertext, Padding::PKCS1)
        .unwrap();
    let len2 = sk
        .private_decrypt(
            &ciphertext[0..len],
            &mut recovered_plaintext,
            Padding::PKCS1,
        )
        .unwrap();

    assert_eq!(&recovered_plaintext[0..len2], b"hello");
}