qubip_aurora 0.11.0

A framework to build OpenSSL Providers tailored for the transition to post-quantum cryptography
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
use super::*;
use bindings::{
    OSSL_CALLBACK, OSSL_KEYMGMT_SELECT_KEYPAIR, OSSL_KEYMGMT_SELECT_PRIVATE_KEY,
    OSSL_KEYMGMT_SELECT_PUBLIC_KEY, OSSL_PKEY_PARAM_BITS, OSSL_PKEY_PARAM_MANDATORY_DIGEST,
    OSSL_PKEY_PARAM_MAX_SIZE, OSSL_PKEY_PARAM_PRIV_KEY, OSSL_PKEY_PARAM_PUB_KEY,
    OSSL_PKEY_PARAM_SECURITY_BITS,
};
use forge::{
    bindings,
    operations::keymgmt::selection::Selection,
    operations::signature::{Signer, VerificationError, Verifier},
    ossl_callback::OSSLCallback,
    osslparams::*,
};
use pqcrypto_traits::sign::DetachedSignature;
use std::{
    ffi::{c_int, c_void},
    fmt::Debug,
};

use pqcrypto_mldsa::mldsa44 as backend_module;

use super::OurError as KMGMTError;
type OurResult<T> = anyhow::Result<T, KMGMTError>;

use super::helpers::MlDsaSeed;
use super::signature::{
    Signature, SignatureBytes, SignatureEncoding, SignerWithCtx, VerifierWithCtx,
};

pub(crate) const PUBKEY_LEN: usize = PublicKey::byte_len();
pub(crate) const SECRETKEY_LEN: usize = PrivateKey::byte_len();
pub(crate) const SIGNATURE_LEN: usize = PrivateKey::signature_bytes();

// The wrapped key from the pqcrypto crate has to be public, or else we can't access it to use it
// with the pqcrypto sign and verify functions.
#[derive(PartialEq)]
pub struct PublicKey(backend_module::PublicKey);

#[derive(PartialEq)]
pub struct PrivateKey {
    private: PrivateKeyData,
    public: backend_module::PublicKey,
}

#[derive(PartialEq)]
pub enum PrivateKeyData {
    Expanded(backend_module::SecretKey),
    Both {
        seed: MlDsaSeed,
        expanded: backend_module::SecretKey,
    },
}

impl core::fmt::Debug for PublicKey {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_tuple("PublicKey").field(&"<opaque field>").finish()
    }
}

impl PublicKey {
    pub fn decode(bytes: &[u8]) -> Result<Self, KMGMTError> {
        let k = <backend_module::PublicKey as pqcrypto_traits::sign::PublicKey>::from_bytes(bytes)
            .map_err(|e| {
                anyhow!(
                    "pqcrypto_traits::sign::PublicKey::from_bytes (MLDSA44) returned {:?}",
                    e
                )
            })?;
        Ok(Self(k))
    }

    pub fn encode(&self) -> Vec<u8> {
        let Self(ref k) = self;
        <backend_module::PublicKey as pqcrypto_traits::sign::PublicKey>::as_bytes(k).to_vec()
    }

    pub const fn byte_len() -> usize {
        backend_module::public_key_bytes()
    }

    pub const fn signature_bytes() -> usize {
        PrivateKey::signature_bytes()
    }

    #[named]
    pub fn from_DER(pk_der_bytes: &[u8]) -> OurResult<Self> {
        use asn_definitions::PublicKey as ASNPublicKey;

        trace!(target: log_target!(), "{}", "Called!");

        let decodedpubkey: ASNPublicKey;
        let slice = match pk_der_bytes.len() {
            PUBKEY_LEN => pk_der_bytes,

            #[cfg(any())]
            _ => {
                decodedpubkey = match rasn::der::decode(pk_der_bytes) {
                    Ok(p) => p,
                    Err(e) => {
                        error!(target: log_target!(), "Failed to decode the inner public key: {e:?}");
                        return Err(OurError::from(e));
                    }
                };

                debug!(target: log_target!(), "Parsed public key material out of ASN.1 for decoding!");

                let slice: &[u8] = decodedpubkey.0.as_slice();
                slice
            }

            #[cfg(not(any()))]
            _ => {
                let _ = decodedpubkey;
                unreachable!();
            }
        };

        debug_assert_eq!(slice.len(), PUBKEY_LEN);
        let pubkey = Self::decode(slice)?;

        Ok(pubkey)
    }

    #[named]
    pub fn to_DER(&self) -> OurResult<Vec<u8>> {
        trace!(target: log_target!(), "{}", "Called!");

        Ok(self.encode())
    }
}

impl Verifier<Signature> for PublicKey {
    #[named]
    fn verify(&self, msg: &[u8], sig: &Signature) -> Result<(), forge::crypto::signature::Error> {
        trace!(target: log_target!(), "Called");
        self.verify_with_ctx(msg, sig, &[])
    }
}

