cosmian_kms_crypto 5.24.0

Cosmian KMS Crypto - cryptographic operations and algorithms
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
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
#[cfg(not(feature = "non-fips"))]
use cosmian_kmip::kmip_2_1::extra::fips::{
    FIPS_PRIVATE_ECC_MASK_SIGN, FIPS_PRIVATE_ECC_MASK_SIGN_ECDH, FIPS_PUBLIC_ECC_MASK_SIGN,
    FIPS_PUBLIC_ECC_MASK_SIGN_ECDH,
};
use cosmian_kmip::{
    SafeBigInt,
    kmip_0::kmip_types::CryptographicUsageMask,
    kmip_2_1::{
        extra::tagging::{SYSTEM_TAG_PRIVATE_KEY, SYSTEM_TAG_PUBLIC_KEY},
        kmip_attributes::Attributes,
        kmip_data_structures::{KeyBlock, KeyMaterial, KeyValue},
        kmip_objects::{Object, ObjectType, PrivateKey, PublicKey},
        kmip_types::{
            CryptographicAlgorithm, CryptographicDomainParameters, CryptographicParameters,
            KeyFormatType, Link, LinkType, LinkedObjectIdentifier, RecommendedCurve,
            UniqueIdentifier,
        },
    },
};
use cosmian_logger::trace;
use openssl::{
    bn::BigNumContext,
    ec::{EcGroup, EcKey, PointConversionForm},
    nid::Nid,
    pkey::PKey,
};
use zeroize::Zeroizing;

use crate::{
    crypto::KeyPair,
    crypto_bail,
    error::{CryptoError, result::CryptoResult},
};

#[cfg(not(feature = "non-fips"))]
/// Check that bits set in `mask` are only bits set in `flags`. If any bit set
/// in `mask` is not set in `flags`, raise an error.
///
/// If `mask` is None, raise an error.
fn check_ecc_mask_against_flags(
    mask: Option<CryptographicUsageMask>,
    flags: CryptographicUsageMask,
) -> Result<(), CryptoError> {
    if (flags & CryptographicUsageMask::Unrestricted).bits() != 0 {
        crypto_bail!(
            "Unrestricted CryptographicUsageMask for elliptic curves is too permissive for FIPS \
             mode."
        )
    }

    let Some(mask) = mask else {
        // Mask is `None` but FIPS mode is restrictive, so it's considered too
        // permissive.
        crypto_bail!(
            "EC: forbidden CryptographicUsageMask value, got None but expected among {:#010X} in \
             FIPS mode.",
            flags.bits()
        )
    };

    if (mask & !flags).bits() != 0 {
        crypto_bail!(
            "EC: forbidden CryptographicUsageMask flag set: {:#010X}, expected among {:#010X} in \
             FIPS mode.",
            mask.bits(),
            flags.bits()
        )
    }
    Ok(())
}

#[cfg(not(feature = "non-fips"))]
/// Check that
/// - `algorithm` is among `allowed` algorithms.
/// - `algorithm` is compliant with usage mask provided for private and public key components.
///
/// For example, `ECDH` and `Sign` are incompatible together since ECDH is for key agreement.
///
/// If `algorithm` is None, raise error.
fn check_ecc_mask_algorithm_compliance(
    private_key_mask: Option<CryptographicUsageMask>,
    public_key_mask: Option<CryptographicUsageMask>,
    algorithm: CryptographicAlgorithm,
    allowed_algorithms: &[CryptographicAlgorithm],
) -> Result<(), CryptoError> {
    if !allowed_algorithms.contains(&algorithm) {
        crypto_bail!("EC: forbidden CryptographicAlgorithm value in FIPS mode.")
    }
    match algorithm {
        CryptographicAlgorithm::ECDH | CryptographicAlgorithm::EC => {
            check_ecc_mask_against_flags(private_key_mask, FIPS_PRIVATE_ECC_MASK_SIGN_ECDH)?;
            check_ecc_mask_against_flags(public_key_mask, FIPS_PUBLIC_ECC_MASK_SIGN_ECDH)?;
        }
        CryptographicAlgorithm::ECDSA
        | CryptographicAlgorithm::Ed25519
        | CryptographicAlgorithm::Ed448 => {
            check_ecc_mask_against_flags(private_key_mask, FIPS_PRIVATE_ECC_MASK_SIGN)?;
            check_ecc_mask_against_flags(public_key_mask, FIPS_PUBLIC_ECC_MASK_SIGN)?;
        }
        // If `allowed` parameter is set correctly, should never fall in this case.
        _ => crypto_bail!("Invalid CryptographicAlgorithm value."),
    }
    Ok(())
}

/// Convert to an Elliptic Curve KMIP Public Key.
/// Supported curves are:
/// X25519, Ed25519, X448, Ed448, P-192, P-224, P-256, P-384, P-521.
///
/// `pkey_bits_number` is passed independently of `len(bytes)` since some key
/// sizes are not multiple of 8, thus it cannot be computed by taking the byte
/// array length.
///
/// No check performed.
pub fn to_ec_public_key(
    bytes: &[u8],
    pkey_bits_number: u32,
    private_key_uid: &str,
    curve: RecommendedCurve,
    algorithm: Option<CryptographicAlgorithm>,
    public_key_mask: Option<CryptographicUsageMask>,
) -> CryptoResult<Object> {
    let cryptographic_length = Some(i32::try_from(bytes.len())? * 8);
    trace!(
        "bytes len: {:?}, bits: {}",
        cryptographic_length, pkey_bits_number
    );

    let q_length = Some(i32::try_from(pkey_bits_number)?);
    Ok(Object::PublicKey(PublicKey {
        key_block: KeyBlock {
            cryptographic_algorithm: algorithm,
            key_format_type: KeyFormatType::TransparentECPublicKey,
            key_compression_type: None,
            key_value: Some(KeyValue::Structure {
                key_material: KeyMaterial::TransparentECPublicKey {
                    recommended_curve: curve,
                    q_string: bytes.to_vec(),
                },
                attributes: Some(Attributes {
                    object_type: Some(ObjectType::PublicKey),
                    cryptographic_algorithm: algorithm,
                    cryptographic_length,
                    cryptographic_usage_mask: public_key_mask,
                    vendor_attributes: None,
                    key_format_type: Some(KeyFormatType::TransparentECPublicKey),
                    cryptographic_parameters: Some(CryptographicParameters {
                        cryptographic_algorithm: algorithm,
                        ..CryptographicParameters::default()
                    }),
                    cryptographic_domain_parameters: Some(CryptographicDomainParameters {
                        qlength: q_length,
                        recommended_curve: Some(curve),
                    }),
                    link: Some(vec![Link {
                        link_type: LinkType::PrivateKeyLink,
                        linked_object_identifier: LinkedObjectIdentifier::TextString(
                            private_key_uid.to_owned(),
                        ),
                    }]),
                    ..Attributes::default()
                }),
            }),
            cryptographic_length,
            key_wrapping_data: None,
        },
    }))
}

