karyon_core/crypto/
key_pair.rs

1use ed25519_dalek::{Signer as _, Verifier as _};
2use rand::rngs::OsRng;
3
4use crate::{error::Error, Result};
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(ed25519_dalek::SigningKey);
63
64impl Ed25519KeyPair {
65    fn generate() -> Self {
66        Self(ed25519_dalek::SigningKey::generate(&mut OsRng))
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        Ok(Self(ed25519_dalek::VerifyingKey::from_bytes(&pk_bytes)?))
128    }
129}
130
131impl PublicKeyExt for Ed25519PublicKey {
132    fn as_bytes(&self) -> &[u8] {
133        self.0.as_bytes()
134    }
135
136    fn verify(&self, msg: &[u8], signature: &[u8]) -> Result<()> {
137        let sig_bytes: [u8; 64] = signature
138            .try_into()
139            .map_err(|_| Error::TryInto("Failed to convert slice to [u8; 64]".to_string()))?;
140        self.0
141            .verify(msg, &ed25519_dalek::Signature::from_bytes(&sig_bytes))?;
142        Ok(())
143    }
144}