bc_components/ed25519/
ed25519_private_key.rs1use 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#[derive(Clone, PartialEq, Eq, Hash)]
26pub struct Ed25519PrivateKey([u8; ED25519_PRIVATE_KEY_SIZE]);
27
28impl Ed25519PrivateKey {
29 pub fn new() -> Self {
31 let mut rng = SecureRandomNumberGenerator;
32 Self::new_using(&mut rng)
33 }
34
35 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] {
44 &self.0
45 }
46
47 pub const fn from_data(data: [u8; ED25519_PRIVATE_KEY_SIZE]) -> Self {
49 Self(data)
50 }
51
52 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 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 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
89impl 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
96impl AsRef<[u8]> for Ed25519PrivateKey {
98 fn as_ref(&self) -> &[u8] {
99 &self.0
100 }
101}
102
103impl 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
110impl 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
117impl Default for Ed25519PrivateKey {
119 fn default() -> Self {
120 Self::new()
121 }
122}
123
124impl<'a> From<&'a Ed25519PrivateKey> for &'a [u8; ED25519_PRIVATE_KEY_SIZE] {
126 fn from(value: &'a Ed25519PrivateKey) -> Self {
127 &value.0
128 }
129}
130
131impl<'a> From<&'a Ed25519PrivateKey> for &'a [u8] {
133 fn from(value: &'a Ed25519PrivateKey) -> Self {
134 &value.0
135 }
136}