kryoptic-lib 1.5.3

A PKCS #11 software token written in 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
// Copyright 2024 Simo Sorce
// See LICENSE.txt file for terms

use crate::kasn1::pkcs;
use crate::tests::*;

use serial_test::parallel;

const AES_BLOCK_SIZE: usize = 16;

#[test]
#[parallel]
fn test_rsa_operations() {
    let mut testtokn = TestToken::initialized(
        "test_rsa_operations",
        Some("testdata/test_rsa_operations.json"),
    );
    let session = testtokn.get_session(true);

    /* login */
    testtokn.login();

    /* public key data */
    let mut handle: CK_ULONG = CK_INVALID_HANDLE;
    let template = make_attr_template(
        &[(CKA_CLASS, CKO_PUBLIC_KEY)],
        &[(CKA_ID, "\x01".as_bytes())],
        &[],
    );
    let mut ret = fn_find_objects_init(session, template.as_ptr() as *mut _, 2);
    assert_eq!(ret, CKR_OK);
    let mut count: CK_ULONG = 0;
    ret = fn_find_objects(session, &mut handle, 1, &mut count);
    assert_eq!(ret, CKR_OK);
    assert_eq!(count, 1);
    assert_ne!(handle, CK_INVALID_HANDLE);
    ret = fn_find_objects_final(session);
    assert_eq!(ret, CKR_OK);

    #[cfg(not(feature = "fips"))]
    {
        /* encrypt init */
        let mut mechanism: CK_MECHANISM = CK_MECHANISM {
            mechanism: CKM_RSA_PKCS,
            pParameter: std::ptr::null_mut(),
            ulParameterLen: 0,
        };
        ret = fn_encrypt_init(session, &mut mechanism, handle);
        assert_eq!(ret, CKR_OK);

        /* a second invocation should return an error */
        ret = fn_encrypt_init(session, &mut mechanism, handle);
        assert_eq!(ret, CKR_OPERATION_ACTIVE);

        let data = "plaintext";
        let enc: [u8; 512] = [0; 512];
        let mut enc_len: CK_ULONG = 512;
        ret = fn_encrypt(
            session,
            CString::new(data).unwrap().into_raw() as *mut u8,
            data.len() as CK_ULONG,
            enc.as_ptr() as *mut _,
            &mut enc_len,
        );
        assert_eq!(ret, CKR_OK);
        assert_eq!(enc_len, 256);

        /* a second invocation should return an error */
        ret = fn_encrypt(
            session,
            CString::new(data).unwrap().into_raw() as *mut u8,
            data.len() as CK_ULONG,
            enc.as_ptr() as *mut _,
            &mut enc_len,
        );
        assert_eq!(ret, CKR_OPERATION_NOT_INITIALIZED);

        /* test that decryption returns the same data back */
        let template = make_attr_template(
            &[(CKA_CLASS, CKO_PRIVATE_KEY)],
            &[(CKA_ID, "\x01".as_bytes())],
            &[],
        );
        let mut ret =
            fn_find_objects_init(session, template.as_ptr() as *mut _, 2);
        assert_eq!(ret, CKR_OK);
        let mut count: CK_ULONG = 0;
        ret = fn_find_objects(session, &mut handle, 1, &mut count);
        assert_eq!(ret, CKR_OK);
        assert_eq!(count, 1);
        assert_ne!(handle, CK_INVALID_HANDLE);
        ret = fn_find_objects_final(session);
        assert_eq!(ret, CKR_OK);

        ret = fn_decrypt_init(session, &mut mechanism, handle);
        assert_eq!(ret, CKR_OK);

        let dec: [u8; 512] = [0; 512];
        let mut dec_len: CK_ULONG = 512;
        ret = fn_decrypt(
            session,
            enc.as_ptr() as *mut u8,
            enc_len,
            dec.as_ptr() as *mut u8,
            &mut dec_len,
        );
        assert_eq!(ret, CKR_OK);
        assert_eq!(data.as_bytes(), &dec[..dec_len as usize]);
    }

    /* RSA PKCS Sig */
    let pri_key_handle = match get_test_key_handle(
        session,
        "SigVer15_186-3.rsp [mod = 2048]",
        CKO_PRIVATE_KEY,
    ) {
        Ok(k) => k,
        Err(e) => panic!("{}", e),
    };
    let pub_key_handle = match get_test_key_handle(
        session,
        "SigVer15_186-3.rsp [mod = 2048]",
        CKO_PUBLIC_KEY,
    ) {
        Ok(k) => k,
        Err(e) => panic!("{}", e),
    };
    let mut msg = hex::decode(
        "6918d6328ca0a8b64bbe81d91cdea519911b59fc2dbd53af76006fec4b18a320\
         787135ce883b2b2edb26041bf86aa52c230b9620335b6e7f9ec08c7ed6b70823\
         d819e9ab019e9929249f966fdb2069311a0ddc680ac468f514d4ed873b04a6be\
         b0985b91a0cfd8ed51b09f9e6d06da739eaa939d5a00275901c4f8cf25076339",
    )
    .expect("Failed to decode msg");
    let mut sig = hex::decode(
        "794d0a45bc9fc6febb586e319dfa6924c888594802b9deb9668963fdb309bf02\
         817960a7457106fc474f91601436e8954cbb6815350b2c51b53c968d2c48cc17\
         99550d5d03b41f6e5a8c3c264d2e2fe0b5b8ff53fdcb9dd111c985cb488d7086\
         e6548b4077ec00721c9cb500fe07a031c2030e8ad1dd0112c34ffd9091d77a18\
         7aac8661b298eee39eb615f9715c4c48a6762ede55a466ec7f3cdb6a937cfc80\
         188a85d8f8d3a2a80b199ce5e6375af8f02f06d706a34d9cf38318903965db54\
         aaa7d3fa7a7ee58034cd58c8435739c8906366e2ddba293f2fb2c15f07fa4951\
         014471e7f677d3bdacffc4c68a906e08d68b39f9010746cbacd22980cee73e8d",
    )
    .expect("Failed to decode sig");

    let mut mechanism: CK_MECHANISM = CK_MECHANISM {
        mechanism: CKM_SHA256_RSA_PKCS,
        pParameter: std::ptr::null_mut(),
        ulParameterLen: 0,
    };

    let ret =
        sig_verify(session, pub_key_handle, &mut msg, &mut sig, &mut mechanism);
    assert_eq!(ret, CKR_OK);

    let result = ret_or_panic!(sig_gen(
        session,
        pri_key_handle,
        &mut msg,
        &mut mechanism
    ));
    assert_eq!(sig, result);

    /* RSA PKCS PSS Sig */
    let pri_key_handle = ret_or_panic!(get_test_key_handle(
        session,
        "SigVerPSS_186-3.rsp [mod = 3072]",
        CKO_PRIVATE_KEY,
    ));
    let pub_key_handle = ret_or_panic!(get_test_key_handle(
        session,
        "SigVerPSS_186-3.rsp [mod = 3072]",
        CKO_PUBLIC_KEY,
    ));
    let _testname = "SigVerPSS_186-3.rsp SHAAlg = SHA384 2514";
    let msg = hex::decode(
        "5e5ca00767fad960921dcbbf16eb8e2ee85ad6db8caa6dbe2c33e17ce7607a8c\
         6bfc6e98c6ac582679bde777ce20d3af6cb3163729c358601fceab49028d7802\
         b131b9f10aee697503b639caf647852d3d678640ff6ec9af4906e014612f5718\
         5786eadbdcc6f497578f2b8036668bee82fe90bdb7b5a8f4d262e8a6ab4efe16",
    )
    .expect("Failed to decode msg");
    let sig = hex::decode(
        "2ad995df3355aafb5dc71f06f10e42ef27d5a755351806961dec23ed08dc9cf0\
         cd8d80a40fffe5ee54bdc71f355f661b59ff7a438a642b96d3e6ef95a54e5fd7\
         d7af188b307914b8b8d05cbc09a046545be5c53908027c7324dd84b42f2a0054\
         768161c6b1bad21de778babfe626f74bc325fed37dbba68648ad0b70881ee765\
         825a215c23f21ae7f4805da65ae14fa8320cfa0cc43396e7a2193317695587bd\
         8b4a3e935607465a0d29aa44f80ffb33e95604d087362a9a297aa8585cfcb4e1\
         781bab34fbe7ea5503fd9a1deeec50caa56d7361d1159de065d2acf667d8bd46\
         026cbca2cf8492e4ab6be427400db381b64e220c1cca709edc2768e80db78920\
         912a929031c9bd0e13ad9fd6560c343904dc1bad633c3cdb7563dd4cf444ef2f\
         7d8df047fe3ded5b277f94d56abf819943303fa6d9f0b55ecc20f98e92e6f1d3\
         4761148e7a51c51d5bd012cd6032aa2b3f0646059df34045f837c7eeaca6fa16\
         357aa2c48922e34d4fb48183d11ca049684ae198c053de473bc167531b712516",
    )
    .expect("Failed to decode sig");
    let salt =
        hex::decode("11223344555432167890").expect("Failed to decode salt");

    let params = CK_RSA_PKCS_PSS_PARAMS {
        hashAlg: CKM_SHA384,
        mgf: CKG_MGF1_SHA384,
        sLen: salt.len() as CK_ULONG,
    };

    /* this is the only allowed mechanism */
    let mechanism: CK_MECHANISM = CK_MECHANISM {
        mechanism: CKM_SHA384_RSA_PKCS_PSS,
        pParameter: &params as *const _ as CK_VOID_PTR,
        ulParameterLen: sizeof!(CK_RSA_PKCS_PSS_PARAMS),
    };

    let ret = sig_verify(session, pub_key_handle, &msg, &sig, &mechanism);
    assert_eq!(ret, CKR_OK);

    /* Re-Verify using the SignatureVerification APIs */
    let ret = sig_verifysig(session, pub_key_handle, &msg, &sig, &mechanism);
    assert_eq!(ret, CKR_OK);

    let signed =
        ret_or_panic!(sig_gen(session, pri_key_handle, &msg, &mechanism));
    /* PSS is non deterministic because saltlen > 0,
     * so we can't compare the result
     * assert_eq!(sig, result); */
    assert_eq!(sig.len(), signed.len());
    /* but we can verify again to ensure signing produced
     * something usable */
    let ret = sig_verify(session, pub_key_handle, &msg, &signed, &mechanism);
    assert_eq!(ret, CKR_OK);

    if testtokn.dbtype != "nssdb" {
        /* this is not allowed mechanism per CKA_ALLOWED_MECHANISMS */
        let params = CK_RSA_PKCS_PSS_PARAMS {
            hashAlg: CKM_SHA512,
            mgf: CKG_MGF1_SHA512,
            sLen: salt.len() as CK_ULONG,
        };
        let mechanism: CK_MECHANISM = CK_MECHANISM {
            mechanism: CKM_SHA512_RSA_PKCS_PSS,
            pParameter: &params as *const _ as CK_VOID_PTR,
            ulParameterLen: sizeof!(CK_RSA_PKCS_PSS_PARAMS),
        };

        match sig_gen(session, pri_key_handle, &msg, &mechanism) {
            Ok(_) => panic!(
                "The operation using non-allowed mechanisms should have failed"
            ),
            Err(e) => assert_eq!(e.rv(), CKR_MECHANISM_INVALID),
        }
    }

    #[cfg(not(feature = "fips"))]
    {
        /* RSA PKCS Enc */
        let pri_key_handle = ret_or_panic!(get_test_key_handle(
            session,
            "pkcs1v15crypt-vectors.txt - Example 15: A 2048-bit RSA key pair",
            CKO_PRIVATE_KEY,
        ));
        let pub_key_handle = ret_or_panic!(get_test_key_handle(
            session,
            "pkcs1v15crypt-vectors.txt - Example 15: A 2048-bit RSA key pair",
            CKO_PUBLIC_KEY,
        ));
        let _testname =
            "pkcs1v15crypt-vectors.txt - PKCS#1 v1.5 Encryption Example 15.20";
        let msg = hex::decode("69b7644855f91d1c61c8498e4ba1ba4d845ba882b173")
            .expect("Failed to decode msg");
        let enc = hex::decode(
            "ab4267972c7796839388d4ad87ded74bb653e9a7050e282e82192875689f70ee\
             1da18a1f7322092cd29fd00119922a6de12601980aa9fa6e619e2775e87adae3\
             1695c1304e77f52cce016665f2267c20762643c6003c016d8480443c701df6c1\
             d8d655549600ee455b70e473319b0d4445e0b7552a1f808e88f3264842735ae6\
             1df0325ed03690d6d5d693ad1fed22668450379db5323dc01c89affae369b9c3\
             01c319c37ddf51edf46e09b21e5de91483e8e3cb21eeb7057bc2ebdc3aaa3d65\
             00c92f99b17b3180bba047d76073776336b15d054d79a440cc5e985ea543fcaa\
             25db1dd892b71bb74a5cf68263d8fd58f1a48e6c2fcb8c0b71a251cfc1a20157",
        )
        .expect("Failed to decode enc");

        let mechanism: CK_MECHANISM = CK_MECHANISM {
            mechanism: CKM_RSA_PKCS,
            pParameter: std::ptr::null_mut(),
            ulParameterLen: 0,
        };

        let result =
            ret_or_panic!(decrypt(session, pri_key_handle, &enc, &mechanism));
        assert_eq!(msg, result);

        let encrypted =
            ret_or_panic!(encrypt(session, pub_key_handle, &msg, &mechanism));
        /* can't really compare the data because padding contains random
         * octets so each encryption produces a different output */
        assert_eq!(enc.len(), encrypted.len());
        /* but we can decrypt again to ensure encryption produced
         * something usable */
        let result = ret_or_panic!(decrypt(
            session,
            pri_key_handle,
            &encrypted,
            &mechanism
        ));
        assert_eq!(msg, result);
    }

    /* RSA PKCS OAEP Enc */
    let pri_key_handle = ret_or_panic!(get_test_key_handle(
        session,
        "oaep-sha512-sha512.txt - First Key Example",
        CKO_PRIVATE_KEY,
    ));
    let pub_key_handle = ret_or_panic!(get_test_key_handle(
        session,
        "oaep-sha512-sha512.txt - First Key Example",
        CKO_PUBLIC_KEY,
    ));
    let _testname =
        "oaep-sha512-sha512.txt - First Key Example - OAEP Example 1 alg=sha512 mgf1=sha512";
    let msg =
        hex::decode("6628194e12073db03ba94cda9ef9532397d50dba79b987004afefe34")
            .expect("Failed to decode msg");
    let enc = hex::decode(
        "7b7dccee97b43d4b6e214efb90c22d6679b8c144891d47f0674f6cdc94b8c4a8\
         7c1fab9ddd6a1d77d4c9d0487a071e2a0323acf7f04554b43952cfd49d1c6428\
         77a78c04dc8922240eee6afc5eb94896b83c3fc4c7e21c59f8fe1bcf03aa7511\
         0c86655e25d55b75476153e39e3a80017fa61c640838b5b27d03d5830746926b\
         ddd6434acacd0fcc03615c5ba850b591c673bc8e882d51465795cc9eaff1f4a6\
         5e70f9c92777f0877c69c26c1e5cb8bf0ae87ab61ecef24d4349eb57a1c1a270\
         04703038f2c56d9d4f408dedfb9e5263249be9edefd704c7aa9f6b3f6db0b61f\
         3848dd894e70a3f448ea6583f5d74b82ec2850ae1d0e335c22087cc468e5af64",
    )
    .expect("Failed to decode enc");

    let params = CK_RSA_PKCS_OAEP_PARAMS {
        hashAlg: CKM_SHA512,
        mgf: CKG_MGF1_SHA512,
        source: CKZ_DATA_SPECIFIED,
        pSourceData: std::ptr::null_mut(),
        ulSourceDataLen: 0,
    };

    let mechanism: CK_MECHANISM = CK_MECHANISM {
        mechanism: CKM_RSA_PKCS_OAEP,
        pParameter: &params as *const _ as CK_VOID_PTR,
        ulParameterLen: sizeof!(CK_RSA_PKCS_OAEP_PARAMS),
    };

    let result =
        ret_or_panic!(decrypt(session, pri_key_handle, &enc, &mechanism));
    assert_eq!(msg, result);

    let encrypted =
        ret_or_panic!(encrypt(session, pub_key_handle, &msg, &mechanism));
    /* can't really compare the data because padding contains random
     * octets so each encryption produces a different output */
    assert_eq!(enc.len(), encrypted.len());
    /* but we can decrypt again to ensure encryption produced
     * something usable */
    let result =
        ret_or_panic!(decrypt(session, pri_key_handle, &encrypted, &mechanism));
    assert_eq!(msg, result);

    /* RSA PKCS Wrap */
    /* RSA PKCS OAEP Wrap */

    /* generate key pair and store it */
    /* RSA key pair */
    let (hpub, hpri) = ret_or_panic!(generate_key_pair(
        session,
        CKM_RSA_PKCS_KEY_PAIR_GEN,
        &[(CKA_MODULUS_BITS, 2048)],
        &[],
        &[
            (CKA_TOKEN, true),
            (CKA_ENCRYPT, true),
            (CKA_VERIFY, true),
            (CKA_WRAP, true),
        ],
        &[(CKA_CLASS, CKO_PRIVATE_KEY), (CKA_KEY_TYPE, CKK_RSA),],
        &[],
        &[
            (CKA_TOKEN, true),
            (CKA_PRIVATE, true),
            (CKA_SENSITIVE, true),
            (CKA_DECRYPT, true),
            (CKA_SIGN, true),
            (CKA_UNWRAP, true),
            (CKA_EXTRACTABLE, true),
        ],
    ));

    assert_eq!(check_validation(session, 1), true);
    assert_eq!(check_object_validation(session, hpri, 1), true);
    assert_eq!(check_object_validation(session, hpub, 1), true);

    let label = "Public Key test 1";
    let mut template = make_ptrs_template(&[(
        CKA_LABEL,
        void_ptr!(label.as_ptr()),
        label.as_bytes().len(),
    )]);
    let ret = fn_set_attribute_value(
        session,
        hpub,
        template.as_mut_ptr(),
        template.len() as CK_ULONG,
    );
    assert_eq!(ret, CKR_OK);

    let label = "Private Key test 1";
    let mut template = make_ptrs_template(&[(
        CKA_LABEL,
        void_ptr!(label.as_ptr()),
        label.as_bytes().len(),
    )]);
    let ret = fn_set_attribute_value(
        session,
        hpri,
        template.as_mut_ptr(),
        template.len() as CK_ULONG,
    );
    assert_eq!(ret, CKR_OK);

    /* Raw sig is disabled in the openssl submodule */

    #[cfg(feature = "dynamic")]
    {
        /* RSA PKCS Sig */
        let pri_key_handle = match get_test_key_handle(
            session,
            "SigVer15_186-3.rsp [mod = 2048]",
            CKO_PRIVATE_KEY,
        ) {
            Ok(k) => k,
            Err(e) => panic!("{}", e),
        };
        let pub_key_handle = match get_test_key_handle(
            session,
            "SigVer15_186-3.rsp [mod = 2048]",
            CKO_PUBLIC_KEY,
        ) {
            Ok(k) => k,
            Err(e) => panic!("{}", e),
        };

        /* Test Raw Signature */
        let mut mechanism: CK_MECHANISM = CK_MECHANISM {
            mechanism: CKM_RSA_X_509,
            pParameter: std::ptr::null_mut(),
            ulParameterLen: 0,
        };

        let ret = fn_sign_init(session, &mut mechanism, pri_key_handle);
        assert_eq!(ret, CKR_OK);

        let mut sig_len: CK_ULONG = 0;
        let data = "0123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345";
        let ret = fn_sign(
            session,
            byte_ptr!(data.as_ptr()),
            data.len() as CK_ULONG,
            std::ptr::null_mut(),
            &mut sig_len,
        );
        assert_eq!(ret, CKR_OK);

        let mut signature = vec![0; sig_len as usize];
        let ret = fn_sign(
            session,
            byte_ptr!(data.as_ptr()),
            data.len() as CK_ULONG,
            signature.as_mut_ptr(),
            &mut sig_len,
        );
        assert_eq!(ret, CKR_OK);

        let ret = fn_verify_init(session, &mut mechanism, pub_key_handle);
        assert_eq!(ret, CKR_OK);

        let ret = fn_verify(
            session,
            byte_ptr!(data.as_ptr()),
            data.len() as CK_ULONG,
            byte_ptr!(signature.as_ptr()),
            signature.len() as CK_ULONG,
        );
        assert_eq!(ret, CKR_OK);
    }

    /* Key Wrap/Unwrap operation of AES key using RSA key */

    /* key to be wrapped */
    let data = [0x55u8; AES_BLOCK_SIZE];
    let wp_handle = ret_or_panic!(import_object(
        session,
        CKO_SECRET_KEY,
        &[(CKA_KEY_TYPE, CKK_AES)],
        &[(CKA_VALUE, &data)],
        &[(CKA_EXTRACTABLE, true)],
    ));

    let params = CK_RSA_PKCS_OAEP_PARAMS {
        hashAlg: CKM_SHA512,
        mgf: CKG_MGF1_SHA512,
        source: CKZ_DATA_SPECIFIED,
        pSourceData: std::ptr::null_mut(),
        ulSourceDataLen: 0,
    };

    let mut mechanism: CK_MECHANISM = CK_MECHANISM {
        mechanism: CKM_RSA_PKCS_OAEP,
        pParameter: &params as *const _ as CK_VOID_PTR,
        ulParameterLen: sizeof!(CK_RSA_PKCS_OAEP_PARAMS),
    };

    /* get length */
    let mut wraplen = 0;
    let ret = fn_wrap_key(
        session,
        &mut mechanism,
        pub_key_handle,
        wp_handle,
        std::ptr::null_mut(),
        &mut wraplen,
    );
    assert_eq!(ret, CKR_OK);
    let mut wrapped = vec![0; wraplen as usize];
    let ret = fn_wrap_key(
        session,
        &mut mechanism,
        pub_key_handle,
        wp_handle,
        wrapped.as_mut_ptr(),
        &mut wraplen,
    );
    assert_eq!(ret, CKR_OK);

    /* Do the decryption trick */
    let dec = ret_or_panic!(decrypt(
        session,
        pri_key_handle,
        &wrapped[..(wraplen as usize)],
        &mechanism,
    ));
    assert_eq!(data, dec.as_slice());

    testtokn.finalize();
}

