bc_components/x25519/
x25519_private_key.rs

1use std::rc::Rc;
2
3use bc_crypto::x25519_new_private_key_using;
4use bc_rand::{RandomNumberGenerator, SecureRandomNumberGenerator};
5use bc_ur::prelude::*;
6
7use crate::{
8    Decrypter, Digest, EncapsulationPrivateKey, Error, Reference,
9    ReferenceProvider, Result, SymmetricKey, X25519PublicKey, tags,
10};
11
12/// A private key for X25519 key agreement operations.
13///
14/// X25519 is an elliptic-curve Diffie-Hellman key exchange protocol based on
15/// Curve25519 as defined in [RFC 7748](https://datatracker.ietf.org/doc/html/rfc7748). It allows
16/// two parties to establish a shared secret key over an insecure channel.
17///
18/// Key features of X25519:
19/// - High security (128-bit security level)
20/// - High performance
21/// - Small key sizes (32 bytes)
22/// - Protection against various side-channel attacks
23/// - Relatively simple implementation compared to other elliptic curve systems
24///
25/// This implementation provides:
26/// - Generation of random X25519 private keys
27/// - Derivation of the corresponding public key
28/// - Shared key generation with another party's public key
29/// - CBOR serialization and deserialization
30/// - Various utility and conversion methods
31#[derive(Clone, PartialEq, Eq, Hash)]
32pub struct X25519PrivateKey([u8; Self::KEY_SIZE]);
33
34impl X25519PrivateKey {
35    pub const KEY_SIZE: usize = 32;
36
37    /// Generate a new random `X25519PrivateKey`.
38    pub fn new() -> Self {
39        let mut rng = SecureRandomNumberGenerator;
40        Self::new_using(&mut rng)
41    }
42
43    /// Generate a new random `X25519PrivateKey` and corresponding
44    /// `X25519PublicKey`.
45    pub fn keypair() -> (X25519PrivateKey, X25519PublicKey) {
46        let private_key = X25519PrivateKey::new();
47        let public_key = private_key.public_key();
48        (private_key, public_key)
49    }
50
51    /// Generate a new random `X25519PrivateKey` and corresponding
52    /// `X25519PublicKey` using the given random number generator.
53    pub fn keypair_using(
54        rng: &mut impl RandomNumberGenerator,
55    ) -> (X25519PrivateKey, X25519PublicKey) {
56        let private_key = X25519PrivateKey::new_using(rng);
57        let public_key = private_key.public_key();
58        (private_key, public_key)
59    }
60
61    /// Generate a new random `X25519PrivateKey` using the given random number
62    /// generator.
63    pub fn new_using(rng: &mut impl RandomNumberGenerator) -> Self {
64        Self(x25519_new_private_key_using(rng))
65    }
66
67    /// Restore an `X25519PrivateKey` from a fixed-size array of bytes.
68    pub const fn from_data(data: [u8; Self::KEY_SIZE]) -> Self { Self(data) }
69
70    /// Restore an `X25519PrivateKey` from a reference to an array of bytes.
71    pub fn from_data_ref(data: impl AsRef<[u8]>) -> Result<Self> {
72        let data = data.as_ref();
73        if data.len() != Self::KEY_SIZE {
74            return Err(Error::invalid_size(
75                "X25519 private key",
76                Self::KEY_SIZE,
77                data.len(),
78            ));
79        }
80        let mut arr = [0u8; Self::KEY_SIZE];
81        arr.copy_from_slice(data);
82        Ok(Self::from_data(arr))
83    }
84
85    /// Get a reference to the fixed-size array of bytes.
86    pub fn data(&self) -> &[u8; Self::KEY_SIZE] { self.into() }
87
88    /// Get the X25519 private key as a byte slice.
89    pub fn as_bytes(&self) -> &[u8] { self.as_ref() }
90
91    /// Restore an `X25519PrivateKey` from a hex string.
92    ///
93    /// # Panics
94    ///
95    /// Panics if the hex string is invalid or the length is not
96    /// `X25519PrivateKey::KEY_SIZE * 2`.
97    pub fn from_hex(hex: impl AsRef<str>) -> Self {
98        Self::from_data_ref(hex::decode(hex.as_ref()).unwrap()).unwrap()
99    }
100
101    /// Get the hex string representation of the `X25519PrivateKey`.
102    pub fn hex(&self) -> String { hex::encode(self.data()) }
103
104    /// Get the `X25519PublicKey` corresponding to this `X25519PrivateKey`.
105    pub fn public_key(&self) -> X25519PublicKey {
106        X25519PublicKey::from_data(
107            bc_crypto::x25519_public_key_from_private_key(self.into()),
108        )
109    }
110
111    /// Derive an `X25519PrivateKey` from the given key material.
112    pub fn derive_from_key_material(key_material: impl AsRef<[u8]>) -> Self {
113        Self::from_data(bc_crypto::derive_agreement_private_key(key_material))
114    }
115
116    /// Derive a shared symmetric key from this `X25519PrivateKey` and the given
117    /// `X25519PublicKey`.
118    pub fn shared_key_with(
119        &self,
120        public_key: &X25519PublicKey,
121    ) -> SymmetricKey {
122        SymmetricKey::from_data(bc_crypto::x25519_shared_key(
123            self.into(),
124            public_key.into(),
125        ))
126    }
127}
128
129impl AsRef<[u8]> for X25519PrivateKey {
130    fn as_ref(&self) -> &[u8] { &self.0 }
131}
132
133/// Implements the Decrypter trait to support key encapsulation mechanisms.
134impl Decrypter for X25519PrivateKey {
135    fn encapsulation_private_key(&self) -> EncapsulationPrivateKey {
136        EncapsulationPrivateKey::X25519(self.clone())
137    }
138}
139
140/// Implements Default to create a new random X25519PrivateKey.
141impl Default for X25519PrivateKey {
142    fn default() -> Self { Self::new() }
143}
144
145/// Implements conversion from an X25519PrivateKey reference to a byte array
146/// reference.
147impl<'a> From<&'a X25519PrivateKey> for &'a [u8; X25519PrivateKey::KEY_SIZE] {
148    fn from(value: &'a X25519PrivateKey) -> Self { &value.0 }
149}
150
151/// Implements conversion from a reference-counted X25519PrivateKey to an owned
152/// X25519PrivateKey.
153impl From<Rc<X25519PrivateKey>> for X25519PrivateKey {
154    fn from(value: Rc<X25519PrivateKey>) -> Self { value.as_ref().clone() }
155}
156
157/// Implements `AsRef<X25519PrivateKey>` to allow self-reference.
158impl AsRef<X25519PrivateKey> for X25519PrivateKey {
159    fn as_ref(&self) -> &Self { self }
160}
161
162/// Implements the CBORTagged trait to provide CBOR tag information.
163impl CBORTagged for X25519PrivateKey {
164    fn cbor_tags() -> Vec<Tag> {
165        tags_for_values(&[tags::TAG_X25519_PRIVATE_KEY])
166    }
167}
168
169/// Implements conversion from X25519PrivateKey to CBOR for serialization.
170impl From<X25519PrivateKey> for CBOR {
171    fn from(value: X25519PrivateKey) -> Self { value.tagged_cbor() }
172}
173
174/// Implements CBORTaggedEncodable to provide CBOR encoding functionality.
175impl CBORTaggedEncodable for X25519PrivateKey {
176    fn untagged_cbor(&self) -> CBOR { CBOR::to_byte_string(self.data()) }
177}
178
179/// Implements `TryFrom<CBOR>` for X25519PrivateKey to support conversion from
180/// CBOR data.
181impl TryFrom<CBOR> for X25519PrivateKey {
182    type Error = dcbor::Error;
183
184    fn try_from(cbor: CBOR) -> dcbor::Result<Self> {
185        Self::from_tagged_cbor(cbor)
186    }
187}
188
189/// Implements CBORTaggedDecodable to provide CBOR decoding functionality.
190impl CBORTaggedDecodable for X25519PrivateKey {
191    fn from_untagged_cbor(untagged_cbor: CBOR) -> dcbor::Result<Self> {
192        let data = CBOR::try_into_byte_string(untagged_cbor)?;
193        Ok(Self::from_data_ref(data)?)
194    }
195}
196
197/// Implements Debug to output the key with a type label.
198impl std::fmt::Debug for X25519PrivateKey {
199    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
200        write!(f, "X25519PrivateKey({})", self.hex())
201    }
202}
203
204/// Implements conversion from an X25519PrivateKey reference to an owned
205/// X25519PrivateKey.
206impl From<&X25519PrivateKey> for X25519PrivateKey {
207    fn from(key: &X25519PrivateKey) -> Self { key.clone() }
208}
209
210/// Implements conversion from an X25519PrivateKey to a byte vector.
211impl From<X25519PrivateKey> for Vec<u8> {
212    fn from(key: X25519PrivateKey) -> Self { key.0.to_vec() }
213}
214
215/// Implements conversion from an X25519PrivateKey reference to a byte vector.
216impl From<&X25519PrivateKey> for Vec<u8> {
217    fn from(key: &X25519PrivateKey) -> Self { key.0.to_vec() }
218}
219
220/// Implements ReferenceProvider to provide a unique reference for the key.
221impl ReferenceProvider for X25519PrivateKey {
222    fn reference(&self) -> Reference {
223        Reference::from_digest(Digest::from_image(
224            self.tagged_cbor().to_cbor_data(),
225        ))
226    }
227}
228
229impl std::fmt::Display for X25519PrivateKey {
230    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
231        write!(f, "X25519PrivateKey({})", self.ref_hex_short())
232    }
233}