bc_components/symmetric/
symmetric_key.rs

1use bc_crypto::{
2    aead_chacha20_poly1305_decrypt_with_aad,
3    aead_chacha20_poly1305_encrypt_with_aad,
4};
5use bc_ur::prelude::*;
6
7use crate::{
8    Digest, EncryptedMessage, Error, Nonce, Reference, ReferenceProvider,
9    Result, tags,
10};
11
12/// A symmetric encryption key used for both encryption and decryption.
13///
14/// `SymmetricKey` is a 32-byte cryptographic key used with ChaCha20-Poly1305
15/// AEAD (Authenticated Encryption with Associated Data) encryption. This
16/// implementation follows the IETF ChaCha20-Poly1305 specification as defined in [RFC-8439](https://datatracker.ietf.org/doc/html/rfc8439).
17///
18/// Symmetric encryption uses the same key for both encryption and decryption,
19/// unlike asymmetric encryption where different keys are used for each
20/// operation.
21///
22/// `SymmetricKey` can be used to encrypt plaintext into an `EncryptedMessage`
23/// that includes:
24/// - Ciphertext (the encrypted data)
25/// - Nonce (a unique number used once for each encryption)
26/// - Authentication tag (to verify message integrity)
27/// - Optional additional authenticated data (AAD)
28#[derive(Clone, PartialEq, Eq, Hash)]
29pub struct SymmetricKey([u8; Self::SYMMETRIC_KEY_SIZE]);
30
31impl SymmetricKey {
32    pub const SYMMETRIC_KEY_SIZE: usize = 32;
33
34    /// Create a new random symmetric key.
35    pub fn new() -> Self {
36        let mut rng = bc_rand::SecureRandomNumberGenerator;
37        Self::new_using(&mut rng)
38    }
39
40    /// Create a new random symmetric key using the given random number
41    /// generator.
42    pub fn new_using(rng: &mut impl bc_rand::RandomNumberGenerator) -> Self {
43        let mut key = [0u8; Self::SYMMETRIC_KEY_SIZE];
44        rng.fill_random_data(&mut key);
45        Self::from_data(key)
46    }
47
48    /// Create a new symmetric key from data.
49    pub const fn from_data(data: [u8; Self::SYMMETRIC_KEY_SIZE]) -> Self {
50        Self(data)
51    }
52
53    /// Create a new symmetric key from data.
54    pub fn from_data_ref(data: impl AsRef<[u8]>) -> Result<Self> {
55        let data = data.as_ref();
56        if data.len() != Self::SYMMETRIC_KEY_SIZE {
57            return Err(Error::invalid_size(
58                "symmetric key",
59                Self::SYMMETRIC_KEY_SIZE,
60                data.len(),
61            ));
62        }
63        let mut arr = [0u8; Self::SYMMETRIC_KEY_SIZE];
64        arr.copy_from_slice(data);
65        Ok(Self::from_data(arr))
66    }
67
68    /// Get the data of the symmetric key.
69    pub fn data(&self) -> &[u8; Self::SYMMETRIC_KEY_SIZE] { self.into() }
70
71    /// Get the data of the symmetric key as a byte slice.
72    pub fn as_bytes(&self) -> &[u8] { self.as_ref() }
73
74    /// Create a new symmetric key from the given hexadecimal string.
75    ///
76    /// # Panics
77    /// Panics if the string is not exactly 24 hexadecimal digits.
78    pub fn from_hex(hex: impl AsRef<str>) -> Result<Self> {
79        Self::from_data_ref(hex::decode(hex.as_ref()).unwrap())
80    }
81
82    /// The data as a hexadecimal string.
83    pub fn hex(&self) -> String { hex::encode(self.data()) }
84
85    /// Encrypt the given plaintext with this key, and the given additional
86    /// authenticated data and nonce.
87    pub fn encrypt(
88        &self,
89        plaintext: impl AsRef<[u8]>,
90        aad: Option<impl AsRef<[u8]>>,
91        nonce: Option<impl AsRef<Nonce>>,
92    ) -> EncryptedMessage {
93        let aad: Vec<u8> = aad.map(|a| a.as_ref().to_vec()).unwrap_or_default();
94        let nonce: Nonce =
95            nonce.map(|n| n.as_ref().clone()).unwrap_or_default();
96        let plaintext = plaintext.as_ref().to_vec();
97        let (ciphertext, auth) = aead_chacha20_poly1305_encrypt_with_aad(
98            plaintext,
99            self.into(),
100            (&nonce).into(),
101            &aad,
102        );
103        EncryptedMessage::new(ciphertext, aad, nonce, auth.into())
104    }
105
106    /// Encrypt the given plaintext with this key, and the given digest of the
107    /// plaintext, and nonce.
108    pub fn encrypt_with_digest(
109        &self,
110        plaintext: impl AsRef<[u8]>,
111        digest: impl AsRef<Digest>,
112        nonce: Option<impl AsRef<Nonce>>,
113    ) -> EncryptedMessage {
114        let cbor: CBOR = digest.as_ref().clone().into();
115        let data = cbor.to_cbor_data();
116        self.encrypt(plaintext, Some(data), nonce)
117    }
118
119    /// Decrypt the given encrypted message with this key.
120    pub fn decrypt(&self, message: &EncryptedMessage) -> Result<Vec<u8>> {
121        Ok(aead_chacha20_poly1305_decrypt_with_aad(
122            message.ciphertext(),
123            self.into(),
124            message.nonce().into(),
125            message.aad(),
126            message.authentication_tag().into(),
127        )?)
128    }
129}
130
131/// Implements Default to create a new random symmetric key.
132impl Default for SymmetricKey {
133    fn default() -> Self { Self::new() }
134}
135
136impl AsRef<[u8]> for SymmetricKey {
137    fn as_ref(&self) -> &[u8] { &self.0 }
138}
139
140/// Implements `AsRef<SymmetricKey>` to allow self-reference.
141impl AsRef<SymmetricKey> for SymmetricKey {
142    fn as_ref(&self) -> &SymmetricKey { self }
143}
144
145/// Implements conversion from a SymmetricKey reference to a byte array
146/// reference.
147impl<'a> From<&'a SymmetricKey> for &'a [u8; SymmetricKey::SYMMETRIC_KEY_SIZE] {
148    fn from(key: &'a SymmetricKey) -> Self { &key.0 }
149}
150
151/// Implements conversion from a SymmetricKey reference to a SymmetricKey.
152impl From<&SymmetricKey> for SymmetricKey {
153    fn from(key: &SymmetricKey) -> Self { key.clone() }
154}
155
156/// Implements conversion from a SymmetricKey to a `Vec<u8>`.
157impl From<SymmetricKey> for Vec<u8> {
158    fn from(key: SymmetricKey) -> Self { key.0.to_vec() }
159}
160
161/// Implements conversion from a SymmetricKey reference to a `Vec<u8>`.
162impl From<&SymmetricKey> for Vec<u8> {
163    fn from(key: &SymmetricKey) -> Self { key.0.to_vec() }
164}
165
166/// Implements conversion from a `Vec<u8>` to a SymmetricKey.
167impl TryFrom<Vec<u8>> for SymmetricKey {
168    type Error = Error;
169
170    fn try_from(value: Vec<u8>) -> std::result::Result<Self, Self::Error> {
171        Self::from_data_ref(value)
172    }
173}
174
175/// Implements Debug formatting to display the key in hexadecimal format.
176impl std::fmt::Debug for SymmetricKey {
177    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
178        write!(f, "SymmetricKey({})", self.hex())
179    }
180}
181
182/// Implements CBORTagged to provide the CBOR tag for the SymmetricKey.
183impl CBORTagged for SymmetricKey {
184    fn cbor_tags() -> Vec<Tag> { tags_for_values(&[tags::TAG_SYMMETRIC_KEY]) }
185}
186
187/// Implements conversion from SymmetricKey to CBOR for serialization.
188impl From<SymmetricKey> for CBOR {
189    fn from(value: SymmetricKey) -> Self { value.tagged_cbor() }
190}
191
192/// Implements CBORTaggedEncodable to provide CBOR encoding functionality.
193impl CBORTaggedEncodable for SymmetricKey {
194    fn untagged_cbor(&self) -> CBOR { CBOR::to_byte_string(self.0) }
195}
196
197/// Implements `TryFrom<CBOR>` for SymmetricKey to support conversion from CBOR
198/// data.
199impl TryFrom<CBOR> for SymmetricKey {
200    type Error = dcbor::Error;
201
202    fn try_from(cbor: CBOR) -> dcbor::Result<Self> {
203        Self::from_untagged_cbor(cbor)
204    }
205}
206
207/// Implements CBORTaggedDecodable to provide CBOR decoding functionality.
208impl CBORTaggedDecodable for SymmetricKey {
209    fn from_untagged_cbor(cbor: CBOR) -> dcbor::Result<Self> {
210        let bytes = CBOR::try_into_byte_string(cbor)?;
211        let instance = Self::from_data_ref(bytes)?;
212        Ok(instance)
213    }
214}
215
216impl ReferenceProvider for SymmetricKey {
217    fn reference(&self) -> Reference {
218        Reference::from_digest(Digest::from_image(
219            self.tagged_cbor().to_cbor_data(),
220        ))
221    }
222}
223
224impl std::fmt::Display for SymmetricKey {
225    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
226        write!(f, "SymmetricKey({})", self.ref_hex_short())
227    }
228}