/// Convert to an Elliptic Curve KMIP Private Key.
/// Supported curves are:
/// X25519, Ed25519, X448, Ed448, P-192, P-224, P-256, P-384, P-521.
///
/// `pkey_bits_number` is passed independently of `len(bytes)` since some key
/// sizes are not multiple of 8, thus it cannot be computed by taking the byte
/// array length.
///
/// No check performed.
pub fn to_ec_private_key(
    bytes: &[u8],
    pkey_bits_number: u32,
    public_key_uid: &str,
    curve: RecommendedCurve,
    algorithm: Option<CryptographicAlgorithm>,
    private_key_mask: Option<CryptographicUsageMask>,
    sensitive: bool,
) -> CryptoResult<Object> {
    let cryptographic_length = Some(i32::try_from(bytes.len())? * 8);

    trace!(
        "bytes len: {:?}, bits: {}",
        cryptographic_length, pkey_bits_number
    );

    let q_length = Some(i32::try_from(pkey_bits_number)?);
    Ok(Object::PrivateKey(PrivateKey {
        key_block: KeyBlock {
            cryptographic_algorithm: algorithm,
            key_format_type: KeyFormatType::TransparentECPrivateKey,
            key_compression_type: None,
            key_value: Some(KeyValue::Structure {
                key_material: KeyMaterial::TransparentECPrivateKey {
                    recommended_curve: curve,
                    d: Box::new(SafeBigInt::from_bytes_be(bytes)),
                },
                attributes: Some(Attributes {
                    object_type: Some(ObjectType::PrivateKey),
                    cryptographic_algorithm: algorithm,
                    cryptographic_length,
                    cryptographic_usage_mask: private_key_mask,
                    vendor_attributes: None,
                    key_format_type: Some(KeyFormatType::TransparentECPrivateKey),
                    cryptographic_parameters: Some(CryptographicParameters {
                        cryptographic_algorithm: algorithm,
                        ..CryptographicParameters::default()
                    }),
                    cryptographic_domain_parameters: Some(CryptographicDomainParameters {
                        qlength: q_length,
                        recommended_curve: Some(curve),
                    }),
                    link: Some(vec![Link {
                        link_type: LinkType::PublicKeyLink,
                        linked_object_identifier: LinkedObjectIdentifier::TextString(
                            public_key_uid.to_owned(),
                        ),
                    }]),
                    sensitive: sensitive.then_some(true),
                    ..Attributes::default()
                }),
            }),
            cryptographic_length,
            key_wrapping_data: None,
        },
    }))
}

/// Generate an X25519 Key Pair. Not FIPS 140-3 compliant.
#[cfg(feature = "non-fips")]
pub fn create_x25519_key_pair(
    vendor_id: &str,
    private_key_uid: &str,
    public_key_uid: &str,
    cryptographic_algorithm: &CryptographicAlgorithm,
    common_attributes: Attributes,
    private_key_attributes: Option<Attributes>,
    public_key_attributes: Option<Attributes>,
) -> Result<KeyPair, CryptoError> {
    let private_key = PKey::generate_x25519()?;

    let private_key_bytes = Zeroizing::from(private_key.raw_private_key()?);
    let private_key_num_bits = private_key.bits();
    let public_key_bytes = private_key.raw_public_key()?;

    create_ec_key_pair(
        vendor_id,
        &private_key_bytes,
        private_key_num_bits,
        &public_key_bytes,
        private_key_uid,
        public_key_uid,
        RecommendedCurve::CURVE25519,
        *cryptographic_algorithm,
        common_attributes,
        private_key_attributes,
        public_key_attributes,
    )
}

/// Generate a SEC 2 Key Pair. Not FIPS 140-3 compliant.
/// SEC 2: Recommended Elliptic Curve Domain Parameters: <https://www.secg.org/sec2-v2.pdf>
#[cfg(feature = "non-fips")]
#[expect(clippy::too_many_arguments)]
pub fn create_secp_key_pair(
    vendor_id: &str,
    private_key_uid: &str,
    public_key_uid: &str,
    curve: RecommendedCurve,
    cryptographic_algorithm: &CryptographicAlgorithm,
    common_attributes: Attributes,
    private_key_attributes: Option<Attributes>,
    public_key_attributes: Option<Attributes>,
) -> Result<KeyPair, CryptoError> {
    let curve_nid = match curve {
        RecommendedCurve::SECP224K1 => Nid::SECP224K1,
        RecommendedCurve::SECP256K1 => Nid::SECP256K1,

        other => crypto_bail!("Curve {:?} not supported by secp_key key generation", other),
    };

    // 1. Get the secp_key curve group
    let group = EcGroup::from_curve_name(curve_nid)?;
    // 2. Generate a new EC keypair
    let ec_key = EcKey::generate(&group)?;
    // 3. Extract the private and public key bytes
    let private_key_bytes = Zeroizing::from(ec_key.private_key().to_vec());
    let private_key_num_bits = u32::try_from(ec_key.private_key().num_bits())?;
    let mut ctx = BigNumContext::new()?;
    let public_key_bytes =
        ec_key
            .public_key()
            .to_bytes(&group, PointConversionForm::COMPRESSED, &mut ctx)?;

    create_ec_key_pair(
        vendor_id,
        &private_key_bytes,
        private_key_num_bits,
        &public_key_bytes,
        private_key_uid,
        public_key_uid,
        curve,
        *cryptographic_algorithm,
        common_attributes,
        private_key_attributes,
        public_key_attributes,
    )
}

/// Generate an X448 Key Pair. Not FIPS 140-3 compliant.
#[cfg(feature = "non-fips")]
pub fn create_x448_key_pair(
    vendor_id: &str,
    private_key_uid: &str,
    public_key_uid: &str,
    cryptographic_algorithm: &CryptographicAlgorithm,
    common_attributes: Attributes,
    private_key_attributes: Option<Attributes>,
    public_key_attributes: Option<Attributes>,
) -> Result<KeyPair, CryptoError> {
    let private_key = PKey::generate_x448()?;

    let private_key_bytes = Zeroizing::from(private_key.raw_private_key()?);
    let private_key_num_bits = private_key.bits();
    let public_key_bytes = private_key.raw_public_key()?;

    create_ec_key_pair(
        vendor_id,
        &private_key_bytes,
        private_key_num_bits,
        &public_key_bytes,
        private_key_uid,
        public_key_uid,
        RecommendedCurve::CURVE448,
        *cryptographic_algorithm,
        common_attributes,
        private_key_attributes,
        public_key_attributes,
    )
}

