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<Nonce>,
92 ) -> EncryptedMessage {
93 let aad: Vec<u8> = aad.map(|a| a.as_ref().to_vec()).unwrap_or_default();
94 let nonce = nonce.unwrap_or_default();
95 let plaintext = plaintext.as_ref().to_vec();
96 let (ciphertext, auth) = aead_chacha20_poly1305_encrypt_with_aad(
97 plaintext,
98 self.into(),
99 nonce.data(),
100 &aad,
101 );
102 EncryptedMessage::new(ciphertext, aad, nonce, auth.into())
103 }
104
105 pub fn encrypt_with_digest(
108 &self,
109 plaintext: impl AsRef<[u8]>,
110 digest: Digest,
111 nonce: Option<Nonce>,
112 ) -> EncryptedMessage {
113 self.encrypt(
114 plaintext,
115 Some(digest.tagged_cbor().to_cbor_data()),
116 nonce,
117 )
118 }
119
120 pub fn decrypt(&self, message: &EncryptedMessage) -> Result<Vec<u8>> {
122 Ok(aead_chacha20_poly1305_decrypt_with_aad(
123 message.ciphertext(),
124 self.into(),
125 message.nonce().into(),
126 message.aad(),
127 message.authentication_tag().into(),
128 )?)
129 }
130}
131
132impl Default for SymmetricKey {
134 fn default() -> Self { Self::new() }
135}
136
137impl AsRef<[u8]> for SymmetricKey {
138 fn as_ref(&self) -> &[u8] { &self.0 }
139}
140
141impl AsRef<SymmetricKey> for SymmetricKey {
143 fn as_ref(&self) -> &SymmetricKey { self }
144}
145
146impl<'a> From<&'a SymmetricKey> for &'a [u8; SymmetricKey::SYMMETRIC_KEY_SIZE] {
149 fn from(key: &'a SymmetricKey) -> Self { &key.0 }
150}
151
152impl From<&SymmetricKey> for SymmetricKey {
154 fn from(key: &SymmetricKey) -> Self { key.clone() }
155}
156
157impl From<SymmetricKey> for Vec<u8> {
159 fn from(key: SymmetricKey) -> Self { key.0.to_vec() }
160}
161
162impl From<&SymmetricKey> for Vec<u8> {
164 fn from(key: &SymmetricKey) -> Self { key.0.to_vec() }
165}
166
167impl TryFrom<Vec<u8>> for SymmetricKey {
169 type Error = Error;
170
171 fn try_from(value: Vec<u8>) -> std::result::Result<Self, Self::Error> {
172 Self::from_data_ref(value)
173 }
174}
175
176impl std::fmt::Debug for SymmetricKey {
178 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
179 write!(f, "SymmetricKey({})", self.hex())
180 }
181}
182
183impl CBORTagged for SymmetricKey {
185 fn cbor_tags() -> Vec<Tag> { tags_for_values(&[tags::TAG_SYMMETRIC_KEY]) }
186}
187
188impl From<SymmetricKey> for CBOR {
190 fn from(value: SymmetricKey) -> Self { value.tagged_cbor() }
191}
192
193impl CBORTaggedEncodable for SymmetricKey {
195 fn untagged_cbor(&self) -> CBOR { CBOR::to_byte_string(self.0) }
196}
197
198impl TryFrom<CBOR> for SymmetricKey {
201 type Error = dcbor::Error;
202
203 fn try_from(cbor: CBOR) -> dcbor::Result<Self> {
204 Self::from_untagged_cbor(cbor)
205 }
206}
207
208impl CBORTaggedDecodable for SymmetricKey {
210 fn from_untagged_cbor(cbor: CBOR) -> dcbor::Result<Self> {
211 let bytes = CBOR::try_into_byte_string(cbor)?;
212 let instance = Self::from_data_ref(bytes)?;
213 Ok(instance)
214 }
215}
216
217impl ReferenceProvider for SymmetricKey {
218 fn reference(&self) -> Reference {
219 Reference::from_digest(Digest::from_image(
220 self.tagged_cbor().to_cbor_data(),
221 ))
222 }
223}
224
225impl std::fmt::Display for SymmetricKey {
226 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
227 write!(f, "SymmetricKey({})", self.ref_hex_short())
228 }
229}