forked from wolfSSL/wolfssl
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathrsa.rs
More file actions
1287 lines (1254 loc) · 50.7 KB
/
rsa.rs
File metadata and controls
1287 lines (1254 loc) · 50.7 KB
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
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
* Copyright (C) 2006-2026 wolfSSL Inc.
*
* This file is part of wolfSSL.
*
* wolfSSL is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 3 of the License, or
* (at your option) any later version.
*
* wolfSSL is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1335, USA
*/
/*!
This module provides a Rust wrapper for the wolfCrypt library's RSA
functionality.
The primary component is the `RSA` struct, which manages the lifecycle of a
wolfSSL `RsaKey` object. It ensures proper initialization and deallocation.
# Examples
```rust
#[cfg(random)]
{
use std::fs;
use wolfssl_wolfcrypt::random::RNG;
use wolfssl_wolfcrypt::rsa::RSA;
let mut rng = RNG::new().expect("Error creating RNG");
let key_path = "../../../certs/client-keyPub.der";
let der: Vec<u8> = fs::read(key_path).expect("Error reading key file");
let mut rsa = RSA::new_public_from_der(&der).expect("Error with new_public_from_der()");
rsa.set_rng(&mut rng).expect("Error with set_rng()");
let plain: &[u8] = b"Test message";
let mut enc: [u8; 512] = [0; 512];
let enc_len = rsa.public_encrypt(plain, &mut enc, &mut rng).expect("Error with public_encrypt()");
assert!(enc_len > 0 && enc_len <= 512);
let key_path = "../../../certs/client-key.der";
let der: Vec<u8> = fs::read(key_path).expect("Error reading key file");
let mut rsa = RSA::new_from_der(&der).expect("Error with new_from_der()");
rsa.set_rng(&mut rng).expect("Error with set_rng()");
let mut plain_out: [u8; 512] = [0; 512];
let dec_len = rsa.private_decrypt(&enc[0..enc_len], &mut plain_out).expect("Error with private_decrypt()");
assert!(dec_len as usize == plain.len());
assert_eq!(plain_out[0..dec_len], *plain);
}
```
*/
#![cfg(rsa)]
use crate::sys;
#[cfg(random)]
use crate::random::RNG;
use std::mem::{MaybeUninit};
/// The `RSA` struct manages the lifecycle of a wolfSSL `RsaKey` object.
///
/// It ensures proper initialization and deallocation.
///
/// An instance can be created with `new_from_der()`, `new_public_from_der()`,
/// or `generate()`.
pub struct RSA {
wc_rsakey: sys::RsaKey,
}
impl RSA {
// Hash type constants used for PSS sign and verify methods.
pub const HASH_TYPE_NONE : u32 = sys::wc_HashType_WC_HASH_TYPE_NONE;
pub const HASH_TYPE_MD2 : u32 = sys::wc_HashType_WC_HASH_TYPE_MD2;
pub const HASH_TYPE_MD4 : u32 = sys::wc_HashType_WC_HASH_TYPE_MD4;
pub const HASH_TYPE_MD5 : u32 = sys::wc_HashType_WC_HASH_TYPE_MD5;
#[cfg(sha)]
pub const HASH_TYPE_SHA : u32 = sys::wc_HashType_WC_HASH_TYPE_SHA;
#[cfg(sha256)]
pub const HASH_TYPE_SHA224 : u32 = sys::wc_HashType_WC_HASH_TYPE_SHA224;
#[cfg(sha256)]
pub const HASH_TYPE_SHA256 : u32 = sys::wc_HashType_WC_HASH_TYPE_SHA256;
#[cfg(sha512)]
pub const HASH_TYPE_SHA384 : u32 = sys::wc_HashType_WC_HASH_TYPE_SHA384;
#[cfg(sha512)]
pub const HASH_TYPE_SHA512 : u32 = sys::wc_HashType_WC_HASH_TYPE_SHA512;
pub const HASH_TYPE_MD5_SHA : u32 = sys::wc_HashType_WC_HASH_TYPE_MD5_SHA;
#[cfg(sha3)]
pub const HASH_TYPE_SHA3_224 : u32 = sys::wc_HashType_WC_HASH_TYPE_SHA3_224;
#[cfg(sha3)]
pub const HASH_TYPE_SHA3_256 : u32 = sys::wc_HashType_WC_HASH_TYPE_SHA3_256;
#[cfg(sha3)]
pub const HASH_TYPE_SHA3_384 : u32 = sys::wc_HashType_WC_HASH_TYPE_SHA3_384;
#[cfg(sha3)]
pub const HASH_TYPE_SHA3_512 : u32 = sys::wc_HashType_WC_HASH_TYPE_SHA3_512;
pub const HASH_TYPE_BLAKE2B : u32 = sys::wc_HashType_WC_HASH_TYPE_BLAKE2B;
pub const HASH_TYPE_BLAKE2S : u32 = sys::wc_HashType_WC_HASH_TYPE_BLAKE2S;
#[cfg(sha512_224)]
pub const HASH_TYPE_SHA512_224 : u32 = sys::wc_HashType_WC_HASH_TYPE_SHA512_224;
#[cfg(sha512_256)]
pub const HASH_TYPE_SHA512_256 : u32 = sys::wc_HashType_WC_HASH_TYPE_SHA512_256;
#[cfg(shake128)]
pub const HASH_TYPE_SHAKE128 : u32 = sys::wc_HashType_WC_HASH_TYPE_SHAKE128;
#[cfg(shake256)]
pub const HASH_TYPE_SHAKE256 : u32 = sys::wc_HashType_WC_HASH_TYPE_SHAKE256;
// Mask generation function (MGF) constants used for PSS sign and verify methods.
pub const MGF1NONE : i32 = sys::WC_MGF1NONE as i32;
pub const MGF1SHA1 : i32 = sys::WC_MGF1SHA1 as i32;
pub const MGF1SHA224 : i32 = sys::WC_MGF1SHA224 as i32;
pub const MGF1SHA256 : i32 = sys::WC_MGF1SHA256 as i32;
pub const MGF1SHA384 : i32 = sys::WC_MGF1SHA384 as i32;
pub const MGF1SHA512 : i32 = sys::WC_MGF1SHA512 as i32;
#[cfg(rsa_mgf1sha512_224)]
pub const MGF1SHA512_224 : i32 = sys::WC_MGF1SHA512_224 as i32;
#[cfg(rsa_mgf1sha512_256)]
pub const MGF1SHA512_256 : i32 = sys::WC_MGF1SHA512_256 as i32;
// Type constants used for `rsa_direct()`.
pub const PUBLIC_ENCRYPT : i32 = sys::RSA_PUBLIC_ENCRYPT;
pub const PUBLIC_DECRYPT : i32 = sys::RSA_PUBLIC_DECRYPT;
pub const PRIVATE_ENCRYPT : i32 = sys::RSA_PRIVATE_ENCRYPT;
pub const PRIVATE_DECRYPT : i32 = sys::RSA_PRIVATE_DECRYPT;
/// Load a public and private RSA keypair from DER-encoded buffer.
///
/// # Parameters
///
/// * `der`: DER-encoded input buffer.
///
/// # Returns
///
/// Returns either Ok(RSA) containing the RSA struct instance or Err(e)
/// containing the wolfSSL library error code value.
///
/// # Example
///
/// ```rust
/// #[cfg(random)]
/// {
/// use std::fs;
/// use wolfssl_wolfcrypt::random::RNG;
/// use wolfssl_wolfcrypt::rsa::RSA;
///
/// let mut rng = RNG::new().expect("Error creating RNG");
/// let key_path = "../../../certs/client-keyPub.der";
/// let der: Vec<u8> = fs::read(key_path).expect("Error reading key file");
/// let mut rsa = RSA::new_public_from_der(&der).expect("Error with new_public_from_der()");
/// rsa.set_rng(&mut rng).expect("Error with set_rng()");
/// let plain: &[u8] = b"Test message";
/// let mut enc: [u8; 512] = [0; 512];
/// let enc_len = rsa.public_encrypt(plain, &mut enc, &mut rng).expect("Error with public_encrypt()");
/// assert!(enc_len > 0 && enc_len <= 512);
///
/// let key_path = "../../../certs/client-key.der";
/// let der: Vec<u8> = fs::read(key_path).expect("Error reading key file");
/// let mut rsa = RSA::new_from_der(&der).expect("Error with new_from_der()");
/// rsa.set_rng(&mut rng).expect("Error with set_rng()");
/// let mut plain_out: [u8; 512] = [0; 512];
/// let dec_len = rsa.private_decrypt(&enc[0..enc_len], &mut plain_out).expect("Error with private_decrypt()");
/// assert!(dec_len as usize == plain.len());
/// assert_eq!(plain_out[0..dec_len], *plain);
/// }
/// ```
pub fn new_from_der(der: &[u8]) -> Result<Self, i32> {
Self::new_from_der_ex(der, None, None)
}
/// Load a public and private RSA keypair from DER-encoded buffer with
/// optional heap and device ID.
///
/// # Parameters
///
/// * `der`: DER-encoded input buffer.
/// * `heap`: Optional heap hint.
/// * `dev_id` Optional device ID to use with crypto callbacks or async hardware.
///
/// # Returns
///
/// Returns either Ok(RSA) containing the RSA struct instance or Err(e)
/// containing the wolfSSL library error code value.
///
/// # Example
///
/// ```rust
/// #[cfg(random)]
/// {
/// use std::fs;
/// use wolfssl_wolfcrypt::random::RNG;
/// use wolfssl_wolfcrypt::rsa::RSA;
///
/// let mut rng = RNG::new().expect("Error creating RNG");
/// let key_path = "../../../certs/client-keyPub.der";
/// let der: Vec<u8> = fs::read(key_path).expect("Error reading key file");
/// let mut rsa = RSA::new_public_from_der(&der).expect("Error with new_public_from_der()");
/// rsa.set_rng(&mut rng).expect("Error with set_rng()");
/// let plain: &[u8] = b"Test message";
/// let mut enc: [u8; 512] = [0; 512];
/// let enc_len = rsa.public_encrypt(plain, &mut enc, &mut rng).expect("Error with public_encrypt()");
/// assert!(enc_len > 0 && enc_len <= 512);
///
/// let key_path = "../../../certs/client-key.der";
/// let der: Vec<u8> = fs::read(key_path).expect("Error reading key file");
/// let mut rsa = RSA::new_from_der_ex(&der, None, None).expect("Error with new_from_der_ex()");
/// rsa.set_rng(&mut rng).expect("Error with set_rng()");
/// let mut plain_out: [u8; 512] = [0; 512];
/// let dec_len = rsa.private_decrypt(&enc[0..enc_len], &mut plain_out).expect("Error with private_decrypt()");
/// assert!(dec_len as usize == plain.len());
/// assert_eq!(plain_out[0..dec_len], *plain);
/// }
/// ```
pub fn new_from_der_ex(der: &[u8], heap: Option<*mut std::os::raw::c_void>, dev_id: Option<i32>) -> Result<Self, i32> {
let mut wc_rsakey: MaybeUninit<sys::RsaKey> = MaybeUninit::uninit();
let heap = match heap {
Some(heap) => heap,
None => core::ptr::null_mut(),
};
let dev_id = match dev_id {
Some(dev_id) => dev_id,
None => sys::INVALID_DEVID,
};
let rc = unsafe { sys::wc_InitRsaKey_ex(wc_rsakey.as_mut_ptr(), heap, dev_id) };
if rc != 0 {
return Err(rc);
}
let mut wc_rsakey = unsafe { wc_rsakey.assume_init() };
let der_size = der.len() as u32;
let mut idx: u32 = 0;
let rc = unsafe {
sys::wc_RsaPrivateKeyDecode(der.as_ptr(), &mut idx, &mut wc_rsakey, der_size)
};
if rc != 0 {
unsafe { sys::wc_FreeRsaKey(&mut wc_rsakey); }
return Err(rc);
}
let rsa = RSA { wc_rsakey };
Ok(rsa)
}
/// Load a public RSA key from DER-encoded buffer.
///
/// # Parameters
///
/// * `der`: DER-encoded input buffer.
///
/// # Returns
///
/// Returns either Ok(RSA) containing the RSA struct instance or Err(e)
/// containing the wolfSSL library error code value.
///
/// # Example
///
/// ```rust
/// #[cfg(random)]
/// {
/// use std::fs;
/// use wolfssl_wolfcrypt::random::RNG;
/// use wolfssl_wolfcrypt::rsa::RSA;
///
/// let mut rng = RNG::new().expect("Error creating RNG");
/// let key_path = "../../../certs/client-keyPub.der";
/// let der: Vec<u8> = fs::read(key_path).expect("Error reading key file");
/// let mut rsa = RSA::new_public_from_der(&der).expect("Error with new_public_from_der()");
/// rsa.set_rng(&mut rng).expect("Error with set_rng()");
/// let plain: &[u8] = b"Test message";
/// let mut enc: [u8; 512] = [0; 512];
/// let enc_len = rsa.public_encrypt(plain, &mut enc, &mut rng).expect("Error with public_encrypt()");
/// assert!(enc_len > 0 && enc_len <= 512);
///
/// let key_path = "../../../certs/client-key.der";
/// let der: Vec<u8> = fs::read(key_path).expect("Error reading key file");
/// let mut rsa = RSA::new_from_der(&der).expect("Error with new_from_der()");
/// rsa.set_rng(&mut rng).expect("Error with set_rng()");
/// let mut plain_out: [u8; 512] = [0; 512];
/// let dec_len = rsa.private_decrypt(&enc[0..enc_len], &mut plain_out).expect("Error with private_decrypt()");
/// assert!(dec_len as usize == plain.len());
/// assert_eq!(plain_out[0..dec_len], *plain);
/// }
/// ```
pub fn new_public_from_der(der: &[u8]) -> Result<Self, i32> {
Self::new_public_from_der_ex(der, None, None)
}
/// Load a public RSA key from DER-encoded buffer with optional heap and
/// device ID.
///
/// # Parameters
///
/// * `der`: DER-encoded input buffer.
/// * `heap`: Optional heap hint.
/// * `dev_id` Optional device ID to use with crypto callbacks or async hardware.
///
/// # Returns
///
/// Returns either Ok(RSA) containing the RSA struct instance or Err(e)
/// containing the wolfSSL library error code value.
///
/// # Example
///
/// ```rust
/// #[cfg(random)]
/// {
/// use std::fs;
/// use wolfssl_wolfcrypt::random::RNG;
/// use wolfssl_wolfcrypt::rsa::RSA;
///
/// let mut rng = RNG::new().expect("Error creating RNG");
/// let key_path = "../../../certs/client-keyPub.der";
/// let der: Vec<u8> = fs::read(key_path).expect("Error reading key file");
/// let mut rsa = RSA::new_public_from_der_ex(&der, None, None).expect("Error with new_public_from_der_ex()");
/// rsa.set_rng(&mut rng).expect("Error with set_rng()");
/// let plain: &[u8] = b"Test message";
/// let mut enc: [u8; 512] = [0; 512];
/// let enc_len = rsa.public_encrypt(plain, &mut enc, &mut rng).expect("Error with public_encrypt()");
/// assert!(enc_len > 0 && enc_len <= 512);
///
/// let key_path = "../../../certs/client-key.der";
/// let der: Vec<u8> = fs::read(key_path).expect("Error reading key file");
/// let mut rsa = RSA::new_from_der(&der).expect("Error with new_from_der()");
/// rsa.set_rng(&mut rng).expect("Error with set_rng()");
/// let mut plain_out: [u8; 512] = [0; 512];
/// let dec_len = rsa.private_decrypt(&enc[0..enc_len], &mut plain_out).expect("Error with private_decrypt()");
/// assert!(dec_len as usize == plain.len());
/// assert_eq!(plain_out[0..dec_len], *plain);
/// }
/// ```
pub fn new_public_from_der_ex(der: &[u8], heap: Option<*mut std::os::raw::c_void>, dev_id: Option<i32>) -> Result<Self, i32> {
let mut wc_rsakey: MaybeUninit<sys::RsaKey> = MaybeUninit::uninit();
let heap = match heap {
Some(heap) => heap,
None => core::ptr::null_mut(),
};
let dev_id = match dev_id {
Some(dev_id) => dev_id,
None => sys::INVALID_DEVID,
};
let rc = unsafe { sys::wc_InitRsaKey_ex(wc_rsakey.as_mut_ptr(), heap, dev_id) };
if rc != 0 {
return Err(rc);
}
let mut wc_rsakey = unsafe { wc_rsakey.assume_init() };
let der_size = der.len() as u32;
let mut idx: u32 = 0;
let rc = unsafe {
sys::wc_RsaPublicKeyDecode(der.as_ptr(), &mut idx, &mut wc_rsakey, der_size)
};
if rc != 0 {
unsafe { sys::wc_FreeRsaKey(&mut wc_rsakey); }
return Err(rc);
}
let rsa = RSA { wc_rsakey };
Ok(rsa)
}
/// Generate a new RSA key using the given size and exponent.
///
/// This function generates an RSA private key of length size (in bits) and
/// given exponent (e). It then returns the RSA structure instance so that
/// it may be used for encryption or signing operations. A secure number to
/// use for e is 65537. size is required to be greater than or equal to
/// RSA_MIN_SIZE and less than or equal to RSA_MAX_SIZE. For this function
/// to be available, the option WOLFSSL_KEY_GEN must be enabled at compile
/// time. This can be accomplished with --enable-keygen if using
/// `./configure`.
///
/// # Parameters
///
/// * `size`: Desired key length in bits.
/// * `e`: Exponent parameter to use for generating the key. A secure
/// choice is 65537.
/// * `rng`: Reference to a `RNG` struct to use for random number
/// generation while making the key.
///
/// # Returns
///
/// Returns either Ok(RSA) containing the RSA struct instance or Err(e)
/// containing the wolfSSL library error code value.
///
/// # Example
///
/// ```rust
/// #[cfg(rsa_keygen)]
/// {
/// use wolfssl_wolfcrypt::random::RNG;
/// use wolfssl_wolfcrypt::rsa::RSA;
///
/// let mut rng = RNG::new().expect("Error creating RNG");
/// let mut rsa = RSA::generate(2048, 65537, &mut rng).expect("Error with generate()");
/// rsa.check().expect("Error with check()");
/// let encrypt_size = rsa.get_encrypt_size().expect("Error with get_encrypt_size()");
/// assert_eq!(encrypt_size, 256);
/// }
/// ```
#[cfg(all(random, rsa_keygen))]
pub fn generate(size: i32, e: i32, rng: &mut RNG) -> Result<Self, i32> {
Self::generate_ex(size, e, rng, None, None)
}
/// Generate a new RSA key using the given size and exponent with optional
/// heap and device ID.
///
/// This function generates an RSA private key of length size (in bits) and
/// given exponent (e). It then returns the RSA structure instance so that
/// it may be used for encryption or signing operations. A secure number to
/// use for e is 65537. size is required to be greater than or equal to
/// RSA_MIN_SIZE and less than or equal to RSA_MAX_SIZE. For this function
/// to be available, the option WOLFSSL_KEY_GEN must be enabled at compile
/// time. This can be accomplished with --enable-keygen if using
/// `./configure`.
///
/// # Parameters
///
/// * `size`: Desired key length in bits.
/// * `e`: Exponent parameter to use for generating the key. A secure
/// choice is 65537.
/// * `rng`: Reference to a `RNG` struct to use for random number
/// generation while making the key.
/// * `heap`: Optional heap hint.
/// * `dev_id` Optional device ID to use with crypto callbacks or async hardware.
///
/// # Returns
///
/// Returns either Ok(RSA) containing the RSA struct instance or Err(e)
/// containing the wolfSSL library error code value.
///
/// # Example
///
/// ```rust
/// #[cfg(rsa_keygen)]
/// {
/// use wolfssl_wolfcrypt::random::RNG;
/// use wolfssl_wolfcrypt::rsa::RSA;
///
/// let mut rng = RNG::new().expect("Error creating RNG");
/// let mut rsa = RSA::generate_ex(2048, 65537, &mut rng, None, None).expect("Error with generate_ex()");
/// rsa.check().expect("Error with check()");
/// let encrypt_size = rsa.get_encrypt_size().expect("Error with get_encrypt_size()");
/// assert_eq!(encrypt_size, 256);
/// }
/// ```
#[cfg(all(random, rsa_keygen))]
pub fn generate_ex(size: i32, e: i32, rng: &mut RNG, heap: Option<*mut std::os::raw::c_void>, dev_id: Option<i32>) -> Result<Self, i32> {
let mut wc_rsakey: MaybeUninit<sys::RsaKey> = MaybeUninit::uninit();
let heap = match heap {
Some(heap) => heap,
None => core::ptr::null_mut(),
};
let dev_id = match dev_id {
Some(dev_id) => dev_id,
None => sys::INVALID_DEVID,
};
let rc = unsafe { sys::wc_InitRsaKey_ex(wc_rsakey.as_mut_ptr(), heap, dev_id) };
if rc != 0 {
return Err(rc);
}
let mut wc_rsakey = unsafe { wc_rsakey.assume_init() };
let e = e as core::ffi::c_long;
let rc = unsafe {
sys::wc_MakeRsaKey(&mut wc_rsakey, size, e, &mut rng.wc_rng)
};
if rc != 0 {
unsafe { sys::wc_FreeRsaKey(&mut wc_rsakey); }
return Err(rc);
}
let rsa = RSA { wc_rsakey };
Ok(rsa)
}
/// Export public and private RSA parameters from an RSA key.
///
/// # Parameters
///
/// * `e`: Slice in which to hold `e` key parameter.
/// * `e_size`: Output holding the number of bytes written to `e`.
/// * `n`: Slice in which to hold `n` key parameter.
/// * `n_size`: Output holding the number of bytes written to `n`.
/// * `d`: Slice in which to hold `d` key parameter.
/// * `d_size`: Output holding the number of bytes written to `d`.
/// * `p`: Slice in which to hold `p` key parameter.
/// * `p_size`: Output holding the number of bytes written to `p`.
/// * `q`: Slice in which to hold `q` key parameter.
/// * `q_size`: Output holding the number of bytes written to `q`.
///
/// # Returns
///
/// Returns Ok(()) on success or Err(e) containing the wolfSSL library
/// error code value.
///
/// # Example
///
/// ```rust
/// #[cfg(rsa_keygen)]
/// {
/// use wolfssl_wolfcrypt::random::RNG;
/// use wolfssl_wolfcrypt::rsa::RSA;
///
/// let mut rng = RNG::new().expect("Error creating RNG");
/// let mut rsa = RSA::generate(2048, 65537, &mut rng).expect("Error with generate()");
/// let mut e: [u8; 256] = [0; 256];
/// let mut e_size: u32 = 0;
/// let mut n: [u8; 256] = [0; 256];
/// let mut n_size: u32 = 0;
/// let mut d: [u8; 256] = [0; 256];
/// let mut d_size: u32 = 0;
/// let mut p: [u8; 256] = [0; 256];
/// let mut p_size: u32 = 0;
/// let mut q: [u8; 256] = [0; 256];
/// let mut q_size: u32 = 0;
/// rsa.export_key(&mut e, &mut e_size, &mut n, &mut n_size,
/// &mut d, &mut d_size, &mut p, &mut p_size, &mut q, &mut q_size).expect("Error with export_key()");
/// }
/// ```
#[allow(clippy::too_many_arguments)]
pub fn export_key(&mut self,
e: &mut [u8], e_size: &mut u32,
n: &mut [u8], n_size: &mut u32,
d: &mut [u8], d_size: &mut u32,
p: &mut [u8], p_size: &mut u32,
q: &mut [u8], q_size: &mut u32) -> Result<(), i32> {
*e_size = e.len() as u32;
*n_size = n.len() as u32;
*d_size = d.len() as u32;
*p_size = p.len() as u32;
*q_size = q.len() as u32;
#[cfg(rsa_const_api)]
let key_ptr = &self.wc_rsakey;
#[cfg(not(rsa_const_api))]
let key_ptr = &mut self.wc_rsakey;
let rc = unsafe {
sys::wc_RsaExportKey(key_ptr,
e.as_mut_ptr(), e_size,
n.as_mut_ptr(), n_size,
d.as_mut_ptr(), d_size,
p.as_mut_ptr(), p_size,
q.as_mut_ptr(), q_size)
};
if rc != 0 {
return Err(rc);
}
Ok(())
}
/// Export public RSA parameters from an RSA key.
///
/// # Parameters
///
/// * `e`: Slice in which to hold `e` key parameter.
/// * `e_size`: Output holding the number of bytes written to `e`.
/// * `n`: Slice in which to hold `n` key parameter.
/// * `n_size`: Output holding the number of bytes written to `n`.
///
/// # Returns
///
/// Returns Ok(()) on success or Err(e) containing the wolfSSL library
/// error code value.
///
/// # Example
///
/// ```rust
/// #[cfg(rsa_keygen)]
/// {
/// use wolfssl_wolfcrypt::random::RNG;
/// use wolfssl_wolfcrypt::rsa::RSA;
///
/// let mut rng = RNG::new().expect("Error creating RNG");
/// let mut rsa = RSA::generate(2048, 65537, &mut rng).expect("Error with generate()");
/// let mut e: [u8; 256] = [0; 256];
/// let mut e_size: u32 = 0;
/// let mut n: [u8; 256] = [0; 256];
/// let mut n_size: u32 = 0;
/// rsa.export_public_key(&mut e, &mut e_size, &mut n, &mut n_size).expect("Error with export_public_key()");
/// }
/// ```
pub fn export_public_key(&mut self,
e: &mut [u8], e_size: &mut u32,
n: &mut [u8], n_size: &mut u32) -> Result<(), i32> {
*e_size = e.len() as u32;
*n_size = n.len() as u32;
#[cfg(rsa_const_api)]
let key = &self.wc_rsakey;
#[cfg(not(rsa_const_api))]
let key = &mut self.wc_rsakey;
let rc = unsafe {
sys::wc_RsaFlattenPublicKey(key,
e.as_mut_ptr(), e_size, n.as_mut_ptr(), n_size)
};
if rc != 0 {
return Err(rc);
}
Ok(())
}
/// Get the encryption size for the RSA key.
///
/// # Returns
///
/// Returns Ok(size) on success or Err(e) containing the wolfSSL library
/// error code value.
///
/// # Example
///
/// ```rust
/// #[cfg(rsa_keygen)]
/// {
/// use wolfssl_wolfcrypt::random::RNG;
/// use wolfssl_wolfcrypt::rsa::RSA;
///
/// let mut rng = RNG::new().expect("Error creating RNG");
/// let mut rsa = RSA::generate(2048, 65537, &mut rng).expect("Error with generate()");
/// let encrypt_size = rsa.get_encrypt_size().expect("Error with get_encrypt_size()");
/// assert_eq!(encrypt_size, 256);
/// }
/// ```
pub fn get_encrypt_size(&self) -> Result<usize, i32> {
let rc = unsafe { sys::wc_RsaEncryptSize(&self.wc_rsakey) };
if rc < 0 {
return Err(rc);
}
Ok(rc as usize)
}
/// Check the RSA key.
///
/// # Returns
///
/// Returns Ok(()) on success or Err(e) containing the wolfSSL library
/// error code value.
///
/// # Example
///
/// ```rust
/// #[cfg(rsa_keygen)]
/// {
/// use wolfssl_wolfcrypt::random::RNG;
/// use wolfssl_wolfcrypt::rsa::RSA;
///
/// let mut rng = RNG::new().expect("Error creating RNG");
/// let mut rsa = RSA::generate(2048, 65537, &mut rng).expect("Error with generate()");
/// rsa.check().expect("Error with check()");
/// }
/// ```
pub fn check(&mut self) -> Result<(), i32> {
let rc = unsafe { sys::wc_CheckRsaKey(&mut self.wc_rsakey) };
if rc != 0 {
return Err(rc);
}
Ok(())
}
/// Encrypt data using an RSA public key.
///
/// # Parameters
///
/// * `din`: Data to encrypt.
/// * `dout`: Buffer in which to store encrypted data.
/// * `rng`: Reference to a `RNG` struct to use for random number
/// generation while encrypting.
///
/// # Returns
///
/// Returns Ok(size) on success or Err(e) containing the wolfSSL library
/// error code value.
/// The size returned specifies the number of bytes written to the `dout`
/// buffer.
///
/// # Example
///
/// ```rust
/// #[cfg(random)]
/// {
/// use std::fs;
/// use wolfssl_wolfcrypt::random::RNG;
/// use wolfssl_wolfcrypt::rsa::RSA;
///
/// let mut rng = RNG::new().expect("Error creating RNG");
/// let key_path = "../../../certs/client-keyPub.der";
/// let der: Vec<u8> = fs::read(key_path).expect("Error reading key file");
/// let mut rsa = RSA::new_public_from_der(&der).expect("Error with new_public_from_der()");
/// rsa.set_rng(&mut rng).expect("Error with set_rng()");
/// let plain: &[u8] = b"Test message";
/// let mut enc: [u8; 512] = [0; 512];
/// let enc_len = rsa.public_encrypt(plain, &mut enc, &mut rng).expect("Error with public_encrypt()");
/// assert!(enc_len > 0 && enc_len <= 512);
///
/// let key_path = "../../../certs/client-key.der";
/// let der: Vec<u8> = fs::read(key_path).expect("Error reading key file");
/// let mut rsa = RSA::new_from_der(&der).expect("Error with new_from_der()");
/// rsa.set_rng(&mut rng).expect("Error with set_rng()");
/// let mut plain_out: [u8; 512] = [0; 512];
/// let dec_len = rsa.private_decrypt(&enc[0..enc_len], &mut plain_out).expect("Error with private_decrypt()");
/// assert!(dec_len as usize == plain.len());
/// assert_eq!(plain_out[0..dec_len], *plain);
/// }
/// ```
#[cfg(random)]
pub fn public_encrypt(&mut self, din: &[u8], dout: &mut [u8], rng: &mut RNG) -> Result<usize, i32> {
let din_size = din.len() as u32;
let dout_size = dout.len() as u32;
let rc = unsafe {
sys::wc_RsaPublicEncrypt(din.as_ptr(), din_size,
dout.as_mut_ptr(), dout_size, &mut self.wc_rsakey,
&mut rng.wc_rng)
};
if rc < 0 {
return Err(rc);
}
Ok(rc as usize)
}
/// Decrypt data using an RSA private key.
///
/// # Parameters
///
/// * `din`: Data to decrypt.
/// * `dout`: Buffer in which to store decrypted data.
///
/// # Returns
///
/// Returns Ok(size) on success or Err(e) containing the wolfSSL library
/// error code value.
/// The size returned specifies the number of bytes written to the `dout`
/// buffer.
///
/// # Example
///
/// ```rust
/// #[cfg(random)]
/// {
/// use std::fs;
/// use wolfssl_wolfcrypt::random::RNG;
/// use wolfssl_wolfcrypt::rsa::RSA;
///
/// let mut rng = RNG::new().expect("Error creating RNG");
/// let key_path = "../../../certs/client-keyPub.der";
/// let der: Vec<u8> = fs::read(key_path).expect("Error reading key file");
/// let mut rsa = RSA::new_public_from_der(&der).expect("Error with new_public_from_der()");
/// rsa.set_rng(&mut rng).expect("Error with set_rng()");
/// let plain: &[u8] = b"Test message";
/// let mut enc: [u8; 512] = [0; 512];
/// let enc_len = rsa.public_encrypt(plain, &mut enc, &mut rng).expect("Error with public_encrypt()");
/// assert!(enc_len > 0 && enc_len <= 512);
///
/// let key_path = "../../../certs/client-key.der";
/// let der: Vec<u8> = fs::read(key_path).expect("Error reading key file");
/// let mut rsa = RSA::new_from_der(&der).expect("Error with new_from_der()");
/// rsa.set_rng(&mut rng).expect("Error with set_rng()");
/// let mut plain_out: [u8; 512] = [0; 512];
/// let dec_len = rsa.private_decrypt(&enc[0..enc_len], &mut plain_out).expect("Error with private_decrypt()");
/// assert!(dec_len as usize == plain.len());
/// assert_eq!(plain_out[0..dec_len], *plain);
/// }
/// ```
pub fn private_decrypt(&mut self, din: &[u8], dout: &mut [u8]) -> Result<usize, i32> {
let din_size = din.len() as u32;
let dout_size = dout.len() as u32;
let rc = unsafe {
sys::wc_RsaPrivateDecrypt(din.as_ptr(), din_size,
dout.as_mut_ptr(), dout_size, &mut self.wc_rsakey)
};
if rc < 0 {
return Err(rc);
}
Ok(rc as usize)
}
/// Sign the provided data with the private key using RSA-PSS signature
/// scheme.
///
/// # Parameters
///
/// * `din`: Data to sign.
/// * `dout`: Buffer in which to store output signature.
/// * `hash_algo`: Hash algorithm type to use, one of RSA::HASH_TYPE_*.
/// * `mgf`: Mask generation function to use, one of RSA::MGF*.
/// * `rng`: Reference to a `RNG` struct to use for random number
/// generation while signing.
///
/// # Returns
///
/// Returns Ok(size) on success or Err(e) containing the wolfSSL library
/// error code value.
/// The size returned specifies the number of bytes written to the `dout`
/// buffer.
///
/// # Example
///
/// ```rust
/// #[cfg(all(random, rsa_pss))]
/// {
/// use std::fs;
/// use wolfssl_wolfcrypt::random::RNG;
/// use wolfssl_wolfcrypt::rsa::RSA;
///
/// let mut rng = RNG::new().expect("Error creating RNG");
///
/// let key_path = "../../../certs/client-key.der";
/// let der: Vec<u8> = fs::read(key_path).expect("Error reading key file");
/// let mut rsa = RSA::new_from_der(&der).expect("Error with new_from_der()");
/// let msg: &[u8] = b"This is the string to be signed!";
/// let mut signature: [u8; 512] = [0; 512];
/// let sig_len = rsa.pss_sign(msg, &mut signature, RSA::HASH_TYPE_SHA256, RSA::MGF1SHA256, &mut rng).expect("Error with pss_sign()");
/// assert!(sig_len > 0 && sig_len <= 512);
///
/// let key_path = "../../../certs/client-keyPub.der";
/// let der: Vec<u8> = fs::read(key_path).expect("Error reading key file");
/// let mut rsa = RSA::new_public_from_der(&der).expect("Error with new_public_from_der()");
/// rsa.set_rng(&mut rng).expect("Error with set_rng()");
/// let signature = &signature[0..sig_len];
/// let mut verify_out: [u8; 512] = [0; 512];
/// let verify_out_size = rsa.pss_verify(signature, &mut verify_out, RSA::HASH_TYPE_SHA256, RSA::MGF1SHA256).expect("Error with pss_verify()");
/// let verify_out = &verify_out[0..verify_out_size];
/// rsa.pss_check_padding(msg, verify_out, RSA::HASH_TYPE_SHA256).expect("Error with pss_check_padding()");
///
/// let mut verify_out: [u8; 512] = [0; 512];
/// rsa.pss_verify_check(signature, &mut verify_out, msg, RSA::HASH_TYPE_SHA256, RSA::MGF1SHA256).expect("Error with pss_verify_check()");
/// }
/// ```
#[cfg(all(random, rsa_pss))]
pub fn pss_sign(&mut self, din: &[u8], dout: &mut [u8], hash_algo: u32, mgf: i32, rng: &mut RNG) -> Result<usize, i32> {
let din_size = din.len() as u32;
let dout_size = dout.len() as u32;
let rc = unsafe {
sys::wc_RsaPSS_Sign(din.as_ptr(), din_size, dout.as_mut_ptr(), dout_size,
hash_algo, mgf, &mut self.wc_rsakey, &mut rng.wc_rng)
};
if rc < 0 {
return Err(rc);
}
Ok(rc as usize)
}
/// Check the PSS data to ensure the signature matches.
///
/// `set_rng()` must be called previously when wolfSSL is built with
/// WC_RSA_BLINDING option enabled.
///
/// # Parameters
///
/// * `din`: Hash of data being verified.
/// * `sig`: Buffer holding PSS data (output from `pss_verify()`).
/// * `hash_algo`: Hash algorithm type to use, one of RSA::HASH_TYPE_*.
///
/// # Returns
///
/// Returns Ok(()) on success or Err(e) containing the wolfSSL library
/// error code value.
///
/// # Example
///
/// ```rust
/// #[cfg(all(random, rsa_pss, rsa_const_api))]
/// {
/// use std::fs;
/// use wolfssl_wolfcrypt::random::RNG;
/// use wolfssl_wolfcrypt::rsa::RSA;
///
/// let mut rng = RNG::new().expect("Error creating RNG");
///
/// let key_path = "../../../certs/client-key.der";
/// let der: Vec<u8> = fs::read(key_path).expect("Error reading key file");
/// let mut rsa = RSA::new_from_der(&der).expect("Error with new_from_der()");
/// let msg: &[u8] = b"This is the string to be signed!";
/// let mut signature: [u8; 512] = [0; 512];
/// let sig_len = rsa.pss_sign(msg, &mut signature, RSA::HASH_TYPE_SHA256, RSA::MGF1SHA256, &mut rng).expect("Error with pss_sign()");
/// assert!(sig_len > 0 && sig_len <= 512);
///
/// let key_path = "../../../certs/client-keyPub.der";
/// let der: Vec<u8> = fs::read(key_path).expect("Error reading key file");
/// let mut rsa = RSA::new_public_from_der(&der).expect("Error with new_public_from_der()");
/// rsa.set_rng(&mut rng).expect("Error with set_rng()");
/// let signature = &signature[0..sig_len];
/// let mut verify_out: [u8; 512] = [0; 512];
/// let verify_out_size = rsa.pss_verify(signature, &mut verify_out, RSA::HASH_TYPE_SHA256, RSA::MGF1SHA256).expect("Error with pss_verify()");
/// let verify_out = &verify_out[0..verify_out_size];
/// rsa.pss_check_padding(msg, verify_out, RSA::HASH_TYPE_SHA256).expect("Error with pss_check_padding()");
///
/// let mut verify_out: [u8; 512] = [0; 512];
/// rsa.pss_verify_check(signature, &mut verify_out, msg, RSA::HASH_TYPE_SHA256, RSA::MGF1SHA256).expect("Error with pss_verify_check()");
/// }
/// ```
#[cfg(all(rsa_pss, rsa_const_api))]
pub fn pss_check_padding(&mut self, din: &[u8], sig: &[u8], hash_algo: u32) -> Result<(), i32> {
let din_size = din.len() as u32;
let sig_size = sig.len() as u32;
let rc = unsafe {
sys::wc_RsaPSS_CheckPadding(din.as_ptr(), din_size,
sig.as_ptr(), sig_size, hash_algo)
};
if rc != 0 {
return Err(rc);
}
Ok(())
}
/// Decrypt input signature to verify that the message was signed by key.
///
/// `set_rng()` must be called previously when wolfSSL is built with
/// WC_RSA_BLINDING option enabled.
///
/// # Parameters
///
/// * `din`: Input data to decrypt.
/// * `dout`: Buffer in which to store decrypted data.
/// * `hash_algo`: Hash algorithm type to use, one of RSA::HASH_TYPE_*.
/// * `mgf`: Mask generation function to use, one of RSA::MGF*.
///
/// # Returns
///
/// Returns Ok(size) on success or Err(e) containing the wolfSSL library
/// error code value.
/// The size returned specifies the number of bytes written to the `dout`
/// buffer.
///
/// # Example
///
/// ```rust
/// #[cfg(all(random, rsa_pss, rsa_const_api))]
/// {
/// use std::fs;
/// use wolfssl_wolfcrypt::random::RNG;
/// use wolfssl_wolfcrypt::rsa::RSA;
///
/// let mut rng = RNG::new().expect("Error creating RNG");
///
/// let key_path = "../../../certs/client-key.der";
/// let der: Vec<u8> = fs::read(key_path).expect("Error reading key file");
/// let mut rsa = RSA::new_from_der(&der).expect("Error with new_from_der()");
/// let msg: &[u8] = b"This is the string to be signed!";
/// let mut signature: [u8; 512] = [0; 512];
/// let sig_len = rsa.pss_sign(msg, &mut signature, RSA::HASH_TYPE_SHA256, RSA::MGF1SHA256, &mut rng).expect("Error with pss_sign()");
/// assert!(sig_len > 0 && sig_len <= 512);
///
/// let key_path = "../../../certs/client-keyPub.der";
/// let der: Vec<u8> = fs::read(key_path).expect("Error reading key file");
/// let mut rsa = RSA::new_public_from_der(&der).expect("Error with new_public_from_der()");
/// rsa.set_rng(&mut rng).expect("Error with set_rng()");
/// let signature = &signature[0..sig_len];
/// let mut verify_out: [u8; 512] = [0; 512];
/// let verify_out_size = rsa.pss_verify(signature, &mut verify_out, RSA::HASH_TYPE_SHA256, RSA::MGF1SHA256).expect("Error with pss_verify()");
/// let verify_out = &verify_out[0..verify_out_size];
/// rsa.pss_check_padding(msg, verify_out, RSA::HASH_TYPE_SHA256).expect("Error with pss_check_padding()");
///
/// let mut verify_out: [u8; 512] = [0; 512];
/// rsa.pss_verify_check(signature, &mut verify_out, msg, RSA::HASH_TYPE_SHA256, RSA::MGF1SHA256).expect("Error with pss_verify_check()");
/// }
/// ```
#[cfg(all(rsa_pss, rsa_const_api))]
pub fn pss_verify(&mut self, din: &[u8], dout: &mut [u8], hash_algo: u32, mgf: i32) -> Result<usize, i32> {
let din_size = din.len() as u32;
let dout_size = dout.len() as u32;
let rc = unsafe {
sys::wc_RsaPSS_Verify(din.as_ptr(), din_size,
dout.as_mut_ptr(), dout_size,
hash_algo, mgf, &mut self.wc_rsakey)
};
if rc < 0 {
return Err(rc);
}
Ok(rc as usize)
}
/// Verify the message signed with RSA-PSS.
///
/// This method combines the functionality of `pss_verify()` and
/// `pss_check_padding()`.
///
/// `set_rng()` must be called previously when wolfSSL is built with
/// WC_RSA_BLINDING option enabled.
///
/// # Parameters
///
/// * `din`: Input data to decrypt.
/// * `dout`: Buffer in which to store decrypted data.
/// * `digest`: Hash of data being verified.
/// * `hash_algo`: Hash algorithm type to use, one of RSA::HASH_TYPE_*.
/// * `mgf`: Mask generation function to use, one of RSA::MGF*.
///
/// # Returns
///
/// Returns Ok(size) on success or Err(e) containing the wolfSSL library
/// error code value.
/// The size returned specifies the number of bytes written to the `dout`
/// buffer.
///
/// # Example
///
/// ```rust
/// #[cfg(all(random, rsa_pss, rsa_const_api))]
/// {
/// use std::fs;
/// use wolfssl_wolfcrypt::random::RNG;
/// use wolfssl_wolfcrypt::rsa::RSA;
///
/// let mut rng = RNG::new().expect("Error creating RNG");
///