bc_components/ec_key/
ec_private_key.rs

1use bc_rand::{RandomNumberGenerator, SecureRandomNumberGenerator};
2use bc_ur::prelude::*;
3
4use crate::{
5    ECKey, ECKeyBase, ECPublicKey, Error, Result, SchnorrPublicKey, tags,
6};
7
8/// The size of an ECDSA private key in bytes (32 bytes).
9pub const ECDSA_PRIVATE_KEY_SIZE: usize = bc_crypto::ECDSA_PRIVATE_KEY_SIZE;
10
11/// A private key for elliptic curve digital signature algorithms.
12///
13/// An `ECPrivateKey` is a 32-byte secret value that can be used to:
14///
15/// - Generate its corresponding public key
16/// - Sign messages using the ECDSA signature scheme
17/// - Sign messages using the Schnorr signature scheme (BIP-340)
18///
19/// These keys use the secp256k1 curve, which is the same curve used in Bitcoin
20/// and other cryptocurrencies. The secp256k1 curve is defined by the Standards
21/// for Efficient Cryptography Group (SECG).
22///
23/// # Security
24///
25/// Private keys should be kept secret and never exposed. They represent
26/// proof of ownership and control over any associated assets or identities.
27///
28/// # Examples
29///
30/// Creating a new random private key:
31///
32/// ```
33/// use bc_components::ECPrivateKey;
34///
35/// // Generate a random private key
36/// let private_key = ECPrivateKey::new();
37/// ```
38///
39/// Signing a message with ECDSA:
40///
41/// ```
42/// use bc_components::ECPrivateKey;
43///
44/// // Generate a random private key
45/// let private_key = ECPrivateKey::new();
46///
47/// // Sign a message
48/// let message = b"Hello, world!";
49/// let signature = private_key.ecdsa_sign(message);
50/// ```
51#[derive(Clone, PartialEq, Eq, Hash)]
52pub struct ECPrivateKey([u8; ECDSA_PRIVATE_KEY_SIZE]);
53
54impl ECPrivateKey {
55    /// Creates a new random ECDSA private key.
56    ///
57    /// Uses a secure random number generator to generate the key.
58    pub fn new() -> Self {
59        let mut rng = SecureRandomNumberGenerator;
60        Self::new_using(&mut rng)
61    }
62
63    /// Creates a new random ECDSA private key using the given random number
64    /// generator.
65    ///
66    /// This allows for deterministic key generation when using a seeded RNG.
67    pub fn new_using(rng: &mut impl RandomNumberGenerator) -> Self {
68        let mut key = [0u8; ECDSA_PRIVATE_KEY_SIZE];
69        rng.fill_random_data(&mut key);
70        Self::from_data(key)
71    }
72
73    /// Returns the ECDSA private key as an array of bytes.
74    pub fn data(&self) -> &[u8; ECDSA_PRIVATE_KEY_SIZE] { &self.0 }
75
76    /// Get the ECDSA private key as a byte slice.
77    pub fn as_bytes(&self) -> &[u8] { self.as_ref() }
78
79    /// Restores an ECDSA private key from an array of bytes.
80    ///
81    /// This method performs no validation on the input data.
82    pub const fn from_data(data: [u8; ECDSA_PRIVATE_KEY_SIZE]) -> Self {
83        Self(data)
84    }
85
86    /// Restores an ECDSA private key from a reference to an array of bytes.
87    ///
88    /// Returns an error if the data is not exactly 32 bytes.
89    pub fn from_data_ref(data: impl AsRef<[u8]>) -> Result<Self> {
90        let data = data.as_ref();
91        if data.len() != ECDSA_PRIVATE_KEY_SIZE {
92            return Err(Error::invalid_size(
93                "EC private key",
94                ECDSA_PRIVATE_KEY_SIZE,
95                data.len(),
96            ));
97        }
98        let mut arr = [0u8; ECDSA_PRIVATE_KEY_SIZE];
99        arr.copy_from_slice(data);
100        Ok(Self::from_data(arr))
101    }
102
103    /// Derives a new private key from the given key material.
104    ///
105    /// This method uses the provided key material to deterministically
106    /// generate a valid private key for the secp256k1 curve.
107    pub fn derive_from_key_material(key_material: impl AsRef<[u8]>) -> Self {
108        Self::from_data(bc_crypto::derive_signing_private_key(key_material))
109    }
110}
111
112impl ECPrivateKey {
113    /// Derives the Schnorr public key from this ECDSA private key.
114    ///
115    /// Schnorr public keys are used with the BIP-340 Schnorr signature scheme.
116    /// Unlike ECDSA public keys, Schnorr public keys are 32 bytes ("x-only")
117    /// rather than 33 bytes.
118    pub fn schnorr_public_key(&self) -> SchnorrPublicKey {
119        bc_crypto::schnorr_public_key_from_private_key(self.into()).into()
120    }
121
122    /// Signs a message using the ECDSA signature scheme.
123    ///
124    /// Returns a 70-72 byte signature in DER format.
125    pub fn ecdsa_sign(
126        &self,
127        message: impl AsRef<[u8]>,
128    ) -> [u8; bc_crypto::ECDSA_SIGNATURE_SIZE] {
129        bc_crypto::ecdsa_sign(&self.0, message.as_ref())
130    }
131
132    /// Signs a message using the Schnorr signature scheme with a custom random
133    /// number generator.
134    ///
135    /// This method implements the BIP-340 Schnorr signature scheme, which
136    /// provides several advantages over ECDSA including linearity (allowing
137    /// for signature aggregation) and non-malleability.
138    ///
139    /// Returns a 64-byte signature.
140    pub fn schnorr_sign_using(
141        &self,
142        message: impl AsRef<[u8]>,
143        rng: &mut dyn RandomNumberGenerator,
144    ) -> [u8; bc_crypto::SCHNORR_SIGNATURE_SIZE] {
145        bc_crypto::schnorr_sign_using(&self.0, message, rng)
146    }
147
148    /// Signs a message using the Schnorr signature scheme.
149    ///
150    /// Uses a secure random number generator for nonce generation.
151    ///
152    /// Returns a 64-byte signature.
153    pub fn schnorr_sign(
154        &self,
155        message: impl AsRef<[u8]>,
156    ) -> [u8; bc_crypto::SCHNORR_SIGNATURE_SIZE] {
157        let mut rng = SecureRandomNumberGenerator;
158        self.schnorr_sign_using(message, &mut rng)
159    }
160}
161
162/// Converts a fixed-size byte array to an `ECPrivateKey`.
163impl From<[u8; ECDSA_PRIVATE_KEY_SIZE]> for ECPrivateKey {
164    /// Converts a 32-byte array into an EC private key.
165    fn from(data: [u8; ECDSA_PRIVATE_KEY_SIZE]) -> Self {
166        Self::from_data(data)
167    }
168}
169
170/// Provides a reference to the key data as a byte slice.
171impl AsRef<[u8]> for ECPrivateKey {
172    /// Returns a reference to the key as a byte slice.
173    fn as_ref(&self) -> &[u8] { self.0.as_ref() }
174}
175
176/// Formats the key as a hexadecimal string.
177impl std::fmt::Display for ECPrivateKey {
178    /// Displays the key as a hexadecimal string.
179    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
180        write!(f, "{}", self.hex())
181    }
182}
183
184/// Formats the key for debugging, showing type name and hexadecimal value.
185impl std::fmt::Debug for ECPrivateKey {
186    /// Displays the key with type information and hexadecimal value.
187    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
188        write!(f, "ECPrivateKey({})", self.hex())
189    }
190}
191
192/// Implements the `Default` trait, creating a random key.
193impl Default for ECPrivateKey {
194    /// Creates a new random key as the default value.
195    fn default() -> Self { Self::new() }
196}
197
198/// Converts a reference to an `ECPrivateKey` to a reference to a fixed-size
199/// byte array.
200impl<'a> From<&'a ECPrivateKey> for &'a [u8; ECDSA_PRIVATE_KEY_SIZE] {
201    /// Returns a reference to the underlying byte array.
202    fn from(value: &'a ECPrivateKey) -> Self { &value.0 }
203}
204
205/// Converts a reference to an `ECPrivateKey` to a reference to a byte slice.
206impl<'a> From<&'a ECPrivateKey> for &'a [u8] {
207    /// Returns a reference to the key as a byte slice.
208    fn from(value: &'a ECPrivateKey) -> Self { value.as_ref() }
209}
210
211/// Implements the `ECKeyBase` trait methods.
212impl ECKeyBase for ECPrivateKey {
213    /// The size of an EC private key (32 bytes).
214    const KEY_SIZE: usize = bc_crypto::ECDSA_PRIVATE_KEY_SIZE;
215
216    /// Creates a key from a byte slice, with validation.
217    fn from_data_ref(data: impl AsRef<[u8]>) -> Result<Self>
218    where
219        Self: Sized,
220    {
221        let data = data.as_ref();
222        if data.len() != ECDSA_PRIVATE_KEY_SIZE {
223            return Err(Error::invalid_size(
224                "EC private key",
225                ECDSA_PRIVATE_KEY_SIZE,
226                data.len(),
227            ));
228        }
229        let mut key = [0u8; ECDSA_PRIVATE_KEY_SIZE];
230        key.copy_from_slice(data);
231        Ok(Self(key))
232    }
233
234    /// Returns the key as a byte slice.
235    fn data(&self) -> &[u8] { self.0.as_ref() }
236}
237
238/// Implements the `ECKey` trait for deriving public keys.
239impl ECKey for ECPrivateKey {
240    /// Derives the corresponding ECDSA compressed public key.
241    fn public_key(&self) -> ECPublicKey {
242        bc_crypto::ecdsa_public_key_from_private_key(&self.0).into()
243    }
244}
245
246/// Defines CBOR tags for EC keys.
247impl CBORTagged for ECPrivateKey {
248    /// Returns the CBOR tags for EC keys.
249    fn cbor_tags() -> Vec<Tag> {
250        tags_for_values(&[tags::TAG_EC_KEY, tags::TAG_EC_KEY_V1])
251    }
252}
253
254/// Converts an `ECPrivateKey` to CBOR.
255impl From<ECPrivateKey> for CBOR {
256    /// Converts to tagged CBOR.
257    fn from(value: ECPrivateKey) -> Self { value.tagged_cbor() }
258}
259
260/// Implements CBOR encoding for EC private keys.
261impl CBORTaggedEncodable for ECPrivateKey {
262    /// Creates the untagged CBOR representation.
263    ///
264    /// The format is a map with:
265    /// - Key 2: boolean true (indicates private key)
266    /// - Key 3: byte string of the key data
267    fn untagged_cbor(&self) -> CBOR {
268        let mut m = Map::new();
269        m.insert(2, true);
270        m.insert(3, CBOR::to_byte_string(self.0));
271        m.into()
272    }
273}