bc_components/ed25519/
ed25519_private_key.rs1use 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#[derive(Clone, PartialEq, Eq, Hash)]
25pub struct Ed25519PrivateKey([u8; ED25519_PRIVATE_KEY_SIZE]);
26
27impl Ed25519PrivateKey {
28 pub fn new() -> Self {
30 let mut rng = SecureRandomNumberGenerator;
31 Self::new_using(&mut rng)
32 }
33
34 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 pub fn data(&self) -> &[u8; ED25519_PRIVATE_KEY_SIZE] { &self.0 }
44
45 pub fn as_bytes(&self) -> &[u8] { self.as_ref() }
47
48 pub const fn from_data(data: [u8; ED25519_PRIVATE_KEY_SIZE]) -> Self {
50 Self(data)
51 }
52
53 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 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 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
95impl 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
102impl AsRef<[u8]> for Ed25519PrivateKey {
105 fn as_ref(&self) -> &[u8] { &self.0 }
106}
107
108impl 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
115impl 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
122impl Default for Ed25519PrivateKey {
124 fn default() -> Self { Self::new() }
125}
126
127impl<'a> From<&'a Ed25519PrivateKey> for &'a [u8; ED25519_PRIVATE_KEY_SIZE] {
130 fn from(value: &'a Ed25519PrivateKey) -> Self { &value.0 }
131}
132
133impl<'a> From<&'a Ed25519PrivateKey> for &'a [u8] {
135 fn from(value: &'a Ed25519PrivateKey) -> Self { &value.0 }
136}