bc_components/symmetric/
symmetric_key.rs1use bc_crypto::{
2 aead_chacha20_poly1305_decrypt_with_aad,
3 aead_chacha20_poly1305_encrypt_with_aad,
4};
5use bc_ur::prelude::*;
6
7use crate::{
8 Digest, EncryptedMessage, Error, Nonce, Reference, ReferenceProvider,
9 Result, tags,
10};
11
12#[derive(Clone, PartialEq, Eq, Hash)]
29pub struct SymmetricKey([u8; Self::SYMMETRIC_KEY_SIZE]);
30
31impl SymmetricKey {
32 pub const SYMMETRIC_KEY_SIZE: usize = 32;
33
34 pub fn new() -> Self {
36 let mut rng = bc_rand::SecureRandomNumberGenerator;
37 Self::new_using(&mut rng)
38 }
39
40 pub fn new_using(rng: &mut impl bc_rand::RandomNumberGenerator) -> Self {
43 let mut key = [0u8; Self::SYMMETRIC_KEY_SIZE];
44 rng.fill_random_data(&mut key);
45 Self::from_data(key)
46 }
47
48 pub const fn from_data(data: [u8; Self::SYMMETRIC_KEY_SIZE]) -> Self {
50 Self(data)
51 }
52
53 pub fn from_data_ref(data: impl AsRef<[u8]>) -> Result<Self> {
55 let data = data.as_ref();
56 if data.len() != Self::SYMMETRIC_KEY_SIZE {
57 return Err(Error::invalid_size(
58 "symmetric key",
59 Self::SYMMETRIC_KEY_SIZE,
60 data.len(),
61 ));
62 }
63 let mut arr = [0u8; Self::SYMMETRIC_KEY_SIZE];
64 arr.copy_from_slice(data);
65 Ok(Self::from_data(arr))
66 }
67
68 pub fn data(&self) -> &[u8; Self::SYMMETRIC_KEY_SIZE] { self.into() }
70
71 pub fn as_bytes(&self) -> &[u8] { self.as_ref() }
73
74 pub fn from_hex(hex: impl AsRef<str>) -> Result<Self> {
79 Self::from_data_ref(hex::decode(hex.as_ref()).unwrap())
80 }
81
82 pub fn hex(&self) -> String { hex::encode(self.data()) }
84
85 pub fn encrypt(
88 &self,
89 plaintext: impl AsRef<[u8]>,
90 aad: Option<impl AsRef<[u8]>>,
91 nonce: Option<impl AsRef<Nonce>>,
92 ) -> EncryptedMessage {
93 let aad: Vec<u8> = aad.map(|a| a.as_ref().to_vec()).unwrap_or_default();
94 let nonce: Nonce =
95 nonce.map(|n| n.as_ref().clone()).unwrap_or_default();
96 let plaintext = plaintext.as_ref().to_vec();
97 let (ciphertext, auth) = aead_chacha20_poly1305_encrypt_with_aad(
98 plaintext,
99 self.into(),
100 (&nonce).into(),
101 &aad,
102 );
103 EncryptedMessage::new(ciphertext, aad, nonce, auth.into())
104 }
105
106 pub fn encrypt_with_digest(
109 &self,
110 plaintext: impl AsRef<[u8]>,
111 digest: impl AsRef<Digest>,
112 nonce: Option<impl AsRef<Nonce>>,
113 ) -> EncryptedMessage {
114 let cbor: CBOR = digest.as_ref().clone().into();
115 let data = cbor.to_cbor_data();
116 self.encrypt(plaintext, Some(data), nonce)
117 }
118
119 pub fn decrypt(&self, message: &EncryptedMessage) -> Result<Vec<u8>> {
121 Ok(aead_chacha20_poly1305_decrypt_with_aad(
122 message.ciphertext(),
123 self.into(),
124 message.nonce().into(),
125 message.aad(),
126 message.authentication_tag().into(),
127 )?)
128 }
129}
130
131impl Default for SymmetricKey {
133 fn default() -> Self { Self::new() }
134}
135
136impl AsRef<[u8]> for SymmetricKey {
137 fn as_ref(&self) -> &[u8] { &self.0 }
138}
139
140impl AsRef<SymmetricKey> for SymmetricKey {
142 fn as_ref(&self) -> &SymmetricKey { self }
143}
144
145impl<'a> From<&'a SymmetricKey> for &'a [u8; SymmetricKey::SYMMETRIC_KEY_SIZE] {
148 fn from(key: &'a SymmetricKey) -> Self { &key.0 }
149}
150
151impl From<&SymmetricKey> for SymmetricKey {
153 fn from(key: &SymmetricKey) -> Self { key.clone() }
154}
155
156impl From<SymmetricKey> for Vec<u8> {
158 fn from(key: SymmetricKey) -> Self { key.0.to_vec() }
159}
160
161impl From<&SymmetricKey> for Vec<u8> {
163 fn from(key: &SymmetricKey) -> Self { key.0.to_vec() }
164}
165
166impl TryFrom<Vec<u8>> for SymmetricKey {
168 type Error = Error;
169
170 fn try_from(value: Vec<u8>) -> std::result::Result<Self, Self::Error> {
171 Self::from_data_ref(value)
172 }
173}
174
175impl std::fmt::Debug for SymmetricKey {
177 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
178 write!(f, "SymmetricKey({})", self.hex())
179 }
180}
181
182impl CBORTagged for SymmetricKey {
184 fn cbor_tags() -> Vec<Tag> { tags_for_values(&[tags::TAG_SYMMETRIC_KEY]) }
185}
186
187impl From<SymmetricKey> for CBOR {
189 fn from(value: SymmetricKey) -> Self { value.tagged_cbor() }
190}
191
192impl CBORTaggedEncodable for SymmetricKey {
194 fn untagged_cbor(&self) -> CBOR { CBOR::to_byte_string(self.0) }
195}
196
197impl TryFrom<CBOR> for SymmetricKey {
200 type Error = dcbor::Error;
201
202 fn try_from(cbor: CBOR) -> dcbor::Result<Self> {
203 Self::from_untagged_cbor(cbor)
204 }
205}
206
207impl CBORTaggedDecodable for SymmetricKey {
209 fn from_untagged_cbor(cbor: CBOR) -> dcbor::Result<Self> {
210 let bytes = CBOR::try_into_byte_string(cbor)?;
211 let instance = Self::from_data_ref(bytes)?;
212 Ok(instance)
213 }
214}
215
216impl ReferenceProvider for SymmetricKey {
217 fn reference(&self) -> Reference {
218 Reference::from_digest(Digest::from_image(
219 self.tagged_cbor().to_cbor_data(),
220 ))
221 }
222}
223
224impl std::fmt::Display for SymmetricKey {
225 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
226 write!(f, "SymmetricKey({})", self.ref_hex_short())
227 }
228}