bc_components/x25519/
x25519_private_key.rs

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
use std::rc::Rc;
use bc_crypto::x25519_new_private_key_using;
use bc_ur::prelude::*;
use crate::{ tags, Decrypter, EncapsulationPrivateKey, SymmetricKey, X25519PublicKey };
use bc_rand::{ SecureRandomNumberGenerator, RandomNumberGenerator };
use anyhow::{ bail, Error, Result };

/// A Curve25519 private key used for X25519 key agreement.
///
/// <https://datatracker.ietf.org/doc/html/rfc7748>
#[derive(Clone, PartialEq, Eq, Hash)]
pub struct X25519PrivateKey([u8; Self::KEY_SIZE]);

impl X25519PrivateKey {
    pub const KEY_SIZE: usize = 32;

    /// Generate a new random `X25519PrivateKey`.
    pub fn new() -> Self {
        let mut rng = SecureRandomNumberGenerator;
        Self::new_using(&mut rng)
    }

    /// Generate a new random `X25519PrivateKey` and corresponding `X25519PublicKey`.
    pub fn keypair() -> (X25519PrivateKey, X25519PublicKey) {
        let private_key = X25519PrivateKey::new();
        let public_key = private_key.public_key();
        (private_key, public_key)
    }

    /// Generate a new random `X25519PrivateKey` and corresponding `X25519PublicKey` using the given random number generator.
    pub fn keypair_using(rng: &mut impl RandomNumberGenerator) -> (X25519PrivateKey, X25519PublicKey) {
        let private_key = X25519PrivateKey::new_using(rng);
        let public_key = private_key.public_key();
        (private_key, public_key)
    }

    /// Generate a new random `X25519PrivateKey` using the given random number generator.
    pub fn new_using(rng: &mut impl RandomNumberGenerator) -> Self {
        Self(x25519_new_private_key_using(rng))
    }

    /// Restore an `X25519PrivateKey` from a fixed-size array of bytes.
    pub const fn from_data(data: [u8; Self::KEY_SIZE]) -> Self {
        Self(data)
    }

    /// Restore an `X25519PrivateKey` from a reference to an array of bytes.
    pub fn from_data_ref(data: impl AsRef<[u8]>) -> Result<Self> {
        let data = data.as_ref();
        if data.len() != Self::KEY_SIZE {
            bail!("Invalid X25519 private key size");
        }
        let mut arr = [0u8; Self::KEY_SIZE];
        arr.copy_from_slice(data);
        Ok(Self::from_data(arr))
    }

    /// Get a reference to the fixed-size array of bytes.
    pub fn data(&self) -> &[u8; Self::KEY_SIZE] {
        self.into()
    }

    /// Restore an `X25519PrivateKey` from a hex string.
    ///
    /// # Panics
    ///
    /// Panics if the hex string is invalid or the length is not `X25519PrivateKey::KEY_SIZE * 2`.
    pub fn from_hex(hex: impl AsRef<str>) -> Self {
        Self::from_data_ref(hex::decode(hex.as_ref()).unwrap()).unwrap()
    }

    /// Get the hex string representation of the `X25519PrivateKey`.
    pub fn hex(&self) -> String {
        hex::encode(self.data())
    }

    /// Get the `X25519PublicKey` corresponding to this `X25519PrivateKey`.
    pub fn public_key(&self) -> X25519PublicKey {
        X25519PublicKey::from_data(
            bc_crypto::x25519_public_key_from_private_key(self.into())
        )
    }

    /// Derive an `X25519PrivateKey` from the given key material.
    pub fn derive_from_key_material(key_material: impl AsRef<[u8]>) -> Self {
        Self::from_data(bc_crypto::x25519_derive_private_key(key_material))
    }

    /// Derive a shared symmetric key from this `X25519PrivateKey` and the given `X25519PublicKey`.
    pub fn shared_key_with(&self, public_key: &X25519PublicKey) -> SymmetricKey {
        SymmetricKey::from_data(bc_crypto::x25519_shared_key(self.into(), public_key.into()))
    }
}

impl Decrypter for X25519PrivateKey{
    fn encapsulation_private_key(&self) -> EncapsulationPrivateKey {
        EncapsulationPrivateKey::X25519(self.clone())
    }
}

impl Default for X25519PrivateKey {
    fn default() -> Self {
        Self::new()
    }
}

// Convert from an `X25519PrivateKey` to a `&'a [u8; X25519PrivateKey::KEY_SIZE]`.
impl<'a> From<&'a X25519PrivateKey> for &'a [u8; X25519PrivateKey::KEY_SIZE] {
    fn from(value: &'a X25519PrivateKey) -> Self {
        &value.0
    }
}

impl From<Rc<X25519PrivateKey>> for X25519PrivateKey {
    fn from(value: Rc<X25519PrivateKey>) -> Self {
        value.as_ref().clone()
    }
}

impl AsRef<X25519PrivateKey> for X25519PrivateKey {
    fn as_ref(&self) -> &Self {
        self
    }
}

impl CBORTagged for X25519PrivateKey {
    fn cbor_tags() -> Vec<Tag> {
        tags_for_values(&[tags::TAG_X25519_PRIVATE_KEY])
    }
}

impl From<X25519PrivateKey> for CBOR {
    fn from(value: X25519PrivateKey) -> Self {
        value.tagged_cbor()
    }
}

impl CBORTaggedEncodable for X25519PrivateKey {
    fn untagged_cbor(&self) -> CBOR {
        CBOR::to_byte_string(self.data())
    }
}

impl TryFrom<CBOR> for X25519PrivateKey {
    type Error = Error;

    fn try_from(cbor: CBOR) -> Result<Self, Self::Error> {
        Self::from_tagged_cbor(cbor)
    }
}

impl CBORTaggedDecodable for X25519PrivateKey {
    fn from_untagged_cbor(untagged_cbor: CBOR) -> Result<Self> {
        let data = CBOR::try_into_byte_string(untagged_cbor)?;
        Self::from_data_ref(data)
    }
}

impl std::fmt::Debug for X25519PrivateKey {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "X25519PrivateKey({})", self.hex())
    }
}

// Convert from a reference to a byte vector to a X25519PrivateKey.
impl From<&X25519PrivateKey> for X25519PrivateKey {
    fn from(key: &X25519PrivateKey) -> Self {
        key.clone()
    }
}

// Convert from a byte vector to a X25519PrivateKey.
impl From<X25519PrivateKey> for Vec<u8> {
    fn from(key: X25519PrivateKey) -> Self {
        key.0.to_vec()
    }
}

// Convert from a reference to a byte vector to a X25519PrivateKey.
impl From<&X25519PrivateKey> for Vec<u8> {
    fn from(key: &X25519PrivateKey) -> Self {
        key.0.to_vec()
    }
}