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 Into<Vec<u8>>,
77 aad: Option<impl Into<Vec<u8>>>,
78 nonce: Option<impl AsRef<Nonce>>
79 ) -> EncryptedMessage {
80 let aad: Vec<u8> = aad.map(|a| a.into()).unwrap_or_default();
81 let nonce: Nonce = nonce.map(|n| n.as_ref().clone()).unwrap_or_default();
82 let plaintext = plaintext.into();
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 Into<Vec<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<SymmetricKey> for SymmetricKey {
125 fn as_ref(&self) -> &SymmetricKey {
126 self
127 }
128}
129
130impl<'a> From<&'a SymmetricKey> for &'a [u8; SymmetricKey::SYMMETRIC_KEY_SIZE] {
132 fn from(key: &'a SymmetricKey) -> Self {
133 &key.0
134 }
135}
136
137impl From<&SymmetricKey> for SymmetricKey {
139 fn from(key: &SymmetricKey) -> Self {
140 key.clone()
141 }
142}
143
144impl From<SymmetricKey> for Vec<u8> {
146 fn from(key: SymmetricKey) -> Self {
147 key.0.to_vec()
148 }
149}
150
151impl From<&SymmetricKey> for Vec<u8> {
153 fn from(key: &SymmetricKey) -> Self {
154 key.0.to_vec()
155 }
156}
157
158impl TryFrom<Vec<u8>> for SymmetricKey {
160 type Error = Error;
161
162 fn try_from(value: Vec<u8>) -> Result<Self, Self::Error> {
163 Self::from_data_ref(value)
164 }
165}
166
167impl std::fmt::Debug for SymmetricKey {
169 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
170 write!(f, "SymmetricKey({})", self.hex())
171 }
172}
173
174impl CBORTagged for SymmetricKey {
176 fn cbor_tags() -> Vec<Tag> {
177 tags_for_values(&[tags::TAG_SYMMETRIC_KEY])
178 }
179}
180
181impl From<SymmetricKey> for CBOR {
183 fn from(value: SymmetricKey) -> Self {
184 value.tagged_cbor()
185 }
186}
187
188impl CBORTaggedEncodable for SymmetricKey {
190 fn untagged_cbor(&self) -> CBOR {
191 CBOR::to_byte_string(self.0)
192 }
193}
194
195impl 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}