1use std::ops::Deref;
2
3use curve25519_dalek::edwards::CompressedEdwardsY;
4use iroh::{PublicKey as PPublicKey, SecretKey as SSecretKey};
5use serde::{Deserialize, Serialize};
6use x25519_dalek::{PublicKey as X25519PublicKey, StaticSecret};
7
8pub const PRIVATE_KEY_SIZE: usize = 32;
10pub const PUBLIC_KEY_SIZE: usize = 32;
12
13#[derive(Debug, thiserror::Error)]
15pub enum KeyError {
16 #[error("key error: {0}")]
17 Default(#[from] anyhow::Error),
18}
19
20#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize, PartialOrd, Ord, Copy)]
39pub struct PublicKey(PPublicKey);
40
41impl Deref for PublicKey {
42 type Target = PPublicKey;
43 fn deref(&self) -> &Self::Target {
44 &self.0
45 }
46}
47
48impl From<PPublicKey> for PublicKey {
49 fn from(key: PPublicKey) -> Self {
50 PublicKey(key)
51 }
52}
53
54impl From<PublicKey> for PPublicKey {
55 fn from(key: PublicKey) -> Self {
56 key.0
57 }
58}
59
60impl From<[u8; PUBLIC_KEY_SIZE]> for PublicKey {
61 fn from(bytes: [u8; PUBLIC_KEY_SIZE]) -> Self {
62 PublicKey(PPublicKey::from_bytes(&bytes).expect("valid public key"))
63 }
64}
65
66impl TryFrom<&[u8]> for PublicKey {
67 type Error = KeyError;
68 fn try_from(bytes: &[u8]) -> Result<Self, Self::Error> {
69 if bytes.len() != PUBLIC_KEY_SIZE {
70 return Err(anyhow::anyhow!(
71 "invalid public key size, expected {}, got {}",
72 PUBLIC_KEY_SIZE,
73 bytes.len()
74 )
75 .into());
76 }
77 let mut buff = [0; PUBLIC_KEY_SIZE];
78 buff.copy_from_slice(bytes);
79 Ok(buff.into())
80 }
81}
82
83impl PublicKey {
84 pub fn from_hex(hex: &str) -> Result<Self, KeyError> {
88 let hex = hex.strip_prefix("0x").unwrap_or(hex);
89 let mut buff = [0; PUBLIC_KEY_SIZE];
90 hex::decode_to_slice(hex, &mut buff)
91 .map_err(|_| anyhow::anyhow!("public key hex decode error"))?;
92 Ok(buff.into())
93 }
94
95 pub fn to_bytes(&self) -> [u8; PUBLIC_KEY_SIZE] {
97 *self.0.as_bytes()
98 }
99
100 pub fn to_hex(&self) -> String {
102 hex::encode(self.to_bytes())
103 }
104
105 #[allow(clippy::wrong_self_convention)]
115 pub(crate) fn to_x25519(&self) -> Result<X25519PublicKey, KeyError> {
116 let edwards_bytes = self.to_bytes();
117 let edwards_point = CompressedEdwardsY::from_slice(&edwards_bytes)
118 .map_err(|_| anyhow::anyhow!("public key invalid edwards point"))?
119 .decompress()
120 .ok_or_else(|| anyhow::anyhow!("public key failed to decompress edwards point"))?;
121
122 let montgomery_point = edwards_point.to_montgomery();
123 Ok(X25519PublicKey::from(montgomery_point.to_bytes()))
124 }
125}
126
127#[derive(Debug, Clone, Serialize, Deserialize)]
154pub struct SecretKey(pub SSecretKey);
155
156impl From<[u8; PRIVATE_KEY_SIZE]> for SecretKey {
157 fn from(secret: [u8; PRIVATE_KEY_SIZE]) -> Self {
158 Self(SSecretKey::from_bytes(&secret))
159 }
160}
161
162impl Deref for SecretKey {
163 type Target = SSecretKey;
164 fn deref(&self) -> &Self::Target {
165 &self.0
166 }
167}
168
169impl SecretKey {
170 pub fn from_hex(hex: &str) -> Result<Self, KeyError> {
174 let hex = hex.strip_prefix("0x").unwrap_or(hex);
175 let mut buff = [0; PRIVATE_KEY_SIZE];
176 hex::decode_to_slice(hex, &mut buff)
177 .map_err(|_| anyhow::anyhow!("private key hex decode error"))?;
178 Ok(Self::from(buff))
179 }
180
181 pub fn generate() -> Self {
183 let mut bytes = [0u8; PRIVATE_KEY_SIZE];
184 getrandom::getrandom(&mut bytes).expect("failed to generate random bytes");
185 Self::from(bytes)
186 }
187
188 pub fn public(&self) -> PublicKey {
190 PublicKey(self.0.public())
191 }
192
193 pub fn to_bytes(&self) -> [u8; PRIVATE_KEY_SIZE] {
195 self.0.to_bytes()
196 }
197
198 pub fn to_hex(&self) -> String {
200 hex::encode(self.to_bytes())
201 }
202
203 pub fn to_pem(&self) -> String {
207 let pem = pem::Pem::new("PRIVATE KEY", self.to_bytes());
208 pem::encode(&pem)
209 }
210
211 pub fn from_pem(pem_str: &str) -> Result<Self, KeyError> {
220 let pem = pem::parse(pem_str).map_err(|e| anyhow::anyhow!("failed to parse PEM: {}", e))?;
221
222 if pem.tag() != "PRIVATE KEY" {
223 return Err(anyhow::anyhow!("invalid PEM tag, expected PRIVATE KEY").into());
224 }
225
226 let contents = pem.contents();
227 if contents.len() != PRIVATE_KEY_SIZE {
228 return Err(anyhow::anyhow!(
229 "invalid private key size in PEM, expected {}, got {}",
230 PRIVATE_KEY_SIZE,
231 contents.len()
232 )
233 .into());
234 }
235
236 let mut bytes = [0u8; PRIVATE_KEY_SIZE];
237 bytes.copy_from_slice(contents);
238 Ok(Self::from(bytes))
239 }
240
241 pub(crate) fn to_x25519(&self) -> StaticSecret {
246 let signing_key = self.0.secret();
247 let scalar_bytes = signing_key.to_scalar_bytes();
248 StaticSecret::from(scalar_bytes)
249 }
250}
251
252#[cfg(test)]
253mod test {
254 use super::*;
255
256 #[test]
257 fn test_keypair_generation() {
258 let private_key = SecretKey::generate();
259 let public_key = private_key.public();
260
261 let private_hex = private_key.to_hex();
263 let recovered_private = SecretKey::from_hex(&private_hex).unwrap();
264 assert_eq!(private_key.to_bytes(), recovered_private.to_bytes());
265
266 let public_hex = public_key.to_hex();
267 let recovered_public = PublicKey::from_hex(&public_hex).unwrap();
268 assert_eq!(public_key.to_bytes(), recovered_public.to_bytes());
269 }
270
271 #[test]
272 fn test_pem_serialization() {
273 let private_key = SecretKey::generate();
274
275 let pem = private_key.to_pem();
277 let recovered_private = SecretKey::from_pem(&pem).unwrap();
278 assert_eq!(private_key.to_bytes(), recovered_private.to_bytes());
279
280 assert_eq!(
282 private_key.public().to_bytes(),
283 recovered_private.public().to_bytes()
284 );
285 }
286}