/// Generate an Ed25519 Key Pair. FIPS 140-3 compliant **for digital signature
/// only**.
///
/// Sources:
/// - NIST.SP.800-186 - Section 3.1.2 table 2.
/// - NIST.FIPS.186-5
pub fn create_ed25519_key_pair(
    vendor_id: &str,
    private_key_uid: &str,
    public_key_uid: &str,
    common_attributes: Attributes,
    private_key_attributes: Option<Attributes>,
    public_key_attributes: Option<Attributes>,
) -> Result<KeyPair, CryptoError> {
    #[cfg(not(feature = "non-fips"))]
    {
        // Cryptographic Usage Masks
        let private_key_mask = private_key_attributes
            .as_ref()
            .and_then(|attr| attr.cryptographic_usage_mask);
        let public_key_mask = public_key_attributes
            .as_ref()
            .and_then(|attr| attr.cryptographic_usage_mask);

        // Validate FIPS algorithms and mask.
        check_ecc_mask_algorithm_compliance(
            private_key_mask,
            public_key_mask,
            CryptographicAlgorithm::Ed25519,
            &[CryptographicAlgorithm::Ed25519],
        )?;
    }

    let private_key = PKey::generate_ed25519()?;
    let private_key_bytes = Zeroizing::from(private_key.raw_private_key()?);
    let private_key_num_bits = private_key.bits();
    let public_key_bytes = private_key.raw_public_key()?;

    create_ec_key_pair(
        vendor_id,
        &private_key_bytes,
        private_key_num_bits,
        &public_key_bytes,
        private_key_uid,
        public_key_uid,
        RecommendedCurve::CURVEED25519,
        CryptographicAlgorithm::Ed25519,
        common_attributes,
        private_key_attributes,
        public_key_attributes,
    )
}

/// Generate an Ed448 Key Pair. FIPS 140-3 compliant **for digital signature
/// only**.
///
/// Sources:
/// - NIST.SP.800-186 - Section 3.1.2 table 2.
/// - NIST.FIPS.186-5
pub fn create_ed448_key_pair(
    vendor_id: &str,
    private_key_uid: &str,
    public_key_uid: &str,
    common_attributes: Attributes,
    private_key_attributes: Option<Attributes>,
    public_key_attributes: Option<Attributes>,
) -> Result<KeyPair, CryptoError> {
    #[cfg(not(feature = "non-fips"))]
    {
        // Cryptographic Usage Masks
        let private_key_mask = private_key_attributes
            .as_ref()
            .and_then(|attr| attr.cryptographic_usage_mask);
        let public_key_mask = public_key_attributes
            .as_ref()
            .and_then(|attr| attr.cryptographic_usage_mask);

        // Validate FIPS algorithms and mask.
        check_ecc_mask_algorithm_compliance(
            private_key_mask,
            public_key_mask,
            CryptographicAlgorithm::Ed448,
            &[CryptographicAlgorithm::Ed448],
        )?;
    }

    let private_key = PKey::generate_ed448()?;
    let private_key_bytes = Zeroizing::from(private_key.raw_private_key()?);
    let private_key_num_bits = private_key.bits();
    let public_key_bytes = private_key.raw_public_key()?;

    create_ec_key_pair(
        vendor_id,
        &private_key_bytes,
        private_key_num_bits,
        &public_key_bytes,
        private_key_uid,
        public_key_uid,
        RecommendedCurve::CURVEED448,
        CryptographicAlgorithm::Ed448,
        common_attributes,
        private_key_attributes,
        public_key_attributes,
    )
}

#[expect(clippy::too_many_arguments)]
pub fn create_approved_ecc_key_pair(
    vendor_id: &str,
    private_key_uid: &str,
    public_key_uid: &str,
    curve: RecommendedCurve,
    cryptographic_algorithm: &CryptographicAlgorithm,
    common_attributes: Attributes,
    private_key_attributes: Option<Attributes>,
    public_key_attributes: Option<Attributes>,
) -> Result<KeyPair, CryptoError> {
    #[cfg(not(feature = "non-fips"))]
    {
        // Cryptographic Usage Masks
        let private_key_mask = private_key_attributes
            .as_ref()
            .and_then(|attr| attr.cryptographic_usage_mask);
        let public_key_mask = public_key_attributes
            .as_ref()
            .and_then(|attr| attr.cryptographic_usage_mask);

        // Validate FIPS algorithms and mask.
        check_ecc_mask_algorithm_compliance(
            private_key_mask,
            public_key_mask,
            *cryptographic_algorithm,
            &[
                CryptographicAlgorithm::EC,
                CryptographicAlgorithm::ECDSA,
                CryptographicAlgorithm::ECDH,
            ],
        )?;
    }

    let curve_nid = match curve {
        #[cfg(feature = "non-fips")]
        RecommendedCurve::P192 => Nid::X9_62_PRIME192V1,
        RecommendedCurve::P224 => Nid::SECP224R1,
        RecommendedCurve::P256 => Nid::X9_62_PRIME256V1,
        RecommendedCurve::P384 => Nid::SECP384R1,
        RecommendedCurve::P521 => Nid::SECP521R1,
        #[cfg(feature = "non-fips")]
        RecommendedCurve::SECP256K1 => Nid::SECP256K1,
        #[cfg(feature = "non-fips")]
        RecommendedCurve::SECP224K1 => Nid::SECP224K1,
        other => crypto_bail!("Curve Nid {:?} not supported by KMS", other),
    };

    let group = EcGroup::from_curve_name(curve_nid)?;
    let ec_private_key = EcKey::generate(&group)?;

    let private_key_bytes = Zeroizing::from(ec_private_key.private_key().to_vec());
    let private_key_num_bits = u32::try_from(ec_private_key.private_key().num_bits())?;
    let mut ctx = BigNumContext::new()?;
    let public_key_bytes =
        ec_private_key
            .public_key()
            .to_bytes(&group, PointConversionForm::COMPRESSED, &mut ctx)?;
    create_ec_key_pair(
        vendor_id,
        &private_key_bytes,
        private_key_num_bits,
        &public_key_bytes,
        private_key_uid,
        public_key_uid,
        curve,
        *cryptographic_algorithm,
        common_attributes,
        private_key_attributes,
        public_key_attributes,
    )
}

// Re-export sign helper from elliptic_curves module root
pub use crate::crypto::elliptic_curves::sign::ecdsa_sign;