impl VerifierWithCtx<Signature> for PublicKey {
    #[named]
    fn verify_with_ctx(
        &self,
        msg: &[u8],
        sig: &Signature,
        ctx: &[u8],
    ) -> Result<(), signature::Error> {
        trace!(target: log_target!(), "Called");

        // validate ctx length
        // FIPS 204 specifies maximum ctx len is 255 bytes, so it should
        // fit into a u8
        let _ctx_len: u8 = ctx.len().try_into().map_err(|e| {
            log::error!("Invalid ctx_len: {} (maximum 255 bytes)", ctx.len());
            forge::crypto::signature::Error::from_source(e)
        })?;

        let sig = sig.to_bytes();
        let sig = sig.as_ref();
        use pqcrypto_traits::sign::DetachedSignature;
        let sig = backend_module::DetachedSignature::from_bytes(sig).map_err(|e| {
            error!(target: log_target!(), "{e:?}");
            forge::crypto::signature::Error::from_source(
                VerificationError::GenericVerificationError,
            )
        })?;
        backend_module::verify_detached_signature_ctx(&sig, msg, ctx, &self.0)
            .map_err(map_into_VerificationError)
            .map_err(forge::crypto::signature::Error::from_source)
    }
}

#[named]
fn map_into_VerificationError(
    value: pqcrypto_traits::sign::VerificationError,
) -> VerificationError {
    match value {
        pqcrypto_traits::sign::VerificationError::InvalidSignature => {
            VerificationError::InvalidSignature
        }
        pqcrypto_traits::sign::VerificationError::UnknownVerificationError => {
            VerificationError::GenericVerificationError
        }
        e => {
            warn!(target: log_target!(), "Unknown error {e:#?}");
            VerificationError::GenericVerificationError
        }
    }
}

impl PrivateKey {
    pub fn seed(&self) -> Result<MlDsaSeed, KMGMTError> {
        match &self.private {
            PrivateKeyData::Expanded(_) => Err(anyhow!("Key does not contain a seed")),
            PrivateKeyData::Both { seed, expanded: _ } => Ok(*seed),
        }
    }

    pub fn expanded_key(&self) -> &backend_module::SecretKey {
        match &self.private {
            PrivateKeyData::Expanded(signing_key) => signing_key,
            PrivateKeyData::Both { seed: _, expanded } => expanded,
        }
    }

    /// Encode the private key as a vector of bytes.
    ///
    /// If the seed is available, only the seed is encoded. Otherwise, the
    /// expanded form of the key is encoded.
    pub fn encode(&self) -> Vec<u8> {
        use pqcrypto_traits::sign::SecretKey;
        match &self.private {
            PrivateKeyData::Expanded(signing_key) => signing_key.as_bytes().to_vec(),
            PrivateKeyData::Both { seed, expanded: _ } => seed.to_vec(),
        }
    }

    /// Attempt to decode `bytes` as a private key.
    ///
    /// If the bytes represent a key in seed format, then the expanded form of
    /// the private key is derived from it, as well as the public key, and all
    /// are stored. If the bytes represent a key in expanded form, then the
    /// public key is derived and stored with it (there is no way to recover the
    /// seed).
    pub fn decode(bytes: &[u8]) -> Result<Self, KMGMTError> {
        let pkd = Self::decode_seed(bytes).or_else(|_| {
            super::helpers::decode_mldsa_secret_key(bytes)
                .map(PrivateKeyData::Expanded)
                .ok_or(anyhow!("Unable to decode private key"))
        })?;

        let backend_key = match pkd {
            PrivateKeyData::Both { seed: _, expanded } => expanded,
            PrivateKeyData::Expanded(expanded) => expanded,
        };

        let public = super::helpers::derive_mldsa_public_key(&backend_key)
            .ok_or(anyhow!("Unable to derive public key from private key"))?;

        Ok(Self {
            private: pkd,
            public,
        })
    }

    /// Attempt to decode `bytes` as a private key in seed format.
    pub fn decode_seed(bytes: &[u8]) -> Result<PrivateKeyData, KMGMTError> {
        let seed = TryInto::<&MlDsaSeed>::try_into(bytes)?;
        let key =
            super::helpers::decode_mldsa_secret_key(seed).map(|expanded| PrivateKeyData::Both {
                seed: *seed,
                expanded,
            });
        key.ok_or(anyhow!("Unable to decode key from seed"))
    }

    pub const fn byte_len() -> usize {
        backend_module::secret_key_bytes()
    }

    pub const fn signature_bytes() -> usize {
        backend_module::signature_bytes()
    }

    pub const fn seed_bytes() -> usize {
        super::helpers::ML_DSA_SEED_SIZE
    }

    /// Derive a matching public key from this private key
    pub fn derive_public_key(&self) -> Option<PublicKey> {
        Some(PublicKey(self.public.clone()))
    }

