Skip to main content

ssh_key/public/
ed25519.rs

1//! Ed25519 public keys.
2//!
3//! Edwards Digital Signature Algorithm (EdDSA) over Curve25519.
4
5use crate::{Error, Result};
6use core::fmt;
7use encoding::{Decode, Encode};
8
9/// Ed25519 public key.
10///
11/// Encodings for Ed25519 public keys are described in [RFC8709 § 4]:
12///
13/// > The "ssh-ed25519" key format has the following encoding:
14/// >
15/// > **string** "ssh-ed25519"
16/// >
17/// > **string** key
18/// >
19/// > Here, 'key' is the 32-octet public key described in RFC8032
20///
21/// [RFC8709 § 4]: https://datatracker.ietf.org/doc/html/rfc8709#section-4
22#[derive(Copy, Clone, Debug, Decode, Encode, Eq, Hash, PartialEq, PartialOrd, Ord)]
23#[ssh(length_prefixed, error = Error)]
24pub struct Ed25519PublicKey(pub [u8; Self::BYTE_SIZE]);
25
26impl Ed25519PublicKey {
27    /// Size of an Ed25519 public key in bytes.
28    pub const BYTE_SIZE: usize = 32;
29}
30
31impl AsRef<[u8; Self::BYTE_SIZE]> for Ed25519PublicKey {
32    fn as_ref(&self) -> &[u8; Self::BYTE_SIZE] {
33        &self.0
34    }
35}
36
37impl TryFrom<&[u8]> for Ed25519PublicKey {
38    type Error = Error;
39
40    fn try_from(bytes: &[u8]) -> Result<Self> {
41        Ok(Self(bytes.try_into()?))
42    }
43}
44
45impl fmt::Display for Ed25519PublicKey {
46    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
47        write!(f, "{self:X}")
48    }
49}
50
51impl fmt::LowerHex for Ed25519PublicKey {
52    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
53        for byte in self.as_ref() {
54            write!(f, "{byte:02x}")?;
55        }
56        Ok(())
57    }
58}
59
60impl fmt::UpperHex for Ed25519PublicKey {
61    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
62        for byte in self.as_ref() {
63            write!(f, "{byte:02X}")?;
64        }
65        Ok(())
66    }
67}
68
69#[cfg(feature = "ed25519")]
70impl TryFrom<Ed25519PublicKey> for ed25519_dalek::VerifyingKey {
71    type Error = Error;
72
73    fn try_from(key: Ed25519PublicKey) -> Result<ed25519_dalek::VerifyingKey> {
74        ed25519_dalek::VerifyingKey::try_from(&key)
75    }
76}
77
78#[cfg(feature = "ed25519")]
79impl TryFrom<&Ed25519PublicKey> for ed25519_dalek::VerifyingKey {
80    type Error = Error;
81
82    fn try_from(key: &Ed25519PublicKey) -> Result<ed25519_dalek::VerifyingKey> {
83        ed25519_dalek::VerifyingKey::from_bytes(key.as_ref()).map_err(|_| Error::Crypto)
84    }
85}
86
87#[cfg(feature = "ed25519")]
88impl From<ed25519_dalek::VerifyingKey> for Ed25519PublicKey {
89    fn from(key: ed25519_dalek::VerifyingKey) -> Ed25519PublicKey {
90        Ed25519PublicKey::from(&key)
91    }
92}
93
94#[cfg(feature = "ed25519")]
95impl From<&ed25519_dalek::VerifyingKey> for Ed25519PublicKey {
96    fn from(key: &ed25519_dalek::VerifyingKey) -> Ed25519PublicKey {
97        Ed25519PublicKey(key.to_bytes())
98    }
99}