bc_components/ed25519/
ed25519_private_key.rs

1use anyhow::{Result, bail};
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
11/// finite field 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
36    /// generator.
37    pub fn new_using(rng: &mut impl RandomNumberGenerator) -> Self {
38        let mut key = [0u8; ED25519_PRIVATE_KEY_SIZE];
39        rng.fill_random_data(&mut key);
40        Self::from_data(key)
41    }
42
43    /// Returns the Ed25519 private key as an array of bytes.
44    pub fn data(&self) -> &[u8; ED25519_PRIVATE_KEY_SIZE] { &self.0 }
45
46    /// Get the Ed25519 private key as a byte slice.
47    pub fn as_bytes(&self) -> &[u8] { self.as_ref() }
48
49    /// Restores an Ed25519 private key from an array of bytes.
50    pub const fn from_data(data: [u8; ED25519_PRIVATE_KEY_SIZE]) -> Self {
51        Self(data)
52    }
53
54    /// Restores an Ed25519 private key from a reference to an array of bytes.
55    pub fn from_data_ref(data: impl AsRef<[u8]>) -> Result<Self> {
56        let data = data.as_ref();
57        if data.len() != ED25519_PRIVATE_KEY_SIZE {
58            bail!("Invalid Ed25519 private key size");
59        }
60        let mut arr = [0u8; ED25519_PRIVATE_KEY_SIZE];
61        arr.copy_from_slice(data);
62        Ok(Self::from_data(arr))
63    }
64
65    /// Derives a new `SigningPrivateKey` from the given key material.
66    pub fn derive_from_key_material(key_material: impl AsRef<[u8]>) -> Self {
67        Self::from_data(bc_crypto::derive_signing_private_key(key_material))
68    }
69
70    pub fn hex(&self) -> String { hex::encode(self.data()) }
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(
85        &self,
86        message: impl AsRef<[u8]>,
87    ) -> [u8; bc_crypto::ED25519_SIGNATURE_SIZE] {
88        bc_crypto::ed25519_sign(&self.0, message.as_ref())
89    }
90}
91
92/// Implements conversion from a byte array to an Ed25519PrivateKey.
93impl From<[u8; ED25519_PRIVATE_KEY_SIZE]> for Ed25519PrivateKey {
94    fn from(data: [u8; ED25519_PRIVATE_KEY_SIZE]) -> Self {
95        Self::from_data(data)
96    }
97}
98
99/// Implements AsRef<[u8]> to allow Ed25519PrivateKey to be treated as a byte
100/// slice.
101impl AsRef<[u8]> for Ed25519PrivateKey {
102    fn as_ref(&self) -> &[u8] { &self.0 }
103}
104
105/// Implements Display to output the key as a hex string.
106impl std::fmt::Display for Ed25519PrivateKey {
107    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
108        write!(f, "{}", self.hex())
109    }
110}
111
112/// Implements Debug to output the key with a type label.
113impl std::fmt::Debug for Ed25519PrivateKey {
114    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
115        write!(f, "Ed25519PrivateKey({})", self.hex())
116    }
117}
118
119/// Implements Default to create a new random Ed25519PrivateKey.
120impl Default for Ed25519PrivateKey {
121    fn default() -> Self { Self::new() }
122}
123
124/// Implements conversion from an Ed25519PrivateKey reference to a byte array
125/// reference.
126impl<'a> From<&'a Ed25519PrivateKey> for &'a [u8; ED25519_PRIVATE_KEY_SIZE] {
127    fn from(value: &'a Ed25519PrivateKey) -> Self { &value.0 }
128}
129
130/// Implements conversion from an Ed25519PrivateKey reference to a byte slice.
131impl<'a> From<&'a Ed25519PrivateKey> for &'a [u8] {
132    fn from(value: &'a Ed25519PrivateKey) -> Self { &value.0 }
133}