Skip to main content

weirdnet_update/
keys.rs

1//! Ed25519 keys and signatures.
2//!
3//! Org root, release and timestamp keys are independent Ed25519 keys. They are not
4//! Weirdnet user keys; an org that wants to tie them to a Weirdnet identity derives an
5//! app-scoped seed itself and passes it to [`SigningKey::from_seed`].
6
7use crate::bytes::decode_hex;
8use crate::{Error, Result};
9use ed25519_dalek::{Signer, VerifyingKey};
10use serde::{Deserialize, Deserializer, Serialize, Serializer};
11use std::fmt;
12use zeroize::Zeroizing;
13
14/// A secret Ed25519 signing key. Wiped on drop, never printed.
15pub struct SigningKey(ed25519_dalek::SigningKey);
16
17impl SigningKey {
18    /// A fresh key from the OS random generator.
19    pub fn generate() -> Result<Self> {
20        let mut seed = Zeroizing::new([0u8; 32]);
21        getrandom::getrandom(seed.as_mut()).map_err(|_| Error::Random)?;
22        Ok(Self::from_seed(&seed))
23    }
24
25    /// A key from a 32-byte seed (for keys held in a keyring or derived elsewhere).
26    pub fn from_seed(seed: &[u8; 32]) -> Self {
27        Self(ed25519_dalek::SigningKey::from_bytes(seed))
28    }
29
30    /// The seed, for the caller to store sealed. Handle as a secret.
31    pub fn to_seed(&self) -> Zeroizing<[u8; 32]> {
32        Zeroizing::new(self.0.to_bytes())
33    }
34
35    /// The public half.
36    pub fn public(&self) -> PublicKey {
37        PublicKey(self.0.verifying_key().to_bytes())
38    }
39
40    pub(crate) fn sign_raw(&self, msg: &[u8]) -> Signature {
41        Signature(self.0.sign(msg).to_bytes())
42    }
43}
44
45impl fmt::Debug for SigningKey {
46    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
47        write!(f, "SigningKey(<redacted>, public {})", self.public())
48    }
49}
50
51/// An Ed25519 public key. Parsing refuses invalid and small-order (weak) points.
52#[derive(Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)]
53pub struct PublicKey([u8; 32]);
54
55impl PublicKey {
56    /// Parses and checks 32 key bytes.
57    pub fn from_bytes(bytes: [u8; 32]) -> Result<Self> {
58        let key = VerifyingKey::from_bytes(&bytes).map_err(|_| Error::InvalidKey("not an Ed25519 point".into()))?;
59        if key.is_weak() {
60            return Err(Error::InvalidKey("weak Ed25519 key".into()));
61        }
62        Ok(Self(bytes))
63    }
64
65    /// Parses 64 hex characters.
66    pub fn from_hex(s: &str) -> Result<Self> {
67        Self::from_bytes(decode_hex("public key", s)?)
68    }
69
70    /// The raw bytes.
71    pub fn as_bytes(&self) -> &[u8; 32] {
72        &self.0
73    }
74
75    /// Lowercase hex.
76    pub fn to_hex(&self) -> String {
77        hex::encode(self.0)
78    }
79
80    /// Strict verification (RFC 8032 with the cofactorless, non-malleable checks).
81    pub fn verify(&self, msg: &[u8], sig: &Signature) -> bool {
82        let Ok(key) = VerifyingKey::from_bytes(&self.0) else { return false };
83        key.verify_strict(msg, &ed25519_dalek::Signature::from_bytes(&sig.0)).is_ok()
84    }
85}
86
87impl fmt::Display for PublicKey {
88    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
89        f.write_str(&self.to_hex())
90    }
91}
92
93impl fmt::Debug for PublicKey {
94    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
95        write!(f, "PublicKey({})", self.to_hex())
96    }
97}
98
99impl Serialize for PublicKey {
100    fn serialize<S: Serializer>(&self, s: S) -> std::result::Result<S::Ok, S::Error> {
101        s.serialize_str(&self.to_hex())
102    }
103}
104
105impl<'de> Deserialize<'de> for PublicKey {
106    fn deserialize<D: Deserializer<'de>>(d: D) -> std::result::Result<Self, D::Error> {
107        let s = String::deserialize(d)?;
108        Self::from_hex(&s).map_err(serde::de::Error::custom)
109    }
110}
111
112/// A 64-byte Ed25519 signature.
113#[derive(Clone, Copy, PartialEq, Eq)]
114pub struct Signature(pub(crate) [u8; 64]);
115
116impl Signature {
117    /// Wraps raw signature bytes (checked only when verified).
118    pub fn from_bytes(bytes: [u8; 64]) -> Self {
119        Self(bytes)
120    }
121
122    /// The raw bytes.
123    pub fn to_bytes(&self) -> [u8; 64] {
124        self.0
125    }
126}
127
128impl fmt::Debug for Signature {
129    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
130        write!(f, "Signature({}…)", hex::encode(&self.0[..8]))
131    }
132}
133
134impl Serialize for Signature {
135    fn serialize<S: Serializer>(&self, s: S) -> std::result::Result<S::Ok, S::Error> {
136        s.serialize_str(&hex::encode(self.0))
137    }
138}
139
140impl<'de> Deserialize<'de> for Signature {
141    fn deserialize<D: Deserializer<'de>>(d: D) -> std::result::Result<Self, D::Error> {
142        let s = String::deserialize(d)?;
143        Ok(Self(decode_hex("signature", &s).map_err(serde::de::Error::custom)?))
144    }
145}