bc_components/ed25519/
ed25519_private_key.rs

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