#[expect(clippy::too_many_arguments)]
fn create_ec_key_pair(
    vendor_id: &str,
    private_key_bytes: &Zeroizing<Vec<u8>>,
    private_key_num_bits: u32,
    public_key_bytes: &[u8],
    private_key_uid: &str,
    public_key_uid: &str,
    curve: RecommendedCurve,
    cryptographic_algorithm: CryptographicAlgorithm,
    mut common_attributes: Attributes,
    private_key_attributes: Option<Attributes>,
    public_key_attributes: Option<Attributes>,
) -> Result<KeyPair, CryptoError> {
    // Cryptographic Usage Masks
    let private_key_mask = private_key_attributes
        .as_ref()
        .and_then(|attr| attr.cryptographic_usage_mask);
    let public_key_mask = public_key_attributes
        .as_ref()
        .and_then(|attr| attr.cryptographic_usage_mask);

    // recover tags and clean them up from the common attributes
    let tags = common_attributes.remove_tags(vendor_id).unwrap_or_default();
    Attributes::check_user_tags(&tags)?;

    // Generate  KMIP private Key
    let mut private_key_attributes = private_key_attributes.unwrap_or_default();
    private_key_attributes.merge(&common_attributes, false);
    let mut private_key = to_ec_private_key(
        private_key_bytes,
        private_key_num_bits,
        public_key_uid,
        curve,
        Some(cryptographic_algorithm),
        private_key_mask,
        private_key_attributes.sensitive.unwrap_or_default(),
    )?;
    // Merge the created object attributes
    private_key_attributes.merge(private_key.attributes()?, true);
    // Set the private key UID
    private_key_attributes.unique_identifier =
        Some(UniqueIdentifier::TextString(private_key_uid.to_owned()));
    // Add the tags
    let mut sk_tags = tags.clone();
    sk_tags.insert(SYSTEM_TAG_PRIVATE_KEY.to_owned());
    private_key_attributes.set_tags(vendor_id, sk_tags)?;
    // and set them on the object
    *private_key.key_block_mut()?.attributes_mut()? = private_key_attributes;
    trace!("private key converted OK");

    // Generate  KMIP public Key
    let mut public_key_attributes = public_key_attributes.unwrap_or_default();
    public_key_attributes.merge(&common_attributes, false);
    let mut public_key = to_ec_public_key(
        public_key_bytes,
        private_key_num_bits,
        private_key_uid,
        curve,
        Some(cryptographic_algorithm),
        public_key_mask,
    )?;
    // Merge the created object attributes
    public_key_attributes.merge(public_key.attributes()?, true);
    // Set the public key UID
    public_key_attributes.unique_identifier =
        Some(UniqueIdentifier::TextString(public_key_uid.to_owned()));
    // Add the tags
    let mut pk_tags = tags;
    pk_tags.insert(SYSTEM_TAG_PUBLIC_KEY.to_owned());
    public_key_attributes.set_tags(vendor_id, pk_tags)?;
    // and set them on the object
    *public_key.key_block_mut()?.attributes_mut()? = public_key_attributes;
    trace!("public key converted OK");

    Ok(KeyPair::new(private_key, public_key))
}

#[expect(clippy::unwrap_used)]
#[cfg(test)]
mod tests {

    #[cfg(not(feature = "non-fips"))]
    use cosmian_kmip::kmip_2_1::extra::fips::{
        FIPS_PRIVATE_ECC_MASK_ECDH, FIPS_PRIVATE_ECC_MASK_SIGN, FIPS_PRIVATE_ECC_MASK_SIGN_ECDH,
        FIPS_PUBLIC_ECC_MASK_ECDH, FIPS_PUBLIC_ECC_MASK_SIGN, FIPS_PUBLIC_ECC_MASK_SIGN_ECDH,
    };
    #[cfg(feature = "non-fips")]
    use cosmian_kmip::kmip_2_1::kmip_data_structures::KeyMaterial;
    use cosmian_kmip::{
        kmip_0::kmip_types::CryptographicUsageMask,
        kmip_2_1::{
            extra::tagging::VENDOR_ID_COSMIAN,
            kmip_attributes::Attributes,
            kmip_types::{CryptographicAlgorithm, RecommendedCurve},
        },
    };
    #[cfg(feature = "non-fips")]
    use openssl::pkey::{Id, PKey};
    // Load FIPS provider module from OpenSSL.
    #[cfg(not(feature = "non-fips"))]
    use openssl::provider::Provider;

    #[cfg(not(feature = "non-fips"))]
    use super::{check_ecc_mask_against_flags, check_ecc_mask_algorithm_compliance};
    use super::{create_approved_ecc_key_pair, create_ed25519_key_pair};
    #[cfg(feature = "non-fips")]
    use super::{create_x448_key_pair, create_x25519_key_pair};
    #[cfg(not(feature = "non-fips"))]
    use crate::crypto::elliptic_curves::operation::create_ed448_key_pair;
    #[cfg(feature = "non-fips")]
    use crate::crypto::elliptic_curves::{X448_PRIVATE_KEY_LENGTH, X25519_PRIVATE_KEY_LENGTH};
    use crate::openssl::{kmip_private_key_to_openssl, kmip_public_key_to_openssl};
    #[cfg(feature = "non-fips")]
    use crate::pad_be_bytes;

    #[test]
    fn test_ed25519_keypair_generation() {
        #[cfg(not(feature = "non-fips"))]
        // Load FIPS provider module from OpenSSL.
        Provider::load(None, "fips").unwrap();

        let private_key_attributes = Attributes {
            cryptographic_usage_mask: Some(CryptographicUsageMask::Sign),
            ..Attributes::default()
        };
        let public_key_attributes = Attributes {
            cryptographic_usage_mask: Some(CryptographicUsageMask::Verify),
            ..Attributes::default()
        };

        let keypair1 = create_ed25519_key_pair(
            VENDOR_ID_COSMIAN,
            "sk_uid1",
            "pk_uid1",
            Attributes::default(),
            Some(private_key_attributes.clone()),
            Some(public_key_attributes.clone()),
        )
        .unwrap();
        let keypair2 = create_ed25519_key_pair(
            VENDOR_ID_COSMIAN,
            "sk_uid2",
            "pk_uid2",
            Attributes::default(),
            Some(private_key_attributes),
            Some(public_key_attributes),
        )
        .unwrap();

        let privkey1 = kmip_private_key_to_openssl(keypair1.private_key()).unwrap();
        let privkey2 = kmip_private_key_to_openssl(keypair2.private_key()).unwrap();

        assert_ne!(
            privkey1.private_key_to_der().unwrap(),
            privkey2.private_key_to_der().unwrap()
        );

        let pubkey1 = kmip_public_key_to_openssl(keypair1.public_key()).unwrap();
        let pubkey2 = kmip_public_key_to_openssl(keypair2.public_key()).unwrap();

        assert_ne!(
            pubkey1.public_key_to_der().unwrap(),
            pubkey2.public_key_to_der().unwrap()
        );
    }

