1use anyhow::Context;
2
3use chrono::{
4 DateTime,
5 Utc,
6};
7
8use sequoia_openpgp as openpgp;
9use openpgp::Profile;
10use openpgp::crypto::{PublicKeyAlgorithm, mpi};
11use openpgp::packet::key::{Key4, Key6};
12use openpgp::packet::key::UnspecifiedRole;
13use openpgp::packet::key::PublicParts;
14use openpgp::packet::key;
15use openpgp::packet;
16use openpgp::types::HashAlgorithm;
17use openpgp::types::SymmetricAlgorithm;
18
19use cryptoki::object::Attribute;
20use cryptoki::object::AttributeType;
21use cryptoki::object::KeyType;
22use cryptoki::object::ObjectClass;
23use cryptoki::object::ParameterSetType;
24
25use crate::Result;
26use crate::keyid::Bundling;
27use crate::objects::Key;
28use crate::oids::oid_to_str;
29
30const TRACE: bool = false;
31
32fn decode_ec_point(value: &[u8], expected_len: u8)
45 -> Result<&[u8]>
46{
47 if value.len() == expected_len as usize {
48 Ok(value)
49 } else if value.len() == expected_len as usize + 2
50 && value[0] == 0x04
51 && value[1] == expected_len
52 {
53 Ok(&value[2..])
54 } else {
55 Err(anyhow::anyhow!("HSM returned an invalid ec parameter (got {} bytes, {})",
56 value.len(),
57 value
58 .iter()
59 .map(|k| format!("{:02X}", k))
60 .collect::<Vec<_>>()
61 .join("")))
62 }
63}
64
65impl Key {
66 pub fn to_openpgp_key(&self)
68 -> Result<packet::Key<PublicParts, UnspecifiedRole>>
69 {
70 tracer!(TRACE, "Key::to_openpgp_key");
71
72 let mut openpgp_key = self.openpgp_key.lock().unwrap();
73 if let Some(key) = openpgp_key.as_ref() {
74 return Ok(key.clone());
75 }
76
77 struct KeyInfo {
78 key_id: Option<Vec<u8>>,
79 object_class: Option<ObjectClass>,
80 key_type: Option<KeyType>,
81 key_value: Option<Vec<u8>>,
82 ec_params: Option<Vec<u8>>,
83 ec_point: Option<Vec<u8>>,
84 modulus: Option<Vec<u8>>,
85 exponent: Option<Vec<u8>>,
86 opaque_parameters: Option<ParameterSetType>,
87 }
88
89 fn get_key_info(key: &Key) -> Result<KeyInfo> {
90 let typs = &[
91 AttributeType::Id,
92 AttributeType::Class,
93 AttributeType::KeyType,
94 AttributeType::Value,
96 AttributeType::EcParams,
98 AttributeType::EcPoint,
99 AttributeType::PublicExponent,
101 AttributeType::Modulus,
102 AttributeType::ParameterSet,
104 ][..];
105
106 let (session, object) = key.open_ro_session()?;
107 let attributes = session.get_attributes(object.clone(), &typs)?;
108
109 let mut key_id = None;
110 let mut object_class = None;
111 let mut key_type = None;
112 let mut key_value = None;
113 let mut ec_params = None;
114 let mut ec_point = None;
115 let mut modulus = None;
116 let mut exponent = None;
117 let mut opaque_parameters = None;
118
119 for attr in attributes.into_iter() {
120 match attr {
121 Attribute::Id(value) => key_id = Some(value),
122 Attribute::Class(value) => object_class = Some(value),
123 Attribute::KeyType(value) => key_type = Some(value),
124 Attribute::Value(value) => key_value = Some(value),
125 Attribute::EcParams(value) => ec_params = Some(value),
126 Attribute::EcPoint(value) => ec_point = Some(value),
127 Attribute::PublicExponent(value) => exponent = Some(value),
128 Attribute::Modulus(value) => modulus = Some(value),
129 Attribute::ParameterSet(v) => opaque_parameters = Some(v),
130 _ => {
131 panic!("PKCS#11 driver returned unrequested attribute: {:?}",
132 attr);
133 }
134 }
135 }
136
137 match object_class {
138 None => {
139 return Err(anyhow::anyhow!(
140 "Token appears to be broken: key is missing object class \
141 attribute"));
142 }
143 Some(ObjectClass::PUBLIC_KEY) => (),
144 Some(cls) => {
145 return Err(anyhow::anyhow!(
146 "Unsupported object class: {:?}", cls));
147 }
148 }
149
150 Ok(KeyInfo {
151 key_id,
152 object_class,
153 key_type,
154 key_value,
155 ec_params,
156 ec_point,
157 exponent,
158 modulus,
159 opaque_parameters,
160 })
161 }
162
163 let key_info = get_key_info(self)?;
164 let composite_info = if let Some(key) = self.composite_key() {
165 Some(get_key_info(key)?)
166 } else {
167 None
168 };
169
170 macro_rules! value {
171 ($key:expr, $name:expr, $attr:expr) => {{
172 let attr: &Option<_> = &$attr;
173 if let Some(value) = attr {
174 Ok(value)
175 } else {
176 Err(anyhow::anyhow!(
177 "Can't export the {} key: the {} attribute is missing",
178 $key, $name))
179 }
180 }};
181 }
182
183 let key_id = if let Some(key_id) = key_info.key_id.as_ref() {
185 key_id
186 } else {
187 return Err(anyhow::anyhow!("Key is missing a key ID"));
188 };
189
190 let key_id = match String::from_utf8(key_id.to_vec()) {
191 Ok(key_id) => key_id,
192 Err(err) => {
193 return Err(err).context(format!(
194 "Key ID {:?} does not identify an OpenPGP key",
195 String::from_utf8_lossy(key_id)));
196 }
197 };
198
199 t!("key id: {}", key_id);
200
201 let invalid_key_id = |err: Option<anyhow::Error>| -> Result<_> {
202 if let Some(err) = err {
203 Err(err).context(format!(
204 "Key ID {:?} does not identify an OpenPGP key",
205 key_id))
206 } else {
207 Err(anyhow::anyhow!(
208 "Key ID {:?} does not identify an OpenPGP key",
209 key_id))
210 }
211 };
212
213 let id = if let Some(id) = key_id.strip_prefix("pgp:v") {
214 id
215 } else {
216 t!("Invalid key ID: Missing pgp:v prefix");
217 return invalid_key_id(Some(anyhow::anyhow!("Missing pgp:v prefix")));
218 };
219 let mut parts = id.split(':');
220
221 let Some(version) = parts.next() else {
223 return invalid_key_id(Some(anyhow::anyhow!("Missing version")));
224 };
225 t!("version component: {}", version);
226 let (profile, bundling) = match version {
227 "6" => (openpgp::Profile::RFC9580,
228 Bundling::Standalone),
229 "6t" => (openpgp::Profile::RFC9580,
230 Bundling::TraditionalHalf),
231 "6pq" => (openpgp::Profile::RFC9580,
232 Bundling::PostQuantumHalf),
233
234 "4" => (openpgp::Profile::RFC4880,
235 Bundling::Standalone),
236 "4t" => (openpgp::Profile::RFC4880,
237 Bundling::TraditionalHalf),
238 "4pq" => (openpgp::Profile::RFC4880,
239 Bundling::PostQuantumHalf),
240
241 v => {
242 t!("Invalid key ID: Unsupported version ({})", v);
243 return invalid_key_id(Some(
244 anyhow::anyhow!("Unsupported version ({})", v)));
245 }
246 };
247
248 let Some(algo_parts) = parts.next() else {
250 return invalid_key_id(Some(anyhow::anyhow!("Missing algorithm")));
251 };
252 t!("algo component: {}", algo_parts);
253 let mut algo_parts = algo_parts.split("-");
254 let Some(algo) = algo_parts.next() else {
255 return invalid_key_id(Some(anyhow::anyhow!("Empty algorithm")));
256 };
257 let algo = if let Ok(algo) = algo.parse::<crate::PublicKeyAlgorithm>() {
258 algo
259 } else {
260 t!("Invalid algorithm ({})", algo);
261 return invalid_key_id(Some(
262 anyhow::anyhow!("Invalid algorithm ({})", algo)));
263 };
264
265 let mut hash_algo = None;
268 let mut sym_algo = None;
269 if profile == openpgp::Profile::RFC4880 {
270 if let Some(part) = algo_parts.next() {
271 hash_algo = match part {
272 "sha256" => Some(HashAlgorithm::SHA256),
273 "sha384" => Some(HashAlgorithm::SHA384),
274 "sha512" => Some(HashAlgorithm::SHA512),
275 _ => None,
276 };
277 }
278
279 if let Some(part) = algo_parts.next() {
280 sym_algo = match part {
281 "aes128" => Some(SymmetricAlgorithm::AES128),
282 "aes192" => Some(SymmetricAlgorithm::AES192),
283 "aes256" => Some(SymmetricAlgorithm::AES256),
284 _ => None,
285 };
286 }
287 } else if let Some(part) = algo_parts.next() {
288 return invalid_key_id(Some(
289 anyhow::anyhow!("Unknown algorithm parameter ({})", part)));
290 }
291
292 let Some(time) = parts.next() else {
295 return invalid_key_id(Some(anyhow::anyhow!("Missing creation time")));
296 };
297 t!("creation time component: {}", time);
298 let l = "19700101T000000Z".len();
299 if time.len() < l {
300 t!("Invalid key ID: Invalid creation time: string is too short");
301 return invalid_key_id(Some(anyhow::anyhow!(
302 "Invalid creation time: string is too short")));
303 }
304 let creation_time: DateTime<Utc> = match DateTime::parse_from_str(
305 &time[..l], "%Y%m%dT%H%M%S%#z")
306 {
307 Ok(time) => time.into(),
308 Err(err) => {
309 t!("Invalid key ID: Invalid time: {}", err);
310 return invalid_key_id(Some(err.into()));
311 }
312 };
313 let creation_time: std::time::SystemTime = creation_time.into();
314
315 t!("Key ID => profile: {:?}, bundling: {:?}, algo: {:?}, creation time: {}, \
316 hash: {:?}, sym: {:?}",
317 profile, bundling, algo,
318 DateTime::<Utc>::from(creation_time.clone()).format("%Y%m%dT%H%M%SZ"),
319 hash_algo, sym_algo);
320
321 let ec_edwards_to_key = |key_info: &KeyInfo|
322 -> Result<key::Key<key::PublicParts, key::UnspecifiedRole>>
323 {
324 let ec_params = value!("ECC", "EC params", key_info.ec_params)?;
329
330 let key = match (algo.clone(), profile, &ec_params[..]) {
340 (crate::PublicKeyAlgorithm::Ed25519
341 | crate::PublicKeyAlgorithm::MLDSA65_Ed25519,
342 Profile::RFC9580,
343 crate::oids::Ed25519) => {
344 let ec_point = decode_ec_point(
345 value!("ECC", "EC point", key_info.ec_point)?,
346 32)?;
347
348 Key6::<key::PublicParts, key::UnspecifiedRole>
349 ::import_public_ed25519(&ec_point, creation_time)?
350 .into()
351 },
352
353 (crate::PublicKeyAlgorithm::Ed448
354 | crate::PublicKeyAlgorithm::MLDSA87_Ed448,
355 Profile::RFC9580,
356 crate::oids::Ed448) => {
357 let ec_point = decode_ec_point(
358 value!("ECC", "EC point", key_info.ec_point)?,
359 57)?;
360
361 Key6::<key::PublicParts, key::UnspecifiedRole>
362 ::import_public_ed448(&ec_point, creation_time)?
363 .into()
364 }
365
366 (crate::PublicKeyAlgorithm::EdDSA,
367 Profile::RFC4880,
368 crate::oids::Ed25519) => {
369 let ec_point = decode_ec_point(
370 value!("ECC", "EC point", key_info.ec_point)?,
371 32)?;
372
373 Key4::<key::PublicParts, key::UnspecifiedRole>
376 ::import_public_ed25519(&ec_point, creation_time)?
377 .into()
378 }
379
380 (crate::PublicKeyAlgorithm::Ed25519,
381 Profile::RFC4880,
382 crate::oids::Ed25519) => {
383 let ec_point = decode_ec_point(
384 value!("ECC", "EC point", key_info.ec_point)?,
385 32)?;
386
387 Key4::new(creation_time,
393 PublicKeyAlgorithm::Ed25519,
394 mpi::PublicKey::Ed25519 {
395 a: ec_point.try_into()?,
396 })?.into()
397 }
398
399 (crate::PublicKeyAlgorithm::Ed448,
400 Profile::RFC4880,
401 crate::oids::Ed448) => {
402 let ec_point = decode_ec_point(
403 value!("ECC", "EC point", key_info.ec_point)?,
404 57)?;
405
406 Key4::<key::PublicParts, key::UnspecifiedRole>
407 ::import_public_ed448(&ec_point, creation_time)?
408 .into()
409 }
410
411 _ => {
412 return Err(anyhow::anyhow!(
413 "unsupported key (algo: {}, profile: {:?}, curve: {})",
414 algo, profile, oid_to_str(&ec_params[..])));
415 }
416 };
417
418 Ok(key)
419 };
420
421 let ec_montgomery_to_key = |key_info: &KeyInfo|
422 -> Result<key::Key<key::PublicParts, key::UnspecifiedRole>>
423 {
424 let ec_params = value!("ECC", "EC params", key_info.ec_params)?;
429
430 let ec_point = value!("ECC", "EC point", key_info.ec_point)?;
436
437 let key = match (algo.clone(), profile, &ec_params[..]) {
447 (crate::PublicKeyAlgorithm::X25519
448 | crate::PublicKeyAlgorithm::MLKEM768_X25519,
449 Profile::RFC9580,
450 crate::oids::X25519) =>
451 Key6::<key::PublicParts, key::UnspecifiedRole>
452 ::import_public_x25519(&ec_point, creation_time)?
453 .into(),
454
455 (crate::PublicKeyAlgorithm::X448
456 | crate::PublicKeyAlgorithm::MLKEM1024_X448,
457 Profile::RFC9580,
458 crate::oids::X448) =>
459 Key6::<key::PublicParts, key::UnspecifiedRole>
460 ::import_public_x448(&ec_point, creation_time)?
461 .into(),
462
463 (crate::PublicKeyAlgorithm::Cv25519,
464 Profile::RFC4880,
465 crate::oids::X25519) => {
466 let hash_algo
475 = hash_algo.unwrap_or(HashAlgorithm::SHA256);
476 let sym_algo
477 = sym_algo.unwrap_or(SymmetricAlgorithm::AES128);
478
479 Key4::<key::PublicParts, key::UnspecifiedRole>
480 ::import_public_cv25519(&ec_point, hash_algo,
481 sym_algo, creation_time)?
482 .into()
483 }
484
485 (crate::PublicKeyAlgorithm::X25519
486 | crate::PublicKeyAlgorithm::MLKEM768_X25519,
487 Profile::RFC4880,
488 crate::oids::X25519) => {
489 Key4::<key::PublicParts, key::UnspecifiedRole>
490 ::import_public_x25519(&ec_point, creation_time)?
491 .into()
492 },
493
494 (crate::PublicKeyAlgorithm::X448
495 | crate::PublicKeyAlgorithm::MLKEM1024_X448,
496 Profile::RFC4880,
497 crate::oids::X448) =>
498 Key4::<key::PublicParts, key::UnspecifiedRole>
499 ::import_public_x448(&ec_point, creation_time)?
500 .into(),
501
502 _=> {
503 return Err(anyhow::anyhow!(
504 "unsupported key (algo: {}, profile: {:?}, curve: {})",
505 algo, profile, oid_to_str(&ec_params[..])));
506 }
507 };
508
509 Ok(key)
510 };
511
512 let key = match (key_info.key_type, composite_info.as_ref().map(|ki| ki.key_type)) {
513 (None, _) => {
514 return Err(anyhow::anyhow!(
515 "Token appears to be broken: key is missing key type \
516 attribute"));
517 }
518 (Some(_), Some(None)) => {
519 return Err(anyhow::anyhow!(
520 "Token appears to be broken: key is missing key type \
521 attribute"));
522 }
523
524 (Some(KeyType::EC_EDWARDS), None) => {
525 ec_edwards_to_key(&key_info)?
526 }
527
528 (Some(KeyType::EC_MONTGOMERY), None) => {
529 ec_montgomery_to_key(&key_info)?
530 },
531
532 (Some(KeyType::RSA), None) => {
533 let modulus = value!("RSA", "modulus", key_info.modulus)?;
534 let exponent = value!("RSA", "exponent", key_info.exponent)?;
535
536 match profile {
537 Profile::RFC9580 =>
538 Key6::<key::PublicParts, key::UnspecifiedRole>
539 ::import_public_rsa(&exponent, &modulus, creation_time)?
540 .into(),
541
542 Profile::RFC4880 =>
543 Key4::<key::PublicParts, key::UnspecifiedRole>
544 ::import_public_rsa(&exponent, &modulus, creation_time)?
545 .into(),
546
547 _ => return Err(anyhow::anyhow!("unsupported profile")),
548 }
549 },
550
551 (Some(KeyType::ML_DSA), Some(Some(KeyType::EC_EDWARDS)))
552 | (Some(KeyType::EC_EDWARDS), Some(Some(KeyType::ML_DSA))) =>
553 {
554 let (mldsa_info, eddsa_info)
555 = if key_info.key_type == Some(KeyType::ML_DSA)
556 {
557 (key_info, composite_info.unwrap())
558 } else {
559 (composite_info.unwrap(), key_info)
560 };
561
562 let eddsa = ec_edwards_to_key(&eddsa_info)?;
563
564 use cryptoki::object::MlDsaParameterSetType;
565 let mldsa = mldsa_info.key_value
566 .ok_or(anyhow::anyhow!("key value not returned by token"))?;
567 let ml_dsa_parameters: Option<MlDsaParameterSetType>
568 = mldsa_info.opaque_parameters.map(|p| p.into());
569
570 match ml_dsa_parameters {
571 Some(MlDsaParameterSetType::ML_DSA_65) => {
572 let eddsa = match eddsa.mpis() {
573 mpi::PublicKey::Ed25519 { a } =>
574 Box::new(a.clone()),
575 _ => return Err(anyhow::anyhow!(
576 "expected an Ed25519 key in \
577 composite construction")),
578 };
579
580 let mldsa = mldsa.try_into()
581 .map_err(|_| anyhow::anyhow!(
582 "ML-DSA key has wrong size"))?;
583
584 Key6::new(creation_time,
585 PublicKeyAlgorithm::MLDSA65_Ed25519,
586 mpi::PublicKey::MLDSA65_Ed25519 {
587 eddsa,
588 mldsa,
589 })?.into()
590 },
591
592 Some(MlDsaParameterSetType::ML_DSA_87) => {
593 let eddsa = match eddsa.mpis() {
594 mpi::PublicKey::Ed448 { a } =>
595 a.clone(),
596 _ => return Err(anyhow::anyhow!(
597 "expected an Ed448 key in \
598 composite construction")),
599 };
600
601 let mldsa = mldsa.try_into()
602 .map_err(|_| anyhow::anyhow!(
603 "ML-DSA key has wrong size"))?;
604
605 Key6::new(creation_time,
606 PublicKeyAlgorithm::MLDSA87_Ed448,
607 mpi::PublicKey::MLDSA87_Ed448 {
608 eddsa,
609 mldsa,
610 })?.into()
611 },
612
613 Some(p) => return Err(anyhow::anyhow!(
614 "ML-DSA parameters {:?} not supported by OpenPGP", p)),
615
616 None => return Err(anyhow::anyhow!(
617 "ML-DSA parameters not returned by token")),
618 }
619 },
620
621 (Some(KeyType::SLH_DSA), None) => {
622 use cryptoki::object::SlhDsaParameterSetType;
623 let slh_dsa = key_info.key_value
624 .ok_or(anyhow::anyhow!("key value not returned by token"))?;
625 let slh_dsa_parameters: Option<SlhDsaParameterSetType>
626 = key_info.opaque_parameters.map(|p| p.into());
627
628 match slh_dsa_parameters {
629 Some(SlhDsaParameterSetType::SHAKE_128S) => {
630 let slh_dsa = slh_dsa.try_into()
631 .map_err(|_| anyhow::anyhow!(
632 "SLH-DSA key has wrong size"))?;
633
634 Key6::new(creation_time,
635 PublicKeyAlgorithm::SLHDSA128s,
636 mpi::PublicKey::SLHDSA128s {
637 public: slh_dsa,
638 })?.into()
639 },
640
641 Some(SlhDsaParameterSetType::SHAKE_128F) => {
642 let slh_dsa = slh_dsa.try_into()
643 .map_err(|_| anyhow::anyhow!(
644 "SLH-DSA key has wrong size"))?;
645
646 Key6::new(creation_time,
647 PublicKeyAlgorithm::SLHDSA128f,
648 mpi::PublicKey::SLHDSA128f {
649 public: slh_dsa,
650 })?.into()
651 },
652
653 Some(SlhDsaParameterSetType::SHAKE_256S) => {
654 let slh_dsa = slh_dsa.try_into()
655 .map_err(|_| anyhow::anyhow!(
656 "SLH-DSA key has wrong size"))?;
657
658 Key6::new(creation_time,
659 PublicKeyAlgorithm::SLHDSA256s,
660 mpi::PublicKey::SLHDSA256s {
661 public: slh_dsa,
662 })?.into()
663 },
664
665 Some(p) => return Err(anyhow::anyhow!(
666 "SLH-DSA parameters {} not supported by OpenPGP", p)),
667
668 None => return Err(anyhow::anyhow!(
669 "SLH-DSA parameters not returned by token")),
670 }
671 },
672
673 (Some(KeyType::ML_KEM), Some(Some(KeyType::EC_MONTGOMERY)))
674 | (Some(KeyType::EC_MONTGOMERY), Some(Some(KeyType::ML_KEM))) =>
675 {
676 let (mlkem_info, ecdh_info)
677 = if key_info.key_type == Some(KeyType::ML_KEM)
678 {
679 (key_info, composite_info.unwrap())
680 } else {
681 (composite_info.unwrap(), key_info)
682 };
683
684 let ecdh = ec_montgomery_to_key(&ecdh_info)?;
685
686 use cryptoki::object::MlKemParameterSetType;
687 let mlkem = mlkem_info.key_value
688 .ok_or(anyhow::anyhow!("key value not returned by token"))?;
689 let mlkem_parameters: Option<MlKemParameterSetType>
690 = mlkem_info.opaque_parameters.map(|p| p.into());
691
692 match mlkem_parameters {
693 Some(MlKemParameterSetType::ML_KEM_768) => {
694 let ecdh = match ecdh.mpis() {
695 mpi::PublicKey::X25519 { u } =>
696 Box::new(u.clone()),
697 _ => return Err(anyhow::anyhow!(
698 "expected an X25519 key in \
699 composite construction, got {:?}", ecdh)),
700 };
701
702 let mlkem = mlkem.try_into()
703 .map_err(|_| anyhow::anyhow!(
704 "ML-KEM key has wrong size"))?;
705
706 match profile {
707 Profile::RFC9580 => {
708 Key6::new(creation_time,
709 PublicKeyAlgorithm::MLKEM768_X25519,
710 mpi::PublicKey::MLKEM768_X25519 {
711 ecdh,
712 mlkem,
713 })?.into()
714 }
715 Profile::RFC4880 => {
716 Key4::new(creation_time,
717 PublicKeyAlgorithm::MLKEM768_X25519,
718 mpi::PublicKey::MLKEM768_X25519 {
719 ecdh,
720 mlkem,
721 })?.into()
722 }
723 _ => return Err(anyhow::anyhow!(
724 "unsupported profile {:?}", profile)),
725 }
726 },
727
728 Some(MlKemParameterSetType::ML_KEM_1024) => {
729 let ecdh = match ecdh.mpis() {
730 mpi::PublicKey::X448 { u } =>
731 u.clone(),
732 _ => return Err(anyhow::anyhow!(
733 "expected an X448 key in \
734 composite construction")),
735 };
736
737 let mlkem = mlkem.try_into()
738 .map_err(|_| anyhow::anyhow!(
739 "ML-KEM key has wrong size"))?;
740
741 match profile {
742 Profile::RFC9580 => {
743 Key6::new(creation_time,
744 PublicKeyAlgorithm::MLKEM1024_X448,
745 mpi::PublicKey::MLKEM1024_X448 {
746 ecdh,
747 mlkem,
748 })?.into()
749 }
750 Profile::RFC4880 => {
751 Key4::new(creation_time,
752 PublicKeyAlgorithm::MLKEM1024_X448,
753 mpi::PublicKey::MLKEM1024_X448 {
754 ecdh,
755 mlkem,
756 })?.into()
757 }
758 _ => return Err(anyhow::anyhow!(
759 "unsupported profile {:?}", profile)),
760 }
761 },
762
763 Some(p) => return Err(anyhow::anyhow!(
764 "ML-KEM parameters {:?} not supported by OpenPGP", p)),
765
766 None => return Err(anyhow::anyhow!(
767 "ML-KEM parameters not returned by token")),
768 }
769 },
770
771 (Some(kt), Some(Some(other))) => {
772 return Err(anyhow::anyhow!(
773 "Can't export key: unsupported composite key: {}+{}",
774 kt, other));
775 }
776
777 (Some(kt), None) => {
778 return Err(anyhow::anyhow!(
779 "Can't export key: unsupported key type: {}", kt));
780 }
781 };
782
783 *openpgp_key = Some(key.clone());
784
785 Ok(key)
786 }
787
788 pub fn armor_headers(&self) -> Vec<(&'static str, String)> {
790 let mut headers = Vec::new();
791
792 if let Some(unique_id) = self.key_unique_id() {
794 if unique_id.iter().all(u8::is_ascii_alphanumeric) {
795 headers.push((
797 "UniqueID",
798 String::from_utf8_lossy(unique_id).to_string()));
799 } else {
800 headers.push((
805 "Cryptoki-UniqueID",
806 self.key_unique_id_hex().unwrap()));
807 }
808 }
809
810 if let Some(id) = self.key_id() {
812 headers.push((
813 "Cryptoki-ID",
814 String::from_utf8_lossy(id).to_string()));
815 }
816
817 if let Some(label) = self.key_label() {
819 headers.push((
820 "Cryptoki-Label",
821 String::from_utf8_lossy(label).to_string()));
822 }
823
824 if let Some(composite_key) = self.composite_key() {
825 if let Some(id) = composite_key.key_id() {
827 headers.push((
828 "Cryptoki-Constituent-ID",
829 String::from_utf8_lossy(id).to_string()));
830 }
831 }
832
833
834 headers
835 }
836}