#[test]
#[parallel]
fn test_rsa_mechs() {
    let mut testtokn = TestToken::initialized("test_rsa_mechs", None);
    let session = testtokn.get_session(true);

    /* login */
    testtokn.login();

    /* generate key pair and store it */
    /* RSA key pair */
    let (pubkey, prikey) = ret_or_panic!(generate_key_pair(
        session,
        CKM_RSA_PKCS_KEY_PAIR_GEN,
        &[(CKA_MODULUS_BITS, 2048)],
        &[],
        &[
            (CKA_TOKEN, true),
            (CKA_ENCRYPT, true),
            (CKA_VERIFY, true),
            (CKA_WRAP, true),
        ],
        &[(CKA_CLASS, CKO_PRIVATE_KEY), (CKA_KEY_TYPE, CKK_RSA),],
        &[],
        &[
            (CKA_TOKEN, true),
            (CKA_PRIVATE, true),
            (CKA_SENSITIVE, true),
            (CKA_DECRYPT, true),
            (CKA_SIGN, true),
            (CKA_UNWRAP, true),
            (CKA_EXTRACTABLE, true),
        ],
    ));

    assert_eq!(check_validation(session, 1), true);
    assert_eq!(check_object_validation(session, pubkey, 1), true);
    assert_eq!(check_object_validation(session, prikey, 1), true);

    /* Classic PKCS 1.5 */
    for mech in [
        CKM_SHA224_RSA_PKCS,
        CKM_SHA256_RSA_PKCS,
        CKM_SHA384_RSA_PKCS,
        CKM_SHA512_RSA_PKCS,
    ] {
        let mechanism = CK_MECHANISM {
            mechanism: mech,
            pParameter: std::ptr::null_mut(),
            ulParameterLen: 0,
        };

        /* Test Signature */
        let data = "RSA PKCS signed data";
        let sig = ret_or_panic!(sig_gen(
            session,
            prikey,
            data.as_bytes(),
            &mechanism,
        ));

        assert_eq!(
            CKR_OK,
            sig_verify(
                session,
                pubkey,
                data.as_bytes(),
                sig.as_slice(),
                &mechanism,
            )
        );
    }

    /* RSA PSS */
    for mech in [
        (CKM_SHA224_RSA_PKCS_PSS, CKM_SHA224, CKG_MGF1_SHA224),
        (CKM_SHA256_RSA_PKCS_PSS, CKM_SHA256, CKG_MGF1_SHA256),
        (CKM_SHA384_RSA_PKCS_PSS, CKM_SHA384, CKG_MGF1_SHA384),
        (CKM_SHA512_RSA_PKCS_PSS, CKM_SHA512, CKG_MGF1_SHA512),
    ] {
        /* init signature */
        let salt: [u8; 10] =
            [0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0A];
        let sig_params = CK_RSA_PKCS_PSS_PARAMS {
            hashAlg: mech.1,
            mgf: mech.2,
            sLen: salt.len() as CK_ULONG,
        };
        let mechanism = CK_MECHANISM {
            mechanism: mech.0,
            pParameter: void_ptr!(&sig_params),
            ulParameterLen: sizeof!(CK_RSA_PKCS_PSS_PARAMS),
        };

        /* Test Signature */
        let data = "RSA PSS signed data";
        let sig = ret_or_panic!(sig_gen(
            session,
            prikey,
            data.as_bytes(),
            &mechanism,
        ));

        assert_eq!(
            CKR_OK,
            sig_verify(
                session,
                pubkey,
                data.as_bytes(),
                sig.as_slice(),
                &mechanism,
            )
        );
    }

    for hash in [
        (CKM_SHA224, CKG_MGF1_SHA224),
        (CKM_SHA256, CKG_MGF1_SHA256),
        (CKM_SHA384, CKG_MGF1_SHA384),
        (CKM_SHA512, CKG_MGF1_SHA512),
    ] {
        let params = CK_RSA_PKCS_OAEP_PARAMS {
            hashAlg: hash.0,
            mgf: hash.1,
            source: CKZ_DATA_SPECIFIED,
            pSourceData: std::ptr::null_mut(),
            ulSourceDataLen: 0,
        };

        let mechanism: CK_MECHANISM = CK_MECHANISM {
            mechanism: CKM_RSA_PKCS_OAEP,
            pParameter: &params as *const _ as CK_VOID_PTR,
            ulParameterLen: sizeof!(CK_RSA_PKCS_OAEP_PARAMS),
        };

        let data = c"RSA OAEP payload";

        let enc = ret_or_panic!(encrypt(
            session,
            pubkey,
            data.to_bytes(),
            &mechanism
        ));
        let result = ret_or_panic!(decrypt(session, prikey, &enc, &mechanism));
        assert_eq!(data.to_bytes(), result);
    }
}