    #[expect(clippy::expect_used, clippy::panic)]
    #[test]
    #[cfg(feature = "non-fips")]
    fn test_x25519_conversions() {
        // Create a Key pair
        // - the private key is a TransparentEcPrivateKey where the key value is the bytes of the scalar
        // - the public key is a TransparentEcPublicKey where the key value is the bytes of the Montgomery point

        use cosmian_kmip::kmip_2_1::kmip_data_structures::KeyValue;
        let algorithm = CryptographicAlgorithm::ECDH;
        let private_key_attributes = Attributes {
            cryptographic_usage_mask: Some(CryptographicUsageMask::Unrestricted),
            ..Attributes::default()
        };
        let public_key_attributes = Attributes {
            cryptographic_usage_mask: Some(CryptographicUsageMask::Unrestricted),
            ..Attributes::default()
        };
        let wrap_key_pair = create_x25519_key_pair(
            VENDOR_ID_COSMIAN,
            "sk_uid",
            "pk_uid",
            &algorithm,
            Attributes::default(),
            Some(private_key_attributes),
            Some(public_key_attributes),
        )
        .expect("failed to create x25519 key pair in test_x25519_conversions");

        // public key
        //
        let Some(KeyValue::Structure { key_material, .. }) =
            &wrap_key_pair.public_key().key_block().unwrap().key_value
        else {
            panic!("failed to get key value from public key in test_x25519_conversions")
        };
        let KeyMaterial::TransparentECPublicKey {
            q_string: original_public_key_bytes,
            ..
        } = key_material
        else {
            panic!("Not a transparent public key")
        };
        // try to convert to openssl
        let p_key = PKey::public_key_from_raw_bytes(original_public_key_bytes, Id::X25519).unwrap();
        // convert back to bytes
        let raw_bytes = p_key.raw_public_key().unwrap();
        assert_eq!(&raw_bytes, original_public_key_bytes);

        // private key
        //
        let Some(KeyValue::Structure { key_material, .. }) =
            &wrap_key_pair.private_key().key_block().unwrap().key_value
        else {
            panic!("failed to get key value from public key in test_x25519_conversions")
        };
        let mut original_private_key_bytes = match key_material {
            KeyMaterial::TransparentECPrivateKey { d, .. } => d.to_bytes_be().1,
            _ => panic!("Not a transparent private key"),
        };
        pad_be_bytes(&mut original_private_key_bytes, X25519_PRIVATE_KEY_LENGTH);
        // try to convert to openssl
        let p_key =
            PKey::private_key_from_raw_bytes(&original_private_key_bytes, Id::X25519).unwrap();
        // convert back to bytes
        let raw_bytes = p_key.raw_private_key().unwrap();
        assert_eq!(raw_bytes, original_private_key_bytes);
        // get public key from private
        let raw_public_key_bytes = p_key.raw_public_key().unwrap();
        assert_eq!(&raw_public_key_bytes, original_public_key_bytes);
    }

    fn keypair_generation(curve: RecommendedCurve) {
        let algorithm = CryptographicAlgorithm::ECDH;
        let private_key_attributes = Attributes {
            cryptographic_usage_mask: Some(CryptographicUsageMask::Sign),
            ..Attributes::default()
        };
        let public_key_attributes = Attributes {
            cryptographic_usage_mask: Some(CryptographicUsageMask::Verify),
            ..Attributes::default()
        };

        let keypair1 = create_approved_ecc_key_pair(
            VENDOR_ID_COSMIAN,
            "sk_uid1",
            "pk_uid1",
            curve,
            &algorithm,
            Attributes::default(),
            Some(private_key_attributes.clone()),
            Some(public_key_attributes.clone()),
        )
        .unwrap();
        let keypair2 = create_approved_ecc_key_pair(
            VENDOR_ID_COSMIAN,
            "sk_uid2",
            "pk_uid2",
            curve,
            &algorithm,
            Attributes::default(),
            Some(private_key_attributes),
            Some(public_key_attributes),
        )
        .unwrap();

        let privkey1 = kmip_private_key_to_openssl(keypair1.private_key()).unwrap();
        let privkey2 = kmip_private_key_to_openssl(keypair2.private_key()).unwrap();

        assert_ne!(
            privkey1.private_key_to_der().unwrap(),
            privkey2.private_key_to_der().unwrap()
        );

        let pubkey1 = kmip_public_key_to_openssl(keypair1.public_key()).unwrap();
        let pubkey2 = kmip_public_key_to_openssl(keypair2.public_key()).unwrap();

        assert_ne!(
            pubkey1.public_key_to_der().unwrap(),
            pubkey2.public_key_to_der().unwrap()
        );
    }

    #[test]
    #[cfg(feature = "non-fips")]
    fn test_p192_keypair_generation() {
        keypair_generation(RecommendedCurve::P192);
    }

    #[test]
    fn test_approved_ecc_keypair_generation() {
        #[cfg(not(feature = "non-fips"))]
        // Load FIPS provider module from OpenSSL.
        Provider::load(None, "fips").unwrap();

        // P-CURVES
        keypair_generation(RecommendedCurve::P224);
        keypair_generation(RecommendedCurve::P256);
        keypair_generation(RecommendedCurve::P384);
        keypair_generation(RecommendedCurve::P521);
    }

