Skip to main content

ssh_key/
certificate.rs

1//! OpenSSH certificate support.
2
3mod builder;
4mod cert_type;
5mod field;
6mod options_map;
7mod unix_time;
8
9pub use self::{builder::Builder, cert_type::CertType, field::Field, options_map::OptionsMap};
10
11use crate::{
12    Algorithm, Comment, Error, Result, Signature,
13    public::{KeyData, SshFormat},
14};
15use alloc::{
16    string::{String, ToString},
17    vec::Vec,
18};
19use core::str::FromStr;
20use encoding::{Base64Reader, CheckedSum, Decode, Decoder, Encode, Reader, Writer};
21use signature::Verifier;
22
23#[cfg(feature = "serde")]
24use serde::{Deserialize, Serialize, de, ser};
25
26#[cfg(feature = "sha2")]
27use crate::{Fingerprint, HashAlg};
28
29#[cfg(feature = "std")]
30use {
31    self::unix_time::UnixTime,
32    std::{fs, path::Path, time::SystemTime},
33};
34
35/// Maximum number of certificate principals. Matches OpenSSH's `SSHKEY_CERT_MAX_PRINCIPALS`.
36/// <https://github.com/openssh/openssh-portable/blob/65666f4/sshkey.h#L96>
37const MAX_PRINCIPALS: usize = 256;
38
39/// OpenSSH certificate as specified in [draft-ietf-sshm-cert].
40///
41/// OpenSSH supports X.509-like certificate authorities, but using a custom encoding format.
42///
43/// The signed portion is retained verbatim when decoding and reused for signature verification
44/// and encoding. Certificates created with [`Builder`] retain the exact bytes passed to the signer.
45///
46/// <div class="warning">
47/// <b>Security Warning</b>
48///
49/// Certificates must be validated before they can be trusted!
50///
51/// The [`Certificate`] type does not automatically perform validation checks and supports parsing
52/// certificates which may potentially be invalid.
53///
54/// Just because a [`Certificate`] parses successfully does not mean that it can be trusted.
55///
56/// See "Certificate Validation" documentation below for more information on  how to properly
57/// validate certificates.
58/// </div>
59///
60/// # Certificate Validation
61///
62/// For a certificate to be trusted, the following properties MUST be validated:
63///
64/// - Certificate is signed by a trusted certificate authority (CA)
65/// - Signature over the certificate verifies successfully
66/// - Current time is within the certificate's validity window
67/// - Certificate authorizes the expected principal
68/// - All critical extensions to the certificate are recognized and validate successfully.
69///
70/// The [`Certificate::validate`] and [`Certificate::validate_at`] methods can be used to validate a
71/// certificate.
72///
73/// ## Example
74///
75/// The following example walks through how to implement the steps outlined above for validating a
76/// certificate:
77///
78#[cfg_attr(all(feature = "p256", feature = "std"), doc = " ```")]
79#[cfg_attr(not(all(feature = "p256", feature = "std")), doc = " ```ignore")]
80/// # fn main() -> Result<(), ssh_key::Error> {
81/// use ssh_key::{Certificate, Fingerprint};
82/// use std::str::FromStr;
83///
84/// // List of trusted certificate authority (CA) fingerprints
85/// let ca_fingerprints = [
86///     Fingerprint::from_str("SHA256:JQ6FV0rf7qqJHZqIj4zNH8eV0oB8KLKh9Pph3FTD98g")?
87/// ];
88///
89/// // Certificate to be validated
90/// let certificate = Certificate::from_str(
91///     "ssh-ed25519-cert-v01@openssh.com AAAAIHNzaC1lZDI1NTE5LWNlcnQtdjAxQG9wZW5zc2guY29tAAAAIE7x9ln6uZLLkfXM8iatrnAAuytVHeCznU8VlEgx7TvLAAAAILM+rvN+ot98qgEN796jTiQfZfG1KaT0PtFDJ/XFSqtiAAAAAAAAAAAAAAABAAAAFGVkMjU1MTktd2l0aC1wMjU2LWNhAAAAAAAAAABiUZm7AAAAAPTaMrsAAAAAAAAAggAAABVwZXJtaXQtWDExLWZvcndhcmRpbmcAAAAAAAAAF3Blcm1pdC1hZ2VudC1mb3J3YXJkaW5nAAAAAAAAABZwZXJtaXQtcG9ydC1mb3J3YXJkaW5nAAAAAAAAAApwZXJtaXQtcHR5AAAAAAAAAA5wZXJtaXQtdXNlci1yYwAAAAAAAAAAAAAAaAAAABNlY2RzYS1zaGEyLW5pc3RwMjU2AAAACG5pc3RwMjU2AAAAQQR8H9hzDOU0V76NkkCY7DZIgw+SqoojY6xlb91FIfpjE+UR8YkbTp5ar44ULQatFaZqQlfz8FHYTooOL5G6gHBHAAAAZAAAABNlY2RzYS1zaGEyLW5pc3RwMjU2AAAASQAAACEA/0Cwxhkac5AeNYE958j8GgvmkIESDH1TE7QYIqxsFsIAAAAgTEw8WVjlz8AnvyaKGOUELMpyFFJagtD2JFAIAJvilrc= user@example.com"
92/// )?;
93///
94/// // Perform basic certificate validation, ensuring that the certificate is
95/// // signed by a trusted certificate authority (CA) and checking that the
96/// // current system clock time is within the certificate's validity window
97/// certificate.validate(&ca_fingerprints)?;
98///
99/// // Check that the certificate includes the expected principal name
100/// // (i.e. username or hostname)
101/// // if !certificate.principals().contains(expected_principal) { return Err(...) }
102///
103/// // Check that all of the critical extensions are recognized
104/// // if !certificate.critical_options.iter().all(|critical| ...) { return Err(...) }
105///
106/// // If we've made it this far, the certificate can be trusted
107/// Ok(())
108/// # }
109/// ```
110///
111/// # Certificate Builder (SSH CA support)
112///
113/// This crate implements all of the functionality needed for a pure Rust SSH certificate authority
114/// which can build and sign OpenSSH certificates.
115///
116/// See the [`Builder`] type's documentation for more information.
117///
118/// # `serde` support
119///
120/// When the `serde` feature of this crate is enabled, this type receives impls of
121/// [`Deserialize`][`serde::Deserialize`] and [`Serialize`][`serde::Serialize`].
122///
123/// The serialization uses a binary encoding with binary formats like bincode and CBOR, and the
124/// OpenSSH string serialization when used with human-readable formats like JSON and TOML.
125///
126/// [draft-ietf-sshm-cert]: https://www.ietf.org/archive/id/draft-ietf-sshm-cert-01.html
127#[derive(Clone, Debug, Eq, Hash, PartialEq, PartialOrd, Ord)]
128pub struct Certificate {
129    /// CA-provided random bitstring of arbitrary length
130    /// (but typically 16 or 32 bytes).
131    nonce: Vec<u8>,
132
133    /// Public key data.
134    public_key: KeyData,
135
136    /// Serial number.
137    serial: u64,
138
139    /// Certificate type.
140    cert_type: CertType,
141
142    /// Key ID.
143    key_id: String,
144
145    /// Valid principals.
146    valid_principals: Vec<String>,
147
148    /// Valid after.
149    valid_after: u64,
150
151    /// Valid before.
152    valid_before: u64,
153
154    /// Critical options.
155    critical_options: OptionsMap,
156
157    /// Extensions.
158    extensions: OptionsMap,
159
160    /// Reserved field.
161    reserved: Vec<u8>,
162
163    /// Signature key of signing CA.
164    signature_key: KeyData,
165
166    /// Signature over the certificate.
167    signature: Signature,
168
169    /// Comment on the certificate.
170    comment: Comment,
171
172    /// Certificate algorithm, including any RSA hash selection in the wire identifier.
173    algorithm: Algorithm,
174
175    /// Exact signed bytes, from the initial algorithm string through the signature key.
176    tbs_certificate: Vec<u8>,
177}
178
179impl Certificate {
180    /// Parse an OpenSSH-formatted certificate.
181    ///
182    /// OpenSSH-formatted certificates look like the following
183    /// (i.e. similar to OpenSSH public keys with `-cert-v01@openssh.com`):
184    ///
185    /// ```text
186    /// ssh-ed25519-cert-v01@openssh.com AAAAIHNzaC1lZDI1NTE5LWNlc...8REbCaAw== user@example.com
187    /// ```
188    ///
189    /// # Errors
190    /// - Returns [`Error::AlgorithmUnknown`] in the event of an algorithm mismatch.
191    /// - Returns [`Error::Encoding`] in the event of an encoding error.
192    /// - Returns [`Error::CertificateFieldInvalid`] if a certificate field is invalid.
193    pub fn from_openssh(certificate_str: &str) -> Result<Self> {
194        let encapsulation = SshFormat::decode(certificate_str.trim_end().as_bytes())?;
195        let mut reader = Decoder::new(Base64Reader::new(encapsulation.base64_data)?)?;
196        let mut cert = Certificate::decode(&mut reader)?;
197
198        // Verify that the algorithm in the Base64-encoded data matches the text
199        if encapsulation.algorithm_id != cert.algorithm.to_certificate_type() {
200            return Err(Error::AlgorithmUnknown);
201        }
202
203        cert.comment = Comment::from(encapsulation.comment);
204        Ok(reader.finish(cert)?)
205    }
206
207    /// Parse a raw binary OpenSSH certificate.
208    ///
209    /// # Errors
210    /// - Returns [`Error::Encoding`] in the event of an encoding error.
211    /// - Returns [`Error::CertificateFieldInvalid`] if a certificate field is invalid.
212    pub fn from_bytes(bytes: &[u8]) -> Result<Self> {
213        let mut reader = Decoder::new(bytes)?;
214        let cert = Certificate::decode(&mut reader)?;
215        Ok(reader.finish(cert)?)
216    }
217
218    /// Encode OpenSSH certificate to a [`String`].
219    ///
220    /// # Errors
221    /// Returns [`Error::Encoding`] in the event of an encoding error.
222    pub fn to_openssh(&self) -> Result<String> {
223        SshFormat::encode_string(&self.algorithm.to_certificate_type(), self, self.comment())
224    }
225
226    /// Serialize OpenSSH certificate as raw bytes.
227    ///
228    /// # Errors
229    /// Returns [`Error::Encoding`] in the event of an encoding error.
230    pub fn to_bytes(&self) -> Result<Vec<u8>> {
231        Ok(self.encode_vec()?)
232    }
233
234    /// Read OpenSSH certificate from a file.
235    ///
236    /// # Errors
237    /// - Returns [`Error::Io`] in the event of an I/O error.
238    /// - Returns [`Error::Encoding`] in the event of an encoding error.
239    #[cfg(feature = "std")]
240    pub fn read_file(path: &Path) -> Result<Self> {
241        let input = fs::read_to_string(path)?;
242        Self::from_openssh(&input)
243    }
244
245    /// Write OpenSSH certificate to a file.
246    ///
247    /// # Errors
248    /// - Returns [`Error::Io`] in the event of an I/O error.
249    /// - Returns [`Error::Encoding`] in the event of an encoding error.
250    #[cfg(feature = "std")]
251    pub fn write_file(&self, path: &Path) -> Result<()> {
252        let encoded = self.to_openssh()?;
253        fs::write(path, encoded.as_bytes())?;
254        Ok(())
255    }
256
257    /// Get the algorithm identified by this certificate.
258    #[must_use]
259    pub fn algorithm(&self) -> Algorithm {
260        self.algorithm.clone()
261    }
262
263    /// Get the comment on this certificate.
264    #[must_use]
265    pub fn comment(&self) -> &str {
266        self.comment.as_str_lossy()
267    }
268
269    /// Set the comment on this certificate.
270    pub fn set_comment(&mut self, comment: impl Into<Comment>) {
271        self.comment = comment.into();
272    }
273
274    /// Nonces are a CA-provided random bitstring of arbitrary length
275    /// (but typically 16 or 32 bytes).
276    ///
277    /// It's included to make attacks that depend on inducing collisions in the
278    /// signature hash infeasible.
279    #[must_use]
280    pub fn nonce(&self) -> &[u8] {
281        &self.nonce
282    }
283
284    /// Get this certificate's public key data.
285    #[must_use]
286    pub fn public_key(&self) -> &KeyData {
287        &self.public_key
288    }
289
290    /// Optional certificate serial number set by the CA to provide an
291    /// abbreviated way to refer to certificates from that CA.
292    ///
293    /// If a CA does not wish to number its certificates, it must set this
294    /// field to zero.
295    #[must_use]
296    pub fn serial(&self) -> u64 {
297        self.serial
298    }
299
300    /// Specifies whether this certificate is for identification of a user or
301    /// a host.
302    #[must_use]
303    pub fn cert_type(&self) -> CertType {
304        self.cert_type
305    }
306
307    /// Key IDs are a free-form text field that is filled in by the CA at the
308    /// time of signing.
309    ///
310    /// The intention is that the contents of this field are used to identify
311    /// the identity principal in log messages.
312    #[must_use]
313    pub fn key_id(&self) -> &str {
314        &self.key_id
315    }
316
317    /// List of 0 to 256 principals for which this certificate is valid.
318    ///
319    /// Principals are hostnames for host certificates and usernames for user
320    /// certificates.
321    ///
322    /// As a special case, a zero-length "valid principals" field means the
323    /// certificate is valid for any principal of the specified type.
324    #[must_use]
325    pub fn valid_principals(&self) -> &[String] {
326        &self.valid_principals
327    }
328
329    /// Valid after (Unix time), i.e. certificate issuance time.
330    #[must_use]
331    pub fn valid_after(&self) -> u64 {
332        self.valid_after
333    }
334
335    /// Valid before (Unix time), i.e. certificate expiration time.
336    #[must_use]
337    pub fn valid_before(&self) -> u64 {
338        self.valid_before
339    }
340
341    /// Valid after (system time), i.e. certificate issuance time.
342    ///
343    /// # Returns
344    /// - `Some` if the `u64` value is a valid `SystemTime`
345    /// - `None` if it is not (i.e. overflows `i64`)
346    #[cfg(feature = "std")]
347    pub fn valid_after_time(&self) -> Option<SystemTime> {
348        UnixTime::try_from(self.valid_after).ok().map(Into::into)
349    }
350
351    /// Valid before (system time), i.e. certificate expiration time.
352    ///
353    /// # Returns
354    /// - `Some` if the `u64` value is a valid `SystemTime`
355    /// - `None` if it is not (i.e. overflows `i64`, effectively never-expiring)
356    #[cfg(feature = "std")]
357    pub fn valid_before_time(&self) -> Option<SystemTime> {
358        UnixTime::try_from(self.valid_before).ok().map(Into::into)
359    }
360
361    /// The critical options section of the certificate specifies zero or more
362    /// options on the certificate's validity.
363    ///
364    /// Each named option may only appear once in a certificate.
365    ///
366    /// All options are "critical"; if an implementation does not recognize an
367    /// option, then the validating party should refuse to accept the
368    /// certificate.
369    #[must_use]
370    pub fn critical_options(&self) -> &OptionsMap {
371        &self.critical_options
372    }
373
374    /// The extensions section of the certificate specifies zero or more
375    /// non-critical certificate extensions.
376    ///
377    /// If an implementation does not recognise an extension, then it should
378    /// ignore it.
379    #[must_use]
380    pub fn extensions(&self) -> &OptionsMap {
381        &self.extensions
382    }
383
384    /// Signature key of signing CA.
385    #[must_use]
386    pub fn signature_key(&self) -> &KeyData {
387        &self.signature_key
388    }
389
390    /// Signature computed over all preceding fields from the initial string up
391    /// to, and including the signature key.
392    #[must_use]
393    pub fn signature(&self) -> &Signature {
394        &self.signature
395    }
396
397    /// Perform certificate validation using the system clock to check that
398    /// the current time is within the certificate's validity window.
399    ///
400    /// <div class="warning">
401    /// <b>Security Warning: Some Assembly Required</b>
402    ///
403    /// See [`Certificate::validate_at`] documentation for important notes on how to properly
404    /// validate certificates!
405    /// </div>
406    ///
407    /// # Errors
408    /// Returns [`Error::CertificateValidation`] if the certificate failed to validate
409    #[cfg(all(feature = "sha2", feature = "std"))]
410    pub fn validate<'a, I>(&self, ca_fingerprints: I) -> Result<()>
411    where
412        I: IntoIterator<Item = &'a Fingerprint>,
413    {
414        self.validate_at(UnixTime::now()?.into(), ca_fingerprints)
415    }
416
417    /// Perform certificate validation.
418    ///
419    /// Checks for the following:
420    ///
421    /// - Specified Unix timestamp is within the certificate's valid range
422    /// - Certificate's signature validates against the public key included in the certificate
423    /// - Fingerprint of the public key included in the certificate matches one of the trusted
424    ///   certificate authority (CA) fingerprints provided in the `ca_fingerprints` parameter.
425    ///
426    /// NOTE: only SHA-256 fingerprints are supported at this time.
427    ///
428    /// <div class="warning">
429    /// <b>Security Warning: Some Assembly Required</b>
430    ///
431    /// This method does not perform the full set of validation checks needed to determine if a
432    /// certificate is to be trusted.
433    ///
434    /// If this method succeeds, the following properties still need to be checked to ensure the
435    /// certificate is valid:
436    ///
437    /// - `valid_principals` is empty or contains the expected principal.
438    /// - `critical_options` is empty or contains *only* options which are recognized, and that the
439    ///   recognized options are all valid.
440    /// </div>
441    ///
442    /// # Errors
443    /// Returns [`Error::CertificateValidation`] if the certificate failed to validate
444    #[cfg(feature = "sha2")]
445    pub fn validate_at<'a, I>(&self, unix_timestamp: u64, ca_fingerprints: I) -> Result<()>
446    where
447        I: IntoIterator<Item = &'a Fingerprint>,
448    {
449        self.verify_signature()?;
450
451        // TODO(tarcieri): support non SHA-256 public key fingerprints?
452        let cert_fingerprint = self.signature_key.fingerprint(HashAlg::Sha256);
453
454        if !ca_fingerprints.into_iter().any(|f| f == &cert_fingerprint) {
455            return Err(Error::CertificateValidation);
456        }
457
458        // From draft-ietf-sshm-cert:
459        //
460        //  "valid after" and "valid before" specify a validity period for the
461        //  certificate. Each represents a time in seconds since 1970-01-01
462        //  A certificate is considered valid if:
463        //
464        //     valid after <= current time < valid before
465        if self.valid_after <= unix_timestamp && unix_timestamp < self.valid_before {
466            Ok(())
467        } else {
468            Err(Error::CertificateValidation)
469        }
470    }
471
472    /// Verify the signature on the certificate against the public key in the
473    /// certificate.
474    ///
475    /// <div class="warning">
476    /// <b>Security Warning: DON'T USE THIS!</b>
477    ///
478    /// This function alone does not provide any security guarantees whatsoever.
479    ///
480    /// It verifies the signature in the certificate matches the CA public key in the certificate,
481    /// but does not ensure the CA is trusted.
482    ///
483    /// It is public only for testing purposes, and deliberately hidden from the documentation for
484    /// that reason.
485    /// </div>
486    #[doc(hidden)]
487    pub fn verify_signature(&self) -> Result<()> {
488        self.signature_key
489            .verify(&self.tbs_certificate, &self.signature)
490            .map_err(|_| Error::CertificateValidation)
491    }
492
493    /// Encode the fields of a newly built certificate before signing it.
494    fn encode_tbs(&self, writer: &mut impl Writer) -> encoding::Result<()> {
495        self.algorithm.to_certificate_type().encode(writer)?;
496        self.nonce.encode(writer)?;
497        self.public_key.encode_key_data(writer)?;
498        self.serial.encode(writer)?;
499        self.cert_type.encode(writer)?;
500        self.key_id.encode(writer)?;
501        self.valid_principals.encode(writer)?;
502        self.valid_after.encode(writer)?;
503        self.valid_before.encode(writer)?;
504        self.critical_options.encode(writer)?;
505        self.extensions.encode(writer)?;
506        self.reserved.encode(writer)?;
507        self.signature_key.encode_prefixed(writer)
508    }
509
510    /// Decode [`Certificate`] for the specified algorithm.
511    ///
512    /// The initial algorithm string has already been consumed. Its encoding is supplied by
513    /// `algorithm.to_certificate_type()`; the remaining signed bytes are retained verbatim.
514    ///
515    /// # Errors
516    /// - Returns [`Error::Encoding`] in the event of an encoding error.
517    /// - Returns [`Error::CertificateFieldInvalid`] if a certificate field is invalid.
518    pub fn decode_as(reader: &mut Decoder<impl Reader>, algorithm: Algorithm) -> Result<Self> {
519        Self::decode_inner(reader, Some(algorithm))
520    }
521
522    fn decode_inner(
523        reader: &mut Decoder<impl Reader>,
524        algorithm: Option<Algorithm>,
525    ) -> Result<Self> {
526        let mut source = reader.clone();
527        let mut tbs = Vec::new();
528        let algorithm = match algorithm {
529            Some(algorithm) => {
530                // The caller already consumed the algorithm string.
531                algorithm.to_certificate_type().encode(&mut tbs)?;
532                algorithm
533            }
534            None => Algorithm::new_certificate(&String::decode(reader)?)?,
535        };
536
537        Ok(Self {
538            nonce: Vec::decode(reader)?,
539            public_key: KeyData::decode_as(reader, algorithm.clone())?,
540            serial: u64::decode(reader)?,
541            cert_type: CertType::decode(reader)?,
542            key_id: String::decode(reader)?,
543            valid_principals: decode_principals(reader)?,
544            valid_after: u64::decode(reader)?,
545            valid_before: u64::decode(reader)?,
546            critical_options: OptionsMap::decode(reader)?,
547            extensions: OptionsMap::decode(reader)?,
548            reserved: Vec::decode(reader)?,
549            signature_key: decode_signature_key(reader)?,
550            tbs_certificate: {
551                // The signature covers everything consumed through the signature key.
552                let len = source.remaining_len() - reader.remaining_len();
553                let start = tbs.len();
554                tbs.try_reserve_exact(len).map_err(encoding::Error::from)?;
555                tbs.resize(start + len, 0);
556                source.read(&mut tbs[start..])?;
557                tbs
558            },
559            signature: reader.read_prefixed(Signature::decode)?,
560            comment: Comment::default(),
561            algorithm,
562        })
563    }
564}
565
566/// Enforces `MAX_PRINCIPALS`.
567fn decode_principals(reader: &mut Decoder<impl Reader>) -> Result<Vec<String>> {
568    reader.read_prefixed(|reader| {
569        let mut principals = Vec::new();
570
571        while !reader.is_finished() {
572            if principals.len() >= MAX_PRINCIPALS {
573                return Err(Field::ValidPrincipals.invalid_error());
574            }
575
576            principals.try_reserve(1).map_err(encoding::Error::from)?;
577            principals.push(String::decode(reader)?);
578        }
579
580        Ok(principals)
581    })
582}
583
584/// From draft-ietf-sshm-cert-01 ยง2.1.1:
585/// > Implementations MUST NOT accept certificate keys as CA keys
586///
587/// See: <https://www.ietf.org/archive/id/draft-ietf-sshm-cert-01.html#section-2.1.1>
588fn decode_signature_key(reader: &mut Decoder<impl Reader>) -> Result<KeyData> {
589    reader.read_prefixed(|reader| {
590        let algorithm = Algorithm::decode(reader)?;
591
592        if Algorithm::new_certificate(algorithm.as_str()).is_ok() {
593            return Err(Field::SignatureKey.invalid_error());
594        }
595
596        KeyData::decode_as(reader, algorithm)
597    })
598}
599
600impl Decode for Certificate {
601    type Error = Error;
602
603    fn decode(reader: &mut Decoder<impl Reader>) -> Result<Self> {
604        Self::decode_inner(reader, None)
605    }
606}
607
608impl Encode for Certificate {
609    fn encoded_len(&self) -> encoding::Result<usize> {
610        [
611            self.tbs_certificate.len(),
612            self.signature.encoded_len_prefixed()?,
613        ]
614        .checked_sum()
615    }
616
617    fn encode(&self, writer: &mut impl Writer) -> encoding::Result<()> {
618        writer.write(&self.tbs_certificate)?;
619        self.signature.encode_prefixed(writer)
620    }
621}
622
623impl FromStr for Certificate {
624    type Err = Error;
625
626    fn from_str(s: &str) -> Result<Self> {
627        Self::from_openssh(s)
628    }
629}
630
631#[allow(
632    clippy::to_string_trait_impl,
633    reason = "`SshFormat` lacks `core::fmt` support"
634)]
635impl ToString for Certificate {
636    fn to_string(&self) -> String {
637        self.to_openssh().expect("SSH certificate encoding error")
638    }
639}
640
641#[cfg(feature = "serde")]
642impl<'de> Deserialize<'de> for Certificate {
643    fn deserialize<D>(deserializer: D) -> core::result::Result<Self, D::Error>
644    where
645        D: de::Deserializer<'de>,
646    {
647        if deserializer.is_human_readable() {
648            let string = String::deserialize(deserializer)?;
649            Self::from_openssh(&string).map_err(de::Error::custom)
650        } else {
651            let bytes = Vec::<u8>::deserialize(deserializer)?;
652            Self::from_bytes(&bytes).map_err(de::Error::custom)
653        }
654    }
655}
656
657#[cfg(feature = "serde")]
658impl Serialize for Certificate {
659    fn serialize<S>(&self, serializer: S) -> core::result::Result<S::Ok, S::Error>
660    where
661        S: ser::Serializer,
662    {
663        if serializer.is_human_readable() {
664            self.to_openssh()
665                .map_err(ser::Error::custom)?
666                .serialize(serializer)
667        } else {
668            self.to_bytes()
669                .map_err(ser::Error::custom)?
670                .serialize(serializer)
671        }
672    }
673}