bc_components/symmetric/
symmetric_key.rs1use anyhow::{Error, Result, bail};
2use bc_crypto::{aead_chacha20_poly1305_decrypt_with_aad, aead_chacha20_poly1305_encrypt_with_aad};
3use bc_ur::prelude::*;
4
5use crate::{Digest, EncryptedMessage, Nonce, tags};
6
7#[derive(Clone, PartialEq, Eq, Hash)]
24pub struct SymmetricKey([u8; Self::SYMMETRIC_KEY_SIZE]);
25
26impl SymmetricKey {
27 pub const SYMMETRIC_KEY_SIZE: usize = 32;
28
29 pub fn new() -> Self {
31 let mut rng = bc_rand::SecureRandomNumberGenerator;
32 Self::new_using(&mut rng)
33 }
34
35 pub fn new_using(rng: &mut impl bc_rand::RandomNumberGenerator) -> Self {
38 let mut key = [0u8; Self::SYMMETRIC_KEY_SIZE];
39 rng.fill_random_data(&mut key);
40 Self::from_data(key)
41 }
42
43 pub const fn from_data(data: [u8; Self::SYMMETRIC_KEY_SIZE]) -> Self { Self(data) }
45
46 pub fn from_data_ref(data: impl AsRef<[u8]>) -> Result<Self> {
48 let data = data.as_ref();
49 if data.len() != Self::SYMMETRIC_KEY_SIZE {
50 bail!("Invalid symmetric key size");
51 }
52 let mut arr = [0u8; Self::SYMMETRIC_KEY_SIZE];
53 arr.copy_from_slice(data);
54 Ok(Self::from_data(arr))
55 }
56
57 pub fn data(&self) -> &[u8; Self::SYMMETRIC_KEY_SIZE] { self.into() }
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 { hex::encode(self.data()) }
70
71 pub fn encrypt(
74 &self,
75 plaintext: impl AsRef<[u8]>,
76 aad: Option<impl AsRef<[u8]>>,
77 nonce: Option<impl AsRef<Nonce>>,
78 ) -> EncryptedMessage {
79 let aad: Vec<u8> = aad.map(|a| a.as_ref().to_vec()).unwrap_or_default();
80 let nonce: Nonce = nonce.map(|n| n.as_ref().clone()).unwrap_or_default();
81 let plaintext = plaintext.as_ref().to_vec();
82 let (ciphertext, auth) =
83 aead_chacha20_poly1305_encrypt_with_aad(plaintext, self.into(), (&nonce).into(), &aad);
84 EncryptedMessage::new(ciphertext, aad, nonce, auth.into())
85 }
86
87 pub fn encrypt_with_digest(
90 &self,
91 plaintext: impl AsRef<[u8]>,
92 digest: impl AsRef<Digest>,
93 nonce: Option<impl AsRef<Nonce>>,
94 ) -> EncryptedMessage {
95 let cbor: CBOR = digest.as_ref().clone().into();
96 let data = cbor.to_cbor_data();
97 self.encrypt(plaintext, Some(data), nonce)
98 }
99
100 pub fn decrypt(&self, message: &EncryptedMessage) -> Result<Vec<u8>> {
102 aead_chacha20_poly1305_decrypt_with_aad(
103 message.ciphertext(),
104 self.into(),
105 message.nonce().into(),
106 message.aad(),
107 message.authentication_tag().into(),
108 )
109 }
110}
111
112impl Default for SymmetricKey {
114 fn default() -> Self { Self::new() }
115}
116
117impl AsRef<[u8]> for SymmetricKey {
118 fn as_ref(&self) -> &[u8] { &self.0 }
119}
120
121impl AsRef<SymmetricKey> for SymmetricKey {
123 fn as_ref(&self) -> &SymmetricKey { self }
124}
125
126impl<'a> From<&'a SymmetricKey> for &'a [u8; SymmetricKey::SYMMETRIC_KEY_SIZE] {
129 fn from(key: &'a SymmetricKey) -> Self { &key.0 }
130}
131
132impl From<&SymmetricKey> for SymmetricKey {
134 fn from(key: &SymmetricKey) -> Self { key.clone() }
135}
136
137impl From<SymmetricKey> for Vec<u8> {
139 fn from(key: SymmetricKey) -> Self { key.0.to_vec() }
140}
141
142impl From<&SymmetricKey> for Vec<u8> {
144 fn from(key: &SymmetricKey) -> Self { key.0.to_vec() }
145}
146
147impl TryFrom<Vec<u8>> for SymmetricKey {
149 type Error = Error;
150
151 fn try_from(value: Vec<u8>) -> Result<Self, Self::Error> { Self::from_data_ref(value) }
152}
153
154impl std::fmt::Debug for SymmetricKey {
156 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
157 write!(f, "SymmetricKey({})", self.hex())
158 }
159}
160
161impl CBORTagged for SymmetricKey {
163 fn cbor_tags() -> Vec<Tag> { tags_for_values(&[tags::TAG_SYMMETRIC_KEY]) }
164}
165
166impl From<SymmetricKey> for CBOR {
168 fn from(value: SymmetricKey) -> Self { value.tagged_cbor() }
169}
170
171impl CBORTaggedEncodable for SymmetricKey {
173 fn untagged_cbor(&self) -> CBOR { CBOR::to_byte_string(self.0) }
174}
175
176impl TryFrom<CBOR> for SymmetricKey {
179 type Error = dcbor::Error;
180
181 fn try_from(cbor: CBOR) -> dcbor::Result<Self> { Self::from_untagged_cbor(cbor) }
182}
183
184impl CBORTaggedDecodable for SymmetricKey {
186 fn from_untagged_cbor(cbor: CBOR) -> dcbor::Result<Self> {
187 let bytes = CBOR::try_into_byte_string(cbor)?;
188 let instance = Self::from_data_ref(bytes)?;
189 Ok(instance)
190 }
191}