bc_components/x25519/
x25519_public_key.rs1use std::rc::Rc;
2use bc_ur::prelude::*;
3use crate::{tags, EncapsulationPublicKey, Encrypter};
4use anyhow::{ bail, Result };
5
6#[derive(Clone, PartialEq, Eq, Hash)]
23pub struct X25519PublicKey([u8; Self::KEY_SIZE]);
24
25impl X25519PublicKey {
26 pub const KEY_SIZE: usize = 32;
27
28 pub const fn from_data(data: [u8; Self::KEY_SIZE]) -> Self {
30 Self(data)
31 }
32
33 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 pub fn data(&self) -> &[u8; Self::KEY_SIZE] {
46 self.into()
47 }
48
49 pub fn from_hex(hex: impl AsRef<str>) -> Self {
55 Self::from_data_ref(hex::decode(hex.as_ref()).unwrap()).unwrap()
56 }
57
58 pub fn hex(&self) -> String {
60 hex::encode(self.data())
61 }
62}
63
64impl From<Rc<X25519PublicKey>> for X25519PublicKey {
66 fn from(value: Rc<X25519PublicKey>) -> Self {
67 value.as_ref().clone()
68 }
69}
70
71impl<'a> From<&'a X25519PublicKey> for &'a [u8; X25519PublicKey::KEY_SIZE] {
73 fn from(value: &'a X25519PublicKey) -> Self {
74 &value.0
75 }
76}
77
78impl AsRef<X25519PublicKey> for X25519PublicKey {
80 fn as_ref(&self) -> &X25519PublicKey {
81 self
82 }
83}
84
85impl CBORTagged for X25519PublicKey {
87 fn cbor_tags() -> Vec<Tag> {
88 tags_for_values(&[tags::TAG_X25519_PUBLIC_KEY])
89 }
90}
91
92impl From<X25519PublicKey> for CBOR {
94 fn from(value: X25519PublicKey) -> Self {
95 value.tagged_cbor()
96 }
97}
98
99impl CBORTaggedEncodable for X25519PublicKey {
101 fn untagged_cbor(&self) -> CBOR {
102 CBOR::to_byte_string(self.data())
103 }
104}
105
106impl 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
115impl 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
123impl 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
130impl From<&X25519PublicKey> for X25519PublicKey {
132 fn from(key: &X25519PublicKey) -> Self {
133 key.clone()
134 }
135}
136
137impl From<X25519PublicKey> for Vec<u8> {
139 fn from(key: X25519PublicKey) -> Self {
140 key.0.to_vec()
141 }
142}
143
144impl From<&X25519PublicKey> for Vec<u8> {
146 fn from(key: &X25519PublicKey) -> Self {
147 key.0.to_vec()
148 }
149}
150
151impl Encrypter for X25519PublicKey {
153 fn encapsulation_public_key(&self) -> EncapsulationPublicKey {
154 EncapsulationPublicKey::X25519(self.clone())
155 }
156}