    #[expect(clippy::expect_used, clippy::panic)]
    #[test]
    #[cfg(feature = "non-fips")]
    fn test_x448_conversions() {
        // Create a Key pair
        // - the private key is a TransparentEcPrivateKey where the key value is the bytes of the scalar
        // - the public key is a TransparentEcPublicKey where the key value is the bytes of the Montgomery point

        use cosmian_kmip::kmip_2_1::kmip_data_structures::KeyValue;
        let algorithm = CryptographicAlgorithm::Ed448;
        let private_key_attributes = Attributes {
            cryptographic_usage_mask: Some(CryptographicUsageMask::Sign),
            ..Attributes::default()
        };
        let public_key_attributes = Attributes {
            cryptographic_usage_mask: Some(CryptographicUsageMask::Verify),
            ..Attributes::default()
        };
        let wrap_key_pair = create_x448_key_pair(
            VENDOR_ID_COSMIAN,
            "sk_uid",
            "pk_uid",
            &algorithm,
            Attributes::default(),
            Some(private_key_attributes),
            Some(public_key_attributes),
        )
        .expect("failed to create x25519 key pair in test_x448_conversions");

        // public key
        //
        let Some(KeyValue::Structure { key_material, .. }) = wrap_key_pair
            .public_key()
            .key_block()
            .unwrap()
            .key_value
            .as_ref()
        else {
            panic!("Key value not found in public key");
        };
        let KeyMaterial::TransparentECPublicKey {
            q_string: original_public_key_bytes,
            ..
        } = key_material
        else {
            panic!("Not a transparent public key")
        };
        // try to convert to openssl
        let p_key = PKey::public_key_from_raw_bytes(original_public_key_bytes, Id::X448).unwrap();
        // convert back to bytes
        let raw_bytes = p_key.raw_public_key().unwrap();
        assert_eq!(&raw_bytes, original_public_key_bytes);

        // private key
        //
        let Some(KeyValue::Structure { key_material, .. }) = wrap_key_pair
            .private_key()
            .key_block()
            .unwrap()
            .key_value
            .as_ref()
        else {
            panic!("Key value not found in private key");
        };
        let mut original_private_key_bytes = match key_material {
            KeyMaterial::TransparentECPrivateKey { d, .. } => d.to_bytes_be().1,
            _ => panic!("Not a transparent private key"),
        };
        pad_be_bytes(&mut original_private_key_bytes, X448_PRIVATE_KEY_LENGTH);
        // try to convert to openssl
        let p_key =
            PKey::private_key_from_raw_bytes(&original_private_key_bytes, Id::X448).unwrap();
        // convert back to bytes
        let raw_bytes = p_key.raw_private_key().unwrap();
        assert_eq!(raw_bytes, original_private_key_bytes);
        // get public key from private
        let raw_public_key_bytes = p_key.raw_public_key().unwrap();
        assert_eq!(&raw_public_key_bytes, original_public_key_bytes);
    }

    #[test]
    #[cfg(not(feature = "non-fips"))]
    fn test_mask_flags_exact() {
        // Load FIPS provider module from OpenSSL.
        Provider::load(None, "fips").unwrap();

        let mask = CryptographicUsageMask::Sign
            | CryptographicUsageMask::Verify
            | CryptographicUsageMask::Encrypt
            | CryptographicUsageMask::Decrypt;

        let flags = CryptographicUsageMask::Sign
            | CryptographicUsageMask::Verify
            | CryptographicUsageMask::Encrypt
            | CryptographicUsageMask::Decrypt;

        let res = check_ecc_mask_against_flags(Some(mask), flags);

        res.unwrap();
    }

    #[test]
    #[cfg(not(feature = "non-fips"))]
    fn test_mask_flags_correct() {
        // Load FIPS provider module from OpenSSL.
        Provider::load(None, "fips").unwrap();

        let mask = CryptographicUsageMask::Authenticate;

        let flags = CryptographicUsageMask::Sign
            | CryptographicUsageMask::Verify
            | CryptographicUsageMask::CertificateSign
            | CryptographicUsageMask::CRLSign
            | CryptographicUsageMask::Authenticate;

        let res = check_ecc_mask_against_flags(Some(mask), flags);

        res.unwrap();
    }

    #[test]
    #[cfg(not(feature = "non-fips"))]
    fn test_mask_flags_none() {
        // Load FIPS provider module from OpenSSL.
        Provider::load(None, "fips").unwrap();

        let flags = CryptographicUsageMask::Unrestricted;

        let res = check_ecc_mask_against_flags(None, flags);

        assert!(res.is_err());
    }

    #[test]
    #[cfg(not(feature = "non-fips"))]
    fn test_mask_flags_all() {
        // Load FIPS provider module from OpenSSL.
        Provider::load(None, "fips").unwrap();

        let mask = FIPS_PRIVATE_ECC_MASK_SIGN;

        let flags = CryptographicUsageMask::Sign
            | CryptographicUsageMask::Verify
            | CryptographicUsageMask::Encrypt
            | CryptographicUsageMask::Decrypt
            | CryptographicUsageMask::WrapKey
            | CryptographicUsageMask::UnwrapKey
            | CryptographicUsageMask::MACGenerate
            | CryptographicUsageMask::MACVerify
            | CryptographicUsageMask::DeriveKey
            | CryptographicUsageMask::KeyAgreement
            | CryptographicUsageMask::CertificateSign
            | CryptographicUsageMask::CRLSign
            | CryptographicUsageMask::Authenticate;

        let res = check_ecc_mask_against_flags(Some(mask), flags);

        res.unwrap();
    }

    #[test]
    #[cfg(not(feature = "non-fips"))]
    fn test_mask_flags_fips_sign() {
        // Load FIPS provider module from OpenSSL.
        Provider::load(None, "fips").unwrap();

        let mask = CryptographicUsageMask::Sign;
        let res = check_ecc_mask_against_flags(Some(mask), FIPS_PRIVATE_ECC_MASK_SIGN);

        res.unwrap();

        let mask = CryptographicUsageMask::Verify;
        let res = check_ecc_mask_against_flags(Some(mask), FIPS_PUBLIC_ECC_MASK_SIGN);

        res.unwrap();
    }

    #[test]
    #[cfg(not(feature = "non-fips"))]
    fn test_mask_flags_fips_dh() {
        // Load FIPS provider module from OpenSSL.
        Provider::load(None, "fips").unwrap();

        let mask = CryptographicUsageMask::KeyAgreement;
        let res = check_ecc_mask_against_flags(Some(mask), FIPS_PRIVATE_ECC_MASK_ECDH);

        res.unwrap();

        let mask = CryptographicUsageMask::KeyAgreement;
        let res = check_ecc_mask_against_flags(Some(mask), FIPS_PUBLIC_ECC_MASK_ECDH);

        res.unwrap();

        let mask = CryptographicUsageMask::CRLSign
            | CryptographicUsageMask::CertificateSign
            | CryptographicUsageMask::KeyAgreement;
        let res = check_ecc_mask_against_flags(Some(mask), FIPS_PRIVATE_ECC_MASK_SIGN_ECDH);

        res.unwrap();

        let mask = CryptographicUsageMask::Verify | CryptographicUsageMask::KeyAgreement;
        let res = check_ecc_mask_against_flags(Some(mask), FIPS_PUBLIC_ECC_MASK_SIGN_ECDH);

        res.unwrap();
    }