    #[named]
    pub fn from_DER(sk_der_bytes: &[u8]) -> OurResult<(Self, Option<PublicKey>)> {
        use asn_definitions::PrivateKey as ASNPrivateKey;

        let decodedprivkey = match rasn::der::decode::<ASNPrivateKey>(sk_der_bytes) {
            Ok(p) => p,
            Err(e) => {
                error!(target: log_target!(), "Failed to decode the inner private key: {e:?}");
                return Err(OurError::from(e));
            }
        };

        debug!(target: log_target!(), "Parsed private key material out of ASN.1 for decoding!");

        let privkey_bytes: &[u8] = match decodedprivkey {
            ASNPrivateKey::seed(ref seed) => &seed,
            ASNPrivateKey::expandedKey(ref expandedKey) => &expandedKey,
            ASNPrivateKey::both(ref private_key_both) => &private_key_both.seed,
        };

        let privkey = keymgmt_functions::PrivateKey::decode(privkey_bytes)?;

        // If we had both seed and expanded in the decoded key, check that the expanded form
        // produced by PrivateKey::decode matches the expected one.
        if let ASNPrivateKey::both(ref private_key_both) = decodedprivkey {
            if private_key_both.expanded_key != privkey.encode() {
                error!(target: log_target!(), "Expanded form derived from seed did not match decoded expanded key");
                return Err(anyhow!(
                    "Expanded form derived from seed did not match decoded expanded key"
                ));
            }
        }

        // We need to derive a public key from the private key
        let pubkey = match privkey.derive_public_key() {
            Some(k) => k,
            None => {
                error!(target: log_target!(), "Could not derive the public key from the inner private key");
                return Err(anyhow!(
                    "Could not derive the public key from the inner private key"
                ));
            }
        };

        Ok((privkey, Some(pubkey)))
    }

    #[named]
    pub fn to_DER(&self) -> OurResult<Vec<u8>> {
        use asn_definitions::PrivateKey as ASNPrivateKey;

        let raw_sk_bytes = self.encode();
        let asn_sk = match self.private {
            PrivateKeyData::Expanded(_) => ASNPrivateKey::expandedKey(raw_sk_bytes.into()),
            PrivateKeyData::Both {
                seed: _,
                expanded: _,
            } => ASNPrivateKey::seed(raw_sk_bytes.into()),
        };
        let asn_sk_bytes = match rasn::der::encode(&asn_sk) {
            Ok(v) => v,
            Err(e) => {
                error!(target: log_target!(), "Failed to encode private key: {e:?}");
                return Err(OurError::from(e));
            }
        };
        Ok(asn_sk_bytes)
    }
}

impl Signer<Signature> for PrivateKey {
    fn try_sign(&self, msg: &[u8]) -> Result<Signature, forge::crypto::signature::Error> {
        self.try_sign_with_ctx(msg, &[])
    }
}

impl SignerWithCtx<Signature> for PrivateKey {
    #[named]
    fn try_sign_with_ctx(&self, msg: &[u8], ctx: &[u8]) -> Result<Signature, signature::Error> {
        trace!(target: log_target!(), "Called");

        let sk = self.expanded_key();

        // validate ctx length
        // FIPS 204 specifies maximum ctx len is 255 bytes, so it should
        // fit into a u8
        let _ctx_len: u8 = ctx.len().try_into().map_err(|e| {
            log::error!("Invalid ctx_len: {} (maximum 255 bytes)", ctx.len());
            forge::crypto::signature::Error::from_source(e)
        })?;

        let signature = backend_module::detached_sign_ctx(msg, ctx, sk);
        Signature::try_from(signature.as_bytes())
            .map_err(|e| forge::crypto::signature::Error::from_source(e))
    }
}

#[expect(dead_code)]
pub struct KeyPair<'a> {
    pub private: Option<PrivateKey>,
    pub public: Option<PublicKey>,
    provctx: &'a ProviderInstance<'a>,
}

impl<'a> Debug for KeyPair<'a> {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        let private = match &self.private {
            #[cfg(not(debug_assertions))] // code compiled only in release builds
            Some(_) => {
                todo!("remove private key printing also from development builds");
                format!("{}", "present")
            }
            #[cfg(debug_assertions)] // code compiled only in development builds
            Some(p) => {
                format!("{:02x?}", p.encode())
            }
            None => format!("{:?}", None::<()>),
        };
        let public = match &self.public {
            Some(p) => format!("{:02x?}", p.encode()),
            None => format!("{:?}", None::<()>),
        };
        f.debug_struct("KeyPair")
            .field("private", &private)
            .field("public", &public)
            .finish()
    }
}

impl<'a> KeyPair<'a> {
    #[named]
    fn new(provctx: &'a ProviderInstance) -> Self {
        trace!(target: log_target!(), "Called");
        KeyPair {
            private: None,
            public: None,
            provctx: provctx,
        }
    }

    #[named]
    pub(super) fn from_parts(
        provctx: &'a ProviderInstance,
        private: Option<PrivateKey>,
        public: Option<PublicKey>,
    ) -> Self {
        trace!(target: log_target!(), "Called");
        KeyPair {
            private,
            public,
            provctx,
        }
    }

    #[named]
    fn generate(provctx: &'a ProviderInstance) -> Result<Self, KMGMTError> {
        trace!(target: log_target!(), "Called");

        // Isn't it weird that this operation can't fail? What does the pqclean implementation do if
        // it can't find a randomness source or it can't allocate memory or something?
        let (pk, sk) = backend_module::keypair();

        let sk = PrivateKey {
            private: PrivateKeyData::Expanded(sk),
            public: pk.clone(),
        };

        Ok(KeyPair {
            private: Some(sk),
            public: Some(PublicKey(pk)),
            provctx,
        })
    }

    #[cfg(test)]
    #[named]
    pub(crate) fn generate_new(provctx: &'a ProviderInstance) -> Result<Self, KMGMTError> {
        trace!(target: log_target!(), "Called");
        let genctx = GenCTX::new(provctx, Selection::KEYPAIR);
        let r = genctx.generate()?;

        Ok(Self {
            private: r.private,
            public: r.public,
            provctx,
        })
    }
}