#[test]
#[parallel]
fn test_rsa_public_key_info() {
    let mut testtokn = TestToken::initialized("test_rsa_public_key_info", None);
    let session = testtokn.get_session(true);

    /* login */
    testtokn.login();

    /* generate key pair and store it */
    let (hpub, hpri) = ret_or_panic!(generate_key_pair(
        session,
        CKM_RSA_PKCS_KEY_PAIR_GEN,
        &[(CKA_MODULUS_BITS, 2048)],
        &[],
        &[(CKA_TOKEN, false) /* CKA_VERIFY is a default */,],
        &[],
        &[],
        &[
            (CKA_TOKEN, false),
            (CKA_PRIVATE, true),
            (CKA_SENSITIVE, false), // Not sensitive to allow extracting components
            (CKA_EXTRACTABLE, true),
        ],
    ));

    // Check generated keys
    let pub_key_info =
        ret_or_panic!(extract_value(session, hpub, CKA_PUBLIC_KEY_INFO));
    assert!(!pub_key_info.is_empty());

    let pri_key_info =
        ret_or_panic!(extract_value(session, hpri, CKA_PUBLIC_KEY_INFO));
    assert!(!pri_key_info.is_empty());
    assert_eq!(pub_key_info, pri_key_info);

    // Verify content of CKA_PUBLIC_KEY_INFO
    let modulus = ret_or_panic!(extract_value(session, hpub, CKA_MODULUS));
    let pub_exp =
        ret_or_panic!(extract_value(session, hpub, CKA_PUBLIC_EXPONENT));

    let rsa_pub_key = pkcs::RsaPublicKey::new(&modulus, &pub_exp)
        .unwrap()
        .serialize()
        .unwrap();
    let spki_der = pkcs::SubjectPublicKeyInfo::new(pkcs::RSA_ALG, &rsa_pub_key)
        .unwrap()
        .serialize()
        .unwrap();
    assert_eq!(pub_key_info, spki_der);

    // Check imported public key
    let imported_hpub = ret_or_panic!(import_object(
        session,
        CKO_PUBLIC_KEY,
        &[(CKA_KEY_TYPE, CKK_RSA)],
        &[(CKA_MODULUS, &modulus), (CKA_PUBLIC_EXPONENT, &pub_exp)],
        &[],
    ));
    let imported_pub_key_info = ret_or_panic!(extract_value(
        session,
        imported_hpub,
        CKA_PUBLIC_KEY_INFO
    ));
    assert_eq!(imported_pub_key_info, spki_der);

    // Check imported private key
    let priv_exp =
        ret_or_panic!(extract_value(session, hpri, CKA_PRIVATE_EXPONENT));
    let prime1 = ret_or_panic!(extract_value(session, hpri, CKA_PRIME_1));
    let prime2 = ret_or_panic!(extract_value(session, hpri, CKA_PRIME_2));
    let exp1 = ret_or_panic!(extract_value(session, hpri, CKA_EXPONENT_1));
    let exp2 = ret_or_panic!(extract_value(session, hpri, CKA_EXPONENT_2));
    let coeff = ret_or_panic!(extract_value(session, hpri, CKA_COEFFICIENT));

    let imported_hpri = ret_or_panic!(import_object(
        session,
        CKO_PRIVATE_KEY,
        &[(CKA_KEY_TYPE, CKK_RSA)],
        &[
            (CKA_MODULUS, &modulus),
            (CKA_PUBLIC_EXPONENT, &pub_exp),
            (CKA_PRIVATE_EXPONENT, &priv_exp),
            (CKA_PRIME_1, &prime1),
            (CKA_PRIME_2, &prime2),
            (CKA_EXPONENT_1, &exp1),
            (CKA_EXPONENT_2, &exp2),
            (CKA_COEFFICIENT, &coeff),
        ],
        &[],
    ));
    let imported_pri_key_info = ret_or_panic!(extract_value(
        session,
        imported_hpri,
        CKA_PUBLIC_KEY_INFO
    ));
    assert_eq!(imported_pri_key_info, spki_der);

    testtokn.finalize();
}