    #[test]
    #[cfg(not(feature = "non-fips"))]
    /// This test should fail for unrestricted should not happen in FIPS mode.
    fn test_mask_flags_unrestricted1() {
        // Load FIPS provider module from OpenSSL.
        Provider::load(None, "fips").unwrap();

        let mask = CryptographicUsageMask::Unrestricted;
        let flags = CryptographicUsageMask::Unrestricted;

        let res = check_ecc_mask_against_flags(Some(mask), flags);

        assert!(res.is_err());
    }

    #[test]
    #[cfg(not(feature = "non-fips"))]
    /// This test should fail for unrestricted should not happen in FIPS mode.
    fn test_mask_flags_unrestricted2() {
        // Load FIPS provider module from OpenSSL.
        Provider::load(None, "fips").unwrap();

        let mask = CryptographicUsageMask::Sign
            | CryptographicUsageMask::Verify
            | CryptographicUsageMask::Encrypt
            | CryptographicUsageMask::Decrypt;
        let flags = CryptographicUsageMask::Unrestricted;

        let res = check_ecc_mask_against_flags(Some(mask), flags);

        assert!(res.is_err());
    }

    #[test]
    #[cfg(not(feature = "non-fips"))]
    /// This test should fail for unrestricted should not happen in FIPS mode.
    fn test_mask_flags_incorrect1() {
        // Load FIPS provider module from OpenSSL.
        Provider::load(None, "fips").unwrap();

        let mask = CryptographicUsageMask::Encrypt | CryptographicUsageMask::Decrypt;
        let flags = CryptographicUsageMask::Encrypt;

        let res = check_ecc_mask_against_flags(Some(mask), flags);

        assert!(res.is_err());
    }

    #[test]
    #[cfg(not(feature = "non-fips"))]
    /// This test should fail for unrestricted should not happen in FIPS mode.
    fn test_mask_flags_incorrect2() {
        // Load FIPS provider module from OpenSSL.
        Provider::load(None, "fips").unwrap();

        let mask = CryptographicUsageMask::WrapKey;
        let flags = CryptographicUsageMask::UnwrapKey;

        let res = check_ecc_mask_against_flags(Some(mask), flags);

        assert!(res.is_err());
    }

    #[test]
    #[cfg(not(feature = "non-fips"))]
    /// This test should fail for unrestricted should not happen in FIPS mode.
    fn test_mask_flags_incorrect3() {
        // Load FIPS provider module from OpenSSL.
        Provider::load(None, "fips").unwrap();

        let mask = CryptographicUsageMask::Sign
            | CryptographicUsageMask::Verify
            | CryptographicUsageMask::Encrypt
            | CryptographicUsageMask::Decrypt;
        let flags = CryptographicUsageMask::Sign
            | CryptographicUsageMask::Verify
            | CryptographicUsageMask::CRLSign
            | CryptographicUsageMask::Decrypt;

        let res = check_ecc_mask_against_flags(Some(mask), flags);

        assert!(res.is_err());
    }

    #[test]
    #[cfg(not(feature = "non-fips"))]
    fn test_check_ecc_algo_contains() {
        // Load FIPS provider module from OpenSSL.
        Provider::load(None, "fips").unwrap();

        let private_key_mask = CryptographicUsageMask::KeyAgreement;
        let public_key_mask = CryptographicUsageMask::KeyAgreement;

        let algorithm = CryptographicAlgorithm::ECDH;
        let allowed = &[
            CryptographicAlgorithm::ECDH,
            CryptographicAlgorithm::ECDSA,
            CryptographicAlgorithm::EC,
        ];
        let res = check_ecc_mask_algorithm_compliance(
            Some(private_key_mask),
            Some(public_key_mask),
            algorithm,
            allowed,
        );

        res.unwrap();
    }

    #[test]
    #[cfg(not(feature = "non-fips"))]
    fn test_check_ecc_algo_not_contains() {
        // Load FIPS provider module from OpenSSL.
        Provider::load(None, "fips").unwrap();

        let private_key_mask = CryptographicUsageMask::KeyAgreement;
        let public_key_mask = CryptographicUsageMask::KeyAgreement;

        let algorithm = CryptographicAlgorithm::ECDH;
        let allowed = &[CryptographicAlgorithm::ECDSA, CryptographicAlgorithm::EC];
        let res = check_ecc_mask_algorithm_compliance(
            Some(private_key_mask),
            Some(public_key_mask),
            algorithm,
            allowed,
        );

        assert!(res.is_err());
    }

    #[test]
    #[cfg(not(feature = "non-fips"))]
    fn test_create_ecc_keys_bad_mask() {
        // Load FIPS provider module from OpenSSL.
        Provider::load(None, "fips").unwrap();

        let algorithm = CryptographicAlgorithm::ECDH;
        let private_key_attributes = Attributes {
            cryptographic_usage_mask: Some(CryptographicUsageMask::Decrypt),
            ..Attributes::default()
        };
        let public_key_attributes = Attributes {
            cryptographic_usage_mask: Some(CryptographicUsageMask::Encrypt),
            ..Attributes::default()
        };
        let res = create_approved_ecc_key_pair(
            VENDOR_ID_COSMIAN,
            "pubkey01",
            "privkey01",
            RecommendedCurve::P256,
            &algorithm,
            Attributes::default(),
            Some(private_key_attributes),
            Some(public_key_attributes),
        );

        assert!(res.is_err());

        let algorithm = CryptographicAlgorithm::ECDSA;
        let private_key_attributes = Attributes {
            cryptographic_usage_mask: Some(CryptographicUsageMask::Unrestricted),
            ..Attributes::default()
        };
        let public_key_attributes = Attributes {
            cryptographic_usage_mask: Some(CryptographicUsageMask::Unrestricted),
            ..Attributes::default()
        };
        let res = create_approved_ecc_key_pair(
            VENDOR_ID_COSMIAN,
            "pubkey02",
            "privkey02",
            RecommendedCurve::P384,
            &algorithm,
            Attributes::default(),
            Some(private_key_attributes),
            Some(public_key_attributes),
        );

        assert!(res.is_err());

        let algorithm = CryptographicAlgorithm::ECDH;
        let private_key_attributes = Attributes {
            cryptographic_usage_mask: Some(CryptographicUsageMask::Unrestricted),
            ..Attributes::default()
        };
        let public_key_attributes = Attributes {
            cryptographic_usage_mask: Some(CryptographicUsageMask::KeyAgreement),
            ..Attributes::default()
        };
        let res = create_approved_ecc_key_pair(
            VENDOR_ID_COSMIAN,
            "pubkey03",
            "privkey03",
            RecommendedCurve::P521,
            &algorithm,
            Attributes::default(),
            Some(private_key_attributes),
            Some(public_key_attributes),
        );

        assert!(res.is_err());

        let algorithm = CryptographicAlgorithm::ECDH;
        let private_key_attributes = Attributes {
            cryptographic_usage_mask: Some(CryptographicUsageMask::KeyAgreement),
            ..Attributes::default()
        };
        let public_key_attributes = Attributes {
            cryptographic_usage_mask: Some(CryptographicUsageMask::Unrestricted),
            ..Attributes::default()
        };
        let res = create_approved_ecc_key_pair(
            VENDOR_ID_COSMIAN,
            "pubkey04",
            "privkey04",
            RecommendedCurve::P521,
            &algorithm,
            Attributes::default(),
            Some(private_key_attributes),
            Some(public_key_attributes),
        );

        assert!(res.is_err());

        let private_key_attributes = Attributes {
            cryptographic_usage_mask: Some(CryptographicUsageMask::Sign),
            ..Attributes::default()
        };
        let public_key_attributes = Attributes {
            cryptographic_usage_mask: Some(
                CryptographicUsageMask::Verify | CryptographicUsageMask::KeyAgreement,
            ),
            ..Attributes::default()
        };
        let res = create_ed448_key_pair(
            VENDOR_ID_COSMIAN,
            "pubkey05",
            "privkey05",
            Attributes::default(),
            Some(private_key_attributes),
            Some(public_key_attributes),
        );

        assert!(res.is_err());
    }