impl<'a> Signer<Signature> for KeyPair<'a> {
    #[named]
    fn try_sign(&self, msg: &[u8]) -> Result<Signature, forge::crypto::signature::Error> {
        trace!(target: log_target!(), "Called");

        let sk = self
            .private
            .as_ref()
            .ok_or_else(|| {
                anyhow!(
                    "This keypair does not have a private key, so it cannot generate signatures"
                )
            })
            .map_err(forge::crypto::signature::Error::from_source)?;
        Ok(sk.try_sign(msg)?)
    }
}

impl<'a> Verifier<Signature> for KeyPair<'a> {
    #[named]
    fn verify(&self, msg: &[u8], sig: &Signature) -> Result<(), forge::crypto::signature::Error> {
        trace!(target: log_target!(), "Called");

        let pk = self
            .public
            .as_ref()
            .ok_or_else(|| {
                anyhow!("This keypair does not have a public key, so it cannot verify signatures")
            })
            .map_err(|e| {
                error!("{e:#}");
                forge::crypto::signature::Error::from_source(
                    VerificationError::GenericVerificationError,
                )
            })?;
        pk.verify(msg, sig)
    }
}

impl TryFrom<*mut c_void> for &mut KeyPair<'_> {
    type Error = KMGMTError;

    #[named]
    fn try_from(vptr: *mut c_void) -> Result<Self, Self::Error> {
        trace!(target: log_target!(), "Called for {}",
        "impl TryFrom<*mut c_void> for &mut KeyPair"
        );
        let ptr = vptr as *mut KeyPair;
        if ptr.is_null() {
            return Err(anyhow::anyhow!("vptr was null"));
        }
        Ok(unsafe { &mut *ptr })
    }
}

impl TryFrom<*mut c_void> for &KeyPair<'_> {
    type Error = KMGMTError;

    #[named]
    fn try_from(vptr: *mut core::ffi::c_void) -> Result<Self, Self::Error> {
        trace!(target: log_target!(), "Called for {}", "impl<'a> TryFrom<*mut core::ffi::c_void> for &KeyPair<'a>");
        let r: &mut KeyPair = vptr.try_into()?;
        Ok(r)
    }
}

impl TryFrom<*const c_void> for &KeyPair<'_> {
    type Error = KMGMTError;

    #[named]
    fn try_from(vptr: *const c_void) -> Result<Self, Self::Error> {
        trace!(target: log_target!(), "Called for {}", "impl<'a> TryFrom<*const c_void> for &KeyPair<'a>");
        let mut_vptr = vptr as *mut c_void;
        let r: &mut KeyPair = mut_vptr.try_into()?;
        Ok(r)
    }
}

#[named]
pub(super) unsafe extern "C" fn new(vprovctx: *mut c_void) -> *mut c_void {
    trace!(target: log_target!(), "{}", "Called!");
    const ERROR_RET: *mut c_void = std::ptr::null_mut();
    let provctx: &ProviderInstance<'_> = handleResult!(vprovctx.try_into());

    let keypair: Box<KeyPair<'_>> = Box::new(KeyPair::new(provctx));
    return Box::into_raw(keypair).cast();
}

#[named]
pub(super) unsafe extern "C" fn free(vkey: *mut c_void) {
    trace!(target: log_target!(), "{}", "Called!");
    if !vkey.is_null() {
        let /* mut  */kp: Box<KeyPair> = unsafe { Box::from_raw(vkey.cast()) };
        //todo!("Cleanse the private key data")
        //todo!("Free the key data")
        drop(kp);
    }
}

#[named]
pub(super) unsafe extern "C" fn has(vkeydata: *const c_void, selection: c_int) -> c_int {
    const ERROR_RET: c_int = 0;

    trace!(target: log_target!(), "{}", "Called!");

    let selection: u32 = selection.try_into().unwrap();

    // From https://github.com/openssl/openssl/blob/fb55383c65bb47eef3bf5f73be5a0ad41d81bb3f/providers/implementations/keymgmt/ml_dsa_kmgmt.c#L145-L155
    if (selection & OSSL_KEYMGMT_SELECT_KEYPAIR) == 0 {
        return 1; // the selection is not missing
    }

    let keydata: &KeyPair = handleResult!(vkeydata.try_into());

    // from https://github.com/openssl/openssl/blob/fb55383c65bb47eef3bf5f73be5a0ad41d81bb3f/crypto/ml_dsa/ml_dsa_key.c#L285-L297
    if (selection & OSSL_KEYMGMT_SELECT_KEYPAIR) != 0 {
        // Note that the public key always exists if there is a private key
        if keydata.public.is_none() {
            return 0; // No public key
        }
        if (selection & OSSL_KEYMGMT_SELECT_PRIVATE_KEY) != 0 && keydata.private.is_none() {
            return 0; // No private key
        }
        return 1;
    }

    return 0;
}

