Skip to main content

ssh_key/public/
key_data.rs

1//! Public key data.
2
3use super::{Ed25519PublicKey, SkEd25519};
4use crate::{Algorithm, Error, Result};
5use encoding::{CheckedSum, Decode, Decoder, Encode, Reader, Writer};
6
7#[cfg(feature = "alloc")]
8use {
9    super::{DsaPublicKey, OpaquePublicKey, RsaPublicKey},
10    crate::Certificate,
11    alloc::boxed::Box,
12};
13
14#[cfg(feature = "ecdsa")]
15use super::{EcdsaPublicKey, SkEcdsaSha2NistP256};
16
17#[cfg(all(feature = "mldsa", feature = "ed25519"))]
18use super::MlDsa44Ed25519PublicKey;
19#[cfg(all(feature = "mldsa", feature = "p384"))]
20use super::MlDsa87P384PublicKey;
21
22#[cfg(feature = "sha2")]
23use crate::{Fingerprint, HashAlg};
24
25/// Public key data.
26#[derive(Clone, Debug, Eq, Hash, PartialEq, PartialOrd, Ord)]
27#[non_exhaustive]
28pub enum KeyData {
29    /// Digital Signature Algorithm (DSA) public key data.
30    #[cfg(feature = "alloc")]
31    Dsa(DsaPublicKey),
32
33    /// Elliptic Curve Digital Signature Algorithm (ECDSA) public key data.
34    #[cfg(feature = "ecdsa")]
35    Ecdsa(EcdsaPublicKey),
36
37    /// Ed25519 public key data.
38    Ed25519(Ed25519PublicKey),
39
40    /// RSA public key data.
41    #[cfg(feature = "alloc")]
42    Rsa(RsaPublicKey),
43
44    /// MLDSA44-Ed25519 public key data.
45    #[cfg(all(feature = "mldsa", feature = "ed25519"))]
46    MlDsa44Ed25519(MlDsa44Ed25519PublicKey),
47
48    /// MLDSA87-P384 public key data.
49    #[cfg(all(feature = "mldsa", feature = "p384"))]
50    MlDsa87P384(MlDsa87P384PublicKey),
51
52    /// Security Key (FIDO/U2F) using ECDSA/NIST P-256 as specified in [PROTOCOL.u2f].
53    ///
54    /// [PROTOCOL.u2f]: https://cvsweb.openbsd.org/src/usr.bin/ssh/PROTOCOL.u2f?annotate=HEAD
55    #[cfg(feature = "ecdsa")]
56    SkEcdsaSha2NistP256(SkEcdsaSha2NistP256),
57
58    /// Security Key (FIDO/U2F) using Ed25519 as specified in [PROTOCOL.u2f].
59    ///
60    /// [PROTOCOL.u2f]: https://cvsweb.openbsd.org/src/usr.bin/ssh/PROTOCOL.u2f?annotate=HEAD
61    SkEd25519(SkEd25519),
62
63    /// Certificate key as specified in [draft-ietf-sshm-cert].
64    ///
65    /// [draft-ietf-sshm-cert]: https://www.ietf.org/archive/id/draft-ietf-sshm-cert-01.html
66    #[cfg(feature = "alloc")]
67    Certificate(Box<Certificate>),
68
69    /// Opaque public key data.
70    #[cfg(feature = "alloc")]
71    Other(OpaquePublicKey),
72}
73
74impl KeyData {
75    /// Get the [`Algorithm`] for this public key.
76    #[must_use]
77    pub fn algorithm(&self) -> Algorithm {
78        match self {
79            #[cfg(feature = "alloc")]
80            Self::Dsa(_) => Algorithm::Dsa,
81            #[cfg(feature = "ecdsa")]
82            Self::Ecdsa(key) => key.algorithm(),
83            Self::Ed25519(_) => Algorithm::Ed25519,
84            #[cfg(feature = "alloc")]
85            Self::Rsa(_) => Algorithm::Rsa { hash: None },
86            #[cfg(all(feature = "mldsa", feature = "ed25519"))]
87            Self::MlDsa44Ed25519(key) => key.algorithm(),
88            #[cfg(all(feature = "mldsa", feature = "p384"))]
89            Self::MlDsa87P384(key) => key.algorithm(),
90            #[cfg(feature = "ecdsa")]
91            Self::SkEcdsaSha2NistP256(_) => Algorithm::SkEcdsaSha2NistP256,
92            Self::SkEd25519(_) => Algorithm::SkEd25519,
93            #[cfg(feature = "alloc")]
94            Self::Certificate(cert) => cert.algorithm(),
95            #[cfg(feature = "alloc")]
96            Self::Other(key) => key.algorithm(),
97        }
98    }
99
100    /// Get DSA public key if this key is the correct type.
101    #[cfg(feature = "alloc")]
102    #[must_use]
103    pub fn dsa(&self) -> Option<&DsaPublicKey> {
104        match self {
105            Self::Dsa(key) => Some(key),
106            _ => None,
107        }
108    }
109
110    /// Get ECDSA public key if this key is the correct type.
111    #[cfg(feature = "ecdsa")]
112    #[must_use]
113    pub fn ecdsa(&self) -> Option<&EcdsaPublicKey> {
114        match self {
115            Self::Ecdsa(key) => Some(key),
116            _ => None,
117        }
118    }
119
120    /// Get Ed25519 public key if this key is the correct type.
121    #[must_use]
122    pub fn ed25519(&self) -> Option<&Ed25519PublicKey> {
123        match self {
124            Self::Ed25519(key) => Some(key),
125            #[allow(unreachable_patterns)]
126            _ => None,
127        }
128    }
129
130    /// Compute key fingerprint.
131    ///
132    /// Use [`Default::default()`] to use the default hash function (SHA-256).
133    #[cfg(feature = "sha2")]
134    #[must_use]
135    pub fn fingerprint(&self, hash_alg: HashAlg) -> Fingerprint {
136        Fingerprint::new(hash_alg, self)
137    }
138
139    /// Get RSA public key if this key is the correct type.
140    #[cfg(feature = "alloc")]
141    #[must_use]
142    pub fn rsa(&self) -> Option<&RsaPublicKey> {
143        match self {
144            Self::Rsa(key) => Some(key),
145            _ => None,
146        }
147    }
148
149    /// Get MLDSA44-Ed25519 public key if this key is the correct type.
150    #[cfg(all(feature = "mldsa", feature = "ed25519"))]
151    #[must_use]
152    pub fn mldsa44_ed25519(&self) -> Option<&MlDsa44Ed25519PublicKey> {
153        match self {
154            Self::MlDsa44Ed25519(key) => Some(key),
155            _ => None,
156        }
157    }
158
159    /// Get MLDSA87-P384 public key if this key is the correct type.
160    #[cfg(all(feature = "mldsa", feature = "p384"))]
161    #[must_use]
162    pub fn mldsa87_p384(&self) -> Option<&MlDsa87P384PublicKey> {
163        match self {
164            Self::MlDsa87P384(key) => Some(key),
165            _ => None,
166        }
167    }
168
169    /// Get FIDO/U2F ECDSA/NIST P-256 public key if this key is the correct type.
170    #[cfg(feature = "ecdsa")]
171    #[must_use]
172    pub fn sk_ecdsa_p256(&self) -> Option<&SkEcdsaSha2NistP256> {
173        match self {
174            Self::SkEcdsaSha2NistP256(sk) => Some(sk),
175            _ => None,
176        }
177    }
178
179    /// Get FIDO/U2F Ed25519 public key if this key is the correct type.
180    #[must_use]
181    pub fn sk_ed25519(&self) -> Option<&SkEd25519> {
182        match self {
183            Self::SkEd25519(sk) => Some(sk),
184            _ => None,
185        }
186    }
187
188    /// Get the custom, opaque public key if this key is the correct type.
189    #[cfg(feature = "alloc")]
190    #[must_use]
191    pub fn other(&self) -> Option<&OpaquePublicKey> {
192        match self {
193            Self::Other(key) => Some(key),
194            _ => None,
195        }
196    }
197
198    /// Get the certificate if this key is the correct type.
199    #[cfg(feature = "alloc")]
200    #[must_use]
201    pub fn certificate(&self) -> Option<&Certificate> {
202        match self {
203            Self::Certificate(certificate) => Some(certificate.as_ref()),
204            _ => None,
205        }
206    }
207
208    /// Get the certificate, consuming the [`KeyData`], if this key is the correct type.
209    #[cfg(feature = "alloc")]
210    #[must_use]
211    pub fn into_certificate(self) -> Option<Certificate> {
212        match self {
213            Self::Certificate(certificate) => Some(*certificate),
214            _ => None,
215        }
216    }
217
218    /// Is this key a DSA key?
219    #[cfg(feature = "alloc")]
220    #[must_use]
221    pub fn is_dsa(&self) -> bool {
222        matches!(self, Self::Dsa(_))
223    }
224
225    /// Is this key an ECDSA key?
226    #[cfg(feature = "ecdsa")]
227    #[must_use]
228    pub fn is_ecdsa(&self) -> bool {
229        matches!(self, Self::Ecdsa(_))
230    }
231
232    /// Is this key an Ed25519 key?
233    #[must_use]
234    pub fn is_ed25519(&self) -> bool {
235        matches!(self, Self::Ed25519(_))
236    }
237
238    /// Is this key an RSA key?
239    #[cfg(feature = "alloc")]
240    #[must_use]
241    pub fn is_rsa(&self) -> bool {
242        matches!(self, Self::Rsa(_))
243    }
244
245    /// Is this key an ML-DSA key?
246    #[cfg(all(feature = "mldsa", feature = "ed25519"))]
247    #[must_use]
248    pub fn is_mldsa44_ed25519(&self) -> bool {
249        matches!(self, Self::MlDsa44Ed25519(_))
250    }
251
252    /// Is this key an ML-DSA-87/P-384 composite key?
253    #[cfg(all(feature = "mldsa", feature = "p384"))]
254    #[must_use]
255    pub fn is_mldsa87_p384(&self) -> bool {
256        matches!(self, Self::MlDsa87P384(_))
257    }
258
259    /// Is this key a FIDO/U2F ECDSA/NIST P-256 key?
260    #[cfg(feature = "ecdsa")]
261    #[must_use]
262    pub fn is_sk_ecdsa_p256(&self) -> bool {
263        matches!(self, Self::SkEcdsaSha2NistP256(_))
264    }
265
266    /// Is this key a FIDO/U2F Ed25519 key?
267    #[must_use]
268    pub fn is_sk_ed25519(&self) -> bool {
269        matches!(self, Self::SkEd25519(_))
270    }
271
272    /// Is this a key with a custom algorithm?
273    #[cfg(feature = "alloc")]
274    #[must_use]
275    pub fn is_other(&self) -> bool {
276        matches!(self, Self::Other(_))
277    }
278
279    /// Is this a certificate?
280    #[cfg(feature = "alloc")]
281    #[must_use]
282    pub fn is_certificate(&self) -> bool {
283        matches!(self, Self::Certificate(_))
284    }
285
286    /// Decode [`KeyData`] for the specified algorithm.
287    ///
288    /// # Errors
289    /// - Returns [`Error::AlgorithmUnknown`] if the provided `algorithm` is unknown or unsupported
290    ///   by this library.
291    /// - Returns [`Error::Encoding`] in the event of an encoding error.
292    pub fn decode_as(reader: &mut Decoder<impl Reader>, algorithm: Algorithm) -> Result<Self> {
293        match algorithm {
294            #[cfg(feature = "alloc")]
295            Algorithm::Dsa => DsaPublicKey::decode(reader).map(Self::Dsa),
296            #[cfg(feature = "ecdsa")]
297            Algorithm::Ecdsa { curve } => match EcdsaPublicKey::decode(reader)? {
298                key if key.curve() == curve => Ok(Self::Ecdsa(key)),
299                _ => Err(Error::AlgorithmUnknown),
300            },
301            Algorithm::Ed25519 => Ed25519PublicKey::decode(reader).map(Self::Ed25519),
302            #[cfg(feature = "alloc")]
303            Algorithm::Rsa { .. } => RsaPublicKey::decode(reader).map(Self::Rsa),
304            #[cfg(all(feature = "mldsa", feature = "ed25519"))]
305            Algorithm::MlDsa44Ed25519 => {
306                MlDsa44Ed25519PublicKey::decode(reader).map(Self::MlDsa44Ed25519)
307            }
308            #[cfg(all(feature = "mldsa", feature = "p384"))]
309            Algorithm::MlDsa87P384 => MlDsa87P384PublicKey::decode(reader).map(Self::MlDsa87P384),
310            #[cfg(feature = "ecdsa")]
311            Algorithm::SkEcdsaSha2NistP256 => {
312                SkEcdsaSha2NistP256::decode(reader).map(Self::SkEcdsaSha2NistP256)
313            }
314            Algorithm::SkEd25519 => SkEd25519::decode(reader).map(Self::SkEd25519),
315            #[cfg(feature = "alloc")]
316            Algorithm::Other(_) => OpaquePublicKey::decode_as(reader, algorithm).map(Self::Other),
317            #[allow(unreachable_patterns)]
318            _ => Err(Error::AlgorithmUnknown),
319        }
320    }
321
322    /// Decode [`KeyData`] as a certificate with the specified algorithm.
323    ///
324    /// # Errors
325    /// Propagates errors from [`Certificate::decode_as`].
326    #[cfg(feature = "alloc")]
327    pub fn decode_as_certificate(
328        reader: &mut Decoder<impl Reader>,
329        algorithm: Algorithm,
330    ) -> Result<Self> {
331        Certificate::decode_as(reader, algorithm).map(|cert| Self::Certificate(Box::new(cert)))
332    }
333
334    /// Get the encoded length of this key data without a leading algorithm
335    /// identifier.
336    pub(crate) fn encoded_key_data_len(&self) -> encoding::Result<usize> {
337        match self {
338            #[cfg(feature = "alloc")]
339            Self::Dsa(key) => key.encoded_len(),
340            #[cfg(feature = "ecdsa")]
341            Self::Ecdsa(key) => key.encoded_len(),
342            Self::Ed25519(key) => key.encoded_len(),
343            #[cfg(feature = "alloc")]
344            Self::Rsa(key) => key.encoded_len(),
345            #[cfg(all(feature = "mldsa", feature = "ed25519"))]
346            Self::MlDsa44Ed25519(key) => key.encoded_len(),
347            #[cfg(all(feature = "mldsa", feature = "p384"))]
348            Self::MlDsa87P384(key) => key.encoded_len(),
349            #[cfg(feature = "ecdsa")]
350            Self::SkEcdsaSha2NistP256(sk) => sk.encoded_len(),
351            Self::SkEd25519(sk) => sk.encoded_len(),
352            #[cfg(feature = "alloc")]
353            Self::Certificate(cert) => cert.encoded_len(),
354            #[cfg(feature = "alloc")]
355            Self::Other(other) => other.key.encoded_len(),
356        }
357    }
358
359    /// Encode the key data without a leading algorithm identifier.
360    pub(crate) fn encode_key_data(&self, writer: &mut impl Writer) -> encoding::Result<()> {
361        match self {
362            #[cfg(feature = "alloc")]
363            Self::Dsa(key) => key.encode(writer),
364            #[cfg(feature = "ecdsa")]
365            Self::Ecdsa(key) => key.encode(writer),
366            Self::Ed25519(key) => key.encode(writer),
367            #[cfg(feature = "alloc")]
368            Self::Rsa(key) => key.encode(writer),
369            #[cfg(all(feature = "mldsa", feature = "ed25519"))]
370            Self::MlDsa44Ed25519(key) => key.encode(writer),
371            #[cfg(all(feature = "mldsa", feature = "p384"))]
372            Self::MlDsa87P384(key) => key.encode(writer),
373            #[cfg(feature = "ecdsa")]
374            Self::SkEcdsaSha2NistP256(sk) => sk.encode(writer),
375            Self::SkEd25519(sk) => sk.encode(writer),
376            #[cfg(feature = "alloc")]
377            Self::Certificate(cert) => cert.encode(writer),
378            #[cfg(feature = "alloc")]
379            Self::Other(other) => other.key.encode(writer),
380        }
381    }
382}
383
384impl Decode for KeyData {
385    type Error = Error;
386
387    fn decode(reader: &mut Decoder<impl Reader>) -> Result<Self> {
388        let algorithm = Algorithm::decode(reader)?;
389        #[cfg(feature = "alloc")]
390        if let Algorithm::Other(name) = &algorithm {
391            if let Ok(certificate_algorithm) = Algorithm::new_certificate(name.as_str()) {
392                return Self::decode_as_certificate(reader, certificate_algorithm);
393            }
394        }
395        Self::decode_as(reader, algorithm)
396    }
397}
398
399impl Encode for KeyData {
400    fn encoded_len(&self) -> encoding::Result<usize> {
401        #[cfg(feature = "alloc")]
402        if self.is_certificate() {
403            // Certificate encodes its own Algorithm
404            return self.encoded_key_data_len();
405        }
406
407        [
408            self.algorithm().encoded_len()?,
409            self.encoded_key_data_len()?,
410        ]
411        .checked_sum()
412    }
413
414    fn encode(&self, writer: &mut impl Writer) -> encoding::Result<()> {
415        #[cfg(feature = "alloc")]
416        if self.is_certificate() {
417            // Certificate encodes its own Algorithm
418            return self.encode_key_data(writer);
419        }
420
421        self.algorithm().encode(writer)?;
422        self.encode_key_data(writer)
423    }
424}
425
426#[cfg(feature = "alloc")]
427impl From<DsaPublicKey> for KeyData {
428    fn from(public_key: DsaPublicKey) -> KeyData {
429        Self::Dsa(public_key)
430    }
431}
432
433#[cfg(feature = "ecdsa")]
434impl From<EcdsaPublicKey> for KeyData {
435    fn from(public_key: EcdsaPublicKey) -> KeyData {
436        Self::Ecdsa(public_key)
437    }
438}
439
440impl From<Ed25519PublicKey> for KeyData {
441    fn from(public_key: Ed25519PublicKey) -> KeyData {
442        Self::Ed25519(public_key)
443    }
444}
445
446#[cfg(feature = "alloc")]
447impl From<RsaPublicKey> for KeyData {
448    fn from(public_key: RsaPublicKey) -> KeyData {
449        Self::Rsa(public_key)
450    }
451}
452
453#[cfg(all(feature = "mldsa", feature = "ed25519"))]
454impl From<MlDsa44Ed25519PublicKey> for KeyData {
455    fn from(public_key: MlDsa44Ed25519PublicKey) -> KeyData {
456        Self::MlDsa44Ed25519(public_key)
457    }
458}
459
460#[cfg(all(feature = "mldsa", feature = "p384"))]
461impl From<MlDsa87P384PublicKey> for KeyData {
462    fn from(public_key: MlDsa87P384PublicKey) -> KeyData {
463        Self::MlDsa87P384(public_key)
464    }
465}
466
467#[cfg(feature = "ecdsa")]
468impl From<SkEcdsaSha2NistP256> for KeyData {
469    fn from(public_key: SkEcdsaSha2NistP256) -> KeyData {
470        Self::SkEcdsaSha2NistP256(public_key)
471    }
472}
473
474impl From<SkEd25519> for KeyData {
475    fn from(public_key: SkEd25519) -> KeyData {
476        Self::SkEd25519(public_key)
477    }
478}
479
480#[cfg(feature = "alloc")]
481impl From<Certificate> for KeyData {
482    fn from(certificate: Certificate) -> KeyData {
483        Self::Certificate(Box::new(certificate))
484    }
485}