Skip to main content

karyon_core/crypto/
key_pair.rs

1use ed25519_dalek::{SignatureError, Signer as _, SigningKey, VerifyingKey};
2use rand::rng;
3
4use crate::{Result, error::Error};
5
6/// key cryptography type
7pub enum KeyPairType {
8    Ed25519,
9}
10
11/// A Secret key
12pub struct SecretKey(pub Vec<u8>);
13
14#[derive(Clone)]
15pub enum KeyPair {
16    Ed25519(Ed25519KeyPair),
17}
18
19impl KeyPair {
20    /// Generate a new random keypair.
21    pub fn generate(kp_type: &KeyPairType) -> Self {
22        match kp_type {
23            KeyPairType::Ed25519 => Self::Ed25519(Ed25519KeyPair::generate()),
24        }
25    }
26
27    /// Sign a message using the private key.
28    pub fn sign(&self, msg: &[u8]) -> Vec<u8> {
29        match self {
30            KeyPair::Ed25519(kp) => kp.sign(msg),
31        }
32    }
33
34    /// Get the public key of this keypair.
35    pub fn public(&self) -> PublicKey {
36        match self {
37            KeyPair::Ed25519(kp) => kp.public(),
38        }
39    }
40
41    /// Get the secret key of this keypair.
42    pub fn secret(&self) -> SecretKey {
43        match self {
44            KeyPair::Ed25519(kp) => kp.secret(),
45        }
46    }
47}
48
49/// An extension trait, adding essential methods to all [`KeyPair`] types.
50trait KeyPairExt {
51    /// Sign a message using the private key.
52    fn sign(&self, msg: &[u8]) -> Vec<u8>;
53
54    /// Get the public key of this keypair.
55    fn public(&self) -> PublicKey;
56
57    /// Get the secret key of this keypair.
58    fn secret(&self) -> SecretKey;
59}
60
61#[derive(Clone)]
62pub struct Ed25519KeyPair(SigningKey);
63
64impl Ed25519KeyPair {
65    fn generate() -> Self {
66        Self(SigningKey::generate(&mut rng()))
67    }
68}
69
70impl KeyPairExt for Ed25519KeyPair {
71    fn sign(&self, msg: &[u8]) -> Vec<u8> {
72        self.0.sign(msg).to_bytes().to_vec()
73    }
74
75    fn public(&self) -> PublicKey {
76        PublicKey::Ed25519(Ed25519PublicKey(self.0.verifying_key()))
77    }
78
79    fn secret(&self) -> SecretKey {
80        SecretKey(self.0.to_bytes().to_vec())
81    }
82}
83
84#[derive(Debug)]
85pub enum PublicKey {
86    Ed25519(Ed25519PublicKey),
87}
88
89impl PublicKey {
90    pub fn from_bytes(kp_type: &KeyPairType, pk: &[u8]) -> Result<Self> {
91        match kp_type {
92            KeyPairType::Ed25519 => Ok(Self::Ed25519(Ed25519PublicKey::from_bytes(pk)?)),
93        }
94    }
95
96    pub fn as_bytes(&self) -> &[u8] {
97        match self {
98            Self::Ed25519(pk) => pk.as_bytes(),
99        }
100    }
101
102    /// Verify a signature on a message with this public key.
103    pub fn verify(&self, msg: &[u8], signature: &[u8]) -> Result<()> {
104        match self {
105            Self::Ed25519(pk) => pk.verify(msg, signature),
106        }
107    }
108}
109
110/// An extension trait, adding essential methods to all [`PublicKey`] types.
111trait PublicKeyExt {
112    fn as_bytes(&self) -> &[u8];
113
114    /// Verify a signature on a message with this public key.
115    fn verify(&self, msg: &[u8], signature: &[u8]) -> Result<()>;
116}
117
118#[derive(Debug)]
119pub struct Ed25519PublicKey(ed25519_dalek::VerifyingKey);
120
121impl Ed25519PublicKey {
122    pub fn from_bytes(pk: &[u8]) -> Result<Self> {
123        let pk_bytes: [u8; 32] = pk
124            .try_into()
125            .map_err(|_| Error::TryInto("Failed to convert slice to [u8; 32]".to_string()))?;
126
127        let pk = VerifyingKey::from_bytes(&pk_bytes)?;
128        // Small-order keys can make one signature valid for any message.
129        if pk.is_weak() {
130            return Err(SignatureError::new().into());
131        }
132        Ok(Self(pk))
133    }
134}
135
136impl PublicKeyExt for Ed25519PublicKey {
137    fn as_bytes(&self) -> &[u8] {
138        self.0.as_bytes()
139    }
140
141    fn verify(&self, msg: &[u8], signature: &[u8]) -> Result<()> {
142        let sig_bytes: [u8; 64] = signature
143            .try_into()
144            .map_err(|_| Error::TryInto("Failed to convert slice to [u8; 64]".to_string()))?;
145        self.0
146            .verify_strict(msg, &ed25519_dalek::Signature::from_bytes(&sig_bytes))?;
147        Ok(())
148    }
149}
150
151#[cfg(test)]
152mod tests {
153    use super::*;
154
155    #[test]
156    fn sign_and_verify() {
157        let kp = KeyPair::generate(&KeyPairType::Ed25519);
158        let sig = kp.sign(b"msg");
159        let pk = PublicKey::from_bytes(&KeyPairType::Ed25519, kp.public().as_bytes()).unwrap();
160        assert!(pk.verify(b"msg", &sig).is_ok());
161        assert!(pk.verify(b"other", &sig).is_err());
162    }
163
164    #[test]
165    fn reject_identity_key() {
166        // The identity point, a small-order key.
167        let mut identity = [0u8; 32];
168        identity[0] = 1;
169        assert!(PublicKey::from_bytes(&KeyPairType::Ed25519, &identity).is_err());
170    }
171
172    #[test]
173    fn reject_identity_signature() {
174        // Bypass from_bytes to check verify_strict on its own.
175        let mut identity = [0u8; 32];
176        identity[0] = 1;
177        let pk = Ed25519PublicKey(VerifyingKey::from_bytes(&identity).unwrap());
178        // R = identity, s = 0.
179        let mut sig = [0u8; 64];
180        sig[0] = 1;
181        assert!(pk.verify(b"any message", &sig).is_err());
182    }
183}