bc_components/x25519/
x25519_private_key.rs

1use std::rc::Rc;
2
3use anyhow::{Result, bail};
4use bc_crypto::x25519_new_private_key_using;
5use bc_rand::{RandomNumberGenerator, SecureRandomNumberGenerator};
6use bc_ur::prelude::*;
7
8use crate::{
9    Decrypter, EncapsulationPrivateKey, 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            bail!("Invalid X25519 private key size");
75        }
76        let mut arr = [0u8; Self::KEY_SIZE];
77        arr.copy_from_slice(data);
78        Ok(Self::from_data(arr))
79    }
80
81    /// Get a reference to the fixed-size array of bytes.
82    pub fn data(&self) -> &[u8; Self::KEY_SIZE] { self.into() }
83
84    /// Get the X25519 private key as a byte slice.
85    pub fn as_bytes(&self) -> &[u8] { self.as_ref() }
86
87    /// Restore an `X25519PrivateKey` from a hex string.
88    ///
89    /// # Panics
90    ///
91    /// Panics if the hex string is invalid or the length is not
92    /// `X25519PrivateKey::KEY_SIZE * 2`.
93    pub fn from_hex(hex: impl AsRef<str>) -> Self {
94        Self::from_data_ref(hex::decode(hex.as_ref()).unwrap()).unwrap()
95    }
96
97    /// Get the hex string representation of the `X25519PrivateKey`.
98    pub fn hex(&self) -> String { hex::encode(self.data()) }
99
100    /// Get the `X25519PublicKey` corresponding to this `X25519PrivateKey`.
101    pub fn public_key(&self) -> X25519PublicKey {
102        X25519PublicKey::from_data(
103            bc_crypto::x25519_public_key_from_private_key(self.into()),
104        )
105    }
106
107    /// Derive an `X25519PrivateKey` from the given key material.
108    pub fn derive_from_key_material(key_material: impl AsRef<[u8]>) -> Self {
109        Self::from_data(bc_crypto::derive_agreement_private_key(key_material))
110    }
111
112    /// Derive a shared symmetric key from this `X25519PrivateKey` and the given
113    /// `X25519PublicKey`.
114    pub fn shared_key_with(
115        &self,
116        public_key: &X25519PublicKey,
117    ) -> SymmetricKey {
118        SymmetricKey::from_data(bc_crypto::x25519_shared_key(
119            self.into(),
120            public_key.into(),
121        ))
122    }
123}
124
125impl AsRef<[u8]> for X25519PrivateKey {
126    fn as_ref(&self) -> &[u8] { &self.0 }
127}
128
129/// Implements the Decrypter trait to support key encapsulation mechanisms.
130impl Decrypter for X25519PrivateKey {
131    fn encapsulation_private_key(&self) -> EncapsulationPrivateKey {
132        EncapsulationPrivateKey::X25519(self.clone())
133    }
134}
135
136/// Implements Default to create a new random X25519PrivateKey.
137impl Default for X25519PrivateKey {
138    fn default() -> Self { Self::new() }
139}
140
141/// Implements conversion from an X25519PrivateKey reference to a byte array
142/// reference.
143impl<'a> From<&'a X25519PrivateKey> for &'a [u8; X25519PrivateKey::KEY_SIZE] {
144    fn from(value: &'a X25519PrivateKey) -> Self { &value.0 }
145}
146
147/// Implements conversion from a reference-counted X25519PrivateKey to an owned
148/// X25519PrivateKey.
149impl From<Rc<X25519PrivateKey>> for X25519PrivateKey {
150    fn from(value: Rc<X25519PrivateKey>) -> Self { value.as_ref().clone() }
151}
152
153/// Implements `AsRef<X25519PrivateKey>` to allow self-reference.
154impl AsRef<X25519PrivateKey> for X25519PrivateKey {
155    fn as_ref(&self) -> &Self { self }
156}
157
158/// Implements the CBORTagged trait to provide CBOR tag information.
159impl CBORTagged for X25519PrivateKey {
160    fn cbor_tags() -> Vec<Tag> {
161        tags_for_values(&[tags::TAG_X25519_PRIVATE_KEY])
162    }
163}
164
165/// Implements conversion from X25519PrivateKey to CBOR for serialization.
166impl From<X25519PrivateKey> for CBOR {
167    fn from(value: X25519PrivateKey) -> Self { value.tagged_cbor() }
168}
169
170/// Implements CBORTaggedEncodable to provide CBOR encoding functionality.
171impl CBORTaggedEncodable for X25519PrivateKey {
172    fn untagged_cbor(&self) -> CBOR { CBOR::to_byte_string(self.data()) }
173}
174
175/// Implements `TryFrom<CBOR>` for X25519PrivateKey to support conversion from
176/// CBOR data.
177impl TryFrom<CBOR> for X25519PrivateKey {
178    type Error = dcbor::Error;
179
180    fn try_from(cbor: CBOR) -> dcbor::Result<Self> {
181        Self::from_tagged_cbor(cbor)
182    }
183}
184
185/// Implements CBORTaggedDecodable to provide CBOR decoding functionality.
186impl CBORTaggedDecodable for X25519PrivateKey {
187    fn from_untagged_cbor(untagged_cbor: CBOR) -> dcbor::Result<Self> {
188        let data = CBOR::try_into_byte_string(untagged_cbor)?;
189        Ok(Self::from_data_ref(data)?)
190    }
191}
192
193/// Implements Debug to output the key with a type label.
194impl std::fmt::Debug for X25519PrivateKey {
195    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
196        write!(f, "X25519PrivateKey({})", self.hex())
197    }
198}
199
200/// Implements conversion from an X25519PrivateKey reference to an owned
201/// X25519PrivateKey.
202impl From<&X25519PrivateKey> for X25519PrivateKey {
203    fn from(key: &X25519PrivateKey) -> Self { key.clone() }
204}
205
206/// Implements conversion from an X25519PrivateKey to a byte vector.
207impl From<X25519PrivateKey> for Vec<u8> {
208    fn from(key: X25519PrivateKey) -> Self { key.0.to_vec() }
209}
210
211/// Implements conversion from an X25519PrivateKey reference to a byte vector.
212impl From<&X25519PrivateKey> for Vec<u8> {
213    fn from(key: &X25519PrivateKey) -> Self { key.0.to_vec() }
214}