1mod 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#[cfg(feature = "sha2")]
26const FINGERPRINT_ERR_MSG: &str = "fingerprint encoding error";
27
28#[derive(Copy, Clone, Debug, Eq, PartialEq, PartialOrd, Ord, Hash)]
49#[non_exhaustive]
50pub enum Fingerprint {
51 Sha256([u8; HashAlg::Sha256.digest_size()]),
53
54 Sha512([u8; HashAlg::Sha512.digest_size()]),
56}
57
58impl Fingerprint {
59 const SHA512_BASE64_SIZE: usize = 86;
61
62 #[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 #[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 #[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 fn footer(self) -> &'static str {
106 match self.algorithm() {
107 HashAlg::Sha256 => "[SHA256]",
108 HashAlg::Sha512 => "[SHA512]",
109 }
110 }
111
112 #[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 #[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 #[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 #[must_use]
141 pub fn is_sha256(self) -> bool {
142 matches!(self, Self::Sha256(_))
143 }
144
145 #[must_use]
147 pub fn is_sha512(self) -> bool {
148 matches!(self, Self::Sha512(_))
149 }
150
151 pub fn fmt_randomart(self, header: &str, f: &mut fmt::Formatter<'_>) -> fmt::Result {
156 Randomart::new(header, self).fmt(f)
157 }
158
159 #[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 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 let algorithm = match alg_str {
206 "SHA256" => HashAlg::Sha256,
207 "SHA512" => HashAlg::Sha512,
208 _ => return Err(Error::AlgorithmUnknown),
209 };
210
211 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}