bc_components/ed25519/
ed25519_private_key.rs

1use anyhow::{bail, Result};
2use bc_rand::{RandomNumberGenerator, SecureRandomNumberGenerator};
3
4use crate::Ed25519PublicKey;
5
6pub const ED25519_PRIVATE_KEY_SIZE: usize = bc_crypto::ED25519_PRIVATE_KEY_SIZE;
7
8/// An Ed25519 private key for creating digital signatures.
9///
10/// Ed25519 is a public-key signature system based on the Edwards curve over the finite field
11/// GF(2^255 - 19). It provides the following features:
12///
13/// - Fast single-signature verification
14/// - Fast key generation
15/// - High security level (equivalent to 128 bits of symmetric security)
16/// - Collision resilience - hash function collisions don't break security
17/// - Protection against side-channel attacks
18/// - Small signatures (64 bytes) and small keys (32 bytes)
19///
20/// This implementation allows:
21/// - Creating random Ed25519 private keys
22/// - Deriving the corresponding public key 
23/// - Signing messages
24/// - Converting between various formats
25#[derive(Clone, PartialEq, Eq, Hash)]
26pub struct Ed25519PrivateKey([u8; ED25519_PRIVATE_KEY_SIZE]);
27
28impl Ed25519PrivateKey {
29    /// Creates a new random Ed25519 private key.
30    pub fn new() -> Self {
31        let mut rng = SecureRandomNumberGenerator;
32        Self::new_using(&mut rng)
33    }
34
35    /// Creates a new random Ed25519 private key using the given random number generator.
36    pub fn new_using(rng: &mut impl RandomNumberGenerator) -> Self {
37        let mut key = [0u8; ED25519_PRIVATE_KEY_SIZE];
38        rng.fill_random_data(&mut key);
39        Self::from_data(key)
40    }
41
42    /// Returns the Ed25519 private key as an array of bytes.
43    pub fn data(&self) -> &[u8; ED25519_PRIVATE_KEY_SIZE] {
44        &self.0
45    }
46
47    /// Restores an Ed25519 private key from an array of bytes.
48    pub const fn from_data(data: [u8; ED25519_PRIVATE_KEY_SIZE]) -> Self {
49        Self(data)
50    }
51
52    /// Restores an Ed25519 private key from a reference to an array of bytes.
53    pub fn from_data_ref(data: impl AsRef<[u8]>) -> Result<Self> {
54        let data = data.as_ref();
55        if data.len() != ED25519_PRIVATE_KEY_SIZE {
56            bail!("Invalid Ed25519 private key size");
57        }
58        let mut arr = [0u8; ED25519_PRIVATE_KEY_SIZE];
59        arr.copy_from_slice(data);
60        Ok(Self::from_data(arr))
61    }
62
63    /// Derives a new `SigningPrivateKey` from the given key material.
64    pub fn derive_from_key_material(key_material: impl AsRef<[u8]>) -> Self {
65        Self::from_data(bc_crypto::x25519_derive_signing_private_key(key_material))
66    }
67
68    pub fn hex(&self) -> String {
69        hex::encode(self.data())
70    }
71
72    pub fn from_hex(hex: impl AsRef<str>) -> Result<Self> {
73        let data = hex::decode(hex.as_ref())?;
74        Self::from_data_ref(data)
75    }
76}
77
78impl Ed25519PrivateKey {
79    /// Derives the public key from this Ed25519 private key.
80    pub fn public_key(&self) -> Ed25519PublicKey {
81        bc_crypto::ed25519_public_key_from_private_key(self.into()).into()
82    }
83
84    pub fn sign(&self, message: impl AsRef<[u8]>) -> [u8; bc_crypto::ED25519_SIGNATURE_SIZE] {
85        bc_crypto::ed25519_sign(&self.0, message.as_ref())
86    }
87}
88
89/// Implements conversion from a byte array to an Ed25519PrivateKey.
90impl From<[u8; ED25519_PRIVATE_KEY_SIZE]> for Ed25519PrivateKey {
91    fn from(data: [u8; ED25519_PRIVATE_KEY_SIZE]) -> Self {
92        Self::from_data(data)
93    }
94}
95
96/// Implements AsRef<[u8]> to allow Ed25519PrivateKey to be treated as a byte slice.
97impl AsRef<[u8]> for Ed25519PrivateKey {
98    fn as_ref(&self) -> &[u8] {
99        &self.0
100    }
101}
102
103/// Implements Display to output the key as a hex string.
104impl std::fmt::Display for Ed25519PrivateKey {
105    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
106        write!(f, "{}", self.hex())
107    }
108}
109
110/// Implements Debug to output the key with a type label.
111impl std::fmt::Debug for Ed25519PrivateKey {
112    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
113        write!(f, "Ed25519PrivateKey({})", self.hex())
114    }
115}
116
117/// Implements Default to create a new random Ed25519PrivateKey.
118impl Default for Ed25519PrivateKey {
119    fn default() -> Self {
120        Self::new()
121    }
122}
123
124/// Implements conversion from an Ed25519PrivateKey reference to a byte array reference.
125impl<'a> From<&'a Ed25519PrivateKey> for &'a [u8; ED25519_PRIVATE_KEY_SIZE] {
126    fn from(value: &'a Ed25519PrivateKey) -> Self {
127        &value.0
128    }
129}
130
131/// Implements conversion from an Ed25519PrivateKey reference to a byte slice.
132impl<'a> From<&'a Ed25519PrivateKey> for &'a [u8] {
133    fn from(value: &'a Ed25519PrivateKey) -> Self {
134        &value.0
135    }
136}