Skip to main content

ssh_key/
fingerprint.rs

1//! SSH public key fingerprints.
2
3mod randomart;
4
5use self::randomart::Randomart;
6use crate::{Error, HashAlg, Result};
7use core::{
8    fmt::{self, Display},
9    str::{self, FromStr},
10};
11use encoding::base64::{Base64Unpadded, Encoding};
12
13#[cfg(feature = "alloc")]
14use alloc::string::{String, ToString};
15#[cfg(all(feature = "alloc", feature = "serde"))]
16use serde::{Deserialize, Serialize, de, ser};
17#[cfg(feature = "sha2")]
18use {
19    crate::public,
20    encoding::{DigestWriter, Encode},
21    sha2::{Digest, Sha256, Sha512},
22};
23
24/// Fingerprint encoding error message.
25#[cfg(feature = "sha2")]
26const FINGERPRINT_ERR_MSG: &str = "fingerprint encoding error";
27
28/// SSH public key fingerprints.
29///
30/// Fingerprints have an associated key fingerprint algorithm, i.e. a hash
31/// function which is used to compute the fingerprint.
32///
33/// # Parsing/serializing fingerprint strings
34///
35/// The [`FromStr`] and [`Display`] impls on [`Fingerprint`] can be used to
36/// parse and serialize fingerprints from the string format.
37///
38/// ### Example
39///
40/// ```text
41/// SHA256:Nh0Me49Zh9fDw/VYUfq43IJmI1T+XrjiYONPND8GzaM
42/// ```
43///
44/// # `serde` support
45///
46/// When the `serde` feature of this crate is enabled, this type receives impls
47/// of [`Deserialize`][`serde::Deserialize`] and [`Serialize`][`serde::Serialize`].
48#[derive(Copy, Clone, Debug, Eq, PartialEq, PartialOrd, Ord, Hash)]
49#[non_exhaustive]
50pub enum Fingerprint {
51    /// Fingerprints computed using SHA-256.
52    Sha256([u8; HashAlg::Sha256.digest_size()]),
53
54    /// Fingerprints computed using SHA-512.
55    Sha512([u8; HashAlg::Sha512.digest_size()]),
56}
57
58impl Fingerprint {
59    /// Size of a SHA-512 hash encoded as Base64.
60    const SHA512_BASE64_SIZE: usize = 86;
61
62    /// Create a fingerprint of the given public key data using the provided
63    /// hash algorithm.
64    #[cfg(feature = "sha2")]
65    #[must_use]
66    #[allow(clippy::missing_panics_doc, reason = "should not panic")]
67    pub fn new(algorithm: HashAlg, public_key: &public::KeyData) -> Self {
68        match algorithm {
69            HashAlg::Sha256 => {
70                let mut digest = Sha256::new();
71                public_key
72                    .encode(&mut DigestWriter(&mut digest))
73                    .expect(FINGERPRINT_ERR_MSG);
74                Self::Sha256(digest.finalize().into())
75            }
76            HashAlg::Sha512 => {
77                let mut digest = Sha512::new();
78                public_key
79                    .encode(&mut DigestWriter(&mut digest))
80                    .expect(FINGERPRINT_ERR_MSG);
81                Self::Sha512(digest.finalize().into())
82            }
83        }
84    }
85
86    /// Get the hash algorithm used for this fingerprint.
87    #[must_use]
88    pub fn algorithm(self) -> HashAlg {
89        match self {
90            Self::Sha256(_) => HashAlg::Sha256,
91            Self::Sha512(_) => HashAlg::Sha512,
92        }
93    }
94
95    /// Get the name of the hash algorithm (upper case e.g. "SHA256").
96    #[must_use]
97    pub fn prefix(self) -> &'static str {
98        match self.algorithm() {
99            HashAlg::Sha256 => "SHA256",
100            HashAlg::Sha512 => "SHA512",
101        }
102    }
103
104    /// Get the bracketed hash algorithm footer for use in "randomart".
105    fn footer(self) -> &'static str {
106        match self.algorithm() {
107            HashAlg::Sha256 => "[SHA256]",
108            HashAlg::Sha512 => "[SHA512]",
109        }
110    }
111
112    /// Get the raw digest output for the fingerprint as bytes.
113    #[must_use]
114    pub fn as_bytes(&self) -> &[u8] {
115        match self {
116            Self::Sha256(bytes) => bytes.as_slice(),
117            Self::Sha512(bytes) => bytes.as_slice(),
118        }
119    }
120
121    /// Get the SHA-256 fingerprint, if this is one.
122    #[must_use]
123    pub fn sha256(self) -> Option<[u8; HashAlg::Sha256.digest_size()]> {
124        match self {
125            Self::Sha256(fingerprint) => Some(fingerprint),
126            _ => None,
127        }
128    }
129
130    /// Get the SHA-512 fingerprint, if this is one.
131    #[must_use]
132    pub fn sha512(self) -> Option<[u8; HashAlg::Sha512.digest_size()]> {
133        match self {
134            Self::Sha512(fingerprint) => Some(fingerprint),
135            _ => None,
136        }
137    }
138
139    /// Is this fingerprint SHA-256?
140    #[must_use]
141    pub fn is_sha256(self) -> bool {
142        matches!(self, Self::Sha256(_))
143    }
144
145    /// Is this fingerprint SHA-512?
146    #[must_use]
147    pub fn is_sha512(self) -> bool {
148        matches!(self, Self::Sha512(_))
149    }
150
151    /// Format "randomart" for this fingerprint using the provided formatter.
152    ///
153    /// # Errors
154    /// Propagates errors from [`fmt::Formatter`].
155    pub fn fmt_randomart(self, header: &str, f: &mut fmt::Formatter<'_>) -> fmt::Result {
156        Randomart::new(header, self).fmt(f)
157    }
158
159    /// Render "randomart" hash visualization for this fingerprint as a string.
160    ///
161    /// ```text
162    /// +--[ED25519 256]--+
163    /// |o+oO==+ o..      |
164    /// |.o++Eo+o..       |
165    /// |. +.oO.o . .     |
166    /// | . o..B.. . .    |
167    /// |  ...+ .S. o     |
168    /// |  .o. . . . .    |
169    /// |  o..    o       |
170    /// |   B      .      |
171    /// |  .o*            |
172    /// +----[SHA256]-----+
173    /// ```
174    #[cfg(feature = "alloc")]
175    #[must_use]
176    pub fn to_randomart(self, header: &str) -> String {
177        Randomart::new(header, self).to_string()
178    }
179}
180
181impl AsRef<[u8]> for Fingerprint {
182    fn as_ref(&self) -> &[u8] {
183        self.as_bytes()
184    }
185}
186
187impl Display for Fingerprint {
188    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
189        let prefix = self.prefix();
190
191        // Buffer size is the largest digest size of of any supported hash function
192        let mut buf = [0u8; Self::SHA512_BASE64_SIZE];
193        let base64 = Base64Unpadded::encode(self.as_bytes(), &mut buf).map_err(|_| fmt::Error)?;
194        write!(f, "{prefix}:{base64}")
195    }
196}
197
198impl FromStr for Fingerprint {
199    type Err = Error;
200
201    fn from_str(id: &str) -> Result<Self> {
202        let (alg_str, base64) = id.split_once(':').ok_or(Error::AlgorithmUnknown)?;
203
204        // Fingerprints use a special upper-case hash algorithm encoding.
205        let algorithm = match alg_str {
206            "SHA256" => HashAlg::Sha256,
207            "SHA512" => HashAlg::Sha512,
208            _ => return Err(Error::AlgorithmUnknown),
209        };
210
211        // Buffer size is the largest digest size of of any supported hash function
212        let mut buf = [0u8; HashAlg::Sha512.digest_size()];
213        let decoded_bytes = Base64Unpadded::decode(base64, &mut buf)?;
214
215        match algorithm {
216            HashAlg::Sha256 => Ok(Self::Sha256(decoded_bytes.try_into()?)),
217            HashAlg::Sha512 => Ok(Self::Sha512(decoded_bytes.try_into()?)),
218        }
219    }
220}
221
222#[cfg(all(feature = "alloc", feature = "serde"))]
223impl<'de> Deserialize<'de> for Fingerprint {
224    fn deserialize<D>(deserializer: D) -> core::result::Result<Self, D::Error>
225    where
226        D: de::Deserializer<'de>,
227    {
228        let string = String::deserialize(deserializer)?;
229        string.parse().map_err(de::Error::custom)
230    }
231}
232
233#[cfg(all(feature = "alloc", feature = "serde"))]
234impl Serialize for Fingerprint {
235    fn serialize<S>(&self, serializer: S) -> core::result::Result<S::Ok, S::Error>
236    where
237        S: ser::Serializer,
238    {
239        self.to_string().serialize(serializer)
240    }
241}