bc_components/symmetric/
symmetric_key.rs

1use 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/// A symmetric encryption key used for both encryption and decryption.
7///
8/// `SymmetricKey` is a 32-byte cryptographic key used with ChaCha20-Poly1305 AEAD
9/// (Authenticated Encryption with Associated Data) encryption. This implementation follows
10/// the IETF ChaCha20-Poly1305 specification as defined in [RFC-8439](https://datatracker.ietf.org/doc/html/rfc8439).
11///
12/// Symmetric encryption uses the same key for both encryption and decryption, unlike
13/// asymmetric encryption where different keys are used for each operation.
14///
15/// `SymmetricKey` can be used to encrypt plaintext into an `EncryptedMessage` that includes:
16/// - Ciphertext (the encrypted data)
17/// - Nonce (a unique number used once for each encryption)
18/// - Authentication tag (to verify message integrity)
19/// - Optional additional authenticated data (AAD)
20#[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    /// Create a new random symmetric key.
27    pub fn new() -> Self {
28        let mut rng = bc_rand::SecureRandomNumberGenerator;
29        Self::new_using(&mut rng)
30    }
31
32    /// Create a new random symmetric key using the given random number generator.
33    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    /// Create a new symmetric key from data.
40    pub const fn from_data(data: [u8; Self::SYMMETRIC_KEY_SIZE]) -> Self {
41        Self(data)
42    }
43
44    /// Create a new symmetric key from data.
45    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    /// Get the data of the symmetric key.
56    pub fn data(&self) -> &[u8; Self::SYMMETRIC_KEY_SIZE] {
57        self.into()
58    }
59
60    /// Create a new symmetric key from the given hexadecimal string.
61    ///
62    /// # Panics
63    /// Panics if the string is not exactly 24 hexadecimal digits.
64    pub fn from_hex(hex: impl AsRef<str>) -> Result<Self> {
65        Self::from_data_ref(hex::decode(hex.as_ref()).unwrap())
66    }
67
68    /// The data as a hexadecimal string.
69    pub fn hex(&self) -> String {
70        hex::encode(self.data())
71    }
72
73    /// Encrypt the given plaintext with this key, and the given additional authenticated data and nonce.
74    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    /// Encrypt the given plaintext with this key, and the given digest of the plaintext, and nonce.
93    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    /// Decrypt the given encrypted message with this key.
105    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
116/// Implements Default to create a new random symmetric key.
117impl 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
129/// Implements `AsRef<SymmetricKey>` to allow self-reference.
130impl AsRef<SymmetricKey> for SymmetricKey {
131    fn as_ref(&self) -> &SymmetricKey {
132        self
133    }
134}
135
136/// Implements conversion from a SymmetricKey reference to a byte array reference.
137impl<'a> From<&'a SymmetricKey> for &'a [u8; SymmetricKey::SYMMETRIC_KEY_SIZE] {
138    fn from(key: &'a SymmetricKey) -> Self {
139        &key.0
140    }
141}
142
143/// Implements conversion from a SymmetricKey reference to a SymmetricKey.
144impl From<&SymmetricKey> for SymmetricKey {
145    fn from(key: &SymmetricKey) -> Self {
146        key.clone()
147    }
148}
149
150/// Implements conversion from a SymmetricKey to a `Vec<u8>`.
151impl From<SymmetricKey> for Vec<u8> {
152    fn from(key: SymmetricKey) -> Self {
153        key.0.to_vec()
154    }
155}
156
157/// Implements conversion from a SymmetricKey reference to a `Vec<u8>`.
158impl From<&SymmetricKey> for Vec<u8> {
159    fn from(key: &SymmetricKey) -> Self {
160        key.0.to_vec()
161    }
162}
163
164/// Implements conversion from a `Vec<u8>` to a SymmetricKey.
165impl 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
173/// Implements Debug formatting to display the key in hexadecimal format.
174impl 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
180/// Implements CBORTagged to provide the CBOR tag for the SymmetricKey.
181impl CBORTagged for SymmetricKey {
182    fn cbor_tags() -> Vec<Tag> {
183        tags_for_values(&[tags::TAG_SYMMETRIC_KEY])
184    }
185}
186
187/// Implements conversion from SymmetricKey to CBOR for serialization.
188impl From<SymmetricKey> for CBOR {
189    fn from(value: SymmetricKey) -> Self {
190        value.tagged_cbor()
191    }
192}
193
194/// Implements CBORTaggedEncodable to provide CBOR encoding functionality.
195impl CBORTaggedEncodable for SymmetricKey {
196    fn untagged_cbor(&self) -> CBOR {
197        CBOR::to_byte_string(self.0)
198    }
199}
200
201/// Implements `TryFrom<CBOR>` for SymmetricKey to support conversion from CBOR data.
202impl 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
210/// Implements CBORTaggedDecodable to provide CBOR decoding functionality.
211impl 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}