Skip to main content

ssh_key/public/
key_data.rs

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