bc_components/symmetric/
symmetric_key.rs

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