bc_components/x25519/
x25519_public_key.rs

1use std::rc::Rc;
2use bc_ur::prelude::*;
3use crate::{tags, EncapsulationPublicKey, Encrypter};
4use anyhow::{ bail, Result };
5
6/// A public key for X25519 key agreement operations.
7///
8/// X25519 is an elliptic-curve Diffie-Hellman key exchange protocol based on Curve25519
9/// as defined in [RFC 7748](https://datatracker.ietf.org/doc/html/rfc7748). It allows
10/// two parties to establish a shared secret key over an insecure channel.
11///
12/// The X25519 public key is generated from a corresponding private key and is designed to be:
13/// - Compact (32 bytes)
14/// - Fast to use in key agreement operations
15/// - Resistant to various cryptographic attacks
16///
17/// This implementation provides:
18/// - Creation of X25519 public keys from raw data
19/// - CBOR serialization and deserialization
20/// - Support for the Encrypter trait for key encapsulation
21/// - Various utility and conversion methods
22#[derive(Clone, PartialEq, Eq, Hash)]
23pub struct X25519PublicKey([u8; Self::KEY_SIZE]);
24
25impl X25519PublicKey {
26    pub const KEY_SIZE: usize = 32;
27
28    /// Restore an `X25519PublicKey` from a fixed-size array of bytes.
29    pub const fn from_data(data: [u8; Self::KEY_SIZE]) -> Self {
30        Self(data)
31    }
32
33    /// Restore an `X25519PublicKey` from a reference to an array of bytes.
34    pub fn from_data_ref(data: impl AsRef<[u8]>) -> Result<Self> {
35        let data = data.as_ref();
36        if data.len() != Self::KEY_SIZE {
37            bail!("Invalid X25519 public key size");
38        }
39        let mut arr = [0u8; Self::KEY_SIZE];
40        arr.copy_from_slice(data);
41        Ok(Self::from_data(arr))
42    }
43
44    /// Get a reference to the fixed-size array of bytes.
45    pub fn data(&self) -> &[u8; Self::KEY_SIZE] {
46        self.into()
47    }
48
49    /// Restore an `X25519PublicKey` from a hex string.
50    ///
51    /// # Panics
52    ///
53    /// Panics if the hex string is invalid or the length is not `X25519PublicKey::KEY_SIZE * 2`.
54    pub fn from_hex(hex: impl AsRef<str>) -> Self {
55        Self::from_data_ref(hex::decode(hex.as_ref()).unwrap()).unwrap()
56    }
57
58    /// Get the hex string representation of the `X25519PublicKey`.
59    pub fn hex(&self) -> String {
60        hex::encode(self.data())
61    }
62}
63
64/// Implements conversion from a reference-counted X25519PublicKey to an owned X25519PublicKey.
65impl From<Rc<X25519PublicKey>> for X25519PublicKey {
66    fn from(value: Rc<X25519PublicKey>) -> Self {
67        value.as_ref().clone()
68    }
69}
70
71/// Implements conversion from an X25519PublicKey reference to a byte array reference.
72impl<'a> From<&'a X25519PublicKey> for &'a [u8; X25519PublicKey::KEY_SIZE] {
73    fn from(value: &'a X25519PublicKey) -> Self {
74        &value.0
75    }
76}
77
78/// Implements `AsRef<X25519PublicKey>` to allow self-reference.
79impl AsRef<X25519PublicKey> for X25519PublicKey {
80    fn as_ref(&self) -> &X25519PublicKey {
81        self
82    }
83}
84
85/// Implements the CBORTagged trait to provide CBOR tag information.
86impl CBORTagged for X25519PublicKey {
87    fn cbor_tags() -> Vec<Tag> {
88        tags_for_values(&[tags::TAG_X25519_PUBLIC_KEY])
89    }
90}
91
92/// Implements conversion from X25519PublicKey to CBOR for serialization.
93impl From<X25519PublicKey> for CBOR {
94    fn from(value: X25519PublicKey) -> Self {
95        value.tagged_cbor()
96    }
97}
98
99/// Implements CBORTaggedEncodable to provide CBOR encoding functionality.
100impl CBORTaggedEncodable for X25519PublicKey {
101    fn untagged_cbor(&self) -> CBOR {
102        CBOR::to_byte_string(self.data())
103    }
104}
105
106/// Implements `TryFrom<CBOR>` for X25519PublicKey to support conversion from CBOR data.
107impl TryFrom<CBOR> for X25519PublicKey {
108    type Error = dcbor::Error;
109
110    fn try_from(cbor: CBOR) -> dcbor::Result<Self> {
111        Self::from_tagged_cbor(cbor)
112    }
113}
114
115/// Implements CBORTaggedDecodable to provide CBOR decoding functionality.
116impl CBORTaggedDecodable for X25519PublicKey {
117    fn from_untagged_cbor(untagged_cbor: CBOR) -> dcbor::Result<Self> {
118        let data = CBOR::try_into_byte_string(untagged_cbor)?;
119        Ok(Self::from_data_ref(data)?)
120    }
121}
122
123/// Implements Debug to output the key with a type label.
124impl std::fmt::Debug for X25519PublicKey {
125    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
126        write!(f, "X25519PublicKey({})", self.hex())
127    }
128}
129
130/// Implements conversion from an X25519PublicKey reference to an owned X25519PublicKey.
131impl From<&X25519PublicKey> for X25519PublicKey {
132    fn from(key: &X25519PublicKey) -> Self {
133        key.clone()
134    }
135}
136
137/// Implements conversion from an X25519PublicKey to a byte vector.
138impl From<X25519PublicKey> for Vec<u8> {
139    fn from(key: X25519PublicKey) -> Self {
140        key.0.to_vec()
141    }
142}
143
144/// Implements conversion from an X25519PublicKey reference to a byte vector.
145impl From<&X25519PublicKey> for Vec<u8> {
146    fn from(key: &X25519PublicKey) -> Self {
147        key.0.to_vec()
148    }
149}
150
151/// Implements the Encrypter trait to support key encapsulation mechanisms.
152impl Encrypter for X25519PublicKey {
153    fn encapsulation_public_key(&self) -> EncapsulationPublicKey {
154        EncapsulationPublicKey::X25519(self.clone())
155    }
156}