bc_components/ed25519/
ed25519_private_key.rs1use 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#[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 {
38 let mut key = [0u8; ED25519_PRIVATE_KEY_SIZE];
39 rng.fill_random_data(&mut key);
40 Self::from_data(key)
41 }
42
43 pub fn data(&self) -> &[u8; ED25519_PRIVATE_KEY_SIZE] { &self.0 }
45
46 pub fn as_bytes(&self) -> &[u8] { self.as_ref() }
48
49 pub const fn from_data(data: [u8; ED25519_PRIVATE_KEY_SIZE]) -> Self {
51 Self(data)
52 }
53
54 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 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 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
92impl 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
99impl AsRef<[u8]> for Ed25519PrivateKey {
102 fn as_ref(&self) -> &[u8] { &self.0 }
103}
104
105impl 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
112impl 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
119impl Default for Ed25519PrivateKey {
121 fn default() -> Self { Self::new() }
122}
123
124impl<'a> From<&'a Ed25519PrivateKey> for &'a [u8; ED25519_PRIVATE_KEY_SIZE] {
127 fn from(value: &'a Ed25519PrivateKey) -> Self { &value.0 }
128}
129
130impl<'a> From<&'a Ed25519PrivateKey> for &'a [u8] {
132 fn from(value: &'a Ed25519PrivateKey) -> Self { &value.0 }
133}