common/crypto/
keys.rs

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
8/// Size of Ed25519 private key in bytes
9pub const PRIVATE_KEY_SIZE: usize = 32;
10/// Size of Ed25519 public key in bytes
11pub const PUBLIC_KEY_SIZE: usize = 32;
12
13/// Errors that can occur during key operations
14#[derive(Debug, thiserror::Error)]
15pub enum KeyError {
16    #[error("key error: {0}")]
17    Default(#[from] anyhow::Error),
18}
19
20/// Public key for peer identity, key sharing, and update provenance
21///
22/// A thin wrapper around Iroh's `PublicKey`, representing the public part of an Ed25519 keypair.
23/// This key serves multiple purposes:
24/// - **Peer Identity**: Uniquely identifies a peer in the network (equivalent to Iroh's NodeId)
25/// - **Key Sharing**: Used in ECDH key exchange (after conversion to X25519)
26/// - **Access Control**: Listed in bucket shares to grant access
27///
28/// # Examples
29///
30/// ```ignore
31/// let secret_key = SecretKey::generate();
32/// let public_key = secret_key.public();
33///
34/// // Serialize to hex for storage/transmission
35/// let hex = public_key.to_hex();
36/// let recovered = PublicKey::from_hex(&hex)?;
37/// ```
38#[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    /// Parse a public key from a hexadecimal string
85    ///
86    /// Accepts both plain hex and "0x"-prefixed hex strings.
87    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    /// Convert public key to raw bytes
96    pub fn to_bytes(&self) -> [u8; PUBLIC_KEY_SIZE] {
97        *self.0.as_bytes()
98    }
99
100    /// Convert public key to hexadecimal string
101    pub fn to_hex(&self) -> String {
102        hex::encode(self.to_bytes())
103    }
104
105    /// Convert Ed25519 public key to X25519 (Montgomery curve) for ECDH
106    ///
107    /// This conversion is necessary for the key sharing protocol, which uses
108    /// Elliptic Curve Diffie-Hellman (ECDH) to establish shared secrets.
109    /// Ed25519 uses the Edwards curve, while ECDH requires the Montgomery curve (X25519).
110    ///
111    /// # Errors
112    ///
113    /// Returns an error if the Ed25519 point cannot be converted (invalid point).
114    #[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/// Secret key for peer identity and key sharing
128///
129/// A thin wrapper around Iroh's `SecretKey`, representing the private part of an Ed25519 keypair.
130/// This key should be kept secret and securely stored (e.g., in the local config file).
131///
132/// # Security Considerations
133///
134/// - Never share this key over the network
135/// - Store encrypted or in a secure location (e.g., `~/.config/jax/secret.pem`)
136/// - Generate a new key for each peer instance
137///
138/// # Examples
139///
140/// ```ignore
141/// // Generate a new keypair
142/// let secret_key = SecretKey::generate();
143/// let public_key = secret_key.public();
144///
145/// // Persist to PEM format
146/// let pem = secret_key.to_pem();
147/// std::fs::write("secret.pem", pem)?;
148///
149/// // Load from PEM
150/// let pem = std::fs::read_to_string("secret.pem")?;
151/// let recovered = SecretKey::from_pem(&pem)?;
152/// ```
153#[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    /// Parse a secret key from a hexadecimal string
171    ///
172    /// Accepts both plain hex and "0x"-prefixed hex strings.
173    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    /// Generate a new random secret key using a cryptographically secure RNG
182    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    /// Derive the public key from this secret key
189    pub fn public(&self) -> PublicKey {
190        PublicKey(self.0.public())
191    }
192
193    /// Convert secret key to raw bytes
194    pub fn to_bytes(&self) -> [u8; PRIVATE_KEY_SIZE] {
195        self.0.to_bytes()
196    }
197
198    /// Convert secret key to hexadecimal string
199    pub fn to_hex(&self) -> String {
200        hex::encode(self.to_bytes())
201    }
202
203    /// Encode secret key in PEM format for secure storage
204    ///
205    /// Returns a PEM-encoded string with tag "PRIVATE KEY".
206    pub fn to_pem(&self) -> String {
207        let pem = pem::Pem::new("PRIVATE KEY", self.to_bytes());
208        pem::encode(&pem)
209    }
210
211    /// Parse a secret key from PEM format
212    ///
213    /// # Errors
214    ///
215    /// Returns an error if:
216    /// - The PEM string is malformed
217    /// - The PEM tag is not "PRIVATE KEY"
218    /// - The key size is incorrect
219    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    /// Convert Ed25519 secret key to X25519 (Montgomery curve) for ECDH
242    ///
243    /// This conversion is used internally for the key sharing protocol.
244    /// The scalar bytes of the Ed25519 key are directly used as the X25519 private key.
245    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        // Test round-trip conversion
262        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        // Test round-trip PEM conversion
276        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        // Verify the recovered key can produce the same public key
281        assert_eq!(
282            private_key.public().to_bytes(),
283            recovered_private.public().to_bytes()
284        );
285    }
286}