bc_components/ed25519/
ed25519_private_key.rs

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