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
use std::rc::Rc;
use bc_crypto::{RandomNumberGenerator, x25519_new_agreement_private_key_using};
use bc_ur::{UREncodable, URDecodable, URCodable};
use dcbor::{Tag, CBORTagged, CBOREncodable, CBORTaggedEncodable, CBORDecodable, CBORTaggedDecodable, CBOR};
use crate::{tags, AgreementPublicKey, SymmetricKey};

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

impl AgreementPrivateKey {
    pub const KEY_SIZE: usize = 32;

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

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

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

    /// Restore an `AgreementPrivateKey` from a reference to an array of bytes.
    pub fn from_data_ref<T>(data: &T) -> Option<Self> where T: AsRef<[u8]> {
        let data = data.as_ref();
        if data.len() != Self::KEY_SIZE {
            return None;
        }
        let mut arr = [0u8; Self::KEY_SIZE];
        arr.copy_from_slice(data);
        Some(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 `AgreementPrivateKey` from a hex string.
    ///
    /// # Panics
    ///
    /// Panics if the hex string is invalid or the length is not `AgreementPrivateKey::KEY_SIZE * 2`.
    pub fn from_hex<T>(hex: T) -> Self where T: AsRef<str> {
        Self::from_data_ref(&hex::decode(hex.as_ref()).unwrap()).unwrap()
    }

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

    /// Get the `AgreementPublicKey` corresponding to this `AgreementPrivateKey`.
    pub fn public_key(&self) -> AgreementPublicKey {
        AgreementPublicKey::from_data(bc_crypto::x25519_agreement_public_key_from_private_key(self.into()))
    }

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

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

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

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

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

impl CBORTagged for AgreementPrivateKey {
    const CBOR_TAG: Tag = tags::AGREEMENT_PRIVATE_KEY;
}

impl CBOREncodable for AgreementPrivateKey {
    fn cbor(&self) -> CBOR {
        self.tagged_cbor()
    }
}

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

impl CBORDecodable for AgreementPrivateKey {
    fn from_cbor(cbor: &CBOR) -> Result<Self, dcbor::Error> {
        Self::from_tagged_cbor(cbor)
    }
}

impl CBORTaggedDecodable for AgreementPrivateKey {
    fn from_untagged_cbor(untagged_cbor: &CBOR) -> Result<Self, dcbor::Error> {
        let data = CBOR::expect_byte_string(untagged_cbor)?;
        let instance = Self::from_data_ref(&data).ok_or(dcbor::Error::InvalidFormat)?;
        Ok(instance)
    }
}

impl UREncodable for AgreementPrivateKey { }

impl URDecodable for AgreementPrivateKey { }

impl URCodable for AgreementPrivateKey { }

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

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

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

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