1use 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
38impl Context {
40 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 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 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 Bundling::Standalone,
106 creation_time.into(),
107 key_label)
108 }
109
110 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 Bundling::Standalone,
129 creation_time.into(),
130 key_label)
131 }
132
133 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 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 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 Bundling::Standalone,
191 creation_time.into(),
192 key_label)
193 }
194
195 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 pub fn generate_mldsa65_ed25519<T>(&self,
231 session: &Session,
232 token: Token,
233 profile: Profile,
234 creation_time: T,
235 key_label: Option<&str>)
236 -> Result<Key>
237 where
238 T: Into<Option<SystemTime>>,
239 {
240 if profile != Profile::RFC9580 {
241 return Err(anyhow::anyhow!(
242 "ML-DSA is only usable with the RFC 9580 profile"));
243 }
244
245 let creation_time = creation_time.into();
246 let creation_time = creation_time.unwrap_or_else(SystemTime::now);
248
249 let mut pq = self.generate_key(
250 session, Cow::Borrowed(&token), PublicKeyAlgorithm::MLDSA65_Ed25519,
251 profile, Bundling::PostQuantumHalf,
252 Some(creation_time.clone()), key_label, None,
253 Mechanism::MlDsaKeyPairGen,
254 vec![
255 Attribute::Class(ObjectClass::PUBLIC_KEY),
256 Attribute::KeyType(KeyType::ML_DSA),
257 Attribute::ParameterSet(MlDsaParameterSetType::ML_DSA_65.into()),
258 Attribute::Verify(true),
259 ],
260 vec![
261 Attribute::Class(ObjectClass::PRIVATE_KEY),
262 Attribute::KeyType(KeyType::ML_DSA),
263 Attribute::ParameterSet(MlDsaParameterSetType::ML_DSA_65.into()),
264 Attribute::Sensitive(true),
265 Attribute::Sign(true),
266 ],
267 )?;
268
269 let key_label
270 = String::from_utf8(pq.key_label().expect("set label").to_vec())
271 .expect("set a UTF-8 label");
272
273 let ed25519 = match self.generate_ed25519_internal(
275 session,
276 token,
277 PublicKeyAlgorithm::MLDSA65_Ed25519,
278 profile,
279 Bundling::TraditionalHalf,
281 Some(creation_time),
282 Some(&key_label))
283 {
284 Ok(key) => key,
285 Err(err) => {
286 return Err(err);
288 }
289 };
290
291 pq.combine_with(ed25519);
292 Ok(pq)
293 }
294
295 pub fn generate_mldsa87_ed448<T>(&self,
301 session: &Session,
302 token: Token,
303 profile: Profile,
304 creation_time: T,
305 key_label: Option<&str>)
306 -> Result<Key>
307 where
308 T: Into<Option<SystemTime>>,
309 {
310 if profile != Profile::RFC9580 {
311 return Err(anyhow::anyhow!(
312 "ML-DSA is only usable with the RFC 9580 profile"));
313 }
314
315 let creation_time = creation_time.into();
316 let creation_time = creation_time.unwrap_or_else(SystemTime::now);
318
319 let mut pq = self.generate_key(
322 session, Cow::Borrowed(&token), PublicKeyAlgorithm::MLDSA87_Ed448,
323 profile, Bundling::PostQuantumHalf,
324 Some(creation_time.clone()), key_label, None,
325 Mechanism::MlDsaKeyPairGen,
326 vec![
327 Attribute::Class(ObjectClass::PUBLIC_KEY),
328 Attribute::KeyType(KeyType::ML_DSA),
329 Attribute::ParameterSet(MlDsaParameterSetType::ML_DSA_87.into()),
330 Attribute::Verify(true),
331 ],
332 vec![
333 Attribute::Class(ObjectClass::PRIVATE_KEY),
334 Attribute::KeyType(KeyType::ML_DSA),
335 Attribute::ParameterSet(MlDsaParameterSetType::ML_DSA_87.into()),
336 Attribute::Sensitive(true),
337 Attribute::Sign(true),
338 ],
339 )?;
340
341 let key_label
342 = String::from_utf8(pq.key_label().expect("set label").to_vec())
343 .expect("set a UTF-8 label");
344
345 let ed448 = match self.generate_ed448_internal(
347 session,
348 token,
349 PublicKeyAlgorithm::MLDSA87_Ed448,
350 profile,
351 Bundling::TraditionalHalf,
353 Some(creation_time),
354 Some(&key_label))
355 {
356 Ok(key) => key,
357 Err(err) => {
358 return Err(err);
360 }
361 };
362
363 pq.combine_with(ed448);
364 Ok(pq)
365 }
366
367 fn generate_slh_dsa_internal(&self,
369 session: &Session,
370 token: Token,
371 algo: PublicKeyAlgorithm,
372 profile: Profile,
373 params: SlhDsaParameterSetType,
374 creation_time: Option<SystemTime>,
375 key_label: Option<&str>)
376 -> Result<Key>
377 {
378 if profile != Profile::RFC9580 {
379 return Err(anyhow::anyhow!(
380 "SLH-DSA is only usable with the RFC 9580 profile"));
381 }
382
383 self.generate_key(
384 session, Cow::Owned(token), algo, profile, Bundling::Standalone,
385 creation_time, key_label, None,
386 Mechanism::SlhDsaKeyPairGen,
387 vec![
388 Attribute::Class(ObjectClass::PUBLIC_KEY),
389 Attribute::KeyType(KeyType::SLH_DSA),
390 Attribute::ParameterSet(params.into()),
391 Attribute::Verify(true),
392 ],
393 vec![
394 Attribute::Class(ObjectClass::PRIVATE_KEY),
395 Attribute::KeyType(KeyType::SLH_DSA),
396 Attribute::ParameterSet(params.into()),
397 Attribute::Sensitive(true),
398 Attribute::Sign(true),
399 ],
400 )
401 }
402
403 pub fn generate_slh_dsa_128s<T>(&self,
405 session: &Session,
406 token: Token,
407 profile: Profile,
408 creation_time: T,
409 key_label: Option<&str>)
410 -> Result<Key>
411 where
412 T: Into<Option<SystemTime>>,
413 {
414 self.generate_slh_dsa_internal(
415 session, token, PublicKeyAlgorithm::SLHDSA128s,
416 profile, SlhDsaParameterSetType::SHAKE_128S,
417 creation_time.into(), key_label)
418 }
419
420 pub fn generate_slh_dsa_128f<T>(&self,
422 session: &Session,
423 token: Token,
424 profile: Profile,
425 creation_time: T,
426 key_label: Option<&str>)
427 -> Result<Key>
428 where
429 T: Into<Option<SystemTime>>,
430 {
431 self.generate_slh_dsa_internal(
432 session, token, PublicKeyAlgorithm::SLHDSA128f,
433 profile, SlhDsaParameterSetType::SHAKE_128F,
434 creation_time.into(), key_label)
435 }
436
437 pub fn generate_slh_dsa_256s<T>(&self,
439 session: &Session,
440 token: Token,
441 profile: Profile,
442 creation_time: T,
443 key_label: Option<&str>)
444 -> Result<Key>
445 where
446 T: Into<Option<SystemTime>>,
447 {
448 self.generate_slh_dsa_internal(
449 session, token, PublicKeyAlgorithm::SLHDSA256s,
450 profile, SlhDsaParameterSetType::SHAKE_256S,
451 creation_time.into(), key_label)
452 }
453
454 pub fn generate_x25519<T>(&self,
465 session: &Session,
466 token: Token,
467 profile: Profile,
468 creation_time: T,
469 key_label: Option<&str>)
470 -> Result<Key>
471 where
472 T: Into<Option<SystemTime>>,
473 {
474 self.generate_x25519_internal(
475 session, token, PublicKeyAlgorithm::X25519,
476 profile, Bundling::Standalone,
477 creation_time.into(), None, None, key_label)
478 }
479
480 fn generate_x25519_internal(&self,
483 session: &Session,
484 token: Token,
485 algo: PublicKeyAlgorithm,
486 profile: Profile,
487 bundling: Bundling,
488 creation_time: Option<SystemTime>,
489 hash_algo: Option<HashAlgorithm>,
490 sym_algo: Option<SymmetricAlgorithm>,
491 key_label: Option<&str>)
492 -> Result<Key>
493 {
494 let base_key_id_extra = match algo {
495 PublicKeyAlgorithm::Cv25519 => {
496 assert_eq!(profile, Profile::RFC4880);
497 assert_eq!(bundling, Bundling::Standalone);
498
499 let hash_algo = match hash_algo {
500 Some(HashAlgorithm::SHA256) | None => "sha256",
501 Some(HashAlgorithm::SHA384) => "sha384",
502 Some(HashAlgorithm::SHA512) => "sha512",
503 Some(algo) => {
504 return Err(anyhow::anyhow!(
505 "{} cannot be used with a cv25519 key", algo));
506 }
507 };
508 let sym_algo = match sym_algo {
509 Some(SymmetricAlgorithm::AES128) | None => "aes128",
510 Some(SymmetricAlgorithm::AES192) => "aes192",
511 Some(SymmetricAlgorithm::AES256) => "aes256",
512 Some(algo) => {
513 return Err(anyhow::anyhow!(
514 "{} cannot be used with a cv25519 key", algo));
515 }
516 };
517
518 Some(format!("{}-{}", hash_algo, sym_algo))
519 }
520 PublicKeyAlgorithm::X25519 => {
521 assert_eq!(bundling, Bundling::Standalone);
522 assert!(hash_algo.is_none());
523 assert!(sym_algo.is_none());
524 None
525 }
526 PublicKeyAlgorithm::MLKEM768_X25519 => {
527 assert_eq!(bundling, Bundling::TraditionalHalf);
528 assert!(hash_algo.is_none());
529 assert!(sym_algo.is_none());
530 None
531 }
532 algo => {
533 panic!("Internal error: generate_x25519_internal called for {}",
534 algo);
535 }
536 };
537
538 self.generate_key(
539 session, Cow::Owned(token), algo, profile, bundling,
540 creation_time.into(), key_label, base_key_id_extra.as_deref(),
541 Mechanism::EccMontgomeryKeyPairGen,
542 vec![
543 Attribute::Class(ObjectClass::PUBLIC_KEY),
544 Attribute::KeyType(KeyType::EC_MONTGOMERY),
545 Attribute::EcParams(crate::oids::X25519.into()),
549 Attribute::Encrypt(true),
550 Attribute::Wrap(true),
551 ],
552 vec![
553 Attribute::Class(ObjectClass::PRIVATE_KEY),
554 Attribute::KeyType(KeyType::EC_MONTGOMERY),
555 Attribute::Sensitive(true),
556 Attribute::Decrypt(true),
557 Attribute::Unwrap(true),
558 Attribute::Derive(true),
559 ],
560 )
561 }
562
563 pub fn generate_mlkem768_x25519<T>(&self,
569 session: &Session,
570 token: Token,
571 profile: Profile,
572 creation_time: T,
573 key_label: Option<&str>)
574 -> Result<Key>
575 where
576 T: Into<Option<SystemTime>>,
577 {
578 let creation_time = creation_time.into();
579 let creation_time = creation_time.unwrap_or_else(SystemTime::now);
581
582 let mut pq = self.generate_key(
583 session, Cow::Borrowed(&token), PublicKeyAlgorithm::MLKEM768_X25519,
584 profile, Bundling::PostQuantumHalf,
585 Some(creation_time.clone()), key_label, None,
586 Mechanism::MlKemKeyPairGen,
587 vec![
588 Attribute::Class(ObjectClass::PUBLIC_KEY),
589 Attribute::KeyType(KeyType::ML_KEM),
590 Attribute::ParameterSet(MlKemParameterSetType::ML_KEM_768.into()),
591 Attribute::Encapsulate(true),
592 ],
593 vec![
594 Attribute::Class(ObjectClass::PRIVATE_KEY),
595 Attribute::KeyType(KeyType::ML_KEM),
596 Attribute::ParameterSet(MlKemParameterSetType::ML_KEM_768.into()),
597 Attribute::Sensitive(true),
598 Attribute::Decapsulate(true),
599 ],
600 ).context("Generating ML-KEM-768 key")?;
601
602 let key_label
603 = String::from_utf8(pq.key_label().expect("set label").to_vec())
604 .expect("set a UTF-8 label");
605
606 let x25519 = match self.generate_x25519_internal(
608 session,
609 token,
610 PublicKeyAlgorithm::MLKEM768_X25519,
611 profile,
612 Bundling::TraditionalHalf,
614 Some(creation_time),
615 None, None,
616 Some(&key_label))
617 {
618 Ok(key) => key,
619 Err(err) => {
620 return Err(err).context("Generating X25519 key");
622 }
623 };
624
625 pq.combine_with(x25519);
626 Ok(pq)
627 }
628
629 fn generate_x448_internal<T>(&self,
631 session: &Session,
632 token: Token,
633 algo: PublicKeyAlgorithm,
634 profile: Profile,
635 bundling: Bundling,
636 creation_time: T,
637 key_label: Option<&str>)
638 -> Result<Key>
639 where
640 T: Into<Option<SystemTime>>,
641 {
642 self.generate_key(
643 session, Cow::Owned(token), algo, profile, bundling,
644 creation_time.into(), key_label, None,
645 Mechanism::EccMontgomeryKeyPairGen,
646 vec![
647 Attribute::Class(ObjectClass::PUBLIC_KEY),
648 Attribute::KeyType(KeyType::EC_MONTGOMERY),
649 Attribute::EcParams(crate::oids::X448.into()),
653 Attribute::Encrypt(true),
654 Attribute::Wrap(true),
655 ],
656 vec![
657 Attribute::Class(ObjectClass::PRIVATE_KEY),
658 Attribute::KeyType(KeyType::EC_MONTGOMERY),
659 Attribute::Sensitive(true),
660 Attribute::Decrypt(true),
661 Attribute::Unwrap(true),
662 Attribute::Derive(true),
663 ],
664 )
665 }
666
667 pub fn generate_x448<T>(&self,
669 session: &Session,
670 token: Token,
671 profile: Profile,
672 creation_time: T,
673 key_label: Option<&str>)
674 -> Result<Key>
675 where
676 T: Into<Option<SystemTime>>,
677 {
678 self.generate_x448_internal(
679 session, token, PublicKeyAlgorithm::X448,
680 profile, Bundling::Standalone,
681 creation_time, key_label)
682 }
683
684 pub fn generate_mlkem1024_x448<T>(&self,
690 session: &Session,
691 token: Token,
692 profile: Profile,
693 creation_time: T,
694 key_label: Option<&str>)
695 -> Result<Key>
696 where
697 T: Into<Option<SystemTime>>,
698 {
699 let creation_time = creation_time.into();
700 let creation_time = creation_time.unwrap_or_else(SystemTime::now);
702
703 let mut pq = self.generate_key(
704 session, Cow::Borrowed(&token), PublicKeyAlgorithm::MLKEM1024_X448,
705 profile, Bundling::PostQuantumHalf,
706 Some(creation_time.clone()), key_label, None,
707 Mechanism::MlKemKeyPairGen,
708 vec![
709 Attribute::Class(ObjectClass::PUBLIC_KEY),
710 Attribute::KeyType(KeyType::ML_KEM),
711 Attribute::ParameterSet(MlKemParameterSetType::ML_KEM_1024.into()),
712 Attribute::Encapsulate(true),
713 ],
714 vec![
715 Attribute::Class(ObjectClass::PRIVATE_KEY),
716 Attribute::KeyType(KeyType::ML_KEM),
717 Attribute::ParameterSet(MlKemParameterSetType::ML_KEM_1024.into()),
718 Attribute::Sensitive(true),
719 Attribute::Decapsulate(true),
720 ],
721 ).context("Generating ML-KEM-1024 key")?;
722
723 let key_label
724 = String::from_utf8(pq.key_label().expect("set label").to_vec())
725 .expect("set a UTF-8 label");
726
727 let x448 = match self.generate_x448_internal(
729 session,
730 token,
731 PublicKeyAlgorithm::MLKEM1024_X448,
732 profile,
733 Bundling::TraditionalHalf,
735 Some(creation_time),
736 Some(&key_label))
737 {
738 Ok(key) => key,
739 Err(err) => {
740 return Err(err).context("Generating X448 key");
742 }
743 };
744
745 pq.combine_with(x448);
746 Ok(pq)
747 }
748
749 pub fn generate_rsa_for_signing<T>(&self,
751 session: &Session,
752 token: Token,
753 profile: Profile,
754 bits: usize,
755 creation_time: T,
756 key_label: Option<&str>)
757 -> Result<Key>
758 where
759 T: Into<Option<SystemTime>>,
760 {
761 self.generate_key(
762 session, Cow::Owned(token),
763 PublicKeyAlgorithm::RSA,
764 profile, Bundling::Standalone,
765 creation_time.into(), key_label, None,
766 Mechanism::RsaPkcsKeyPairGen,
767 vec![
768 Attribute::Class(ObjectClass::PUBLIC_KEY),
769 Attribute::KeyType(KeyType::RSA),
770 Attribute::ModulusBits(bits.try_into()?),
771 Attribute::Verify(true),
772 ],
773 vec![
774 Attribute::Class(ObjectClass::PRIVATE_KEY),
775 Attribute::KeyType(KeyType::RSA),
776 Attribute::Sensitive(true),
777 Attribute::Sign(true),
778 ],
779 )
780 }
781
782 pub fn generate_rsa_for_encryption<T>(&self,
784 session: &Session,
785 token: Token,
786 profile: Profile,
787 bits: usize,
788 creation_time: T,
789 key_label: Option<&str>)
790 -> Result<Key>
791 where
792 T: Into<Option<SystemTime>>,
793 {
794 self.generate_key(
795 session, Cow::Owned(token),
796 PublicKeyAlgorithm::RSA,
797 profile, Bundling::Standalone,
798 creation_time.into(), key_label, None,
799 Mechanism::RsaPkcsKeyPairGen,
800 vec![
801 Attribute::Class(ObjectClass::PUBLIC_KEY),
802 Attribute::KeyType(KeyType::RSA),
803 Attribute::ModulusBits(bits.try_into()?),
804 Attribute::Encrypt(true),
805 ],
806 vec![
807 Attribute::Class(ObjectClass::PRIVATE_KEY),
808 Attribute::KeyType(KeyType::RSA),
809 Attribute::Sensitive(true),
810 Attribute::Decrypt(true),
811 ],
812 )
813 }
814
815 fn generate_key(&self,
817 session: &Session,
818 token: Cow<Token>,
819 algo: PublicKeyAlgorithm,
820 profile: Profile,
821 bundling: Bundling,
822 creation_time: Option<SystemTime>,
823 key_label: Option<&str>,
824 key_id_extra: Option<&str>,
825 mechanism: Mechanism,
826 mut public_key_parameters: Vec<Attribute>,
827 mut private_key_parameters: Vec<Attribute>)
828 -> Result<Key>
829 {
830 let (key_id, key_label) = self.generate_key_id(
831 algo, profile, bundling, creation_time, key_id_extra, key_label)
832 .context("Constructing key ID")?;
833
834 let common_attributes = [
835 Attribute::Id(key_id.clone().into()),
837 Attribute::Token(true),
839 Attribute::Label(key_label.as_bytes().to_vec()),
840 ];
841
842 public_key_parameters.extend(common_attributes.iter().cloned());
843 private_key_parameters.extend(common_attributes.into_iter());
844
845 let (public, _secret) = session.generate_key_pair(
847 &mechanism, &public_key_parameters, &private_key_parameters)
848 .context("Generating key pair")?;
849
850 Key::from_object(token.into_owned(), session, public)
851 }
852}