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