#[named]
pub(super) unsafe extern "C" fn gen(
    vgenctx: *mut c_void,
    _cb: OSSL_CALLBACK,
    _cbarg: *mut c_void,
) -> *mut c_void {
    const ERROR_RET: *mut c_void = std::ptr::null_mut();
    trace!(target: log_target!(), "{}", "Called!");
    let genctx: &mut GenCTX<'_> = handleResult!(vgenctx.try_into());

    let keypair = handleResult!(genctx.generate());
    let keypair: Box<KeyPair<'_>> = Box::new(keypair);

    let keypair_ptr = Box::into_raw(keypair);

    return keypair_ptr.cast();
}

#[named]
pub(super) unsafe extern "C" fn gen_cleanup(vgenctx: *mut c_void) {
    trace!(target: log_target!(), "{}", "Called!");
    if !vgenctx.is_null() {
        let /* mut  */genctx: Box<GenCTX> = unsafe { Box::from_raw(vgenctx.cast()) };
        //todo!("clean up and free the key object generation context genctx");
        drop(genctx);
    }
}

struct GenCTX<'a> {
    provctx: &'a ProviderInstance<'a>,
    selection: Selection,
}

impl<'a> GenCTX<'a> {
    fn new(provctx: &'a ProviderInstance, selection: Selection) -> Self {
        Self {
            provctx: provctx,
            selection: selection,
        }
    }

    #[named]
    fn generate(&self) -> Result<KeyPair<'_>, KMGMTError> {
        trace!(target: log_target!(), "Called");
        if !self.selection.contains(Selection::KEYPAIR) {
            trace!(target: log_target!(), "Returning empty keypair due to selection bits {:?}", self.selection);
            return Ok(KeyPair::new(self.provctx));
        }
        trace!(target: log_target!(), "Generating a new KeyPair");

        KeyPair::generate(self.provctx)
    }
}

impl<'a> TryFrom<*mut c_void> for &mut GenCTX<'a> {
    type Error = KMGMTError;

    #[named]
    fn try_from(vctx: *mut c_void) -> Result<Self, Self::Error> {
        trace!(target: log_target!(), "Called for {}",
        "impl<'a> TryFrom<*mut c_void> for &mut GenCTX<'a>"
        );
        let ctxp = vctx as *mut GenCTX;
        if ctxp.is_null() {
            panic!("vctx was null");
        }
        Ok(unsafe { &mut *ctxp })
    }
}

#[named]
pub(super) unsafe extern "C" fn gen_init(
    vprovctx: *mut c_void,
    selection: c_int,
    params: *const OSSL_PARAM,
) -> *mut c_void {
    const ERROR_RET: *mut c_void = std::ptr::null_mut();
    trace!(target: log_target!(), "{}", "Called!");
    let provctx: &ProviderInstance<'_> = handleResult!(vprovctx.try_into());
    let selection: Selection = handleResult!((selection as u32).try_into());
    let newctx = Box::new(GenCTX::new(provctx, selection));

    if !params.is_null() {
        warn!(target: log_target!(), "Ignoring params!");
        //todo!("set params on the context if params is not null")
    }

    let newctx_raw_ptr = Box::into_raw(newctx);

    return newctx_raw_ptr.cast();
}

#[named]
pub(super) unsafe extern "C" fn import(
    _keydata: *mut c_void,
    _selection: c_int,
    _params: *const OSSL_PARAM,
) -> c_int {
    trace!(target: log_target!(), "{}", "Called!");
    todo!("import data indicated by selection into keydata with values taken from the params array")
}

#[cfg(feature = "export")]
#[named]
pub(super) unsafe extern "C" fn export(
    vkeydata: *mut c_void,
    selection: c_int,
    param_cb: OSSL_CALLBACK,
    cbarg: *mut c_void,
) -> c_int {
    // based on OpenSSL's providers/implementations/keymgmt/ml_dsa_keymgmt.c:ml_dsa_export()
    const ERROR_RET: c_int = 0;
    trace!(target: log_target!(), "{}", "Called!");

    let selection = selection as u32;
    let keydata: &KeyPair = handleResult!(vkeydata.try_into());

    if vkeydata.is_null() || ((selection & OSSL_KEYMGMT_SELECT_KEYPAIR) == 0) {
        return ERROR_RET;
    }

    let include_private = (selection & OSSL_KEYMGMT_SELECT_PRIVATE_KEY) != 0;
    debug!(target: log_target!(), "include_private is: {}", include_private);

    // In OpenSSL, they either 1) give the private key and/or the seed (if the private key was
    // requested, or 2) give only the public key (if the private key wasn't requested). Since the
    // former could require storing 1 or 2 elements in a params array, they allocate an array of 3
    // elements (for it and the END marker). We don't have a way to get the seed out of the pqcrypto
    // crate, unless I'm missing something, but for now I've kept the "put these in a list" design
    // anyway (instead of putting it in an Option), in case we find a way to get the seed out later.
    // (They need to be transformed into an END-terminated slice eventually anyway.)
    let mut params: Vec<CONST_OSSL_PARAM> = Vec::new();
    // I want to do something concise like this, but I haven't figured out the right incantations to
    // get around the "cannot move out of shared reference" stuff.
    /*
    let (key_part, param_name) = if include_private {
        (keydata.private.map(|k| k.encode()), OSSL_PKEY_PARAM_PRIV_KEY)
    } else {
        (keydata.public.map(|k| k.encode()), OSSL_PKEY_PARAM_PUB_KEY)
    };
    // (transform key_part from Option<Vec<u8>> to Option<&[i8]> before the next line)
    params.push(OSSLParam::new_const_octetstring(param_name, key_part));
    */
    if include_private {
        if let Some(private_key) = &keydata.private {
            debug!(target: log_target!(), "exporting private key");
            let bytes = private_key.encode();
            params.push(OSSLParam::new_const_octetstring(
                OSSL_PKEY_PARAM_PRIV_KEY,
                Some(
                    bytes
                        .iter()
                        .map(|&b| b as i8)
                        .collect::<Vec<i8>>()
                        .as_slice(),
                ),
            ));
        }
    } else {
        if let Some(public_key) = &keydata.public {
            debug!(target: log_target!(), "exporting public key");
            let bytes = public_key.encode();
            params.push(OSSLParam::new_const_octetstring(
                OSSL_PKEY_PARAM_PUB_KEY,
                Some(
                    bytes
                        .iter()
                        .map(|&b| b as i8)
                        .collect::<Vec<i8>>()
                        .as_slice(),
                ),
            ));
        }
    }

    // if we couldn't find the key part they wanted, there's nothing more to do
    if params.is_empty() {
        return ERROR_RET;
    }

    // but if we did find it, then we construct the params slice for the callback and call it!
    params.push(CONST_OSSL_PARAM::END);
    let params = params.into_boxed_slice();
    let cb = handleResult!(OSSLCallback::try_new(param_cb, cbarg));
    cb.call(params.as_ptr() as *const OSSL_PARAM)
}
#[cfg(not(feature = "export"))]
pub(super) use crate::adapters::common::keymgmt_functions::export_forbidden as export;

