bc_components/x25519/
x25519_public_key.rs1use std::rc::Rc;
2
3use anyhow::{Result, bail};
4use bc_ur::prelude::*;
5
6use crate::{EncapsulationPublicKey, Encrypter, tags};
7
8#[derive(Clone, PartialEq, Eq, Hash)]
26pub struct X25519PublicKey([u8; Self::KEY_SIZE]);
27
28impl X25519PublicKey {
29 pub const KEY_SIZE: usize = 32;
30
31 pub const fn from_data(data: [u8; Self::KEY_SIZE]) -> Self { Self(data) }
33
34 pub fn from_data_ref(data: impl AsRef<[u8]>) -> Result<Self> {
36 let data = data.as_ref();
37 if data.len() != Self::KEY_SIZE {
38 bail!("Invalid X25519 public key size");
39 }
40 let mut arr = [0u8; Self::KEY_SIZE];
41 arr.copy_from_slice(data);
42 Ok(Self::from_data(arr))
43 }
44
45 pub fn data(&self) -> &[u8; Self::KEY_SIZE] { self.into() }
47
48 pub fn as_bytes(&self) -> &[u8] { self.as_ref() }
50
51 pub fn from_hex(hex: impl AsRef<str>) -> Self {
58 Self::from_data_ref(hex::decode(hex.as_ref()).unwrap()).unwrap()
59 }
60
61 pub fn hex(&self) -> String { hex::encode(self.data()) }
63}
64
65impl AsRef<[u8]> for X25519PublicKey {
66 fn as_ref(&self) -> &[u8] { &self.0 }
67}
68
69impl From<Rc<X25519PublicKey>> for X25519PublicKey {
72 fn from(value: Rc<X25519PublicKey>) -> Self { value.as_ref().clone() }
73}
74
75impl<'a> From<&'a X25519PublicKey> for &'a [u8; X25519PublicKey::KEY_SIZE] {
78 fn from(value: &'a X25519PublicKey) -> Self { &value.0 }
79}
80
81impl AsRef<X25519PublicKey> for X25519PublicKey {
83 fn as_ref(&self) -> &X25519PublicKey { self }
84}
85
86impl CBORTagged for X25519PublicKey {
88 fn cbor_tags() -> Vec<Tag> {
89 tags_for_values(&[tags::TAG_X25519_PUBLIC_KEY])
90 }
91}
92
93impl From<X25519PublicKey> for CBOR {
95 fn from(value: X25519PublicKey) -> Self { value.tagged_cbor() }
96}
97
98impl CBORTaggedEncodable for X25519PublicKey {
100 fn untagged_cbor(&self) -> CBOR { CBOR::to_byte_string(self.data()) }
101}
102
103impl TryFrom<CBOR> for X25519PublicKey {
106 type Error = dcbor::Error;
107
108 fn try_from(cbor: CBOR) -> dcbor::Result<Self> {
109 Self::from_tagged_cbor(cbor)
110 }
111}
112
113impl CBORTaggedDecodable for X25519PublicKey {
115 fn from_untagged_cbor(untagged_cbor: CBOR) -> dcbor::Result<Self> {
116 let data = CBOR::try_into_byte_string(untagged_cbor)?;
117 Ok(Self::from_data_ref(data)?)
118 }
119}
120
121impl std::fmt::Debug for X25519PublicKey {
123 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
124 write!(f, "X25519PublicKey({})", self.hex())
125 }
126}
127
128impl From<&X25519PublicKey> for X25519PublicKey {
131 fn from(key: &X25519PublicKey) -> Self { key.clone() }
132}
133
134impl From<X25519PublicKey> for Vec<u8> {
136 fn from(key: X25519PublicKey) -> Self { key.0.to_vec() }
137}
138
139impl From<&X25519PublicKey> for Vec<u8> {
141 fn from(key: &X25519PublicKey) -> Self { key.0.to_vec() }
142}
143
144impl Encrypter for X25519PublicKey {
146 fn encapsulation_public_key(&self) -> EncapsulationPublicKey {
147 EncapsulationPublicKey::X25519(self.clone())
148 }
149}