    #[test]
    #[cfg(not(feature = "non-fips"))]
    fn test_create_ecc_keys_bad_algorithm() {
        // Load FIPS provider module from OpenSSL.
        Provider::load(None, "fips").unwrap();

        let algorithm = CryptographicAlgorithm::Ed25519;
        let private_key_attributes = Attributes {
            cryptographic_usage_mask: Some(CryptographicUsageMask::Sign),
            ..Attributes::default()
        };
        let public_key_attributes = Attributes {
            cryptographic_usage_mask: Some(CryptographicUsageMask::Verify),
            ..Attributes::default()
        };
        let res = create_approved_ecc_key_pair(
            VENDOR_ID_COSMIAN,
            "pubkey01",
            "privkey01",
            RecommendedCurve::P256,
            &algorithm,
            Attributes::default(),
            Some(private_key_attributes),
            Some(public_key_attributes),
        );

        assert!(res.is_err());
    }

    #[test]
    #[cfg(not(feature = "non-fips"))]
    fn test_create_ecc_keys_incorrect_mask_and_algorithm_ecdh() {
        // Load FIPS provider module from OpenSSL.
        Provider::load(None, "fips").unwrap();

        // ECDH algorithm should not have the Unrestricted mask;
        let algorithm = CryptographicAlgorithm::ECDH;
        let private_key_attributes = Attributes {
            cryptographic_usage_mask: Some(
                CryptographicUsageMask::Sign
                    | CryptographicUsageMask::KeyAgreement
                    | CryptographicUsageMask::DeriveKey
                    | CryptographicUsageMask::Unrestricted,
            ),
            ..Attributes::default()
        };
        let public_key_attributes = Attributes {
            cryptographic_usage_mask: Some(
                CryptographicUsageMask::Verify
                    | CryptographicUsageMask::KeyAgreement
                    | CryptographicUsageMask::DeriveKey,
            ),
            ..Attributes::default()
        };
        let res = create_approved_ecc_key_pair(
            VENDOR_ID_COSMIAN,
            "pubkey01",
            "privkey01",
            RecommendedCurve::P256,
            &algorithm,
            Attributes::default(),
            Some(private_key_attributes),
            Some(public_key_attributes),
        );

        assert!(res.is_err());
    }

    #[test]
    #[cfg(not(feature = "non-fips"))]
    fn test_create_ecc_keys_incorrect_mask_and_algorithm_ecdsa() {
        // Load FIPS provider module from OpenSSL.
        Provider::load(None, "fips").unwrap();

        // ECDSA algorithm should not have KeyAgreement mask;
        let algorithm = CryptographicAlgorithm::ECDSA;
        let private_key_attributes = Attributes {
            cryptographic_usage_mask: Some(CryptographicUsageMask::Sign),
            ..Attributes::default()
        };
        let public_key_attributes = Attributes {
            cryptographic_usage_mask: Some(
                CryptographicUsageMask::Verify | CryptographicUsageMask::KeyAgreement,
            ),
            ..Attributes::default()
        };

        let res = create_approved_ecc_key_pair(
            VENDOR_ID_COSMIAN,
            "pubkey01",
            "privkey01",
            RecommendedCurve::P256,
            &algorithm,
            Attributes::default(),
            Some(private_key_attributes),
            Some(public_key_attributes),
        );

        assert!(res.is_err());
    }

    #[test]
    #[cfg(not(feature = "non-fips"))]
    fn test_create_ecc_keys_incorrect_private_mask() {
        // Load FIPS provider module from OpenSSL.
        Provider::load(None, "fips").unwrap();

        let algorithm = CryptographicAlgorithm::ECDSA;
        let private_key_attributes = Attributes {
            cryptographic_usage_mask: Some(
                CryptographicUsageMask::Sign | CryptographicUsageMask::Verify,
            ),
            ..Attributes::default()
        };
        let public_key_attributes = Attributes {
            cryptographic_usage_mask: Some(CryptographicUsageMask::Verify),
            ..Attributes::default()
        };
        let res = create_approved_ecc_key_pair(
            VENDOR_ID_COSMIAN,
            "pubkey01",
            "privkey01",
            RecommendedCurve::P256,
            &algorithm,
            Attributes::default(),
            Some(private_key_attributes),
            Some(public_key_attributes),
        );

        assert!(res.is_err());
    }

    #[test]
    #[cfg(not(feature = "non-fips"))]
    fn test_create_ecc_keys_incorrect_public_mask() {
        // Load FIPS provider module from OpenSSL.
        Provider::load(None, "fips").unwrap();

        let algorithm = CryptographicAlgorithm::ECDSA;
        let private_key_attributes = Attributes {
            cryptographic_usage_mask: Some(CryptographicUsageMask::Sign),
            ..Attributes::default()
        };
        let public_key_attributes = Attributes {
            cryptographic_usage_mask: Some(CryptographicUsageMask::Sign),
            ..Attributes::default()
        };
        let res = create_approved_ecc_key_pair(
            VENDOR_ID_COSMIAN,
            "pubkey01",
            "privkey01",
            RecommendedCurve::P256,
            &algorithm,
            Attributes::default(),
            Some(private_key_attributes),
            Some(public_key_attributes),
        );

        assert!(res.is_err());
    }
}