bc_components/symmetric/
symmetric_key.rs1use crate::{ EncryptedMessage, Nonce, tags, Digest };
2use bc_crypto::{ aead_chacha20_poly1305_encrypt_with_aad, aead_chacha20_poly1305_decrypt_with_aad };
3use bc_ur::prelude::*;
4use anyhow::{ bail, Result, Error };
5
6#[derive(Clone, PartialEq, Eq, Hash)]
21pub struct SymmetricKey([u8; Self::SYMMETRIC_KEY_SIZE]);
22
23impl SymmetricKey {
24 pub const SYMMETRIC_KEY_SIZE: usize = 32;
25
26 pub fn new() -> Self {
28 let mut rng = bc_rand::SecureRandomNumberGenerator;
29 Self::new_using(&mut rng)
30 }
31
32 pub fn new_using(rng: &mut impl bc_rand::RandomNumberGenerator) -> Self {
34 let mut key = [0u8; Self::SYMMETRIC_KEY_SIZE];
35 rng.fill_random_data(&mut key);
36 Self::from_data(key)
37 }
38
39 pub const fn from_data(data: [u8; Self::SYMMETRIC_KEY_SIZE]) -> Self {
41 Self(data)
42 }
43
44 pub fn from_data_ref(data: impl AsRef<[u8]>) -> Result<Self> {
46 let data = data.as_ref();
47 if data.len() != Self::SYMMETRIC_KEY_SIZE {
48 bail!("Invalid symmetric key size");
49 }
50 let mut arr = [0u8; Self::SYMMETRIC_KEY_SIZE];
51 arr.copy_from_slice(data);
52 Ok(Self::from_data(arr))
53 }
54
55 pub fn data(&self) -> &[u8; Self::SYMMETRIC_KEY_SIZE] {
57 self.into()
58 }
59
60 pub fn from_hex(hex: impl AsRef<str>) -> Result<Self> {
65 Self::from_data_ref(hex::decode(hex.as_ref()).unwrap())
66 }
67
68 pub fn hex(&self) -> String {
70 hex::encode(self.data())
71 }
72
73 pub fn encrypt(
75 &self,
76 plaintext: impl AsRef<[u8]>,
77 aad: Option<impl AsRef<[u8]>>,
78 nonce: Option<impl AsRef<Nonce>>
79 ) -> EncryptedMessage {
80 let aad: Vec<u8> = aad.map(|a| a.as_ref().to_vec()).unwrap_or_default();
81 let nonce: Nonce = nonce.map(|n| n.as_ref().clone()).unwrap_or_default();
82 let plaintext = plaintext.as_ref().to_vec();
83 let (ciphertext, auth) = aead_chacha20_poly1305_encrypt_with_aad(
84 plaintext,
85 self.into(),
86 (&nonce).into(),
87 &aad
88 );
89 EncryptedMessage::new(ciphertext, aad, nonce, auth.into())
90 }
91
92 pub fn encrypt_with_digest(
94 &self,
95 plaintext: impl AsRef<[u8]>,
96 digest: impl AsRef<Digest>,
97 nonce: Option<impl AsRef<Nonce>>
98 ) -> EncryptedMessage {
99 let cbor: CBOR = digest.as_ref().clone().into();
100 let data = cbor.to_cbor_data();
101 self.encrypt(plaintext, Some(data), nonce)
102 }
103
104 pub fn decrypt(&self, message: &EncryptedMessage) -> Result<Vec<u8>> {
106 aead_chacha20_poly1305_decrypt_with_aad(
107 message.ciphertext(),
108 self.into(),
109 message.nonce().into(),
110 message.aad(),
111 message.authentication_tag().into()
112 )
113 }
114}
115
116impl Default for SymmetricKey {
118 fn default() -> Self {
119 Self::new()
120 }
121}
122
123impl AsRef<[u8]> for SymmetricKey {
124 fn as_ref(&self) -> &[u8] {
125 &self.0
126 }
127}
128
129impl AsRef<SymmetricKey> for SymmetricKey {
131 fn as_ref(&self) -> &SymmetricKey {
132 self
133 }
134}
135
136impl<'a> From<&'a SymmetricKey> for &'a [u8; SymmetricKey::SYMMETRIC_KEY_SIZE] {
138 fn from(key: &'a SymmetricKey) -> Self {
139 &key.0
140 }
141}
142
143impl From<&SymmetricKey> for SymmetricKey {
145 fn from(key: &SymmetricKey) -> Self {
146 key.clone()
147 }
148}
149
150impl From<SymmetricKey> for Vec<u8> {
152 fn from(key: SymmetricKey) -> Self {
153 key.0.to_vec()
154 }
155}
156
157impl From<&SymmetricKey> for Vec<u8> {
159 fn from(key: &SymmetricKey) -> Self {
160 key.0.to_vec()
161 }
162}
163
164impl TryFrom<Vec<u8>> for SymmetricKey {
166 type Error = Error;
167
168 fn try_from(value: Vec<u8>) -> Result<Self, Self::Error> {
169 Self::from_data_ref(value)
170 }
171}
172
173impl std::fmt::Debug for SymmetricKey {
175 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
176 write!(f, "SymmetricKey({})", self.hex())
177 }
178}
179
180impl CBORTagged for SymmetricKey {
182 fn cbor_tags() -> Vec<Tag> {
183 tags_for_values(&[tags::TAG_SYMMETRIC_KEY])
184 }
185}
186
187impl From<SymmetricKey> for CBOR {
189 fn from(value: SymmetricKey) -> Self {
190 value.tagged_cbor()
191 }
192}
193
194impl CBORTaggedEncodable for SymmetricKey {
196 fn untagged_cbor(&self) -> CBOR {
197 CBOR::to_byte_string(self.0)
198 }
199}
200
201impl TryFrom<CBOR> for SymmetricKey {
203 type Error = dcbor::Error;
204
205 fn try_from(cbor: CBOR) -> dcbor::Result<Self> {
206 Self::from_untagged_cbor(cbor)
207 }
208}
209
210impl CBORTaggedDecodable for SymmetricKey {
212 fn from_untagged_cbor(cbor: CBOR) -> dcbor::Result<Self> {
213 let bytes = CBOR::try_into_byte_string(cbor)?;
214 let instance = Self::from_data_ref(bytes)?;
215 Ok(instance)
216 }
217}