Skip to main content

sequoia_cryptoki/
generate_key.rs

1//! Key generation.
2
3use std::{
4    borrow::Cow,
5    time::SystemTime,
6};
7
8use anyhow::Context as _;
9
10use cryptoki::{
11    mechanism::Mechanism,
12    object::{
13        Attribute,
14        KeyType,
15        MlDsaParameterSetType,
16        MlKemParameterSetType,
17        ObjectClass,
18        SlhDsaParameterSetType,
19    },
20    session::Session,
21};
22
23use sequoia_openpgp::{
24    Profile,
25    types::HashAlgorithm,
26    types::SymmetricAlgorithm,
27};
28
29use crate::{
30    Context,
31    Key,
32    PublicKeyAlgorithm,
33    Result,
34    Token,
35    keyid::Bundling,
36};
37
38/// Key generation.
39impl Context {
40    /// Generates a new Ed25519 key.
41    ///
42    /// `bundling` indicates whether the key is a standalone key or
43    /// half of a composite key.
44    fn generate_ed25519_internal(&self,
45                                 session: &Session,
46                                 token: Token,
47                                 algo: PublicKeyAlgorithm,
48                                 profile: Profile,
49                                 bundling: Bundling,
50                                 creation_time: Option<SystemTime>,
51                                 key_label: Option<&str>)
52        -> Result<Key>
53    {
54        assert!(bundling == Bundling::TraditionalHalf
55                || bundling == Bundling::Standalone);
56
57        self.generate_key(
58            session, Cow::Owned(token), algo, profile, bundling,
59            creation_time, key_label, None,
60            Mechanism::EccEdwardsKeyPairGen,
61            vec![
62                Attribute::Class(ObjectClass::PUBLIC_KEY),
63                Attribute::KeyType(KeyType::EC_EDWARDS),
64                // DER encoding of the OID and some other parameters.
65                // See PKCS#11, v3.2, draft 13, Section 6.3.5, Edwards
66                // Elliptic Curve public key objects
67                Attribute::EcParams(crate::oids::Ed25519.into()),
68                Attribute::Verify(true),
69            ],
70            vec![
71                Attribute::Class(ObjectClass::PRIVATE_KEY),
72                Attribute::KeyType(KeyType::EC_EDWARDS),
73                Attribute::Sensitive(true),
74                Attribute::Sign(true),
75            ],
76        )
77    }
78
79    /// Generates a new EdDSA key.
80    ///
81    /// [EdDSA keys] are based on elliptical curve cryptography, and
82    /// can be used for signing.  They are only defined for version
83    /// 4 keys.
84    ///
85    /// [EdDSA keys]: https://www.rfc-editor.org/rfc/rfc9580.html#name-ecc-curves
86    /// [RFC 9580, section 11.5.1. ECDH Parameters]: https://www.rfc-editor.org/rfc/rfc9580.html#ecdh
87    ///
88    /// To generate a version 6 key, use `Context::generate_ed25519`.
89    pub fn generate_eddsa<T>(&self,
90                             session: &Session,
91                             token: Token,
92                             creation_time: T,
93                             key_label: Option<&str>)
94        -> Result<Key>
95    where
96        T: Into<Option<SystemTime>>,
97    {
98        self.generate_ed25519_internal(
99            session,
100            token,
101            PublicKeyAlgorithm::EdDSA,
102            Profile::RFC4880,
103            // This is a standalone key, and not a (post quantum)
104            // composite key.
105            Bundling::Standalone,
106            creation_time.into(),
107            key_label)
108    }
109
110    /// Generates a new Ed25519 key.
111    pub fn generate_ed25519<T>(&self,
112                               session: &Session,
113                               token: Token,
114                               profile: Profile,
115                               creation_time: T,
116                               key_label: Option<&str>)
117                               -> Result<Key>
118    where
119        T: Into<Option<SystemTime>>,
120    {
121        self.generate_ed25519_internal(
122            session,
123            token,
124            PublicKeyAlgorithm::Ed25519,
125            profile,
126            // This is a standalone key, and not a (post
127            // quantum) composite key.
128            Bundling::Standalone,
129            creation_time.into(),
130            key_label)
131    }
132
133    /// Generates a new Ed448 key.
134    ///
135    /// `bundling` indicates whether the key is a standalone key or
136    /// half of a composite key.
137    fn generate_ed448_internal(&self,
138                               session: &Session,
139                               token: Token,
140                               algo: PublicKeyAlgorithm,
141                               profile: Profile,
142                               bundling: Bundling,
143                               creation_time: Option<SystemTime>,
144                               key_label: Option<&str>)
145                               -> Result<Key>
146    {
147        assert!(bundling == Bundling::TraditionalHalf
148                || bundling == Bundling::Standalone);
149
150        self.generate_key(
151            session, Cow::Owned(token), algo, profile, bundling,
152            creation_time, key_label, None,
153            Mechanism::EccEdwardsKeyPairGen,
154            vec![
155                Attribute::Class(ObjectClass::PUBLIC_KEY),
156                Attribute::KeyType(KeyType::EC_EDWARDS),
157                // DER encoding of the OID and some other parameters.
158                // See PKCS#11, v3.2, draft 13, Section 6.3.5, Edwards
159                // Elliptic Curve public key objects
160                Attribute::EcParams(crate::oids::Ed448.into()),
161                Attribute::Verify(true),
162            ],
163            vec![
164                Attribute::Class(ObjectClass::PRIVATE_KEY),
165                Attribute::KeyType(KeyType::EC_EDWARDS),
166                Attribute::Sensitive(true),
167                Attribute::Sign(true),
168            ],
169        )
170    }
171
172    /// Generates a new Ed448 key.
173    pub fn generate_ed448<T>(&self,
174                             session: &Session,
175                             token: Token,
176                             profile: Profile,
177                             creation_time: T,
178                             key_label: Option<&str>)
179                             -> Result<Key>
180    where
181        T: Into<Option<SystemTime>>,
182    {
183        self.generate_ed448_internal(
184            session,
185            token,
186            PublicKeyAlgorithm::Ed448,
187            profile,
188            // This is a standalone key, and not a (post
189            // quantum) composite key.
190            Bundling::Standalone,
191            creation_time.into(),
192            key_label)
193    }
194
195    /// Generates a new cv25519 key.
196    ///
197    /// [cv25519 keys] are based on elliptical curve cryptography, and
198    /// can be used for encryption.  They are only defined for version
199    /// 4 keys, and they take two parameters: a hash function, and a
200    /// symmetric algorithm.  If either parameter is `None`, we use
201    /// the recommended values as per [RFC 9580, section 11.5.1. ECDH
202    /// Parameters].
203    ///
204    /// [cv25519 keys]: https://www.rfc-editor.org/rfc/rfc9580.html#name-ecc-curves
205    /// [RFC 9580, section 11.5.1. ECDH Parameters]: https://www.rfc-editor.org/rfc/rfc9580.html#ecdh
206    ///
207    /// To generate a version 6 key, use `Context::generate_x25519`.
208    pub fn generate_legacy_cv25519<T>(&self,
209                                      session: &Session,
210                                      token: Token,
211                                      creation_time: T,
212                                      hash_algo: Option<HashAlgorithm>,
213                                      sym_algo: Option<SymmetricAlgorithm>,
214                                      key_label: Option<&str>)
215        -> Result<Key>
216    where
217        T: Into<Option<SystemTime>>,
218    {
219        self.generate_x25519_internal(
220            session, token, PublicKeyAlgorithm::Cv25519,
221            Profile::RFC4880, Bundling::Standalone,
222            creation_time.into(), hash_algo, sym_algo, key_label)
223    }
224
225    /// Generates a new MLDSA65+Ed25519 key.
226    ///
227    /// This generates two PKCS#11 keys: an MLDSA65 key and an Ed25519
228    /// key.  The two keys are linked via their key ID.  Hence, either
229    /// can be specified and the other will be found automatically.
230    ///
231    /// The traditional component is generated on `session`/`token`,
232    /// and the post-quantum component is generated on the
233    /// `pqc_session_token`.  If `pqc_session_token` is `None`, then
234    /// the post quantum component is generated on the same token as
235    /// the traditional component.
236    ///
237    /// The traditional component is returned as the [`Key`]'s primary
238    /// component.  The post quantum component is returned as its
239    /// composite component.
240    pub fn generate_mldsa65_ed25519<T>(&self,
241                                       session: &Session, token: Token,
242                                       pqc_session_token: Option<(&Session, Token)>,
243                                       profile: Profile,
244                                       creation_time: T,
245                                       key_label: Option<&str>)
246                                       -> Result<Key>
247    where
248        T: Into<Option<SystemTime>>,
249    {
250        if profile != Profile::RFC9580 {
251            return Err(anyhow::anyhow!(
252                "ML-DSA is only usable with the RFC 9580 profile"));
253        }
254
255        let creation_time = creation_time.into();
256        // Resolve now to ensure the keys have the same creation time.
257        let creation_time = creation_time.unwrap_or_else(SystemTime::now);
258
259        let session_token = (session, token);
260
261        let (session, token) = if let Some(pqc_session_token) = pqc_session_token.as_ref() {
262            pqc_session_token
263        } else {
264            &session_token
265        };
266
267        let pq = self.generate_key(
268            session, Cow::Borrowed(token),
269            PublicKeyAlgorithm::MLDSA65_Ed25519,
270            profile, Bundling::PostQuantumHalf,
271            Some(creation_time.clone()), key_label, None,
272            Mechanism::MlDsaKeyPairGen,
273            vec![
274                Attribute::Class(ObjectClass::PUBLIC_KEY),
275                Attribute::KeyType(KeyType::ML_DSA),
276                Attribute::ParameterSet(MlDsaParameterSetType::ML_DSA_65.into()),
277                Attribute::Verify(true),
278            ],
279            vec![
280                Attribute::Class(ObjectClass::PRIVATE_KEY),
281                Attribute::KeyType(KeyType::ML_DSA),
282                Attribute::ParameterSet(MlDsaParameterSetType::ML_DSA_65.into()),
283                Attribute::Sensitive(true),
284                Attribute::Sign(true),
285            ],
286        )?;
287
288        let key_label
289            = String::from_utf8(pq.key_label().expect("set label").to_vec())
290            .expect("set a UTF-8 label");
291
292        let (session, token) = session_token;
293
294        // Now create the traditional half.
295        let mut ed25519 = match self.generate_ed25519_internal(
296            session,
297            token,
298            PublicKeyAlgorithm::MLDSA65_Ed25519,
299            profile,
300            // This is a composite key, and not a standalone key.
301            Bundling::TraditionalHalf,
302            Some(creation_time),
303            Some(&key_label))
304        {
305            Ok(key) => key,
306            Err(err) => {
307                // XXX: Destroy the PQ key.
308                return Err(err);
309            }
310        };
311
312        ed25519.combine_with(pq);
313        Ok(ed25519)
314    }
315
316    /// Generates a new MLDSA87+Ed448 key.
317    ///
318    /// This generates two PKCS#11 keys: an MLDSA87 key and an ED448
319    /// key.  The two keys are linked via their key ID.  Hence, either
320    /// can be specified and the other will be found automatically.
321    ///
322    /// The traditional component is generated on `session`/`token`,
323    /// and the post-quantum component is generated on the
324    /// `pqc_session_token`.  If `pqc_session_token` is `None`, then
325    /// the post quantum component is generated on the same token as
326    /// the traditional component.
327    ///
328    /// The traditional component is returned as the [`Key`]'s primary
329    /// component.  The post quantum component is returned as its
330    /// composite component.
331    pub fn generate_mldsa87_ed448<T>(&self,
332                                     session: &Session, token: Token,
333                                     pqc_session_token: Option<(&Session, Token)>,
334                                     profile: Profile,
335                                     creation_time: T,
336                                     key_label: Option<&str>)
337                                     -> Result<Key>
338    where
339        T: Into<Option<SystemTime>>,
340    {
341        if profile != Profile::RFC9580 {
342            return Err(anyhow::anyhow!(
343                "ML-DSA is only usable with the RFC 9580 profile"));
344        }
345
346        let creation_time = creation_time.into();
347        // Resolve now to ensure the keys have the same creation time.
348        let creation_time = creation_time.unwrap_or_else(SystemTime::now);
349
350        let session_token = (session, token);
351
352        // Create the PQ half first.  The token is more likely to not
353        // support PQ algorithms.
354        let (session, token) = if let Some(pqc_session_token) = pqc_session_token.as_ref() {
355            pqc_session_token
356        } else {
357            &session_token
358        };
359
360        let pq = self.generate_key(
361            session, Cow::Borrowed(&token), PublicKeyAlgorithm::MLDSA87_Ed448,
362            profile, Bundling::PostQuantumHalf,
363            Some(creation_time.clone()), key_label, None,
364            Mechanism::MlDsaKeyPairGen,
365            vec![
366                Attribute::Class(ObjectClass::PUBLIC_KEY),
367                Attribute::KeyType(KeyType::ML_DSA),
368                Attribute::ParameterSet(MlDsaParameterSetType::ML_DSA_87.into()),
369                Attribute::Verify(true),
370            ],
371            vec![
372                Attribute::Class(ObjectClass::PRIVATE_KEY),
373                Attribute::KeyType(KeyType::ML_DSA),
374                Attribute::ParameterSet(MlDsaParameterSetType::ML_DSA_87.into()),
375                Attribute::Sensitive(true),
376                Attribute::Sign(true),
377            ],
378        )?;
379
380        let key_label
381            = String::from_utf8(pq.key_label().expect("set label").to_vec())
382            .expect("set a UTF-8 label");
383
384        // Now create the traditional half.
385        let (session, token) = session_token;
386
387        let mut ed448 = match self.generate_ed448_internal(
388            session,
389            token,
390            PublicKeyAlgorithm::MLDSA87_Ed448,
391            profile,
392            // This is a composite key, and not a standalone key.
393            Bundling::TraditionalHalf,
394            Some(creation_time),
395            Some(&key_label))
396        {
397            Ok(key) => key,
398            Err(err) => {
399                // XXX: Destroy the PQ key.
400                return Err(err);
401            }
402        };
403
404        ed448.combine_with(pq);
405        Ok(ed448)
406    }
407
408    /// Generates a new SLH-DSA key.
409    fn generate_slh_dsa_internal(&self,
410                                 session: &Session,
411                                 token: Token,
412                                 algo: PublicKeyAlgorithm,
413                                 profile: Profile,
414                                 params: SlhDsaParameterSetType,
415                                 creation_time: Option<SystemTime>,
416                                 key_label: Option<&str>)
417        -> Result<Key>
418    {
419        if profile != Profile::RFC9580 {
420            return Err(anyhow::anyhow!(
421                "SLH-DSA is only usable with the RFC 9580 profile"));
422        }
423
424        self.generate_key(
425            session, Cow::Owned(token), algo, profile, Bundling::Standalone,
426            creation_time, key_label, None,
427            Mechanism::SlhDsaKeyPairGen,
428            vec![
429                Attribute::Class(ObjectClass::PUBLIC_KEY),
430                Attribute::KeyType(KeyType::SLH_DSA),
431                Attribute::ParameterSet(params.into()),
432                Attribute::Verify(true),
433            ],
434            vec![
435                Attribute::Class(ObjectClass::PRIVATE_KEY),
436                Attribute::KeyType(KeyType::SLH_DSA),
437                Attribute::ParameterSet(params.into()),
438                Attribute::Sensitive(true),
439                Attribute::Sign(true),
440            ],
441        )
442    }
443
444    /// Generates a new SLH-DSA-128s key.
445    pub fn generate_slh_dsa_128s<T>(&self,
446                                    session: &Session,
447                                    token: Token,
448                                    profile: Profile,
449                                    creation_time: T,
450                                    key_label: Option<&str>)
451        -> Result<Key>
452    where
453        T: Into<Option<SystemTime>>,
454    {
455        self.generate_slh_dsa_internal(
456            session, token, PublicKeyAlgorithm::SLHDSA128s,
457            profile, SlhDsaParameterSetType::SHAKE_128S,
458            creation_time.into(), key_label)
459    }
460
461    /// Generates a new SLH-DSA-128f key.
462    pub fn generate_slh_dsa_128f<T>(&self,
463                                    session: &Session,
464                                    token: Token,
465                                    profile: Profile,
466                                    creation_time: T,
467                                    key_label: Option<&str>)
468        -> Result<Key>
469    where
470        T: Into<Option<SystemTime>>,
471    {
472        self.generate_slh_dsa_internal(
473            session, token, PublicKeyAlgorithm::SLHDSA128f,
474            profile, SlhDsaParameterSetType::SHAKE_128F,
475            creation_time.into(), key_label)
476    }
477
478    /// Generates a new SLH-DSA-256s key.
479    pub fn generate_slh_dsa_256s<T>(&self,
480                                    session: &Session,
481                                    token: Token,
482                                    profile: Profile,
483                                    creation_time: T,
484                                    key_label: Option<&str>)
485        -> Result<Key>
486    where
487        T: Into<Option<SystemTime>>,
488    {
489        self.generate_slh_dsa_internal(
490            session, token, PublicKeyAlgorithm::SLHDSA256s,
491            profile, SlhDsaParameterSetType::SHAKE_256S,
492            creation_time.into(), key_label)
493    }
494
495    /// Generates a new X25519 key.
496    ///
497    /// [x25519 keys] are based on elliptical curve cryptography, and
498    /// can be used for encryption.
499    ///
500    /// If `profile` is `RFC4880`, then a version 4 key is created
501    /// using the default parameters.  See
502    /// [`Context::generate_legacy_cv25519`] for more information
503    /// about version 4 keys.  Note: version 6 keys don't have any
504    /// free parameters.
505    pub fn generate_x25519<T>(&self,
506                              session: &Session,
507                              token: Token,
508                              profile: Profile,
509                              creation_time: T,
510                              key_label: Option<&str>)
511                              -> Result<Key>
512    where
513        T: Into<Option<SystemTime>>,
514    {
515        self.generate_x25519_internal(
516            session, token, PublicKeyAlgorithm::X25519,
517            profile, Bundling::Standalone,
518            creation_time.into(), None, None, key_label)
519    }
520
521    /// hash_algo and sym_algo are only relevant if `profile` is
522    /// `RFC4880` and `bundling` is `Standalone`.
523    fn generate_x25519_internal(&self,
524                                session: &Session,
525                                token: Token,
526                                algo: PublicKeyAlgorithm,
527                                profile: Profile,
528                                bundling: Bundling,
529                                creation_time: Option<SystemTime>,
530                                hash_algo: Option<HashAlgorithm>,
531                                sym_algo: Option<SymmetricAlgorithm>,
532                                key_label: Option<&str>)
533        -> Result<Key>
534    {
535	let base_key_id_extra = match algo {
536	    PublicKeyAlgorithm::Cv25519 => {
537		assert_eq!(profile, Profile::RFC4880);
538		assert_eq!(bundling, Bundling::Standalone);
539
540		let hash_algo = match hash_algo {
541                    Some(HashAlgorithm::SHA256) | None => "sha256",
542                    Some(HashAlgorithm::SHA384) => "sha384",
543                    Some(HashAlgorithm::SHA512) => "sha512",
544                    Some(algo) => {
545			return Err(anyhow::anyhow!(
546                            "{} cannot be used with a cv25519 key", algo));
547                    }
548		};
549		let sym_algo = match sym_algo {
550                    Some(SymmetricAlgorithm::AES128) | None => "aes128",
551                    Some(SymmetricAlgorithm::AES192) => "aes192",
552                    Some(SymmetricAlgorithm::AES256) => "aes256",
553                    Some(algo) => {
554			return Err(anyhow::anyhow!(
555                            "{} cannot be used with a cv25519 key", algo));
556                    }
557		};
558
559		Some(format!("{}-{}", hash_algo, sym_algo))
560	    }
561	    PublicKeyAlgorithm::X25519 => {
562		assert_eq!(bundling, Bundling::Standalone);
563		assert!(hash_algo.is_none());
564		assert!(sym_algo.is_none());
565		None
566	    }
567	    PublicKeyAlgorithm::MLKEM768_X25519 => {
568		assert_eq!(bundling, Bundling::TraditionalHalf);
569		assert!(hash_algo.is_none());
570		assert!(sym_algo.is_none());
571		None
572	    }
573	    algo => {
574		panic!("Internal error: generate_x25519_internal called for {}",
575		       algo);
576	    }
577	};
578
579        self.generate_key(
580            session, Cow::Owned(token), algo, profile, bundling,
581            creation_time.into(), key_label, base_key_id_extra.as_deref(),
582            Mechanism::EccMontgomeryKeyPairGen,
583            vec![
584                Attribute::Class(ObjectClass::PUBLIC_KEY),
585                Attribute::KeyType(KeyType::EC_MONTGOMERY),
586                // DER encoding of the OID and some other parameters.
587                // See PKCS#11, v3.2, draft 13, Section 6.3.5, Edwards
588                // Elliptic Curve public key objects
589                Attribute::EcParams(crate::oids::X25519.into()),
590                Attribute::Encrypt(true),
591                Attribute::Wrap(true),
592            ],
593            vec![
594                Attribute::Class(ObjectClass::PRIVATE_KEY),
595                Attribute::KeyType(KeyType::EC_MONTGOMERY),
596                Attribute::Sensitive(true),
597                Attribute::Decrypt(true),
598                Attribute::Unwrap(true),
599                Attribute::Derive(true),
600            ],
601        )
602    }
603
604    /// Generates a new MLKEM768+X25519 key.
605    ///
606    /// This generates two PKCS#11 keys: an MLKEM768 key and a X25519
607    /// key.  The two keys are linked via their key ID.  Hence, either
608    /// can be specified and the other will be found automatically.
609    ///
610    /// The traditional component is generated on `session`/`token`,
611    /// and the post-quantum component is generated on the
612    /// `pqc_session_token`.  If `pqc_session_token` is `None`, then
613    /// the post quantum component is generated on the same token as
614    /// the traditional component.
615    ///
616    /// The traditional component is returned as the [`Key`]'s primary
617    /// component.  The post quantum component is returned as its
618    /// composite component.
619    pub fn generate_mlkem768_x25519<T>(&self,
620                                       session: &Session, token: Token,
621                                       pqc_session_token: Option<(&Session, Token)>,
622                                       profile: Profile,
623                                       creation_time: T,
624                                       key_label: Option<&str>)
625                                       -> Result<Key>
626    where
627        T: Into<Option<SystemTime>>,
628    {
629        let creation_time = creation_time.into();
630        // Resolve now to ensure the keys have the same creation time.
631        let creation_time = creation_time.unwrap_or_else(SystemTime::now);
632
633        let session_token = (session, token);
634
635        // Create the PQ half first.  The token is more likely to not
636        // support PQ algorithms.
637        let (session, token) = if let Some(pqc_session_token) = pqc_session_token.as_ref() {
638            pqc_session_token
639        } else {
640            &session_token
641        };
642
643        let pq = self.generate_key(
644            session, Cow::Borrowed(&token), PublicKeyAlgorithm::MLKEM768_X25519,
645            profile, Bundling::PostQuantumHalf,
646            Some(creation_time.clone()), key_label, None,
647            Mechanism::MlKemKeyPairGen,
648            vec![
649                Attribute::Class(ObjectClass::PUBLIC_KEY),
650                Attribute::KeyType(KeyType::ML_KEM),
651                Attribute::ParameterSet(MlKemParameterSetType::ML_KEM_768.into()),
652                Attribute::Encapsulate(true),
653            ],
654            vec![
655                Attribute::Class(ObjectClass::PRIVATE_KEY),
656                Attribute::KeyType(KeyType::ML_KEM),
657                Attribute::ParameterSet(MlKemParameterSetType::ML_KEM_768.into()),
658                Attribute::Sensitive(true),
659                Attribute::Decapsulate(true),
660            ],
661        ).context("Generating ML-KEM-768 key")?;
662
663        let key_label
664            = String::from_utf8(pq.key_label().expect("set label").to_vec())
665            .expect("set a UTF-8 label");
666
667        // Now create the traditional half.
668        let (session, token) = session_token;
669
670        let mut x25519 = match self.generate_x25519_internal(
671            session,
672            token,
673            PublicKeyAlgorithm::MLKEM768_X25519,
674            profile,
675            // This is a composite key, and not a standalone key.
676            Bundling::TraditionalHalf,
677            Some(creation_time),
678            None, None,
679            Some(&key_label))
680        {
681            Ok(key) => key,
682            Err(err) => {
683                // XXX: Destroy the PQ key.
684                return Err(err).context("Generating X25519 key");
685            }
686        };
687
688        x25519.combine_with(pq);
689        Ok(x25519)
690    }
691
692    /// Generates a new X448 key.
693    fn generate_x448_internal<T>(&self,
694                                 session: &Session,
695                                 token: Token,
696                                 algo: PublicKeyAlgorithm,
697                                 profile: Profile,
698                                 bundling: Bundling,
699                                 creation_time: T,
700                                 key_label: Option<&str>)
701        -> Result<Key>
702    where
703        T: Into<Option<SystemTime>>,
704    {
705        self.generate_key(
706            session, Cow::Owned(token), algo, profile, bundling,
707            creation_time.into(), key_label, None,
708            Mechanism::EccMontgomeryKeyPairGen,
709            vec![
710                Attribute::Class(ObjectClass::PUBLIC_KEY),
711                Attribute::KeyType(KeyType::EC_MONTGOMERY),
712                // DER encoding of the OID and some other parameters.
713                // See PKCS#11, v3.2, draft 13, Section 6.3.5, Edwards
714                // Elliptic Curve public key objects
715                Attribute::EcParams(crate::oids::X448.into()),
716                Attribute::Encrypt(true),
717                Attribute::Wrap(true),
718            ],
719            vec![
720                Attribute::Class(ObjectClass::PRIVATE_KEY),
721                Attribute::KeyType(KeyType::EC_MONTGOMERY),
722                Attribute::Sensitive(true),
723                Attribute::Decrypt(true),
724                Attribute::Unwrap(true),
725                Attribute::Derive(true),
726            ],
727        )
728    }
729
730    /// Generates a new X448 key.
731    pub fn generate_x448<T>(&self,
732                            session: &Session,
733                            token: Token,
734                            profile: Profile,
735                            creation_time: T,
736                            key_label: Option<&str>)
737                            -> Result<Key>
738    where
739        T: Into<Option<SystemTime>>,
740    {
741        self.generate_x448_internal(
742            session, token, PublicKeyAlgorithm::X448,
743            profile, Bundling::Standalone,
744            creation_time, key_label)
745    }
746
747    /// Generates a new MLKEM1024+X448 key.
748    ///
749    /// This generates two PKCS#11 keys: an MLKEM1024 key and a X448
750    /// key.  The two keys are linked via their key ID.  Hence, either
751    /// can be specified and the other will be found automatically.
752    ///
753    /// The traditional component is generated on `session`/`token`,
754    /// and the post-quantum component is generated on the
755    /// `pqc_session_token`.  If `pqc_session_token` is `None`, then
756    /// the post quantum component is generated on the same token as
757    /// the traditional component.
758    ///
759    /// The traditional component is returned as the [`Key`]'s primary
760    /// component.  The post quantum component is returned as its
761    /// composite component.
762    pub fn generate_mlkem1024_x448<T>(&self,
763                                      session: &Session, token: Token,
764                                      pqc_session_token: Option<(&Session, Token)>,
765                                      profile: Profile,
766                                      creation_time: T,
767                                      key_label: Option<&str>)
768        -> Result<Key>
769    where
770        T: Into<Option<SystemTime>>,
771    {
772        let creation_time = creation_time.into();
773        // Resolve now to ensure the keys have the same creation time.
774        let creation_time = creation_time.unwrap_or_else(SystemTime::now);
775
776        let session_token = (session, token);
777
778        // Create the PQ half first.  The token is more likely to not
779        // support PQ algorithms.
780        let (session, token) = if let Some(pqc_session_token) = pqc_session_token.as_ref() {
781            pqc_session_token
782        } else {
783            &session_token
784        };
785
786        let pq = self.generate_key(
787            session, Cow::Borrowed(&token), PublicKeyAlgorithm::MLKEM1024_X448,
788            profile, Bundling::PostQuantumHalf,
789            Some(creation_time.clone()), key_label, None,
790            Mechanism::MlKemKeyPairGen,
791            vec![
792                Attribute::Class(ObjectClass::PUBLIC_KEY),
793                Attribute::KeyType(KeyType::ML_KEM),
794                Attribute::ParameterSet(MlKemParameterSetType::ML_KEM_1024.into()),
795                Attribute::Encapsulate(true),
796            ],
797            vec![
798                Attribute::Class(ObjectClass::PRIVATE_KEY),
799                Attribute::KeyType(KeyType::ML_KEM),
800                Attribute::ParameterSet(MlKemParameterSetType::ML_KEM_1024.into()),
801                Attribute::Sensitive(true),
802                Attribute::Decapsulate(true),
803            ],
804        ).context("Generating ML-KEM-1024 key")?;
805
806        let key_label
807            = String::from_utf8(pq.key_label().expect("set label").to_vec())
808            .expect("set a UTF-8 label");
809
810        // Now create the traditional half.
811        let (session, token) = session_token;
812
813        let mut x448 = match self.generate_x448_internal(
814            session,
815            token,
816            PublicKeyAlgorithm::MLKEM1024_X448,
817            profile,
818            // This is a composite key, and not a standalone key.
819            Bundling::TraditionalHalf,
820            Some(creation_time),
821            Some(&key_label))
822        {
823            Ok(key) => key,
824            Err(err) => {
825                // XXX: Destroy the PQ key.
826                return Err(err).context("Generating X448 key");
827            }
828        };
829
830        x448.combine_with(pq);
831        Ok(x448)
832    }
833
834    /// Generates a new signing-capable RSA key.
835    pub fn generate_rsa_for_signing<T>(&self,
836                                       session: &Session,
837                                       token: Token,
838                                       profile: Profile,
839                                       bits: usize,
840                                       creation_time: T,
841                                       key_label: Option<&str>)
842        -> Result<Key>
843    where
844        T: Into<Option<SystemTime>>,
845    {
846        self.generate_key(
847            session, Cow::Owned(token),
848            PublicKeyAlgorithm::RSA,
849            profile, Bundling::Standalone,
850            creation_time.into(), key_label, None,
851            Mechanism::RsaPkcsKeyPairGen,
852            vec![
853                Attribute::Class(ObjectClass::PUBLIC_KEY),
854                Attribute::KeyType(KeyType::RSA),
855                Attribute::ModulusBits(bits.try_into()?),
856                Attribute::Verify(true),
857            ],
858            vec![
859                Attribute::Class(ObjectClass::PRIVATE_KEY),
860                Attribute::KeyType(KeyType::RSA),
861                Attribute::Sensitive(true),
862                Attribute::Sign(true),
863            ],
864        )
865    }
866
867    /// Generates a new encryption-capable RSA key.
868    pub fn generate_rsa_for_encryption<T>(&self,
869                                          session: &Session,
870                                          token: Token,
871                                          profile: Profile,
872                                          bits: usize,
873                                          creation_time: T,
874                                          key_label: Option<&str>)
875        -> Result<Key>
876    where
877        T: Into<Option<SystemTime>>,
878    {
879        self.generate_key(
880            session, Cow::Owned(token),
881            PublicKeyAlgorithm::RSA,
882            profile, Bundling::Standalone,
883            creation_time.into(), key_label, None,
884            Mechanism::RsaPkcsKeyPairGen,
885            vec![
886                Attribute::Class(ObjectClass::PUBLIC_KEY),
887                Attribute::KeyType(KeyType::RSA),
888                Attribute::ModulusBits(bits.try_into()?),
889                Attribute::Encrypt(true),
890            ],
891            vec![
892                Attribute::Class(ObjectClass::PRIVATE_KEY),
893                Attribute::KeyType(KeyType::RSA),
894                Attribute::Sensitive(true),
895                Attribute::Decrypt(true),
896            ],
897        )
898    }
899
900    /// Generates a key with the given parameters.
901    fn generate_key(&self,
902                    session: &Session,
903                    token: Cow<Token>,
904                    algo: PublicKeyAlgorithm,
905                    profile: Profile,
906                    bundling: Bundling,
907                    creation_time: Option<SystemTime>,
908                    key_label: Option<&str>,
909                    key_id_extra: Option<&str>,
910                    mechanism: Mechanism,
911                    mut public_key_parameters: Vec<Attribute>,
912                    mut private_key_parameters: Vec<Attribute>)
913                    -> Result<Key>
914    {
915        let (key_id, key_label) = self.generate_key_id(
916            algo, profile, bundling, creation_time, key_id_extra, key_label)
917            .context("Constructing key ID")?;
918
919        let common_attributes = [
920            // The common ID.
921            Attribute::Id(key_id.clone().into()),
922            // Persist the object on the token.
923            Attribute::Token(true),
924            Attribute::Label(key_label.as_bytes().to_vec()),
925        ];
926
927        public_key_parameters.extend(common_attributes.iter().cloned());
928        private_key_parameters.extend(common_attributes.into_iter());
929
930        // Generate the key pair.
931        let (public, _secret) = session.generate_key_pair(
932            &mechanism, &public_key_parameters, &private_key_parameters)
933            .context("Generating key pair")?;
934
935        Key::from_object(token.into_owned(), session, public)
936    }
937}