const HANDLED_KEY_TYPES: [OSSL_PARAM; 3] = [
    OSSL_PARAM {
        key: OSSL_PKEY_PARAM_PUB_KEY.as_ptr(),
        data_type: OSSL_PARAM_OCTET_STRING,
        data: std::ptr::null::<std::ffi::c_void>() as *mut std::ffi::c_void,
        data_size: 0,
        return_size: 0,
    },
    OSSL_PARAM {
        key: OSSL_PKEY_PARAM_PRIV_KEY.as_ptr(),
        data_type: OSSL_PARAM_OCTET_STRING,
        data: std::ptr::null::<std::ffi::c_void>() as *mut std::ffi::c_void,
        data_size: 0,
        return_size: 0,
    },
    OSSL_PARAM::END,
];

// I think using {import,export}_types_ex instead of the non-_ex variant means we only
// support OSSL 3.2 and up, but I also think that's fine...?
#[named]
pub(super) unsafe extern "C" fn import_types_ex(
    vprovctx: *mut c_void,
    selection: c_int,
) -> *const OSSL_PARAM {
    const ERROR_RET: *const OSSL_PARAM = std::ptr::null();
    trace!(target: log_target!(), "{}", "Called!");
    let _provctx: &ProviderInstance<'_> = handleResult!(vprovctx.try_into());
    let selection: Selection = handleResult!((selection as u32).try_into());

    if selection.intersects(Selection::KEYPAIR) {
        return HANDLED_KEY_TYPES.as_ptr();
    }
    ERROR_RET
}

#[cfg(feature = "export")]
#[named]
pub(super) unsafe extern "C" fn export_types_ex(
    vprovctx: *mut c_void,
    _selection: c_int,
) -> *const OSSL_PARAM {
    const ERROR_RET: *const OSSL_PARAM = std::ptr::null();
    trace!(target: log_target!(), "{}", "Called!");
    let _provctx: &ProviderInstance<'_> = match vprovctx.try_into() {
        Ok(p) => p,
        Err(e) => {
            error!(target: log_target!(), "{}", e);
            return ERROR_RET;
        }
    };
    todo!("return a constant array of descriptor OSSL_PARAM(3) for data indicated by selection, that the OSSL_FUNC_keymgmt_export() callback can expect to receive")
}
#[cfg(not(feature = "export"))]
pub(super) use crate::adapters::common::keymgmt_functions::export_types_ex_forbidden as export_types_ex;

#[named]
pub(super) unsafe extern "C" fn gen_set_params(
    _vgenctx: *mut c_void,
    _params: *const OSSL_PARAM,
) -> c_int {
    trace!(target: log_target!(), "{}", "Called!");

    #[cfg(not(debug_assertions))] // code compiled only in release builds
    {
        todo!("set genctx params");
    }

    #[cfg(debug_assertions)] // code compiled only in development builds
    {
        warn!(target: log_target!(), "{}", "Ignoring params!");
        return 1;
    }
}

#[named]
pub(super) unsafe extern "C" fn gen_settable_params(
    _vgenctx: *mut c_void,
    vprovctx: *mut c_void,
) -> *const OSSL_PARAM {
    const ERROR_RET: *const OSSL_PARAM = std::ptr::null();
    trace!(target: log_target!(), "{}", "Called!");
    let _provctx: &ProviderInstance<'_> = match vprovctx.try_into() {
        Ok(p) => p,
        Err(e) => {
            error!(target: log_target!(), "{}", e);
            return ERROR_RET;
        }
    };

    #[cfg(not(debug_assertions))] // code compiled only in release builds
    {
        todo!("return pointer to array of settable genctx params")
    }

    #[cfg(debug_assertions)] // code compiled only in development builds
    {
        warn!(target: log_target!(), "{}", "TODO: return pointer to (non-empty) array of settable genctx params");

        crate::osslparams::EMPTY_PARAMS.as_ptr()
    }
}

