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::{Digest, EncryptedMessage, Error, Nonce, Result, tags};
8
9#[derive(Clone, PartialEq, Eq, Hash)]
26pub struct SymmetricKey([u8; Self::SYMMETRIC_KEY_SIZE]);
27
28impl SymmetricKey {
29 pub const SYMMETRIC_KEY_SIZE: usize = 32;
30
31 pub fn new() -> Self {
33 let mut rng = bc_rand::SecureRandomNumberGenerator;
34 Self::new_using(&mut rng)
35 }
36
37 pub fn new_using(rng: &mut impl bc_rand::RandomNumberGenerator) -> Self {
40 let mut key = [0u8; Self::SYMMETRIC_KEY_SIZE];
41 rng.fill_random_data(&mut key);
42 Self::from_data(key)
43 }
44
45 pub const fn from_data(data: [u8; Self::SYMMETRIC_KEY_SIZE]) -> Self {
47 Self(data)
48 }
49
50 pub fn from_data_ref(data: impl AsRef<[u8]>) -> Result<Self> {
52 let data = data.as_ref();
53 if data.len() != Self::SYMMETRIC_KEY_SIZE {
54 return Err(Error::invalid_size(
55 "symmetric key",
56 Self::SYMMETRIC_KEY_SIZE,
57 data.len(),
58 ));
59 }
60 let mut arr = [0u8; Self::SYMMETRIC_KEY_SIZE];
61 arr.copy_from_slice(data);
62 Ok(Self::from_data(arr))
63 }
64
65 pub fn data(&self) -> &[u8; Self::SYMMETRIC_KEY_SIZE] { self.into() }
67
68 pub fn as_bytes(&self) -> &[u8] { self.as_ref() }
70
71 pub fn from_hex(hex: impl AsRef<str>) -> Result<Self> {
76 Self::from_data_ref(hex::decode(hex.as_ref()).unwrap())
77 }
78
79 pub fn hex(&self) -> String { hex::encode(self.data()) }
81
82 pub fn encrypt(
85 &self,
86 plaintext: impl AsRef<[u8]>,
87 aad: Option<impl AsRef<[u8]>>,
88 nonce: Option<impl AsRef<Nonce>>,
89 ) -> EncryptedMessage {
90 let aad: Vec<u8> = aad.map(|a| a.as_ref().to_vec()).unwrap_or_default();
91 let nonce: Nonce =
92 nonce.map(|n| n.as_ref().clone()).unwrap_or_default();
93 let plaintext = plaintext.as_ref().to_vec();
94 let (ciphertext, auth) = aead_chacha20_poly1305_encrypt_with_aad(
95 plaintext,
96 self.into(),
97 (&nonce).into(),
98 &aad,
99 );
100 EncryptedMessage::new(ciphertext, aad, nonce, auth.into())
101 }
102
103 pub fn encrypt_with_digest(
106 &self,
107 plaintext: impl AsRef<[u8]>,
108 digest: impl AsRef<Digest>,
109 nonce: Option<impl AsRef<Nonce>>,
110 ) -> EncryptedMessage {
111 let cbor: CBOR = digest.as_ref().clone().into();
112 let data = cbor.to_cbor_data();
113 self.encrypt(plaintext, Some(data), nonce)
114 }
115
116 pub fn decrypt(&self, message: &EncryptedMessage) -> Result<Vec<u8>> {
118 Ok(aead_chacha20_poly1305_decrypt_with_aad(
119 message.ciphertext(),
120 self.into(),
121 message.nonce().into(),
122 message.aad(),
123 message.authentication_tag().into(),
124 )?)
125 }
126}
127
128impl Default for SymmetricKey {
130 fn default() -> Self { Self::new() }
131}
132
133impl AsRef<[u8]> for SymmetricKey {
134 fn as_ref(&self) -> &[u8] { &self.0 }
135}
136
137impl AsRef<SymmetricKey> for SymmetricKey {
139 fn as_ref(&self) -> &SymmetricKey { self }
140}
141
142impl<'a> From<&'a SymmetricKey> for &'a [u8; SymmetricKey::SYMMETRIC_KEY_SIZE] {
145 fn from(key: &'a SymmetricKey) -> Self { &key.0 }
146}
147
148impl From<&SymmetricKey> for SymmetricKey {
150 fn from(key: &SymmetricKey) -> Self { key.clone() }
151}
152
153impl From<SymmetricKey> for Vec<u8> {
155 fn from(key: SymmetricKey) -> Self { key.0.to_vec() }
156}
157
158impl From<&SymmetricKey> for Vec<u8> {
160 fn from(key: &SymmetricKey) -> Self { key.0.to_vec() }
161}
162
163impl TryFrom<Vec<u8>> for SymmetricKey {
165 type Error = Error;
166
167 fn try_from(value: Vec<u8>) -> std::result::Result<Self, Self::Error> {
168 Self::from_data_ref(value)
169 }
170}
171
172impl std::fmt::Debug for SymmetricKey {
174 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
175 write!(f, "SymmetricKey({})", self.hex())
176 }
177}
178
179impl CBORTagged for SymmetricKey {
181 fn cbor_tags() -> Vec<Tag> { tags_for_values(&[tags::TAG_SYMMETRIC_KEY]) }
182}
183
184impl From<SymmetricKey> for CBOR {
186 fn from(value: SymmetricKey) -> Self { value.tagged_cbor() }
187}
188
189impl CBORTaggedEncodable for SymmetricKey {
191 fn untagged_cbor(&self) -> CBOR { CBOR::to_byte_string(self.0) }
192}
193
194impl TryFrom<CBOR> for SymmetricKey {
197 type Error = dcbor::Error;
198
199 fn try_from(cbor: CBOR) -> dcbor::Result<Self> {
200 Self::from_untagged_cbor(cbor)
201 }
202}
203
204impl CBORTaggedDecodable for SymmetricKey {
206 fn from_untagged_cbor(cbor: CBOR) -> dcbor::Result<Self> {
207 let bytes = CBOR::try_into_byte_string(cbor)?;
208 let instance = Self::from_data_ref(bytes)?;
209 Ok(instance)
210 }
211}