bc_components/symmetric/
symmetric_key.rs

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