#[named]
pub(super) unsafe extern "C" fn get_params(
    vkeydata: *mut c_void,
    params: *mut OSSL_PARAM,
) -> c_int {
    const ERROR_RET: c_int = 0;
    const SUCCESS: c_int = 1;

    trace!(target: log_target!(), "{}", "Called!");
    let _keydata: &KeyPair = handleResult!(vkeydata.try_into());

    let params = match OSSLParam::try_from(params) {
        Ok(params) => params,
        Err(e) => {
            error!(target: log_target!(), "Failed decoding params: {:?}", e);
            return ERROR_RET;
        }
    };

    for mut p in params {
        let key = match p.get_key() {
            Some(key) => key,
            None => {
                error!(target: log_target!(), "Param without valid key {:?}", p);
                return ERROR_RET;
            }
        };

        if key == OSSL_PKEY_PARAM_BITS {
            //const BITS: c_int = 8 * (PUBKEY_LEN as c_int);
            //let _ = handleResult!(p.set(BITS));
            let _ = handleResult!(p.set(super::SECURITY_BITS as c_int));
        } else if key == OSSL_PKEY_PARAM_MAX_SIZE {
            let _ = handleResult!(p.set(SIGNATURE_LEN as c_int));
        } else if key == OSSL_PKEY_PARAM_SECURITY_BITS {
            let _ = handleResult!(p.set(super::SECURITY_BITS as c_int));
        } else if key == OSSL_PKEY_PARAM_MANDATORY_DIGEST {
            let _ = handleResult!(p.set(c""));
        } else {
            debug!(target: log_target!(), "Ignoring param {:?}", key);
        }
    }
    return SUCCESS;
}

#[named]
pub(super) unsafe extern "C" fn gettable_params(vprovctx: *mut c_void) -> *const OSSL_PARAM {
    trace!(target: log_target!(), "{}", "Called!");
    const ERROR_RET: *const OSSL_PARAM = std::ptr::null();
    let _provctx: &ProviderInstance<'_> = match vprovctx.try_into() {
        Ok(p) => p,
        Err(e) => {
            error!(target: log_target!(), "{}", e);
            return ERROR_RET;
        }
    };

    static LIST: &[CONST_OSSL_PARAM] = &[
        OSSLParam::new_const_int::<c_int>(OSSL_PKEY_PARAM_BITS, None),
        OSSLParam::new_const_int::<c_int>(OSSL_PKEY_PARAM_MAX_SIZE, None),
        OSSLParam::new_const_int::<c_int>(OSSL_PKEY_PARAM_SECURITY_BITS, None),
        OSSLParam::new_const_utf8string(OSSL_PKEY_PARAM_MANDATORY_DIGEST, None),
        CONST_OSSL_PARAM::END,
    ];

    let first: &bindings::OSSL_PARAM = &LIST[0];
    let ptr: *const bindings::OSSL_PARAM = std::ptr::from_ref(first);

    return ptr;
}

#[named]
pub(super) unsafe extern "C" fn set_params(
    vkeydata: *mut c_void,
    params: *const OSSL_PARAM,
) -> c_int {
    const ERROR_RET: c_int = 0;
    const SUCCESS: c_int = 1;

    trace!(target: log_target!(), "{}", "Called!");
    let _keydata: &mut KeyPair = handleResult!(vkeydata.try_into());

    let params = match OSSLParam::try_from(params) {
        Ok(params) => params,
        Err(e) => {
            error!(target: log_target!(), "Failed decoding params: {:?}", e);
            return ERROR_RET;
        }
    };

    for p in params {
        let key = match p.get_key() {
            Some(key) => key,
            None => {
                error!(target: log_target!(), "Param without valid key {:?}", p);
                return ERROR_RET;
            }
        };

        if false && key == OSSL_PKEY_PARAM_SECURITY_BITS {
            unreachable!();
            //let bytes: &[u8] = match p.get() {
            //    Some(bytes) => bytes,
            //    None => handleResult!(Err(anyhow!("Invalid ENCODED_PUBLIC_KEY"))),
            //};
            //debug!(target: log_target!(), "The received encoded public key is (len: {}): {:X?}", bytes.len(), bytes);

            //keydata.public = Some(handleResult!(PublicKey::decode(bytes)));
        } else {
            debug!(target: log_target!(), "Ignoring param {:?}", key);
        }
    }
    return SUCCESS;
}

#[named]
pub(super) unsafe extern "C" fn settable_params(vprovctx: *mut c_void) -> *const OSSL_PARAM {
    const ERROR_RET: *const OSSL_PARAM = std::ptr::null();
    trace!(target: log_target!(), "{}", "Called!");
    let _provctx: &ProviderInstance<'_> = match vprovctx.try_into() {
        Ok(p) => p,
        Err(e) => {
            error!(target: log_target!(), "{}", e);
            return ERROR_RET;
        }
    };

    static LIST: &[CONST_OSSL_PARAM] = &[CONST_OSSL_PARAM::END];

    let first: &bindings::OSSL_PARAM = &LIST[0];
    let ptr: *const bindings::OSSL_PARAM = std::ptr::from_ref(first);

    return ptr;
}

