ssh_key/public.rs
1//! SSH public key support.
2//!
3//! Support for decoding SSH public keys from the OpenSSH file format.
4
5#[cfg(feature = "alloc")]
6mod dsa;
7#[cfg(feature = "ecdsa")]
8mod ecdsa;
9mod ed25519;
10mod key_data;
11#[cfg(feature = "alloc")]
12mod opaque;
13#[cfg(feature = "alloc")]
14mod rsa;
15mod sk;
16mod ssh_format;
17
18pub use self::{ed25519::Ed25519PublicKey, key_data::KeyData, sk::SkEd25519};
19
20#[cfg(feature = "alloc")]
21pub use self::{
22 dsa::DsaPublicKey,
23 opaque::{OpaquePublicKey, OpaquePublicKeyBytes},
24 rsa::RsaPublicKey,
25};
26
27#[cfg(feature = "ecdsa")]
28pub use self::{ecdsa::EcdsaPublicKey, sk::SkEcdsaSha2NistP256};
29
30#[cfg(all(feature = "mldsa", feature = "ed25519"))]
31pub use crate::composite::MlDsa44Ed25519PublicKey;
32#[cfg(all(feature = "mldsa", feature = "p384"))]
33pub use crate::composite::MlDsa87P384PublicKey;
34
35pub(crate) use self::ssh_format::SshFormat;
36
37use crate::{Algorithm, Error, Result};
38use core::str::{self, FromStr};
39use encoding::{Decode, Decoder, Reader};
40
41#[cfg(feature = "alloc")]
42use {
43 crate::{AssociatedHashAlg, Comment, SshSig},
44 alloc::{
45 borrow::ToOwned,
46 string::{String, ToString},
47 vec::Vec,
48 },
49 encoding::{Encode, digest::Digest},
50};
51
52#[cfg(all(feature = "alloc", feature = "serde"))]
53use serde::{Deserialize, Serialize, de, ser};
54
55#[cfg(feature = "sha2")]
56use crate::{Fingerprint, HashAlg};
57
58#[cfg(feature = "std")]
59use std::{fs::File, path::Path};
60
61#[cfg(feature = "std")]
62use std::io::{self, Read, Write};
63
64#[cfg(doc)]
65use crate::PrivateKey;
66
67/// SSH public key.
68///
69/// # OpenSSH encoding
70///
71/// The OpenSSH encoding of an SSH public key looks like following:
72///
73/// ```text
74/// ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAILM+rvN+ot98qgEN796jTiQfZfG1KaT0PtFDJ/XFSqti user@example.com
75/// ```
76///
77/// It consists of the following three parts:
78///
79/// 1. Algorithm identifier (in this example `ssh-ed25519`)
80/// 2. Key data encoded as Base64
81/// 3. [`Comment`] (optional): arbitrary label describing a key. Usually an email address
82///
83/// The [`PublicKey::from_openssh`] and [`PublicKey::to_openssh`] methods can be
84/// used to decode/encode public keys, or alternatively, the [`FromStr`] and
85/// [`ToString`] impls.
86///
87/// # `serde` support
88///
89/// When the `serde` feature of this crate is enabled, this type receives impls
90/// of [`Deserialize`][`serde::Deserialize`] and [`Serialize`][`serde::Serialize`].
91///
92/// The serialization uses a binary encoding with binary formats like bincode
93/// and CBOR, and the OpenSSH string serialization when used with
94/// human-readable formats like JSON and TOML.
95///
96/// Note that since the `comment` is an artifact on the string serialization of
97/// a public key, it will be implicitly dropped when encoding as a binary
98/// format. To ensure it's always preserved even when using binary formats, you
99/// will first need to convert the [`PublicKey`] to a string using e.g.
100/// [`PublicKey::to_openssh`].
101#[derive(Clone, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)]
102pub struct PublicKey {
103 /// Key data.
104 pub(crate) key_data: KeyData,
105
106 /// Comment on the key (e.g. email address)
107 ///
108 /// Note that when a [`PublicKey`] is serialized in a private key, the
109 /// comment is encoded as an RFC4251 `string` which may contain arbitrary
110 /// binary data, so `Vec<u8>` is used to store the comment to ensure keys
111 /// containing such comments successfully round-trip.
112 #[cfg(feature = "alloc")]
113 pub(crate) comment: Comment,
114}
115
116impl PublicKey {
117 /// Create a new public key with the given comment.
118 ///
119 /// On `no_std` platforms, use `PublicKey::from(key_data)` instead.
120 #[cfg(feature = "alloc")]
121 pub fn new(key_data: KeyData, comment: impl Into<Comment>) -> Self {
122 Self {
123 key_data,
124 comment: comment.into(),
125 }
126 }
127
128 /// Parse an OpenSSH-formatted public key.
129 ///
130 /// OpenSSH-formatted public keys look like the following:
131 ///
132 /// ```text
133 /// ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAILM+rvN+ot98qgEN796jTiQfZfG1KaT0PtFDJ/XFSqti foo@bar.com
134 /// ```
135 ///
136 /// # Errors
137 /// Returns [`Error::Encoding`] in the event of an encoding error.
138 pub fn from_openssh(public_key: &str) -> Result<Self> {
139 let encapsulation = SshFormat::decode(public_key.trim_end().as_bytes())?;
140 let mut reader = Decoder::from_base64(encapsulation.base64_data)?;
141 let key_data = KeyData::decode(&mut reader)?;
142
143 // Verify that the algorithm in the Base64-encoded data matches the text
144 if encapsulation.algorithm_id != key_data.algorithm().as_str() {
145 return Err(Error::AlgorithmUnknown);
146 }
147
148 let public_key = Self {
149 key_data,
150 #[cfg(feature = "alloc")]
151 comment: encapsulation.comment.to_owned().into(),
152 };
153
154 Ok(reader.finish(public_key)?)
155 }
156
157 /// Parse a raw binary SSH public key.
158 ///
159 /// # Errors
160 /// Returns [`Error::Encoding`] in the event of an encoding error.
161 pub fn from_bytes(bytes: &[u8]) -> Result<Self> {
162 let mut reader = Decoder::from_bytes(bytes)?;
163 let key_data = KeyData::decode(&mut reader)?;
164 Ok(reader.finish(key_data.into())?)
165 }
166
167 /// Encode OpenSSH-formatted public key.
168 ///
169 /// # Errors
170 /// Returns [`Error::Encoding`] in the event of an encoding error.
171 pub fn encode_openssh<'o>(&self, out: &'o mut [u8]) -> Result<&'o str> {
172 #[cfg(not(feature = "alloc"))]
173 let comment = "";
174 #[cfg(feature = "alloc")]
175 let comment = self.comment.as_str_lossy();
176
177 SshFormat::encode(self.algorithm().as_str(), &self.key_data, comment, out)
178 }
179
180 /// Encode an OpenSSH-formatted public key, allocating a [`String`] for the result.
181 ///
182 /// # Errors
183 /// Returns [`Error::Encoding`] in the event of an encoding error.
184 #[cfg(feature = "alloc")]
185 pub fn to_openssh(&self) -> Result<String> {
186 SshFormat::encode_string(
187 self.algorithm().as_str(),
188 &self.key_data,
189 self.comment.as_str_lossy(),
190 )
191 }
192
193 /// Serialize SSH public key as raw bytes.
194 ///
195 /// # Errors
196 /// Returns [`Error::Encoding`] in the event of an encoding error.
197 #[cfg(feature = "alloc")]
198 pub fn to_bytes(&self) -> Result<Vec<u8>> {
199 Ok(self.key_data.encode_vec()?)
200 }
201
202 /// Verify the [`SshSig`] signature is valid the given message using this public key.
203 ///
204 /// These signatures can be produced using `ssh-keygen -Y sign`. They're
205 /// encoded as PEM and begin with the following:
206 ///
207 /// ```text
208 /// -----BEGIN SSH SIGNATURE-----
209 /// ```
210 ///
211 /// See [PROTOCOL.sshsig] for more information.
212 ///
213 /// # Notes
214 ///
215 /// This method loads the entire message has to be loaded into memory for verification.
216 /// If loading the entire message into memory is a problem consider computing a [Digest]
217 /// of the data first, and using [`PublicKey::verify_prehash`].
218 ///
219 /// # Usage
220 ///
221 /// See also: [`PrivateKey::sign`].
222 ///
223 #[cfg_attr(feature = "ed25519", doc = "```")]
224 #[cfg_attr(not(feature = "ed25519"), doc = "```ignore")]
225 /// # fn main() -> Result<(), ssh_key::Error> {
226 /// use ssh_key::{PublicKey, SshSig};
227 ///
228 /// // Message to be verified.
229 /// let message = b"testing";
230 ///
231 /// // Example domain/namespace used for the message.
232 /// let namespace = "example";
233 ///
234 /// // Public key which computed the signature.
235 /// let encoded_public_key = "ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAILM+rvN+ot98qgEN796jTiQfZfG1KaT0PtFDJ/XFSqti user@example.com";
236 ///
237 /// // Example signature to be verified.
238 /// let signature_str = r#"
239 /// -----BEGIN SSH SIGNATURE-----
240 /// U1NIU0lHAAAAAQAAADMAAAALc3NoLWVkMjU1MTkAAAAgsz6u836i33yqAQ3v3qNOJB9l8b
241 /// UppPQ+0UMn9cVKq2IAAAAHZXhhbXBsZQAAAAAAAAAGc2hhNTEyAAAAUwAAAAtzc2gtZWQy
242 /// NTUxOQAAAEBPEav+tMGNnox4MuzM7rlHyVBajCn8B0kAyiOWwPKprNsG3i6X+voz/WCSik
243 /// /FowYwqhgCABUJSvRX3AERVBUP
244 /// -----END SSH SIGNATURE-----
245 /// "#;
246 ///
247 /// let public_key = encoded_public_key.parse::<PublicKey>()?;
248 /// let signature = signature_str.parse::<SshSig>()?;
249 /// public_key.verify(namespace, message, &signature)?;
250 /// # Ok(())
251 /// # }
252 /// ```
253 ///
254 /// [PROTOCOL.sshsig]: https://cvsweb.openbsd.org/src/usr.bin/ssh/PROTOCOL.sshsig?annotate=HEAD
255 /// [Digest]: https://docs.rs/digest/latest/digest/trait.Digest.html
256 ///
257 /// # Errors
258 /// - Returns [`Error::PublicKey`] if this key does not match the one in the signature.
259 /// - Returns [`Error::Namespace`] if the provided `namespace` does not match the signature.
260 /// - Returns [`Error::Signature`] in the event signature verification failed.
261 #[cfg(all(feature = "alloc", feature = "sha2"))]
262 pub fn verify(&self, namespace: &str, msg: &[u8], signature: &SshSig) -> Result<()> {
263 self.verify_prehash(
264 namespace,
265 signature.hash_alg().digest(msg).as_slice(),
266 signature,
267 )
268 }
269
270 /// Verify the [`SshSig`] signature is valid the given message [`Digest`] using this public key.
271 ///
272 /// See [`PublicKey::verify`] for more information.
273 ///
274 /// # Errors
275 /// - Returns [`Error::PublicKey`] if this key does not match the one in the signature.
276 /// - Returns [`Error::Namespace`] if the provided `namespace` does not match the signature.
277 /// - Returns [`Error::Signature`] in the event signature verification failed.
278 #[cfg(feature = "alloc")]
279 pub fn verify_digest<D: AssociatedHashAlg + Digest>(
280 &self,
281 namespace: &str,
282 digest: D,
283 signature: &SshSig,
284 ) -> Result<()> {
285 if D::HASH_ALG != signature.hash_alg() {
286 return Err(Error::Crypto);
287 }
288
289 self.verify_prehash(namespace, digest.finalize().as_slice(), signature)
290 }
291
292 /// Verify the [`SshSig`] signature matches the given prehashed message digest using this
293 /// public key.
294 ///
295 /// See [`PublicKey::verify`] for more information.
296 ///
297 /// # Errors
298 /// - Returns [`Error::PublicKey`] if this key does not match the one in the signature.
299 /// - Returns [`Error::Namespace`] if the provided `namespace` does not match the signature.
300 /// - Returns [`Error::Signature`] in the event signature verification failed.
301 #[cfg(feature = "alloc")]
302 pub fn verify_prehash(
303 &self,
304 namespace: &str,
305 prehash: &[u8],
306 signature: &SshSig,
307 ) -> Result<()> {
308 if self.key_data() != signature.public_key() {
309 return Err(Error::PublicKey);
310 }
311
312 if namespace != signature.namespace() {
313 return Err(Error::Namespace);
314 }
315
316 signature.verify_prehash(prehash)
317 }
318
319 /// Read public key from an OpenSSH-formatted source.
320 ///
321 /// # Errors
322 /// - Returns [`Error::Io`] in the event of an I/O error.
323 /// - Returns [`Error::Encoding`] in the event of an encoding error.
324 #[cfg(feature = "std")]
325 pub fn read_openssh(reader: &mut impl Read) -> Result<Self> {
326 let input = io::read_to_string(reader)?;
327 Self::from_openssh(&input)
328 }
329
330 /// Read public key from an OpenSSH-formatted file.
331 ///
332 /// # Errors
333 /// - Returns [`Error::Io`] in the event of an I/O error.
334 /// - Returns [`Error::Encoding`] in the event of an encoding error.
335 #[cfg(feature = "std")]
336 pub fn read_openssh_file(path: impl AsRef<Path>) -> Result<Self> {
337 let mut file = File::open(path)?;
338 Self::read_openssh(&mut file)
339 }
340
341 /// Write public key as an OpenSSH-formatted file.
342 ///
343 /// # Errors
344 /// - Returns [`Error::Io`] in the event of an I/O error.
345 /// - Returns [`Error::Encoding`] in the event of an encoding error.
346 #[cfg(feature = "std")]
347 pub fn write_openssh(&self, writer: &mut impl Write) -> Result<()> {
348 let mut encoded = self.to_openssh()?;
349 encoded.push('\n'); // TODO(tarcieri): OS-specific line endings?
350
351 writer.write_all(encoded.as_bytes())?;
352 Ok(())
353 }
354
355 /// Write public key as an OpenSSH-formatted file.
356 ///
357 /// # Errors
358 /// - Returns [`Error::Io`] in the event of an I/O error.
359 /// - Returns [`Error::Encoding`] in the event of an encoding error.
360 #[cfg(feature = "std")]
361 pub fn write_openssh_file(&self, path: impl AsRef<Path>) -> Result<()> {
362 let mut file = File::create(path)?;
363 self.write_openssh(&mut file)
364 }
365
366 /// Get the digital signature [`Algorithm`] used by this key.
367 #[must_use]
368 pub fn algorithm(&self) -> Algorithm {
369 self.key_data.algorithm()
370 }
371
372 /// Comment on the key (e.g. email address).
373 #[cfg(feature = "alloc")]
374 #[must_use]
375 pub fn comment(&self) -> &Comment {
376 &self.comment
377 }
378
379 /// Public key data.
380 #[must_use]
381 pub fn key_data(&self) -> &KeyData {
382 &self.key_data
383 }
384
385 /// Compute key fingerprint.
386 ///
387 /// Use [`Default::default()`] to use the default hash function (SHA-256).
388 #[cfg(feature = "sha2")]
389 #[must_use]
390 pub fn fingerprint(&self, hash_alg: HashAlg) -> Fingerprint {
391 self.key_data.fingerprint(hash_alg)
392 }
393
394 /// Set the comment on the key.
395 #[cfg(feature = "alloc")]
396 pub fn set_comment(&mut self, comment: impl Into<Comment>) {
397 self.comment = comment.into();
398 }
399
400 /// Decode comment (e.g. email address).
401 ///
402 /// This is a stub implementation that ignores the comment.
403 #[cfg(not(feature = "alloc"))]
404 pub(crate) fn decode_comment(&mut self, reader: &mut Decoder<impl Reader>) -> Result<()> {
405 reader.drain_prefixed()?;
406 Ok(())
407 }
408
409 /// Decode comment (e.g. email address)
410 #[cfg(feature = "alloc")]
411 pub(crate) fn decode_comment(&mut self, reader: &mut Decoder<impl Reader>) -> Result<()> {
412 self.comment = Comment::decode(reader)?;
413 Ok(())
414 }
415}
416
417impl From<KeyData> for PublicKey {
418 fn from(key_data: KeyData) -> PublicKey {
419 PublicKey {
420 key_data,
421 #[cfg(feature = "alloc")]
422 comment: Comment::default(),
423 }
424 }
425}
426
427impl From<PublicKey> for KeyData {
428 fn from(public_key: PublicKey) -> KeyData {
429 public_key.key_data
430 }
431}
432
433impl From<&PublicKey> for KeyData {
434 fn from(public_key: &PublicKey) -> KeyData {
435 public_key.key_data.clone()
436 }
437}
438
439#[cfg(feature = "alloc")]
440impl From<DsaPublicKey> for PublicKey {
441 fn from(public_key: DsaPublicKey) -> PublicKey {
442 KeyData::from(public_key).into()
443 }
444}
445
446#[cfg(feature = "ecdsa")]
447impl From<EcdsaPublicKey> for PublicKey {
448 fn from(public_key: EcdsaPublicKey) -> PublicKey {
449 KeyData::from(public_key).into()
450 }
451}
452
453impl From<Ed25519PublicKey> for PublicKey {
454 fn from(public_key: Ed25519PublicKey) -> PublicKey {
455 KeyData::from(public_key).into()
456 }
457}
458
459#[cfg(all(feature = "mldsa", feature = "ed25519"))]
460impl From<MlDsa44Ed25519PublicKey> for PublicKey {
461 fn from(public_key: MlDsa44Ed25519PublicKey) -> PublicKey {
462 KeyData::from(public_key).into()
463 }
464}
465
466#[cfg(all(feature = "mldsa", feature = "p384"))]
467impl From<MlDsa87P384PublicKey> for PublicKey {
468 fn from(public_key: MlDsa87P384PublicKey) -> PublicKey {
469 KeyData::from(public_key).into()
470 }
471}
472
473#[cfg(feature = "alloc")]
474impl From<RsaPublicKey> for PublicKey {
475 fn from(public_key: RsaPublicKey) -> PublicKey {
476 KeyData::from(public_key).into()
477 }
478}
479
480#[cfg(feature = "ecdsa")]
481impl From<SkEcdsaSha2NistP256> for PublicKey {
482 fn from(public_key: SkEcdsaSha2NistP256) -> PublicKey {
483 KeyData::from(public_key).into()
484 }
485}
486
487impl From<SkEd25519> for PublicKey {
488 fn from(public_key: SkEd25519) -> PublicKey {
489 KeyData::from(public_key).into()
490 }
491}
492
493impl FromStr for PublicKey {
494 type Err = Error;
495
496 fn from_str(s: &str) -> Result<Self> {
497 Self::from_openssh(s)
498 }
499}
500
501#[cfg(feature = "alloc")]
502#[allow(clippy::to_string_trait_impl)]
503impl ToString for PublicKey {
504 fn to_string(&self) -> String {
505 self.to_openssh().expect("SSH public key encoding error")
506 }
507}
508
509#[cfg(all(feature = "alloc", feature = "serde"))]
510impl<'de> Deserialize<'de> for PublicKey {
511 fn deserialize<D>(deserializer: D) -> core::result::Result<Self, D::Error>
512 where
513 D: de::Deserializer<'de>,
514 {
515 if deserializer.is_human_readable() {
516 let string = String::deserialize(deserializer)?;
517 Self::from_openssh(&string).map_err(de::Error::custom)
518 } else {
519 let bytes = Vec::<u8>::deserialize(deserializer)?;
520 Self::from_bytes(&bytes).map_err(de::Error::custom)
521 }
522 }
523}
524
525#[cfg(all(feature = "alloc", feature = "serde"))]
526impl Serialize for PublicKey {
527 fn serialize<S>(&self, serializer: S) -> core::result::Result<S::Ok, S::Error>
528 where
529 S: ser::Serializer,
530 {
531 if serializer.is_human_readable() {
532 self.to_openssh()
533 .map_err(ser::Error::custom)?
534 .serialize(serializer)
535 } else {
536 self.to_bytes()
537 .map_err(ser::Error::custom)?
538 .serialize(serializer)
539 }
540 }
541}