in_toto/
crypto.rs

1//! Cryptographic structures and functions.
2
3use data_encoding::HEXLOWER;
4use derp::{self, Der, Tag};
5use ring::digest::{self, SHA256, SHA512};
6use ring::rand::SystemRandom;
7use ring::signature::{
8    EcdsaKeyPair, Ed25519KeyPair, KeyPair, RsaKeyPair, ECDSA_P256_SHA256_ASN1,
9    ECDSA_P256_SHA256_ASN1_SIGNING, ED25519, RSA_PSS_2048_8192_SHA256,
10    RSA_PSS_2048_8192_SHA512, RSA_PSS_SHA256, RSA_PSS_SHA512,
11};
12use serde::de::{Deserializer, Error as DeserializeError};
13use serde::ser::{Error as SerializeError, Serializer};
14use serde::{Deserialize, Serialize};
15use std::cmp::Ordering;
16use std::collections::HashMap;
17use std::fmt::{self, Debug, Display};
18use std::hash;
19use std::io::{Read, Write};
20use std::process::{Command, Stdio};
21use std::str::FromStr;
22use std::sync::Arc;
23use untrusted::Input;
24
25use crate::error::Error;
26use crate::interchange::cjson::shims;
27use crate::Result;
28
29const HASH_ALG_PREFS: &[HashAlgorithm] =
30    &[HashAlgorithm::Sha512, HashAlgorithm::Sha256];
31
32/// 1.2.840.113549.1.1.1 rsaEncryption(PKCS #1)
33const RSA_SPKI_OID: &[u8] =
34    &[0x2a, 0x86, 0x48, 0x86, 0xf7, 0x0d, 0x01, 0x01, 0x01];
35
36/// 1.3.101.112 curveEd25519(EdDSA 25519 signature algorithm)
37const ED25519_SPKI_OID: &[u8] = &[0x2b, 0x65, 0x70];
38
39/// 1.2.840.10045.2.1 ecPublicKey (Elliptic Curve public key cryptography)
40const ECC_SPKI_OID: &[u8] = &[0x2a, 0x86, 0x48, 0xce, 0x3d, 0x02, 0x01];
41
42/// The length of an ed25519 private key in bytes
43const ED25519_PRIVATE_KEY_LENGTH: usize = 32;
44
45/// The length of an ed25519 public key in bytes
46const ED25519_PUBLIC_KEY_LENGTH: usize = 32;
47
48/// The length of an ed25519 keypair in bytes
49const ED25519_KEYPAIR_LENGTH: usize =
50    ED25519_PRIVATE_KEY_LENGTH + ED25519_PUBLIC_KEY_LENGTH;
51
52/// Pem header of a rsa private key
53const PEM_PUBLIC_KEY: &str = "PUBLIC KEY";
54
55fn python_sslib_compatibility_keyid_hash_algorithms() -> Option<Vec<String>> {
56    Some(vec!["sha256".to_string(), "sha512".to_string()])
57}
58
59/// Given a map of hash algorithms and their values, get the prefered algorithm and the hash
60/// calculated by it. Returns an `Err` if there is no match.
61///
62/// ```
63/// use std::collections::HashMap;
64/// use in_toto::crypto::{hash_preference, HashValue, HashAlgorithm};
65///
66/// let mut map = HashMap::new();
67/// assert!(hash_preference(&map).is_err());
68///
69/// let _ = map.insert(HashAlgorithm::Sha512, HashValue::new(vec![0x00, 0x01]));
70/// assert_eq!(hash_preference(&map).unwrap().0, &HashAlgorithm::Sha512);
71///
72/// let _ = map.insert(HashAlgorithm::Sha256, HashValue::new(vec![0x02, 0x03]));
73/// assert_eq!(hash_preference(&map).unwrap().0, &HashAlgorithm::Sha512);
74/// ```
75pub fn hash_preference(
76    hashes: &HashMap<HashAlgorithm, HashValue>,
77) -> Result<(&'static HashAlgorithm, &HashValue)> {
78    for alg in HASH_ALG_PREFS {
79        match hashes.get(alg) {
80            Some(v) => return Ok((alg, v)),
81            None => continue,
82        }
83    }
84    Err(Error::NoSupportedHashAlgorithm)
85}
86
87/// Calculate the size and hash digest from a given `Read`.
88pub fn calculate_hashes<R: Read>(
89    mut read: R,
90    hash_algs: &[HashAlgorithm],
91) -> Result<(u64, HashMap<HashAlgorithm, HashValue>)> {
92    if hash_algs.is_empty() {
93        return Err(Error::IllegalArgument(
94            "Cannot provide empty set of hash algorithms".into(),
95        ));
96    }
97
98    let mut size = 0;
99    let mut hashes = HashMap::new();
100    for alg in hash_algs {
101        let _ = hashes.insert(alg, alg.digest_context()?);
102    }
103
104    let mut buf = vec![0; 1024];
105    loop {
106        match read.read(&mut buf) {
107            Ok(read_bytes) => {
108                if read_bytes == 0 {
109                    break;
110                }
111
112                size += read_bytes as u64;
113
114                for context in hashes.values_mut() {
115                    context.update(&buf[0..read_bytes]);
116                }
117            }
118            e @ Err(_) => e.map(|_| ())?,
119        }
120    }
121
122    let hashes = hashes
123        .drain()
124        .map(|(k, v)| (k.clone(), HashValue::new(v.finish().as_ref().to_vec())))
125        .collect();
126    Ok((size, hashes))
127}
128
129fn shim_public_key(
130    key_type: &KeyType,
131    signature_scheme: &SignatureScheme,
132    keyid_hash_algorithms: &Option<Vec<String>>,
133    public_key: &[u8],
134    private_key: bool,
135    keyid: Option<&str>,
136) -> Result<shims::PublicKey> {
137    let key = match key_type {
138        KeyType::Ed25519 => HEXLOWER.encode(public_key),
139        KeyType::Rsa => {
140            let contents = write_spki(public_key, key_type)?;
141            let public_pem =
142                pem::Pem::new(PEM_PUBLIC_KEY.to_string(), contents);
143            pem::encode(&public_pem)
144                .replace("\r\n", "\n")
145                .trim()
146                .to_string()
147        }
148        KeyType::Ecdsa => HEXLOWER.encode(public_key),
149        KeyType::Unknown(inner) => {
150            return Err(Error::UnknownKeyType(format!("content: {}", inner)))
151        }
152    };
153
154    let private_key = private_key.then_some("");
155
156    Ok(shims::PublicKey::new(
157        key_type.clone(),
158        signature_scheme.clone(),
159        keyid_hash_algorithms.clone(),
160        key,
161        keyid,
162        private_key,
163    ))
164}
165
166/// Calculate unique key_id. This function will convert the der bytes
167/// of the public key into PKIX-encoded pem bytes to keep consistent
168/// with the python and golang version.
169fn calculate_key_id(
170    key_type: &KeyType,
171    signature_scheme: &SignatureScheme,
172    keyid_hash_algorithms: &Option<Vec<String>>,
173    public_key: &[u8],
174) -> Result<KeyId> {
175    use crate::interchange::{DataInterchange, Json};
176
177    let public_key = shim_public_key(
178        key_type,
179        signature_scheme,
180        keyid_hash_algorithms,
181        public_key,
182        false,
183        None,
184    )?;
185    let public_key = Json::canonicalize(&Json::serialize(&public_key)?)?;
186    let public_key = String::from_utf8(public_key)
187        .map_err(|e| {
188            Error::Encoding(format!(
189                "public key from bytes to string failed: {}",
190                e,
191            ))
192        })?
193        .replace("\\n", "\n");
194    let mut context = digest::Context::new(&SHA256);
195    context.update(public_key.as_bytes());
196
197    let key_id = HEXLOWER.encode(context.finish().as_ref());
198
199    Ok(KeyId(key_id))
200}
201
202/// Wrapper type for public key's ID.
203///
204/// # Calculating
205/// A `KeyId` is calculated as the hex digest of the SHA-256 hash of the canonical form of the
206/// public key, or `hexdigest(sha256(cjson(public_key)))`.
207#[derive(Clone, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)]
208pub struct KeyId(String);
209
210impl KeyId {
211    /// Return the first 8 hex digits of the key id
212    pub fn prefix(&self) -> String {
213        assert!(self.0.len() >= 8);
214        self.0[0..8].to_string()
215    }
216}
217
218impl FromStr for KeyId {
219    type Err = Error;
220
221    /// Parse a key ID from a string.
222    fn from_str(string: &str) -> Result<Self> {
223        if string.len() != 64 {
224            return Err(Error::IllegalArgument(
225                "key ID must be 64 characters long".into(),
226            ));
227        }
228        Ok(KeyId(string.to_owned()))
229    }
230}
231
232impl Serialize for KeyId {
233    fn serialize<S>(&self, ser: S) -> ::std::result::Result<S::Ok, S::Error>
234    where
235        S: Serializer,
236    {
237        self.0.serialize(ser)
238    }
239}
240
241impl<'de> Deserialize<'de> for KeyId {
242    fn deserialize<D: Deserializer<'de>>(
243        de: D,
244    ) -> ::std::result::Result<Self, D::Error> {
245        let string: String = Deserialize::deserialize(de)?;
246        KeyId::from_str(&string)
247            .map_err(|e| DeserializeError::custom(format!("{:?}", e)))
248    }
249}
250
251/// Cryptographic signature schemes.
252#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
253pub enum SignatureScheme {
254    /// [Ed25519](https://ed25519.cr.yp.to/)
255    #[serde(rename = "ed25519")]
256    Ed25519,
257    /// [RSASSA-PSS](https://tools.ietf.org/html/rfc5756) calculated over SHA256
258    #[serde(rename = "rsassa-pss-sha256")]
259    RsaSsaPssSha256,
260    /// [RSASSA-PSS](https://tools.ietf.org/html/rfc5756) calculated over SHA512
261    #[serde(rename = "rsassa-pss-sha512")]
262    RsaSsaPssSha512,
263    /// [ECDSA](https://www.rfc-editor.org/rfc/rfc5480) calculated over SHA256
264    /// Also known as 'prime256v1', 'P-256', and 'sepc256r1').
265    #[serde(rename = "ecdsa-sha2-nistp256")]
266    EcdsaP256Sha256,
267    /// Placeholder for an unknown scheme.
268    Unknown(String),
269}
270
271/// Wrapper type for the value of a cryptographic signature.
272#[derive(Clone, PartialEq, Eq, Serialize, Deserialize)]
273pub struct SignatureValue(#[serde(with = "crate::format_hex")] Vec<u8>);
274
275impl SignatureValue {
276    /// Create a new `SignatureValue` from the given bytes.
277    ///
278    /// Note: It is unlikely that you ever want to do this manually.
279    pub fn new(bytes: Vec<u8>) -> Self {
280        SignatureValue(bytes)
281    }
282
283    /// Create a new `SignatureValue` from the given hex string.
284    ///
285    /// Note: It is unlikely that you ever want to do this manually.
286    pub fn from_hex(string: &str) -> Result<Self> {
287        Ok(SignatureValue(HEXLOWER.decode(string.as_bytes())?))
288    }
289
290    /// Return the signature as bytes.
291    pub fn as_bytes(&self) -> &[u8] {
292        &self.0
293    }
294}
295
296impl Debug for SignatureValue {
297    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
298        f.debug_tuple("SignatureValue")
299            .field(&HEXLOWER.encode(&self.0))
300            .finish()
301    }
302}
303
304/// Types of public keys.
305#[derive(Clone, PartialEq, Debug, Eq, Hash)]
306pub enum KeyType {
307    /// [Ed25519](https://ed25519.cr.yp.to/)
308    Ed25519,
309    /// [RSA](https://en.wikipedia.org/wiki/RSA_%28cryptosystem%29)
310    Rsa,
311    /// [ECDSA](https://www.rfc-editor.org/rfc/rfc5480)
312    Ecdsa,
313    /// Placeholder for an unknown key type.
314    Unknown(String),
315}
316
317impl KeyType {
318    pub fn from_oid(oid: &[u8]) -> Result<Self> {
319        match oid {
320            RSA_SPKI_OID => Ok(KeyType::Rsa),
321            ED25519_SPKI_OID => Ok(KeyType::Ed25519),
322            ECC_SPKI_OID => Ok(KeyType::Ecdsa),
323            oid => {
324                let oid = HEXLOWER.encode(oid);
325                Err(Error::Encoding(format!("Unknown OID: {}", oid)))
326            }
327        }
328    }
329
330    pub fn as_oid(&self) -> Result<&'static [u8]> {
331        match *self {
332            KeyType::Rsa => Ok(RSA_SPKI_OID),
333            KeyType::Ed25519 => Ok(ED25519_SPKI_OID),
334            KeyType::Ecdsa => Ok(ECC_SPKI_OID),
335            KeyType::Unknown(ref s) => Err(Error::UnknownKeyType(s.clone())),
336        }
337    }
338}
339
340impl FromStr for KeyType {
341    type Err = Error;
342
343    fn from_str(s: &str) -> ::std::result::Result<Self, Self::Err> {
344        match s {
345            "ed25519" => Ok(KeyType::Ed25519),
346            "rsa" => Ok(KeyType::Rsa),
347            "ecdsa" => Ok(KeyType::Ecdsa),
348            typ => Err(Error::Encoding(typ.into())),
349        }
350    }
351}
352
353impl fmt::Display for KeyType {
354    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
355        write!(
356            f,
357            "{}",
358            match *self {
359                KeyType::Ed25519 => "ed25519",
360                KeyType::Rsa => "rsa",
361                KeyType::Ecdsa => "ecdsa",
362                KeyType::Unknown(ref s) => s,
363            }
364        )
365    }
366}
367
368impl Serialize for KeyType {
369    fn serialize<S>(&self, ser: S) -> ::std::result::Result<S::Ok, S::Error>
370    where
371        S: Serializer,
372    {
373        ser.serialize_str(&self.to_string())
374    }
375}
376
377impl<'de> Deserialize<'de> for KeyType {
378    fn deserialize<D: Deserializer<'de>>(
379        de: D,
380    ) -> ::std::result::Result<Self, D::Error> {
381        let string: String = Deserialize::deserialize(de)?;
382        string
383            .parse()
384            .map_err(|e| DeserializeError::custom(format!("{:?}", e)))
385    }
386}
387
388enum PrivateKeyType {
389    Ed25519(Ed25519KeyPair),
390    Rsa(Arc<RsaKeyPair>),
391    Ecdsa(EcdsaKeyPair),
392}
393
394impl Debug for PrivateKeyType {
395    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
396        let s = match *self {
397            PrivateKeyType::Ed25519(_) => "Ed25519",
398            PrivateKeyType::Rsa(_) => "Rsa",
399            PrivateKeyType::Ecdsa(_) => "Ecdsa",
400        };
401        f.debug_tuple(s).field(&"_").finish()
402    }
403}
404
405/// A structure containing information about a private key.
406pub struct PrivateKey {
407    private: PrivateKeyType,
408    public: PublicKey,
409}
410
411impl PrivateKey {
412    /// Generate a new `PrivateKey` bytes in pkcs8 format.
413    ///
414    /// Note: For RSA keys, `openssl` needs to the on the `$PATH`.
415    pub fn new(key_type: KeyType) -> Result<Vec<u8>> {
416        match key_type {
417            KeyType::Ed25519 => {
418                Ed25519KeyPair::generate_pkcs8(&SystemRandom::new())
419                    .map(|bytes| bytes.as_ref().to_vec())
420                    .map_err(|_| {
421                        Error::Opaque("Failed to generate Ed25519 key".into())
422                    })
423            }
424            KeyType::Rsa => Self::rsa_gen(),
425            KeyType::Ecdsa => EcdsaKeyPair::generate_pkcs8(
426                &ECDSA_P256_SHA256_ASN1_SIGNING,
427                &SystemRandom::new(),
428            )
429            .map(|bytes| bytes.as_ref().to_vec())
430            .map_err(|_| Error::Opaque("Failed to generate Ecdsa key".into())),
431            KeyType::Unknown(s) => {
432                Err(Error::IllegalArgument(format!("Unknown key type: {}", s)))
433            }
434        }
435    }
436
437    /// Create a new `PrivateKey` from an ed25519 keypair, a 64 byte slice, where the first 32
438    /// bytes are the ed25519 seed, and the second 32 bytes are the public key.
439    pub fn from_ed25519(key: &[u8]) -> Result<Self> {
440        Self::from_ed25519_with_keyid_hash_algorithms(key, None)
441    }
442
443    fn from_ed25519_with_keyid_hash_algorithms(
444        key: &[u8],
445        keyid_hash_algorithms: Option<Vec<String>>,
446    ) -> Result<Self> {
447        if key.len() != ED25519_KEYPAIR_LENGTH {
448            return Err(Error::Encoding(
449                "ed25519 private keys must be 64 bytes long".into(),
450            ));
451        }
452
453        let (private_key_bytes, public_key_bytes) =
454            key.split_at(ED25519_PRIVATE_KEY_LENGTH);
455
456        let key = Ed25519KeyPair::from_seed_and_public_key(
457            private_key_bytes,
458            public_key_bytes,
459        )
460        .map_err(|err| Error::Encoding(err.to_string()))?;
461
462        let public = PublicKey::new(
463            KeyType::Ed25519,
464            SignatureScheme::Ed25519,
465            keyid_hash_algorithms,
466            key.public_key().as_ref().to_vec(),
467        )?;
468        let private = PrivateKeyType::Ed25519(key);
469
470        Ok(PrivateKey { private, public })
471    }
472
473    /// Create a private key from PKCS#8v2 DER bytes.
474    ///
475    /// # Generating Keys
476    ///
477    /// ## Ed25519
478    ///
479    /// ```bash
480    /// $ touch ed25519-private-key.pk8
481    /// $ chmod 0600 ed25519-private-key.pk8
482    /// ```
483    ///
484    /// ```no_run
485    /// # use ring::rand::SystemRandom;
486    /// # use ring::signature::Ed25519KeyPair;
487    /// # use std::fs::File;
488    /// # use std::io::Write;
489    /// # fn main() {
490    /// let mut file = File::open("ed25519-private-key.pk8").unwrap();
491    /// let key = Ed25519KeyPair::generate_pkcs8(&SystemRandom::new()).unwrap();
492    /// file.write_all(key.as_ref()).unwrap()
493    /// # }
494    /// ```
495    ///
496    /// ## RSA
497    ///
498    /// ```bash
499    /// $ umask 077
500    /// $ openssl genpkey -algorithm RSA \
501    ///     -pkeyopt rsa_keygen_bits:4096 \
502    ///     -pkeyopt rsa_keygen_pubexp:65537 | \
503    ///     openssl pkcs8 -topk8 -nocrypt -outform der > rsa-4096-private-key.pk8
504    /// ```
505    ///
506    /// ## Ecdsa
507    ///
508    /// ```bash
509    /// $ openssl ecparam -name prime256v1 -genkey -noout -out ec.pem
510    /// $ openssl pkcs8 -in ec.pem -outform der -out ec.pk8.der -topk8 -nocrypt
511    /// ```
512    pub fn from_pkcs8(der_key: &[u8], scheme: SignatureScheme) -> Result<Self> {
513        let res = Self::ed25519_from_pkcs8(der_key);
514        if res.is_ok() {
515            if scheme != SignatureScheme::Ed25519 {
516                return Err(Error::IllegalArgument(format!(
517                    "Cannot use signature scheme {:?} with Ed25519 keys",
518                    scheme,
519                )));
520            }
521            return res;
522        }
523
524        let res = Self::rsa_from_pkcs8(der_key, scheme.clone());
525        if res.is_ok() {
526            return res;
527        }
528
529        let res = Self::ecdsa_from_pkcs8(der_key, scheme);
530        if res.is_ok() {
531            return res;
532        }
533
534        Err(Error::Opaque(
535            "Key was not Ed25519, RSA, or ECDSA".to_string(),
536        ))
537    }
538
539    fn ed25519_from_pkcs8(der_key: &[u8]) -> Result<Self> {
540        Self::ed25519_from_pkcs8_with_keyid_hash_algorithms(
541            der_key,
542            python_sslib_compatibility_keyid_hash_algorithms(),
543        )
544    }
545
546    fn ed25519_from_pkcs8_with_keyid_hash_algorithms(
547        der_key: &[u8],
548        keyid_hash_algorithms: Option<Vec<String>>,
549    ) -> Result<Self> {
550        let key = Ed25519KeyPair::from_pkcs8(der_key).map_err(|_| {
551            Error::Encoding("Could not parse key as PKCS#8v2".into())
552        })?;
553
554        let public = PublicKey::new(
555            KeyType::Ed25519,
556            SignatureScheme::Ed25519,
557            keyid_hash_algorithms,
558            key.public_key().as_ref().to_vec(),
559        )?;
560        let private = PrivateKeyType::Ed25519(key);
561
562        Ok(PrivateKey { private, public })
563    }
564
565    fn rsa_from_pkcs8(der_key: &[u8], scheme: SignatureScheme) -> Result<Self> {
566        if SignatureScheme::Ed25519 == scheme {
567            return Err(Error::IllegalArgument(
568                "RSA keys do not support the Ed25519 signing scheme".into(),
569            ));
570        }
571
572        let key = RsaKeyPair::from_pkcs8(der_key).map_err(|_| {
573            Error::Encoding("Could not parse key as PKCS#8v2".into())
574        })?;
575
576        if key.public().modulus_len() < 256 {
577            return Err(Error::IllegalArgument(format!(
578                "RSA public modulus must be 2048 or greater. Found {}",
579                key.public().modulus_len() * 8
580            )));
581        }
582
583        let pub_key = extract_rsa_pub_from_pkcs8(der_key)?;
584
585        let public = PublicKey::new(
586            KeyType::Rsa,
587            scheme,
588            python_sslib_compatibility_keyid_hash_algorithms(),
589            pub_key,
590        )?;
591        let private = PrivateKeyType::Rsa(Arc::new(key));
592
593        Ok(PrivateKey { private, public })
594    }
595
596    fn ecdsa_from_pkcs8(
597        der_key: &[u8],
598        scheme: SignatureScheme,
599    ) -> Result<Self> {
600        let key_pair = EcdsaKeyPair::from_pkcs8(
601            &ECDSA_P256_SHA256_ASN1_SIGNING,
602            der_key,
603            &SystemRandom::new(),
604        )
605        .unwrap();
606        let public = PublicKey::new(
607            KeyType::Ecdsa,
608            scheme,
609            python_sslib_compatibility_keyid_hash_algorithms(),
610            key_pair.public_key().as_ref().to_vec(),
611        )?;
612        let private = PrivateKeyType::Ecdsa(key_pair);
613        Ok(PrivateKey { private, public })
614    }
615
616    /// Sign a message.
617    pub fn sign(&self, msg: &[u8]) -> Result<Signature> {
618        let value = match (&self.private, &self.public.scheme) {
619            (PrivateKeyType::Rsa(rsa), &SignatureScheme::RsaSsaPssSha256) => {
620                let rng = SystemRandom::new();
621                let mut buf = vec![0; rsa.public().modulus_len()];
622                rsa.sign(&RSA_PSS_SHA256, &rng, msg, &mut buf).map_err(
623                    |_| Error::Opaque("Failed to sign message.".into()),
624                )?;
625                SignatureValue(buf)
626            }
627            (PrivateKeyType::Rsa(rsa), &SignatureScheme::RsaSsaPssSha512) => {
628                let rng = SystemRandom::new();
629                let mut buf = vec![0; rsa.public().modulus_len()];
630                rsa.sign(&RSA_PSS_SHA512, &rng, msg, &mut buf).map_err(
631                    |_| Error::Opaque("Failed to sign message.".into()),
632                )?;
633                SignatureValue(buf)
634            }
635            (PrivateKeyType::Ed25519(ed), &SignatureScheme::Ed25519) => {
636                SignatureValue(ed.sign(msg).as_ref().into())
637            }
638            (PrivateKeyType::Ecdsa(ec), &SignatureScheme::EcdsaP256Sha256) => {
639                let rng = SystemRandom::new();
640                let s = ec.sign(&rng, msg).map_err(|_| {
641                    Error::Opaque("Failed to sign message.".into())
642                })?;
643                SignatureValue(s.as_ref().into())
644            }
645            (k, s) => {
646                return Err(Error::IllegalArgument(format!(
647                    "Key {:?} can't be used with scheme {:?}",
648                    k, s
649                )));
650            }
651        };
652
653        Ok(Signature {
654            key_id: self.key_id().clone(),
655            value,
656        })
657    }
658
659    fn rsa_gen() -> Result<Vec<u8>> {
660        let gen = Command::new("openssl")
661            .args([
662                "genpkey",
663                "-algorithm",
664                "RSA",
665                "-pkeyopt",
666                "rsa_keygen_bits:4096",
667                "-pkeyopt",
668                "rsa_keygen_pubexp:65537",
669                "-outform",
670                "der",
671            ])
672            .output()?;
673
674        let mut pk8 = Command::new("openssl")
675            .args([
676                "pkcs8", "-inform", "der", "-topk8", "-nocrypt", "-outform",
677                "der",
678            ])
679            .stdin(Stdio::piped())
680            .stdout(Stdio::piped())
681            .spawn()?;
682
683        match pk8.stdin {
684            Some(ref mut stdin) => stdin.write_all(&gen.stdout)?,
685            None => return Err(Error::Opaque("openssl has no stdin".into())),
686        };
687
688        Ok(pk8.wait_with_output()?.stdout)
689    }
690
691    /// Return the public component of the key.
692    pub fn public(&self) -> &PublicKey {
693        &self.public
694    }
695
696    /// Return the key ID of the public key.
697    pub fn key_id(&self) -> &KeyId {
698        &self.public.key_id
699    }
700}
701
702/// A structure containing information about a public key.
703#[derive(Clone, Debug)]
704pub struct PublicKey {
705    typ: KeyType,
706    key_id: KeyId,
707    scheme: SignatureScheme,
708    keyid_hash_algorithms: Option<Vec<String>>,
709    value: PublicKeyValue,
710}
711
712impl PublicKey {
713    fn new(
714        typ: KeyType,
715        scheme: SignatureScheme,
716        keyid_hash_algorithms: Option<Vec<String>>,
717        value: Vec<u8>,
718    ) -> Result<Self> {
719        let key_id =
720            calculate_key_id(&typ, &scheme, &keyid_hash_algorithms, &value)?;
721        let value = PublicKeyValue(value);
722        Ok(PublicKey {
723            typ,
724            key_id,
725            scheme,
726            keyid_hash_algorithms,
727            value,
728        })
729    }
730
731    /// Parse DER bytes as an SPKI key.
732    ///
733    /// See the documentation on `KeyValue` for more information on SPKI.
734    pub fn from_spki(
735        der_bytes: &[u8],
736        scheme: SignatureScheme,
737    ) -> Result<Self> {
738        Self::from_spki_with_keyid_hash_algorithms(
739            der_bytes,
740            scheme,
741            python_sslib_compatibility_keyid_hash_algorithms(),
742        )
743    }
744
745    /// Parse PEM as an Subject Public Key Info (SPKI) key.
746    ///
747    /// See the documentation on `KeyValue` for more information on SPKI.
748    pub fn from_pem_spki(pem: &str, scheme: SignatureScheme) -> Result<Self> {
749        let der_bytes = pem::parse(pem).unwrap();
750        Self::from_spki_with_keyid_hash_algorithms(
751            der_bytes.contents(),
752            scheme,
753            python_sslib_compatibility_keyid_hash_algorithms(),
754        )
755    }
756
757    /// Parse DER bytes as an SPKI key and the `keyid_hash_algorithms`.
758    ///
759    /// See the documentation on `KeyValue` for more information on SPKI.
760    fn from_spki_with_keyid_hash_algorithms(
761        der_bytes: &[u8],
762        scheme: SignatureScheme,
763        keyid_hash_algorithms: Option<Vec<String>>,
764    ) -> Result<Self> {
765        let input = Input::from(der_bytes);
766
767        let (typ, value) = input.read_all(derp::Error::Read, |input| {
768            derp::nested(input, Tag::Sequence, |input| {
769                let typ = derp::nested(input, Tag::Sequence, |input| {
770                    let typ = derp::expect_tag_and_get_value(input, Tag::Oid)?;
771
772                    let typ = KeyType::from_oid(typ.as_slice_less_safe())
773                        .map_err(|_| derp::Error::WrongValue)?;
774
775                    if typ == KeyType::Ecdsa {
776                        let _alg_oid =
777                            derp::expect_tag_and_get_value(input, Tag::Oid)?;
778                    } else {
779                        // for RSA / ed25519 this is null, so don't both parsing it
780                        derp::read_null(input)?;
781                    }
782                    Ok(typ)
783                })?;
784                let value = derp::bit_string_with_no_unused_bits(input)?;
785                Ok((typ, value.as_slice_less_safe().to_vec()))
786            })
787        })?;
788
789        Self::new(typ, scheme, keyid_hash_algorithms, value)
790    }
791
792    /// Parse ED25519 bytes as a public key.
793    pub fn from_ed25519<T: Into<Vec<u8>>>(bytes: T) -> Result<Self> {
794        Self::from_ed25519_with_keyid_hash_algorithms(bytes, None)
795    }
796
797    /// Parse ED25519 bytes as a public key with a custom `keyid_hash_algorithms`.
798    pub fn from_ed25519_with_keyid_hash_algorithms<T: Into<Vec<u8>>>(
799        bytes: T,
800        keyid_hash_algorithms: Option<Vec<String>>,
801    ) -> Result<Self> {
802        let bytes = bytes.into();
803        if bytes.len() != 32 {
804            return Err(Error::IllegalArgument(
805                "ed25519 keys must be 32 bytes long".into(),
806            ));
807        }
808
809        Self::new(
810            KeyType::Ed25519,
811            SignatureScheme::Ed25519,
812            keyid_hash_algorithms,
813            bytes,
814        )
815    }
816
817    /// Parse Ecdsa bytes as a public key.
818    pub fn from_ecdsa<T: Into<Vec<u8>>>(bytes: T) -> Result<Self> {
819        Self::from_ecdsa_with_keyid_hash_algorithms(bytes, None)
820    }
821
822    /// Parse Ecdsa bytes as a public key with a custom `keyid_hash_algorithms`.
823    pub fn from_ecdsa_with_keyid_hash_algorithms<T: Into<Vec<u8>>>(
824        bytes: T,
825        keyid_hash_algorithms: Option<Vec<String>>,
826    ) -> Result<Self> {
827        let bytes = bytes.into();
828        Self::new(
829            KeyType::Ecdsa,
830            SignatureScheme::EcdsaP256Sha256,
831            keyid_hash_algorithms,
832            bytes,
833        )
834    }
835
836    pub fn from_ecdsa_with_keyid_hash_algorithm<T: Into<Vec<u8>>>(
837        der_bytes: T,
838        scheme: SignatureScheme,
839        keyid_hash_algorithms: Option<Vec<String>>,
840    ) -> Result<Self> {
841        let bytes = der_bytes.into();
842        Self::new(KeyType::Ecdsa, scheme, keyid_hash_algorithms, bytes)
843    }
844
845    /// Write the public key as SPKI DER bytes.
846    ///
847    /// See the documentation on `KeyValue` for more information on SPKI.
848    pub fn as_spki(&self) -> Result<Vec<u8>> {
849        Ok(write_spki(&self.value.0, &self.typ)?)
850    }
851
852    /// An immutable reference to the key's type.
853    pub fn typ(&self) -> &KeyType {
854        &self.typ
855    }
856
857    /// An immutable referece to the key's authorized signing scheme.
858    pub fn scheme(&self) -> &SignatureScheme {
859        &self.scheme
860    }
861
862    /// An immutable reference to the key's ID.
863    pub fn key_id(&self) -> &KeyId {
864        &self.key_id
865    }
866
867    /// Return the public key as bytes.
868    pub fn as_bytes(&self) -> &[u8] {
869        &self.value.0
870    }
871
872    /// Use this key to verify a message with a signature.
873    pub fn verify(&self, msg: &[u8], sig: &Signature) -> Result<()> {
874        let alg: &dyn ring::signature::VerificationAlgorithm = match self.scheme
875        {
876            SignatureScheme::Ed25519 => &ED25519,
877            SignatureScheme::RsaSsaPssSha256 => &RSA_PSS_2048_8192_SHA256,
878            SignatureScheme::RsaSsaPssSha512 => &RSA_PSS_2048_8192_SHA512,
879            SignatureScheme::EcdsaP256Sha256 => &ECDSA_P256_SHA256_ASN1,
880            SignatureScheme::Unknown(ref s) => {
881                return Err(Error::IllegalArgument(format!(
882                    "Unknown signature scheme: {}",
883                    s
884                )));
885            }
886        };
887
888        let key = ring::signature::UnparsedPublicKey::new(alg, &self.value.0);
889        key.verify(msg, &sig.value.0)
890            .map_err(|_| Error::BadSignature)
891    }
892}
893
894impl PartialEq for PublicKey {
895    fn eq(&self, other: &Self) -> bool {
896        // key_id is derived from these fields, so we ignore it.
897        self.typ == other.typ
898            && self.scheme == other.scheme
899            && self.keyid_hash_algorithms == other.keyid_hash_algorithms
900            && self.value == other.value
901    }
902}
903
904impl Eq for PublicKey {}
905
906impl Ord for PublicKey {
907    fn cmp(&self, other: &Self) -> Ordering {
908        self.key_id.cmp(&other.key_id)
909    }
910}
911
912impl PartialOrd for PublicKey {
913    fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
914        Some(self.key_id.cmp(&other.key_id))
915    }
916}
917
918impl hash::Hash for PublicKey {
919    fn hash<H: hash::Hasher>(&self, state: &mut H) {
920        // key_id is derived from these fields, so we ignore it.
921        self.typ.hash(state);
922        self.scheme.hash(state);
923        self.keyid_hash_algorithms.hash(state);
924        self.value.hash(state);
925    }
926}
927
928impl Serialize for PublicKey {
929    fn serialize<S>(&self, ser: S) -> ::std::result::Result<S::Ok, S::Error>
930    where
931        S: Serializer,
932    {
933        let key = shim_public_key(
934            &self.typ,
935            &self.scheme,
936            &self.keyid_hash_algorithms,
937            &self.value.0,
938            true,
939            Some(&self.key_id.0),
940        )
941        .map_err(|e| {
942            SerializeError::custom(format!(
943                "Couldn't write key as SPKI: {:?}",
944                e
945            ))
946        })?;
947        key.serialize(ser)
948    }
949}
950
951impl<'de> Deserialize<'de> for PublicKey {
952    fn deserialize<D: Deserializer<'de>>(
953        de: D,
954    ) -> ::std::result::Result<Self, D::Error> {
955        let intermediate: shims::PublicKey = Deserialize::deserialize(de)?;
956
957        let key = match intermediate.keytype() {
958            KeyType::Ed25519 => {
959                if intermediate.scheme() != &SignatureScheme::Ed25519 {
960                    return Err(DeserializeError::custom(format!(
961                        "ed25519 key type must be used with the ed25519 signature scheme, not {:?}",
962                        intermediate.scheme()
963                    )));
964                }
965
966                let bytes = HEXLOWER
967                    .decode(intermediate.public_key().as_bytes())
968                    .map_err(|e| {
969                        DeserializeError::custom(format!(
970                            "Couldn't parse key as HEX: {:?}",
971                            e
972                        ))
973                    })?;
974
975                PublicKey::from_ed25519_with_keyid_hash_algorithms(
976                    bytes,
977                    intermediate.keyid_hash_algorithms().clone(),
978                )
979                .map_err(|e| {
980                    DeserializeError::custom(format!(
981                        "Couldn't parse key as ed25519: {:?}",
982                        e
983                    ))
984                })?
985            }
986            KeyType::Rsa => {
987                let pub_pem = pem::parse(intermediate.public_key().as_bytes())
988                    .map_err(|e| {
989                        DeserializeError::custom(format!(
990                            "pem deserialize failed: {:?}",
991                            e
992                        ))
993                    })?;
994
995                PublicKey::from_spki_with_keyid_hash_algorithms(
996                    pub_pem.contents(),
997                    intermediate.scheme().clone(),
998                    intermediate.keyid_hash_algorithms().clone(),
999                )
1000                .map_err(|e| {
1001                    DeserializeError::custom(format!(
1002                        "Couldn't parse key as SPKI: {:?}",
1003                        e
1004                    ))
1005                })?
1006            }
1007            KeyType::Ecdsa => {
1008                if intermediate.scheme() != &SignatureScheme::EcdsaP256Sha256 {
1009                    return Err(DeserializeError::custom(format!(
1010                        "ecdsa key type must be used with the ecdsa signature scheme, not {:?}",
1011                        intermediate.scheme()
1012                    )));
1013                }
1014                let bytes = HEXLOWER
1015                    .decode(intermediate.public_key().as_bytes())
1016                    .map_err(|e| {
1017                        DeserializeError::custom(format!(
1018                            "Couldn't parse key as HEX: {:?}",
1019                            e
1020                        ))
1021                    })?;
1022                PublicKey::from_ecdsa_with_keyid_hash_algorithm(
1023                    bytes,
1024                    intermediate.scheme().clone(),
1025                    intermediate.keyid_hash_algorithms().clone(),
1026                )
1027                .map_err(|e| {
1028                    DeserializeError::custom(format!(
1029                        "Couldn't parse key as SPKI: {:?}",
1030                        e
1031                    ))
1032                })?
1033            }
1034            KeyType::Unknown(inner) => {
1035                return Err(DeserializeError::custom(format!(
1036                    "Unknown key type, content: {}",
1037                    inner
1038                )))
1039            }
1040        };
1041
1042        if intermediate.keytype() != &key.typ {
1043            return Err(DeserializeError::custom(format!(
1044                "Key type listed in the metadata did not match the type extrated \
1045                 from the key. {:?} vs. {:?}",
1046                intermediate.keytype(),
1047                key.typ,
1048            )));
1049        }
1050
1051        Ok(key)
1052    }
1053}
1054
1055#[derive(Clone, PartialEq, Hash, Eq)]
1056struct PublicKeyValue(Vec<u8>);
1057
1058impl Debug for PublicKeyValue {
1059    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1060        f.debug_tuple("PublicKeyValue")
1061            .field(&HEXLOWER.encode(&self.0))
1062            .finish()
1063    }
1064}
1065
1066/// A structure that contains a `Signature` and associated data for verifying it.
1067#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
1068pub struct Signature {
1069    #[serde(rename = "keyid")]
1070    key_id: KeyId,
1071    #[serde(rename = "sig")]
1072    value: SignatureValue,
1073}
1074
1075impl Signature {
1076    /// An immutable reference to the `KeyId` of the key that produced the signature.
1077    pub fn key_id(&self) -> &KeyId {
1078        &self.key_id
1079    }
1080
1081    /// An immutable reference to the `SignatureValue`.
1082    pub fn value(&self) -> &SignatureValue {
1083        &self.value
1084    }
1085}
1086
1087/// The available hash algorithms.
1088#[derive(
1089    Debug, Clone, Hash, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize,
1090)]
1091pub enum HashAlgorithm {
1092    /// SHA256 as describe in [RFC-6234](https://tools.ietf.org/html/rfc6234)
1093    #[serde(rename = "sha256")]
1094    Sha256,
1095    /// SHA512 as describe in [RFC-6234](https://tools.ietf.org/html/rfc6234)
1096    #[serde(rename = "sha512")]
1097    Sha512,
1098    /// Placeholder for an unknown hash algorithm.
1099    Unknown(String),
1100}
1101
1102impl HashAlgorithm {
1103    /// Create a new `digest::Context` suitable for computing the hash of some data using this hash
1104    /// algorithm.
1105    pub(crate) fn digest_context(&self) -> Result<digest::Context> {
1106        match self {
1107            HashAlgorithm::Sha256 => Ok(digest::Context::new(&SHA256)),
1108            HashAlgorithm::Sha512 => Ok(digest::Context::new(&SHA512)),
1109            HashAlgorithm::Unknown(ref s) => Err(Error::IllegalArgument(
1110                format!("Unknown hash algorithm: {}", s),
1111            )),
1112        }
1113    }
1114    pub fn return_all() -> HashMap<String, HashAlgorithm> {
1115        let mut map = HashMap::new();
1116        map.insert(String::from("sha256"), HashAlgorithm::Sha256);
1117        map.insert(String::from("sha512"), HashAlgorithm::Sha512);
1118        map
1119    }
1120}
1121
1122/// Wrapper for the value of a hash digest.
1123#[derive(Clone, Eq, PartialEq, Hash, Serialize, Deserialize)]
1124pub struct HashValue(#[serde(with = "crate::format_hex")] Vec<u8>);
1125
1126impl HashValue {
1127    /// Create a new `HashValue` from the given digest bytes.
1128    pub fn new(bytes: Vec<u8>) -> Self {
1129        HashValue(bytes)
1130    }
1131
1132    /// An immutable reference to the bytes of the hash value.
1133    pub fn value(&self) -> &[u8] {
1134        &self.0
1135    }
1136}
1137
1138impl Debug for HashValue {
1139    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1140        f.debug_tuple("HashValue")
1141            .field(&HEXLOWER.encode(&self.0))
1142            .finish()
1143    }
1144}
1145
1146impl Display for HashValue {
1147    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1148        write!(f, "{}", HEXLOWER.encode(&self.0))
1149    }
1150}
1151
1152fn write_spki(
1153    public: &[u8],
1154    key_type: &KeyType,
1155) -> ::std::result::Result<Vec<u8>, derp::Error> {
1156    let mut output = Vec::new();
1157    {
1158        let mut der = Der::new(&mut output);
1159        der.sequence(|der| {
1160            der.sequence(|der| match key_type.as_oid().ok() {
1161                Some(tag) => {
1162                    der.element(Tag::Oid, tag)?;
1163                    der.null()
1164                }
1165                None => Err(derp::Error::WrongValue),
1166            })?;
1167            der.bit_string(0, public)
1168        })?;
1169    }
1170
1171    Ok(output)
1172}
1173
1174fn extract_rsa_pub_from_pkcs8(
1175    der_key: &[u8],
1176) -> ::std::result::Result<Vec<u8>, derp::Error> {
1177    let input = Input::from(der_key);
1178    input.read_all(derp::Error::Read, |input| {
1179        derp::nested(input, Tag::Sequence, |input| {
1180            if derp::small_nonnegative_integer(input)? != 0 {
1181                return Err(derp::Error::WrongValue);
1182            }
1183
1184            derp::nested(input, Tag::Sequence, |input| {
1185                let actual_alg_id =
1186                    derp::expect_tag_and_get_value(input, Tag::Oid)?;
1187                if actual_alg_id.as_slice_less_safe() != RSA_SPKI_OID {
1188                    return Err(derp::Error::WrongValue);
1189                }
1190                let _ = derp::expect_tag_and_get_value(input, Tag::Null)?;
1191                Ok(())
1192            })?;
1193
1194            derp::nested(input, Tag::OctetString, |input| {
1195                derp::nested(input, Tag::Sequence, |input| {
1196                    if derp::small_nonnegative_integer(input)? != 0 {
1197                        return Err(derp::Error::WrongValue);
1198                    }
1199
1200                    let n = derp::positive_integer(input)?;
1201                    let e = derp::positive_integer(input)?;
1202                    input.skip_to_end();
1203                    write_pkcs1(n.as_slice_less_safe(), e.as_slice_less_safe())
1204                })
1205            })
1206        })
1207    })
1208}
1209
1210fn write_pkcs1(
1211    n: &[u8],
1212    e: &[u8],
1213) -> ::std::result::Result<Vec<u8>, derp::Error> {
1214    let mut output = Vec::new();
1215    {
1216        let mut der = Der::new(&mut output);
1217        der.sequence(|der| {
1218            der.positive_integer(n)?;
1219            der.positive_integer(e)
1220        })?;
1221    }
1222
1223    Ok(output)
1224}
1225
1226#[cfg(test)]
1227mod test {
1228    use crate::models::Metablock;
1229
1230    use super::*;
1231    use pretty_assertions::assert_eq;
1232    use serde_json::{self, json};
1233    use std::str;
1234
1235    const RSA_2048_PK8: &'static [u8] =
1236        include_bytes!("../tests/rsa/rsa-2048.pk8.der");
1237    const RSA_2048_SPKI: &'static [u8] =
1238        include_bytes!("../tests/rsa/rsa-2048.spki.der");
1239    const RSA_2048_PKCS1: &'static [u8] =
1240        include_bytes!("../tests/rsa/rsa-2048.pkcs1.der");
1241
1242    const RSA_4096_PK8: &'static [u8] =
1243        include_bytes!("../tests/rsa/rsa-4096.pk8.der");
1244    const RSA_4096_SPKI: &'static [u8] =
1245        include_bytes!("../tests/rsa/rsa-4096.spki.der");
1246    const RSA_4096_PKCS1: &'static [u8] =
1247        include_bytes!("../tests/rsa/rsa-4096.pkcs1.der");
1248
1249    const ED25519_1_PRIVATE_KEY: &'static [u8] =
1250        include_bytes!("../tests/ed25519/ed25519-1");
1251    const ED25519_1_PUBLIC_KEY: &'static [u8] =
1252        include_bytes!("../tests/ed25519/ed25519-1.pub");
1253    const ED25519_1_PK8: &'static [u8] =
1254        include_bytes!("../tests/ed25519/ed25519-1.pk8.der");
1255    const ED25519_1_SPKI: &'static [u8] =
1256        include_bytes!("../tests/ed25519/ed25519-1.spki.der");
1257    const ED25519_2_PK8: &'static [u8] =
1258        include_bytes!("../tests/ed25519/ed25519-2.pk8.der");
1259
1260    const ECDSA_PK8: &'static [u8] =
1261        include_bytes!("../tests/ecdsa/ec.pk8.der");
1262    const ECDSA_SPKI: &'static [u8] =
1263        include_bytes!("../tests/ecdsa/ec.spki.der");
1264    const ECDSA_PUBLIC_KEY: &'static [u8] =
1265        include_bytes!("../tests/ecdsa/ec.pub");
1266
1267    const DEMO_KEY_ID: &str =
1268        "556caebdc0877eed53d419b60eddb1e57fa773e4e31d70698b588f3e9cc48b35";
1269    const DEMO_PUBLIC_KEY: &'static [u8] =
1270        include_bytes!("../tests/rsa/alice.pub");
1271    const DEMO_LAYOUT: &'static [u8] =
1272        include_bytes!("../tests/test_verifylib/workdir/root.layout");
1273
1274    #[test]
1275    fn parse_public_rsa_2048_spki() {
1276        let key = PublicKey::from_spki(
1277            RSA_2048_SPKI,
1278            SignatureScheme::RsaSsaPssSha256,
1279        )
1280        .unwrap();
1281        assert_eq!(key.typ, KeyType::Rsa);
1282        assert_eq!(key.scheme, SignatureScheme::RsaSsaPssSha256);
1283    }
1284
1285    #[test]
1286    fn parse_public_rsa_4096_spki() {
1287        let key = PublicKey::from_spki(
1288            RSA_4096_SPKI,
1289            SignatureScheme::RsaSsaPssSha256,
1290        )
1291        .unwrap();
1292        assert_eq!(key.typ, KeyType::Rsa);
1293        assert_eq!(key.scheme, SignatureScheme::RsaSsaPssSha256);
1294    }
1295
1296    #[test]
1297    fn parse_public_ed25519_spki() {
1298        let key =
1299            PublicKey::from_spki(ED25519_1_SPKI, SignatureScheme::Ed25519)
1300                .unwrap();
1301        assert_eq!(key.typ, KeyType::Ed25519);
1302        assert_eq!(key.scheme, SignatureScheme::Ed25519);
1303    }
1304
1305    #[test]
1306    fn parse_public_ecdsa_spki() {
1307        let key =
1308            PublicKey::from_spki(ECDSA_SPKI, SignatureScheme::EcdsaP256Sha256)
1309                .unwrap();
1310        assert_eq!(key.typ, KeyType::Ecdsa);
1311        assert_eq!(key.scheme, SignatureScheme::EcdsaP256Sha256);
1312    }
1313
1314    #[test]
1315    fn parse_public_ed25519() {
1316        let key = PublicKey::from_ed25519(ED25519_1_PUBLIC_KEY).unwrap();
1317        assert_eq!(
1318            key.key_id(),
1319            &KeyId::from_str("e0294a3f17cc8563c3ed5fceb3bd8d3f6bfeeaca499b5c9572729ae015566554")
1320                .unwrap()
1321        );
1322        assert_eq!(key.typ, KeyType::Ed25519);
1323        assert_eq!(key.scheme, SignatureScheme::Ed25519);
1324    }
1325
1326    #[test]
1327    fn parse_public_ecdsa() {
1328        let key = PublicKey::from_ecdsa(ECDSA_PUBLIC_KEY).unwrap();
1329        assert_eq!(
1330            key.key_id(),
1331            &KeyId::from_str("d23fafcd03bf36532580dbab48b54f53e280ccb119db5846cc6fbe094c612947")
1332                .unwrap()
1333        );
1334        assert_eq!(key.typ, KeyType::Ecdsa);
1335        assert_eq!(key.scheme, SignatureScheme::EcdsaP256Sha256);
1336    }
1337
1338    #[test]
1339    fn parse_public_ed25519_without_keyid_hash_algo() {
1340        let key = PublicKey::from_ed25519_with_keyid_hash_algorithms(
1341            ED25519_1_PUBLIC_KEY,
1342            None,
1343        )
1344        .unwrap();
1345        assert_eq!(
1346            key.key_id(),
1347            &KeyId::from_str("e0294a3f17cc8563c3ed5fceb3bd8d3f6bfeeaca499b5c9572729ae015566554")
1348                .unwrap()
1349        );
1350        assert_eq!(key.typ, KeyType::Ed25519);
1351        assert_eq!(key.scheme, SignatureScheme::Ed25519);
1352    }
1353
1354    #[test]
1355    fn parse_public_ed25519_with_keyid_hash_algo() {
1356        let key = PublicKey::from_ed25519_with_keyid_hash_algorithms(
1357            ED25519_1_PUBLIC_KEY,
1358            python_sslib_compatibility_keyid_hash_algorithms(),
1359        )
1360        .unwrap();
1361        assert_eq!(
1362            key.key_id(),
1363            &KeyId::from_str("a9f3ebc9b138762563a9c27b6edd439959e559709babd123e8d449ba2c18c61a")
1364                .unwrap(),
1365        );
1366        assert_eq!(key.typ, KeyType::Ed25519);
1367        assert_eq!(key.scheme, SignatureScheme::Ed25519);
1368    }
1369
1370    #[test]
1371    fn rsa_2048_read_pkcs8_and_sign() {
1372        let msg = b"test";
1373
1374        let key = PrivateKey::from_pkcs8(
1375            RSA_2048_PK8,
1376            SignatureScheme::RsaSsaPssSha256,
1377        )
1378        .unwrap();
1379        let sig = key.sign(msg).unwrap();
1380        key.public.verify(msg, &sig).unwrap();
1381
1382        let key = PrivateKey::from_pkcs8(
1383            RSA_2048_PK8,
1384            SignatureScheme::RsaSsaPssSha512,
1385        )
1386        .unwrap();
1387        let sig = key.sign(msg).unwrap();
1388        key.public.verify(msg, &sig).unwrap();
1389    }
1390
1391    #[test]
1392    fn rsa_4096_read_pkcs8_and_sign() {
1393        let msg = b"test";
1394
1395        let key = PrivateKey::from_pkcs8(
1396            RSA_4096_PK8,
1397            SignatureScheme::RsaSsaPssSha256,
1398        )
1399        .unwrap();
1400        let sig = key.sign(msg).unwrap();
1401        key.public.verify(msg, &sig).unwrap();
1402
1403        let key = PrivateKey::from_pkcs8(
1404            RSA_4096_PK8,
1405            SignatureScheme::RsaSsaPssSha512,
1406        )
1407        .unwrap();
1408        let sig = key.sign(msg).unwrap();
1409        key.public.verify(msg, &sig).unwrap();
1410    }
1411
1412    #[test]
1413    fn extract_pkcs1_from_rsa_2048_pkcs8() {
1414        let res = extract_rsa_pub_from_pkcs8(RSA_2048_PK8).unwrap();
1415        assert_eq!(res.as_slice(), RSA_2048_PKCS1);
1416    }
1417
1418    #[test]
1419    fn extract_pkcs1_from_rsa_4096_pkcs8() {
1420        let res = extract_rsa_pub_from_pkcs8(RSA_4096_PK8).unwrap();
1421        assert_eq!(res.as_slice(), RSA_4096_PKCS1);
1422    }
1423
1424    #[test]
1425    fn ed25519_read_pkcs8_and_sign() {
1426        let key =
1427            PrivateKey::from_pkcs8(ED25519_1_PK8, SignatureScheme::Ed25519)
1428                .unwrap();
1429        let msg = b"test";
1430
1431        let sig = key.sign(msg).unwrap();
1432
1433        let pub_key = PublicKey::from_spki(
1434            &key.public.as_spki().unwrap(),
1435            SignatureScheme::Ed25519,
1436        )
1437        .unwrap();
1438
1439        assert_eq!(pub_key.verify(msg, &sig), Ok(()));
1440
1441        // Make sure we match what ring expects.
1442        let ring_key =
1443            ring::signature::Ed25519KeyPair::from_pkcs8(ED25519_1_PK8).unwrap();
1444        assert_eq!(key.public().as_bytes(), ring_key.public_key().as_ref());
1445        assert_eq!(sig.value().as_bytes(), ring_key.sign(msg).as_ref());
1446
1447        // Make sure verification fails with the wrong key.
1448        let bad_pub_key =
1449            PrivateKey::from_pkcs8(ED25519_2_PK8, SignatureScheme::Ed25519)
1450                .unwrap()
1451                .public()
1452                .clone();
1453
1454        assert_eq!(bad_pub_key.verify(msg, &sig), Err(Error::BadSignature));
1455    }
1456
1457    #[test]
1458    fn ecdsa_read_pkcs8_and_sign() {
1459        let msg = b"test";
1460
1461        let key =
1462            PrivateKey::from_pkcs8(ECDSA_PK8, SignatureScheme::EcdsaP256Sha256)
1463                .unwrap();
1464        let sig = key.sign(msg).unwrap();
1465        key.public.verify(msg, &sig).unwrap();
1466
1467        let key =
1468            PrivateKey::from_pkcs8(ECDSA_PK8, SignatureScheme::EcdsaP256Sha256)
1469                .unwrap();
1470        let sig = key.sign(msg).unwrap();
1471        key.public.verify(msg, &sig).unwrap();
1472    }
1473
1474    #[test]
1475    fn ed25519_read_keypair_and_sign() {
1476        let key = PrivateKey::from_ed25519(ED25519_1_PRIVATE_KEY).unwrap();
1477        let pub_key = PublicKey::from_ed25519(ED25519_1_PUBLIC_KEY).unwrap();
1478        assert_eq!(key.public(), &pub_key);
1479
1480        let msg = b"test";
1481        let sig = key.sign(msg).unwrap();
1482        assert_eq!(pub_key.verify(msg, &sig), Ok(()));
1483
1484        // Make sure we match what ring expects.
1485        let ring_key =
1486            ring::signature::Ed25519KeyPair::from_pkcs8(ED25519_1_PK8).unwrap();
1487        assert_eq!(key.public().as_bytes(), ring_key.public_key().as_ref());
1488        assert_eq!(sig.value().as_bytes(), ring_key.sign(msg).as_ref());
1489
1490        // Make sure verification fails with the wrong key.
1491        let bad_pub_key =
1492            PrivateKey::from_pkcs8(ED25519_2_PK8, SignatureScheme::Ed25519)
1493                .unwrap()
1494                .public()
1495                .clone();
1496
1497        assert_eq!(bad_pub_key.verify(msg, &sig), Err(Error::BadSignature));
1498    }
1499
1500    #[test]
1501    fn ed25519_read_keypair_and_sign_with_keyid_hash_algorithms() {
1502        let key = PrivateKey::from_ed25519_with_keyid_hash_algorithms(
1503            ED25519_1_PRIVATE_KEY,
1504            python_sslib_compatibility_keyid_hash_algorithms(),
1505        )
1506        .unwrap();
1507        let pub_key = PublicKey::from_ed25519_with_keyid_hash_algorithms(
1508            ED25519_1_PUBLIC_KEY,
1509            python_sslib_compatibility_keyid_hash_algorithms(),
1510        )
1511        .unwrap();
1512        assert_eq!(key.public(), &pub_key);
1513
1514        let msg = b"test";
1515        let sig = key.sign(msg).unwrap();
1516        assert_eq!(pub_key.verify(msg, &sig), Ok(()));
1517
1518        // Make sure we match what ring expects.
1519        let ring_key =
1520            ring::signature::Ed25519KeyPair::from_pkcs8(ED25519_1_PK8).unwrap();
1521        assert_eq!(key.public().as_bytes(), ring_key.public_key().as_ref());
1522        assert_eq!(sig.value().as_bytes(), ring_key.sign(msg).as_ref());
1523
1524        // Make sure verification fails with the wrong key.
1525        let bad_pub_key =
1526            PrivateKey::from_pkcs8(ED25519_2_PK8, SignatureScheme::Ed25519)
1527                .unwrap()
1528                .public()
1529                .clone();
1530
1531        assert_eq!(bad_pub_key.verify(msg, &sig), Err(Error::BadSignature));
1532    }
1533
1534    #[test]
1535    fn serde_key_id() {
1536        let s =
1537            "4750eaf6878740780d6f97b12dbad079fb012bec88c78de2c380add56d3f51db";
1538        let jsn = json!(s);
1539        let parsed: KeyId =
1540            serde_json::from_str(&format!("\"{}\"", s)).unwrap();
1541        assert_eq!(parsed, KeyId::from_str(s).unwrap());
1542        let encoded = serde_json::to_value(&parsed).unwrap();
1543        assert_eq!(encoded, jsn);
1544    }
1545
1546    #[test]
1547    fn serde_signature_value() {
1548        let s =
1549            "4750eaf6878740780d6f97b12dbad079fb012bec88c78de2c380add56d3f51db";
1550        let jsn = json!(s);
1551        let parsed: SignatureValue =
1552            serde_json::from_str(&format!("\"{}\"", s)).unwrap();
1553        assert_eq!(parsed, SignatureValue::from_hex(s).unwrap());
1554        let encoded = serde_json::to_value(&parsed).unwrap();
1555        assert_eq!(encoded, jsn);
1556    }
1557
1558    #[test]
1559    fn serde_rsa_public_key() {
1560        let der = RSA_2048_SPKI;
1561        let pub_key =
1562            PublicKey::from_spki(der, SignatureScheme::RsaSsaPssSha256)
1563                .unwrap();
1564        let pem = pem::encode(&pem::Pem::new(
1565            PEM_PUBLIC_KEY.to_string(),
1566            der.to_vec(),
1567        ))
1568        .trim()
1569        .replace("\r\n", "\n")
1570        .to_string();
1571        let encoded = serde_json::to_value(&pub_key).unwrap();
1572        let jsn = json!({
1573            "keyid": "c2620e94b6ff57f433c24436013a89d403fa6934a2ee490f44f897176c2c52e9",
1574            "keytype": "rsa",
1575            "scheme": "rsassa-pss-sha256",
1576            "keyid_hash_algorithms": ["sha256", "sha512"],
1577            "keyval": {
1578                "private": "",
1579                "public": pem,
1580            }
1581        });
1582        assert_eq!(encoded, jsn);
1583        let decoded: PublicKey = serde_json::from_value(encoded).unwrap();
1584        assert_eq!(decoded, pub_key);
1585    }
1586
1587    #[test]
1588    fn de_ser_rsa_public_key_with_keyid_hash_algo() {
1589        let pem = pem::encode(&pem::Pem::new(
1590            PEM_PUBLIC_KEY.to_string(),
1591            RSA_2048_SPKI.to_vec(),
1592        ))
1593        .trim()
1594        .replace("\r\n", "\n")
1595        .to_string();
1596
1597        let original = json!({
1598            "keyid": "c2620e94b6ff57f433c24436013a89d403fa6934a2ee490f44f897176c2c52e9",
1599            "keytype": "rsa",
1600            "scheme": "rsassa-pss-sha256",
1601            "keyid_hash_algorithms": ["sha256", "sha512"],
1602            "keyval": {
1603                "private": "",
1604                "public": pem,
1605            }
1606        });
1607
1608        let decoded: PublicKey =
1609            serde_json::from_value(original.clone()).unwrap();
1610        let encoded = serde_json::to_value(&decoded).unwrap();
1611
1612        assert_eq!(original, encoded);
1613    }
1614
1615    #[test]
1616    fn de_ser_rsa_public_key_without_keyid_hash_algo() {
1617        let pem = pem::encode(&pem::Pem::new(
1618            PEM_PUBLIC_KEY.to_string(),
1619            RSA_2048_SPKI.to_vec(),
1620        ))
1621        .trim()
1622        .replace("\r\n", "\n")
1623        .to_string();
1624
1625        let original = json!({
1626            "keyid": "3733b56bfa06e9d731b561891d413569e0795c74d9c3434bc6373ff809683dde",
1627            "keytype": "rsa",
1628            "scheme": "rsassa-pss-sha256",
1629            "keyval": {
1630                "private": "",
1631                "public": pem,
1632            }
1633        });
1634
1635        let decoded: PublicKey =
1636            serde_json::from_value(original.clone()).unwrap();
1637        let encoded = serde_json::to_value(&decoded).unwrap();
1638
1639        assert_eq!(original, encoded);
1640    }
1641
1642    #[test]
1643    fn serde_ed25519_public_key() {
1644        let pub_key =
1645            PrivateKey::from_pkcs8(ED25519_1_PK8, SignatureScheme::Ed25519)
1646                .unwrap()
1647                .public()
1648                .clone();
1649
1650        let pub_key = PublicKey::from_ed25519_with_keyid_hash_algorithms(
1651            pub_key.as_bytes().to_vec(),
1652            python_sslib_compatibility_keyid_hash_algorithms(),
1653        )
1654        .unwrap();
1655        let encoded = serde_json::to_value(&pub_key).unwrap();
1656        let jsn = json!({
1657            "keyid": "a9f3ebc9b138762563a9c27b6edd439959e559709babd123e8d449ba2c18c61a",
1658            "keytype": "ed25519",
1659            "scheme": "ed25519",
1660            "keyid_hash_algorithms": ["sha256", "sha512"],
1661            "keyval": {
1662                "private": "",
1663                "public": HEXLOWER.encode(pub_key.as_bytes()),
1664            }
1665        });
1666        assert_eq!(encoded, jsn);
1667        let decoded: PublicKey = serde_json::from_value(encoded).unwrap();
1668        assert_eq!(decoded, pub_key);
1669    }
1670
1671    #[test]
1672    fn de_ser_ed25519_public_key_with_keyid_hash_algo() {
1673        let pub_key =
1674            PrivateKey::from_pkcs8(ED25519_1_PK8, SignatureScheme::Ed25519)
1675                .unwrap()
1676                .public()
1677                .clone();
1678        let pub_key = PublicKey::from_ed25519_with_keyid_hash_algorithms(
1679            pub_key.as_bytes().to_vec(),
1680            python_sslib_compatibility_keyid_hash_algorithms(),
1681        )
1682        .unwrap();
1683        let original = json!({
1684            "keyid": "a9f3ebc9b138762563a9c27b6edd439959e559709babd123e8d449ba2c18c61a",
1685            "keytype": "ed25519",
1686            "scheme": "ed25519",
1687            "keyid_hash_algorithms": ["sha256", "sha512"],
1688            "keyval": {
1689                "private": "",
1690                "public": HEXLOWER.encode(pub_key.as_bytes()),
1691            }
1692        });
1693
1694        let encoded: PublicKey =
1695            serde_json::from_value(original.clone()).unwrap();
1696        let decoded = serde_json::to_value(&encoded).unwrap();
1697
1698        assert_eq!(original, decoded);
1699    }
1700
1701    #[test]
1702    fn de_ser_ed25519_public_key_without_keyid_hash_algo() {
1703        let pub_key =
1704            PrivateKey::from_pkcs8(ED25519_1_PK8, SignatureScheme::Ed25519)
1705                .unwrap()
1706                .public()
1707                .clone();
1708        let pub_key = PublicKey::from_ed25519_with_keyid_hash_algorithms(
1709            pub_key.as_bytes().to_vec(),
1710            None,
1711        )
1712        .unwrap();
1713        let original = json!({
1714            "keyid": "e0294a3f17cc8563c3ed5fceb3bd8d3f6bfeeaca499b5c9572729ae015566554",
1715            "keytype": "ed25519",
1716            "scheme": "ed25519",
1717            "keyval": {
1718                "private": "",
1719                "public": HEXLOWER.encode(pub_key.as_bytes()),
1720            }
1721        });
1722
1723        let encoded: PublicKey =
1724            serde_json::from_value(original.clone()).unwrap();
1725        let decoded = serde_json::to_value(&encoded).unwrap();
1726
1727        assert_eq!(original, decoded);
1728    }
1729
1730    #[test]
1731    fn serde_ecdsa_public_key() {
1732        let pub_key =
1733            PrivateKey::from_pkcs8(ECDSA_PK8, SignatureScheme::EcdsaP256Sha256)
1734                .unwrap()
1735                .public()
1736                .clone();
1737        let pub_key = PublicKey::from_ecdsa_with_keyid_hash_algorithms(
1738            pub_key.as_bytes().to_vec(),
1739            python_sslib_compatibility_keyid_hash_algorithms(),
1740        )
1741        .unwrap();
1742        let encoded = serde_json::to_value(&pub_key).unwrap();
1743        let jsn = json!({
1744            "keyid": "562b12b3f14a84bfe37d9de25c64f2e98eea7ab1918366361a7e37b5ab83b5f3",
1745            "keytype": "ecdsa",
1746            "scheme": "ecdsa-sha2-nistp256",
1747            "keyid_hash_algorithms": ["sha256", "sha512"],
1748            "keyval": {
1749                "public": HEXLOWER.encode(pub_key.as_bytes()),
1750                "private": ""
1751            }
1752        });
1753        assert_eq!(encoded, jsn);
1754        let decoded: PublicKey = serde_json::from_value(encoded).unwrap();
1755        assert_eq!(decoded, pub_key);
1756    }
1757
1758    #[test]
1759    fn serde_signature() {
1760        let key =
1761            PrivateKey::from_pkcs8(ED25519_1_PK8, SignatureScheme::Ed25519)
1762                .unwrap();
1763        let msg = b"test";
1764        let sig = key.sign(msg).unwrap();
1765        let encoded = serde_json::to_value(&sig).unwrap();
1766        let jsn = json!({
1767            "keyid": "a9f3ebc9b138762563a9c27b6edd439959e559709babd123e8d449ba2c18c61a",
1768            "sig": "fe4d13b2a73c033a1de7f5107b205fc7ba0e1566cb95b92349cae6aa453\
1769                8956013bfe0f7bf977cb072bb65e8782b5f33a0573fe78816299a017ca5ba55\
1770                9e390c",
1771        });
1772        assert_eq!(encoded, jsn);
1773
1774        let decoded: Signature = serde_json::from_value(encoded).unwrap();
1775        assert_eq!(decoded, sig);
1776    }
1777
1778    #[test]
1779    fn serde_signature_without_keyid_hash_algo() {
1780        let key = PrivateKey::ed25519_from_pkcs8_with_keyid_hash_algorithms(
1781            ED25519_1_PK8,
1782            None,
1783        )
1784        .unwrap();
1785        let msg = b"test";
1786        let sig = key.sign(msg).unwrap();
1787        let encoded = serde_json::to_value(&sig).unwrap();
1788        let jsn = json!({
1789            "keyid": "e0294a3f17cc8563c3ed5fceb3bd8d3f6bfeeaca499b5c9572729ae015566554",
1790            "sig": "fe4d13b2a73c033a1de7f5107b205fc7ba0e1566cb95b92349cae6aa453\
1791                    8956013bfe0f7bf977cb072bb65e8782b5f33a0573fe78816299a017ca5ba55\
1792                    9e390c",
1793        });
1794        assert_eq!(encoded, jsn);
1795
1796        let decoded: Signature = serde_json::from_value(encoded).unwrap();
1797        assert_eq!(decoded, sig);
1798    }
1799
1800    #[test]
1801    #[cfg(not(any(target_os = "fuchsia", windows)))]
1802    fn new_rsa_key() {
1803        let bytes = PrivateKey::new(KeyType::Rsa).unwrap();
1804        let _ =
1805            PrivateKey::from_pkcs8(&bytes, SignatureScheme::RsaSsaPssSha256)
1806                .unwrap();
1807    }
1808
1809    #[test]
1810    fn new_ed25519_key() {
1811        let bytes = PrivateKey::new(KeyType::Ed25519).unwrap();
1812        let _ =
1813            PrivateKey::from_pkcs8(&bytes, SignatureScheme::Ed25519).unwrap();
1814    }
1815
1816    #[test]
1817    fn new_ecdsa_key() {
1818        let bytes = PrivateKey::new(KeyType::Ecdsa).unwrap();
1819        let _ =
1820            PrivateKey::from_pkcs8(&bytes, SignatureScheme::EcdsaP256Sha256)
1821                .unwrap();
1822    }
1823
1824    #[test]
1825    fn test_public_key_eq() {
1826        let key256 = PublicKey::from_spki(
1827            RSA_2048_SPKI,
1828            SignatureScheme::RsaSsaPssSha256,
1829        )
1830        .unwrap();
1831        let key512 = PublicKey::from_spki(
1832            RSA_2048_SPKI,
1833            SignatureScheme::RsaSsaPssSha512,
1834        )
1835        .unwrap();
1836        assert_eq!(key256, key256);
1837        assert_ne!(key256, key512);
1838    }
1839
1840    #[test]
1841    fn test_public_key_hash() {
1842        use std::hash::{BuildHasher, Hash, Hasher};
1843
1844        let key256 = PublicKey::from_spki(
1845            RSA_2048_SPKI,
1846            SignatureScheme::RsaSsaPssSha256,
1847        )
1848        .unwrap();
1849        let key512 = PublicKey::from_spki(
1850            RSA_2048_SPKI,
1851            SignatureScheme::RsaSsaPssSha512,
1852        )
1853        .unwrap();
1854
1855        let state = std::collections::hash_map::RandomState::new();
1856        let mut hasher256 = state.build_hasher();
1857        key256.hash(&mut hasher256);
1858
1859        let mut hasher512 = state.build_hasher();
1860        key512.hash(&mut hasher512);
1861
1862        assert_ne!(hasher256.finish(), hasher512.finish());
1863    }
1864
1865    #[test]
1866    fn parse_public_rsa_from_pem_spki() {
1867        let pem = str::from_utf8(&DEMO_PUBLIC_KEY).unwrap();
1868        let key =
1869            PublicKey::from_pem_spki(&pem, SignatureScheme::RsaSsaPssSha256)
1870                .unwrap();
1871        assert_eq!(key.typ, KeyType::Rsa);
1872        assert_eq!(key.scheme, SignatureScheme::RsaSsaPssSha256);
1873    }
1874
1875    #[test]
1876    fn parse_public_ed25519_from_pem_spki() {
1877        let pem = pubkey_as_pem(
1878            &PublicKey::from_ed25519(ED25519_1_PUBLIC_KEY).unwrap(),
1879        );
1880        let key =
1881            PublicKey::from_pem_spki(&pem, SignatureScheme::Ed25519).unwrap();
1882        assert_eq!(key.typ, KeyType::Ed25519);
1883        assert_eq!(key.scheme, SignatureScheme::Ed25519);
1884    }
1885
1886    #[test]
1887    fn parse_public_key_ecdsa_from_pem_spki() {
1888        let pem = str::from_utf8(&ECDSA_PUBLIC_KEY).unwrap();
1889        let public_key =
1890            PublicKey::from_pem_spki(&pem, SignatureScheme::EcdsaP256Sha256)
1891                .unwrap();
1892        assert_eq!(public_key.typ(), &KeyType::Ecdsa);
1893        assert_eq!(public_key.scheme(), &SignatureScheme::EcdsaP256Sha256);
1894    }
1895
1896    #[test]
1897    fn compatibility_keyid_with_python_in_toto() {
1898        let der = pem::parse(DEMO_PUBLIC_KEY)
1899            .expect("parse alice.pub in pem format failed");
1900        let key = PublicKey::from_spki(
1901            der.contents(),
1902            SignatureScheme::RsaSsaPssSha256,
1903        )
1904        .expect("create PublicKey failed");
1905        assert_eq!(key.key_id.0, DEMO_KEY_ID);
1906    }
1907
1908    #[test]
1909    fn compatibility_rsa_verify_with_python_in_toto() {
1910        let der = pem::parse(DEMO_PUBLIC_KEY)
1911            .expect("parse alice.pub in pem format failed");
1912        let key = PublicKey::from_spki(
1913            der.contents(),
1914            SignatureScheme::RsaSsaPssSha256,
1915        )
1916        .expect("create PublicKey failed");
1917        let meta: Metablock =
1918            serde_json::from_slice(DEMO_LAYOUT).expect("failed to deserialize");
1919        let msg = meta.metadata.to_bytes().expect("failed to canonicalize");
1920        let msg = String::from_utf8(msg)
1921            .expect("failed to parse metadata string")
1922            .replace("\\n", "\n");
1923        let sig = &meta.signatures[0];
1924        let res = key.verify(msg.as_bytes(), &sig);
1925        assert!(res.is_ok(), "{:?}", res);
1926    }
1927
1928    fn pubkey_as_pem(key: &PublicKey) -> String {
1929        pem::encode(&pem::Pem::new(
1930            PEM_PUBLIC_KEY.to_string(),
1931            key.as_spki().unwrap(),
1932        ))
1933        .trim()
1934        .replace("\r\n", "\n")
1935        .to_string()
1936    }
1937}