/// Regression test: C_Encrypt with a too-small output buffer must return
/// CKR_BUFFER_TOO_SMALL *and* report the real required length in
/// pulEncryptedDataLen (PKCS#11 v3.2 5.2), so a caller can retry with a
/// correctly-sized buffer. Every existing RSA encrypt test either
/// pre-allocates an already-large-enough buffer or probes with a NULL
/// buffer first (see tests::util::encrypt) -- neither exercises this path,
/// which is why this went unnoticed: on a too-small non-NULL buffer,
/// encrypt() in ossl/rsa.rs returns Err(Error::buf_too_small(outlen)), but
/// the CK_RV conversion in fns/encryption.rs (`Err(e) => e.rv()`) discarded
/// e.reqsize() and never wrote it back into *pul_encrypted_data_len --
/// which was left holding whatever the caller originally passed in.
#[test]
#[parallel]
fn test_rsa_encrypt_buffer_too_small_reports_required_len() {
    let mut testtokn = TestToken::initialized(
        "test_rsa_encrypt_buffer_too_small_reports_required_len",
        None,
    );
    let session = testtokn.get_session(true);
    testtokn.login();

    let (hpub, _hpri) = ret_or_panic!(generate_key_pair(
        session,
        CKM_RSA_PKCS_KEY_PAIR_GEN,
        &[(CKA_MODULUS_BITS, 2048)],
        &[],
        &[(CKA_TOKEN, false), (CKA_ENCRYPT, true),],
        &[(CKA_CLASS, CKO_PRIVATE_KEY), (CKA_KEY_TYPE, CKK_RSA),],
        &[],
        &[
            (CKA_TOKEN, false),
            (CKA_SENSITIVE, true),
            (CKA_DECRYPT, true),
        ],
    ));

    /* OAEP, not classic RSA_PKCS v1.5 encryption: raw PKCS#1v1.5 encryption
     * is denied in FIPS-mode builds, and this test must pass there too. */
    let params = CK_RSA_PKCS_OAEP_PARAMS {
        hashAlg: CKM_SHA256,
        mgf: CKG_MGF1_SHA256,
        source: CKZ_DATA_SPECIFIED,
        pSourceData: std::ptr::null_mut(),
        ulSourceDataLen: 0,
    };
    let mut mechanism: CK_MECHANISM = CK_MECHANISM {
        mechanism: CKM_RSA_PKCS_OAEP,
        pParameter: &params as *const _ as CK_VOID_PTR,
        ulParameterLen: sizeof!(CK_RSA_PKCS_OAEP_PARAMS),
    };
    let ret = fn_encrypt_init(session, &mut mechanism, hpub);
    assert_eq!(ret, CKR_OK);

    /* Deliberately too small: a 2048-bit key's RSA_PKCS_OAEP ciphertext is
     * exactly 256 bytes. */
    let data = "plaintext";
    let mut enc: [u8; 8] = [0; 8];
    let mut enc_len: CK_ULONG = enc.len() as CK_ULONG;
    let ret = fn_encrypt(
        session,
        data.as_ptr() as *mut u8,
        data.len() as CK_ULONG,
        enc.as_mut_ptr(),
        &mut enc_len,
    );
    assert_eq!(ret, CKR_BUFFER_TOO_SMALL);
    assert_eq!(
        enc_len, 256,
        "CKR_BUFFER_TOO_SMALL must report the real required length (256 \
         for a 2048-bit RSA_PKCS_OAEP ciphertext), not leave \
         *pulEncryptedDataLen at whatever the caller originally passed in (8)"
    );

    /* Retry with a correctly-sized buffer, exactly as a real caller would;
     * confirm the operation is still active and produces real output. */
    let mut enc2 = vec![0u8; enc_len as usize];
    let mut enc2_len = enc2.len() as CK_ULONG;
    let ret = fn_encrypt(
        session,
        data.as_ptr() as *mut u8,
        data.len() as CK_ULONG,
        enc2.as_mut_ptr(),
        &mut enc2_len,
    );
    assert_eq!(ret, CKR_OK);
    assert_eq!(enc2_len, 256);

    testtokn.finalize();
}

