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