#[named]
/// Implements key loading by object reference, also a constructor for a new Key object
///
/// Refer to [provider-keymgmt(7ossl)] and [provider-object(7ossl)].
///
/// # Notes
///
/// This function is tightly integrated with the
/// [`OSSL_FUNC_decoder_decode_fn`][provider-decoder(7ossl)]
/// exposed by [decoders registered][`super::decoder_functions`]
/// for [this algorithm][`super`]
/// by [this adapter][`super::super`].
///
/// Eventually this function is called by the callback passed to OSSL_FUNC_decoder_decode_fn
/// hence they must agree on how the reference is being passed around.
///
/// [provider-keymgmt(7ossl)]: https://docs.openssl.org/master/man7/provider-keymgmt/
/// [provider-object(7ossl)]: https://docs.openssl.org/master/man7/provider-object/
/// [provider-decoder(7ossl)]: https://docs.openssl.org/master/man7/provider-decoder/
pub(super) unsafe extern "C" fn load(reference: *const c_void, reference_sz: usize) -> *mut c_void {
    const ERROR_RET: *mut c_void = std::ptr::null_mut();
    trace!(target: log_target!(), "{}", "Called!");

    if reference_sz != std::mem::size_of::<KeyPair>() {
        error!(target: log_target!(), "reference_sz should equal size_of::<KeyPair>");
        return ERROR_RET;
    }

    if reference.is_null() {
        error!(target: log_target!(), "reference should not be NULL");
        unreachable!()
    }

    let keypair = handleResult!(<&KeyPair>::try_from(reference as *mut c_void));

    return std::ptr::from_ref(keypair).cast_mut() as *mut c_void;
}

// based on OpenSSL 3.5's crypto/ml_dsa/ml_dsa_key.c:ossl_ml_dsa_key_equal()
// (and we can't just call it "match", because that's a Rust keyword)
#[named]
pub(super) unsafe extern "C" fn match_(
    keydata1: *const c_void,
    keydata2: *const c_void,
    selection: c_int,
) -> c_int {
    const ERROR_RET: c_int = 0;
    trace!(target: log_target!(), "{}", "Called!");

    let keypair1 = handleResult!(<&KeyPair>::try_from(keydata1 as *mut c_void));
    let keypair2 = handleResult!(<&KeyPair>::try_from(keydata2 as *mut c_void));
    let mut key_checked = false;

    if (selection & OSSL_KEYMGMT_SELECT_KEYPAIR as c_int) != 0 {
        if (selection & OSSL_KEYMGMT_SELECT_PUBLIC_KEY as c_int) != 0 {
            if keypair1.public != keypair2.public {
                return ERROR_RET;
            }
            key_checked = true;
        }
        if !key_checked && (selection & OSSL_KEYMGMT_SELECT_PRIVATE_KEY as c_int) != 0 {
            if keypair1.private != keypair2.private {
                return ERROR_RET;
            }
            key_checked = true;
        }
        return key_checked as c_int;
    }

    return 1;
}

pub(super) mod asn_definitions {
    pub use crate::asn_definitions::x509_ml_dsa_2025 as defns;

    pub use defns::MLDSA44PrivateKey as PrivateKey;
    pub use defns::MLDSA44PublicKey as PublicKey;
}

#[cfg(test)]
mod tests {
    use super::*;

    struct TestCTX<'a> {
        provctx: ProviderInstance<'a>,
    }

    fn setup<'a>() -> Result<TestCTX<'a>, OurError> {
        use crate::tests::new_provctx_for_testing;

        crate::tests::common::setup()?;

        let provctx = new_provctx_for_testing();

        let testctx = TestCTX { provctx };

        Ok(testctx)
    }

    #[test]
    fn test_roundtrip_encode_decode() {
        let testctx = setup().expect("Failed to initialize test setup");

        let provctx = testctx.provctx;

        let keypair = KeyPair::generate_new(&provctx).expect("Failed to generate keypair");

        match (keypair.public, keypair.private) {
            (None, None) => panic!("No public or private key generated"),
            (None, Some(_)) => panic!("No public key generated"),
            (Some(_), None) => panic!("No private key generated"),
            (Some(pk), Some(sk)) => {
                let encoded_pk = pk.encode();
                let roundtripped_pk = PublicKey::decode(&encoded_pk).unwrap();
                // we can't use assert_eq! without having a Debug impl for both arguments
                assert!(pk == roundtripped_pk);

                let encoded_sk = sk.encode();
                let roundtripped_sk = PrivateKey::decode(&encoded_sk).unwrap();
                assert!(sk == roundtripped_sk);
            }
        }
    }

    #[test]
    fn const_sanity_assertions() {
        crate::tests::common::setup().expect("Failed to initialize test setup");

        // Compare against FIPS 204 Table 2
        assert_eq!(PUBKEY_LEN, 1312);
        assert_eq!(SECRETKEY_LEN, 2560);
        assert_eq!(SIGNATURE_LEN, 2420);

        // Compare against FIPS 204 Table 1 Row "λ - collision strength of c̃"
        assert_eq!(SECURITY_BITS, 128);
    }
}