/// Same as test_rsa_encrypt_buffer_too_small_reports_required_len, but for the mirror
/// C_Decrypt call site (a distinct fn_encrypt/fn_decrypt pair in fns/encryption.rs, so a
/// distinct place the fix could have been missed).
#[test]
#[parallel]
fn test_rsa_decrypt_buffer_too_small_reports_required_len() {
    let mut testtokn = TestToken::initialized(
        "test_rsa_decrypt_buffer_too_small_reports_required_len",
        None,
    );
    let session = testtokn.get_session(true);
    testtokn.login();

    let (hpub, hpri) = ret_or_panic!(generate_key_pair(
        session,
        CKM_RSA_PKCS_KEY_PAIR_GEN,
        &[(CKA_MODULUS_BITS, 2048)],
        &[],
        &[(CKA_TOKEN, false), (CKA_ENCRYPT, true),],
        &[(CKA_CLASS, CKO_PRIVATE_KEY), (CKA_KEY_TYPE, CKK_RSA),],
        &[],
        &[
            (CKA_TOKEN, false),
            (CKA_SENSITIVE, true),
            (CKA_DECRYPT, true),
        ],
    ));

    /* OAEP, not classic RSA_PKCS v1.5 encryption: raw PKCS#1v1.5 encryption
     * is denied in FIPS-mode builds, and this test must pass there too. */
    let params = CK_RSA_PKCS_OAEP_PARAMS {
        hashAlg: CKM_SHA256,
        mgf: CKG_MGF1_SHA256,
        source: CKZ_DATA_SPECIFIED,
        pSourceData: std::ptr::null_mut(),
        ulSourceDataLen: 0,
    };
    let mechanism: CK_MECHANISM = CK_MECHANISM {
        mechanism: CKM_RSA_PKCS_OAEP,
        pParameter: &params as *const _ as CK_VOID_PTR,
        ulParameterLen: sizeof!(CK_RSA_PKCS_OAEP_PARAMS),
    };
    let data = "plaintext";
    /* the safe null-probe idiom (tests::util::encrypt) is unaffected by the bug -- use it to
     * produce a real ciphertext to decrypt */
    let enc =
        ret_or_panic!(encrypt(session, hpub, data.as_bytes(), &mechanism));
    assert_eq!(enc.len(), 256);

    let mut mechanism = mechanism;
    let ret = fn_decrypt_init(session, &mut mechanism, hpri);
    assert_eq!(ret, CKR_OK);

    /* Deliberately too small. Unlike encrypt (whose ciphertext length is always exactly
     * the modulus size), RSA_PKCS_OAEP decrypt cannot know the exact unpadded plaintext
     * length without fully performing the decryption (that's what the tmp-buffer bridging
     * further down in ossl/rsa.rs::decrypt is for) -- so, consistent with what the
     * null-buffer probe (decryption_len(), used by C_Decrypt's NULL-output path) already
     * reports, the required length here is the conservative modulus-size upper bound (256),
     * not the eventual 9-byte plaintext. */
    let mut dec: [u8; 2] = [0; 2];
    let mut dec_len: CK_ULONG = dec.len() as CK_ULONG;
    let ret = fn_decrypt(
        session,
        enc.as_ptr() as *mut u8,
        enc.len() as CK_ULONG,
        dec.as_mut_ptr(),
        &mut dec_len,
    );
    assert_eq!(ret, CKR_BUFFER_TOO_SMALL);
    assert_eq!(
        dec_len, 256,
        "CKR_BUFFER_TOO_SMALL must report the modulus-size upper bound \
         (256, matching decryption_len()'s own null-probe answer), not \
         leave *pulDataLen at whatever the caller originally passed in (2)"
    );

    let mut dec2 = vec![0u8; dec_len as usize];
    let mut dec2_len = dec2.len() as CK_ULONG;
    let ret = fn_decrypt(
        session,
        enc.as_ptr() as *mut u8,
        enc.len() as CK_ULONG,
        dec2.as_mut_ptr(),
        &mut dec2_len,
    );
    assert_eq!(ret, CKR_OK);
    assert_eq!(&dec2[..dec2_len as usize], data.as_bytes());

    testtokn.finalize();
}