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 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    /// 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 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    /// 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
123/// Implements `AsRef<SymmetricKey>` to allow self-reference.
124impl AsRef<SymmetricKey> for SymmetricKey {
125    fn as_ref(&self) -> &SymmetricKey {
126        self
127    }
128}
129
130/// Implements conversion from a SymmetricKey reference to a byte array reference.
131impl<'a> From<&'a SymmetricKey> for &'a [u8; SymmetricKey::SYMMETRIC_KEY_SIZE] {
132    fn from(key: &'a SymmetricKey) -> Self {
133        &key.0
134    }
135}
136
137/// Implements conversion from a SymmetricKey reference to a SymmetricKey.
138impl From<&SymmetricKey> for SymmetricKey {
139    fn from(key: &SymmetricKey) -> Self {
140        key.clone()
141    }
142}
143
144/// Implements conversion from a SymmetricKey to a `Vec<u8>`.
145impl From<SymmetricKey> for Vec<u8> {
146    fn from(key: SymmetricKey) -> Self {
147        key.0.to_vec()
148    }
149}
150
151/// Implements conversion from a SymmetricKey reference to a `Vec<u8>`.
152impl From<&SymmetricKey> for Vec<u8> {
153    fn from(key: &SymmetricKey) -> Self {
154        key.0.to_vec()
155    }
156}
157
158/// Implements conversion from a `Vec<u8>` to a SymmetricKey.
159impl 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
167/// Implements Debug formatting to display the key in hexadecimal format.
168impl 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
174/// Implements CBORTagged to provide the CBOR tag for the SymmetricKey.
175impl CBORTagged for SymmetricKey {
176    fn cbor_tags() -> Vec<Tag> {
177        tags_for_values(&[tags::TAG_SYMMETRIC_KEY])
178    }
179}
180
181/// Implements conversion from SymmetricKey to CBOR for serialization.
182impl From<SymmetricKey> for CBOR {
183    fn from(value: SymmetricKey) -> Self {
184        value.tagged_cbor()
185    }
186}
187
188/// Implements CBORTaggedEncodable to provide CBOR encoding functionality.
189impl CBORTaggedEncodable for SymmetricKey {
190    fn untagged_cbor(&self) -> CBOR {
191        CBOR::to_byte_string(self.0)
192    }
193}
194
195/// Implements `TryFrom<CBOR>` for SymmetricKey to support conversion from CBOR 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}