Skip to main content

miden_crypto/aead/xchacha/
mod.rs

1//! Cryptographic utilities for encrypting and decrypting data using XChaCha20-Poly1305 AEAD.
2//!
3//! This module provides secure encryption and decryption functionality. It uses
4//! the XChaCha20-Poly1305 authenticated encryption with associated data (AEAD) algorithm,
5//! which provides both confidentiality and integrity.
6//!
7//! # Key Components
8//!
9//! - [`SecretKey`]: A 256-bit secret key for encryption and decryption operations
10//! - [`Nonce`]: A 192-bit nonce that should be sampled randomly per encryption operation
11//! - [`EncryptedData`]: Encrypted data
12
13use alloc::{string::ToString, vec::Vec};
14
15use chacha20poly1305::{
16    XChaCha20Poly1305,
17    aead::{Aead, KeyInit, Payload},
18};
19use miden_crypto_derive::SilentDebug;
20use rand::CryptoRng;
21#[cfg(any(test, feature = "testing"))]
22use subtle::ConstantTimeEq;
23
24use crate::{
25    Felt,
26    aead::{AeadScheme, DataType, EncryptionError},
27    utils::{
28        BudgetedReader, ByteReader, ByteWriter, Deserializable, DeserializationError, Serializable,
29        SliceReader, bytes_to_elements_exact, elements_to_bytes, read_sensitive_array,
30        zeroize::{Zeroize, ZeroizeOnDrop, Zeroizing},
31    },
32};
33
34#[cfg(test)]
35mod test;
36
37// CONSTANTS
38// ================================================================================================
39
40/// Size of nonce in bytes
41const NONCE_SIZE_BYTES: usize = 24;
42/// Size of secret key in bytes
43const SK_SIZE_BYTES: usize = 32;
44
45/// Domain separator for the authenticated XChaCha encrypted-data representation.
46const AAD_DOMAIN: &[u8] = b"miden-crypto/xchacha20poly1305/encrypted-data";
47/// Version of the authenticated XChaCha encrypted-data representation.
48const AAD_VERSION: u8 = 1;
49/// Size of the fixed authenticated header that precedes the caller's associated data.
50const AAD_HEADER_SIZE: usize = AAD_DOMAIN.len() + 2;
51
52// STRUCTS AND IMPLEMENTATIONS
53// ================================================================================================
54
55/// Encrypted data
56#[derive(Debug, PartialEq, Eq)]
57pub struct EncryptedData {
58    /// Indicates the original format of the data before encryption.
59    ///
60    /// This value is bound into the authentication tag, so changing it invalidates the tag.
61    data_type: DataType,
62    /// The encrypted ciphertext, including the authentication tag
63    ciphertext: Vec<u8>,
64    /// The nonce used during encryption
65    nonce: Nonce,
66}
67
68/// A 192-bit nonce
69///
70/// Note: This should be drawn randomly from a CSPRNG.
71#[derive(Clone, Debug, PartialEq, Eq)]
72pub struct Nonce {
73    inner: chacha20poly1305::XNonce,
74}
75
76impl Nonce {
77    /// Creates a new random nonce using the provided random number generator
78    pub fn with_rng<R: CryptoRng>(rng: &mut R) -> Self {
79        let mut bytes = [0u8; NONCE_SIZE_BYTES];
80        rng.fill_bytes(&mut bytes);
81        Self::from_slice(&bytes)
82    }
83
84    /// Creates a new nonce from the provided array of bytes
85    pub fn from_slice(bytes: &[u8; NONCE_SIZE_BYTES]) -> Self {
86        Nonce { inner: (*bytes).into() }
87    }
88}
89
90/// A 256-bit secret key
91#[derive(SilentDebug)]
92pub struct SecretKey([u8; SK_SIZE_BYTES]);
93
94#[cfg(any(test, feature = "testing"))]
95impl PartialEq for SecretKey {
96    fn eq(&self, other: &Self) -> bool {
97        // Constant-time comparison to avoid timing side channels in test builds.
98        bool::from(self.0.ct_eq(&other.0))
99    }
100}
101
102#[cfg(any(test, feature = "testing"))]
103impl Eq for SecretKey {}
104
105fn read_encrypted_data_strict(ciphertext: &[u8]) -> Result<EncryptedData, EncryptionError> {
106    let mut reader = BudgetedReader::new(SliceReader::new(ciphertext), ciphertext.len());
107    let encrypted_data =
108        EncryptedData::read_from(&mut reader).map_err(|_| EncryptionError::FailedOperation)?;
109
110    if reader.has_more_bytes() {
111        return Err(EncryptionError::FailedOperation);
112    }
113
114    Ok(encrypted_data)
115}
116
117/// Builds the authenticated associated data for a ciphertext of the given data type.
118///
119/// The fixed domain tag, version byte, and data type byte form a fixed-length header. The
120/// caller's associated data follows unchanged, so the authenticated input is unambiguous and
121/// binds the data type to the tag.
122fn authenticated_associated_data(
123    data_type: DataType,
124    associated_data: &[u8],
125) -> Result<Vec<u8>, EncryptionError> {
126    let capacity = associated_data
127        .len()
128        .checked_add(AAD_HEADER_SIZE)
129        .ok_or(EncryptionError::InputTooLong)?;
130
131    let mut bound = Vec::with_capacity(capacity);
132    bound.extend_from_slice(AAD_DOMAIN);
133    bound.push(AAD_VERSION);
134    bound.push(data_type as u8);
135    bound.extend_from_slice(associated_data);
136
137    Ok(bound)
138}
139
140impl SecretKey {
141    // CONSTRUCTORS
142    // --------------------------------------------------------------------------------------------
143
144    /// Creates a new random secret key using the default random number generator
145    #[cfg(feature = "std")]
146    #[allow(clippy::new_without_default)]
147    pub fn new() -> Self {
148        let mut rng = rand::rng();
149        Self::with_rng(&mut rng)
150    }
151
152    /// Creates a new random secret key using the provided random number generator
153    pub fn with_rng<R: CryptoRng>(rng: &mut R) -> Self {
154        let mut key = Zeroizing::new([0u8; SK_SIZE_BYTES]);
155        rng.fill_bytes(key.as_mut());
156        Self(*key)
157    }
158
159    // BYTE ENCRYPTION
160    // --------------------------------------------------------------------------------------------
161
162    /// Encrypts and authenticates the provided data using this secret key and a random
163    /// nonce
164    #[cfg(feature = "std")]
165    pub fn encrypt_bytes(&self, data: &[u8]) -> Result<EncryptedData, EncryptionError> {
166        self.encrypt_bytes_with_associated_data(data, &[])
167    }
168
169    /// Encrypts the provided data and authenticates both the ciphertext as well as
170    /// the provided associated data using this secret key and a random nonce
171    #[cfg(feature = "std")]
172    pub fn encrypt_bytes_with_associated_data(
173        &self,
174        data: &[u8],
175        associated_data: &[u8],
176    ) -> Result<EncryptedData, EncryptionError> {
177        let mut rng = rand::rng();
178        let nonce = Nonce::with_rng(&mut rng);
179
180        self.encrypt_bytes_with_nonce(data, associated_data, nonce)
181    }
182
183    /// Encrypts the provided data using this secret key and a specified nonce
184    pub fn encrypt_bytes_with_nonce(
185        &self,
186        data: &[u8],
187        associated_data: &[u8],
188        nonce: Nonce,
189    ) -> Result<EncryptedData, EncryptionError> {
190        self.encrypt_with_data_type(data, associated_data, nonce, DataType::Bytes)
191    }
192
193    /// Encrypts data with the selected data type and binds that type into the tag.
194    fn encrypt_with_data_type(
195        &self,
196        data: &[u8],
197        associated_data: &[u8],
198        nonce: Nonce,
199        data_type: DataType,
200    ) -> Result<EncryptedData, EncryptionError> {
201        let aad = authenticated_associated_data(data_type, associated_data)?;
202        let payload = Payload { msg: data, aad: &aad };
203
204        let cipher = XChaCha20Poly1305::new(&self.0.into());
205
206        let ciphertext = cipher
207            .encrypt(&nonce.inner, payload)
208            .map_err(|_| EncryptionError::FailedOperation)?;
209
210        Ok(EncryptedData { data_type, ciphertext, nonce })
211    }
212
213    // ELEMENT ENCRYPTION
214    // --------------------------------------------------------------------------------------------
215
216    /// Encrypts and authenticates the provided sequence of field elements using this secret key
217    /// and a random nonce.
218    #[cfg(feature = "std")]
219    pub fn encrypt_elements(&self, data: &[Felt]) -> Result<EncryptedData, EncryptionError> {
220        self.encrypt_elements_with_associated_data(data, &[])
221    }
222
223    /// Encrypts the provided sequence of field elements and authenticates both the ciphertext as
224    /// well as the provided associated data using this secret key and a random nonce.
225    #[cfg(feature = "std")]
226    pub fn encrypt_elements_with_associated_data(
227        &self,
228        data: &[Felt],
229        associated_data: &[Felt],
230    ) -> Result<EncryptedData, EncryptionError> {
231        let mut rng = rand::rng();
232        let nonce = Nonce::with_rng(&mut rng);
233
234        self.encrypt_elements_with_nonce(data, associated_data, nonce)
235    }
236
237    /// Encrypts the provided sequence of field elements and authenticates both the ciphertext as
238    /// well as the provided associated data using this secret key and the specified nonce.
239    pub fn encrypt_elements_with_nonce(
240        &self,
241        data: &[Felt],
242        associated_data: &[Felt],
243        nonce: Nonce,
244    ) -> Result<EncryptedData, EncryptionError> {
245        let data_bytes = elements_to_bytes(data);
246        let ad_bytes = elements_to_bytes(associated_data);
247
248        self.encrypt_with_data_type(&data_bytes, &ad_bytes, nonce, DataType::Elements)
249    }
250
251    // BYTE DECRYPTION
252    // --------------------------------------------------------------------------------------------
253
254    /// Decrypts the provided encrypted data using this secret key.
255    ///
256    /// # Errors
257    /// Returns an error if decryption fails or if the underlying data was encrypted as elements
258    /// rather than as bytes.
259    pub fn decrypt_bytes(
260        &self,
261        encrypted_data: &EncryptedData,
262    ) -> Result<Vec<u8>, EncryptionError> {
263        self.decrypt_bytes_with_associated_data(encrypted_data, &[])
264    }
265
266    /// Decrypts the provided encrypted data given some associated data using this secret key.
267    ///
268    /// # Errors
269    /// Returns an error if decryption fails or if the underlying data was encrypted as elements
270    /// rather than as bytes.
271    pub fn decrypt_bytes_with_associated_data(
272        &self,
273        encrypted_data: &EncryptedData,
274        associated_data: &[u8],
275    ) -> Result<Vec<u8>, EncryptionError> {
276        if encrypted_data.data_type != DataType::Bytes {
277            return Err(EncryptionError::InvalidDataType {
278                expected: DataType::Bytes,
279                found: encrypted_data.data_type,
280            });
281        }
282        self.decrypt_bytes_with_associated_data_unchecked(encrypted_data, associated_data)
283    }
284
285    /// Decrypts the provided encrypted data given some associated data using this secret key.
286    fn decrypt_bytes_with_associated_data_unchecked(
287        &self,
288        encrypted_data: &EncryptedData,
289        associated_data: &[u8],
290    ) -> Result<Vec<u8>, EncryptionError> {
291        let EncryptedData { ciphertext, nonce, data_type } = encrypted_data;
292        let aad = authenticated_associated_data(*data_type, associated_data)?;
293        let payload = Payload { msg: ciphertext, aad: &aad };
294
295        let cipher = XChaCha20Poly1305::new(&self.0.into());
296
297        cipher
298            .decrypt(&nonce.inner, payload)
299            .map_err(|_| EncryptionError::FailedOperation)
300    }
301
302    // ELEMENT DECRYPTION
303    // --------------------------------------------------------------------------------------------
304
305    /// Decrypts the provided encrypted data using this secret key.
306    ///
307    /// # Errors
308    /// Returns an error if decryption fails or if the underlying data was encrypted as bytes
309    /// rather than as field elements.
310    pub fn decrypt_elements(
311        &self,
312        encrypted_data: &EncryptedData,
313    ) -> Result<Vec<Felt>, EncryptionError> {
314        self.decrypt_elements_with_associated_data(encrypted_data, &[])
315    }
316
317    /// Decrypts the provided encrypted data, given some associated data, using this secret key.
318    ///
319    /// # Errors
320    /// Returns an error if decryption fails or if the underlying data was encrypted as bytes
321    /// rather than as field elements.
322    pub fn decrypt_elements_with_associated_data(
323        &self,
324        encrypted_data: &EncryptedData,
325        associated_data: &[Felt],
326    ) -> Result<Vec<Felt>, EncryptionError> {
327        if encrypted_data.data_type != DataType::Elements {
328            return Err(EncryptionError::InvalidDataType {
329                expected: DataType::Elements,
330                found: encrypted_data.data_type,
331            });
332        }
333
334        let ad_bytes = elements_to_bytes(associated_data);
335
336        let plaintext_bytes =
337            self.decrypt_bytes_with_associated_data_unchecked(encrypted_data, &ad_bytes)?;
338        match bytes_to_elements_exact(&plaintext_bytes) {
339            Some(elements) => Ok(elements),
340            None => Err(EncryptionError::FailedBytesToElementsConversion),
341        }
342    }
343}
344
345impl AsRef<[u8]> for SecretKey {
346    fn as_ref(&self) -> &[u8] {
347        &self.0
348    }
349}
350
351impl Drop for SecretKey {
352    fn drop(&mut self) {
353        self.zeroize();
354    }
355}
356
357impl Zeroize for SecretKey {
358    fn zeroize(&mut self) {
359        self.0.zeroize();
360    }
361}
362
363impl ZeroizeOnDrop for SecretKey {}
364
365// IES IMPLEMENTATION
366// ================================================================================================
367
368pub struct XChaCha;
369
370impl AeadScheme for XChaCha {
371    const KEY_SIZE: usize = SK_SIZE_BYTES;
372
373    type Key = SecretKey;
374
375    fn key_from_bytes(bytes: &[u8]) -> Result<Self::Key, EncryptionError> {
376        if bytes.len() != SK_SIZE_BYTES {
377            return Err(EncryptionError::FailedOperation);
378        }
379
380        SecretKey::read_from_bytes_with_budget(bytes, SK_SIZE_BYTES)
381            .map_err(|_| EncryptionError::FailedOperation)
382    }
383
384    fn encrypt_bytes<R: CryptoRng>(
385        key: &Self::Key,
386        rng: &mut R,
387        plaintext: &[u8],
388        associated_data: &[u8],
389    ) -> Result<Vec<u8>, EncryptionError> {
390        let nonce = Nonce::with_rng(rng);
391        let encrypted_data = key
392            .encrypt_bytes_with_nonce(plaintext, associated_data, nonce)
393            .map_err(|_| EncryptionError::FailedOperation)?;
394        Ok(encrypted_data.to_bytes())
395    }
396
397    fn decrypt_bytes_with_associated_data(
398        key: &Self::Key,
399        ciphertext: &[u8],
400        associated_data: &[u8],
401    ) -> Result<Vec<u8>, EncryptionError> {
402        let encrypted_data = read_encrypted_data_strict(ciphertext)?;
403
404        key.decrypt_bytes_with_associated_data(&encrypted_data, associated_data)
405            .map_err(|_| EncryptionError::FailedOperation)
406    }
407
408    fn encrypt_elements<R: CryptoRng>(
409        key: &Self::Key,
410        rng: &mut R,
411        plaintext: &[Felt],
412        associated_data: &[Felt],
413    ) -> Result<Vec<u8>, EncryptionError> {
414        let encrypted_data = key
415            .encrypt_elements_with_nonce(plaintext, associated_data, Nonce::with_rng(rng))
416            .map_err(|_| EncryptionError::FailedOperation)?;
417        Ok(encrypted_data.to_bytes())
418    }
419
420    fn decrypt_elements_with_associated_data(
421        key: &Self::Key,
422        ciphertext: &[u8],
423        associated_data: &[Felt],
424    ) -> Result<Vec<Felt>, EncryptionError> {
425        let encrypted_data = read_encrypted_data_strict(ciphertext)?;
426        key.decrypt_elements_with_associated_data(&encrypted_data, associated_data)
427            .map_err(|_| EncryptionError::FailedOperation)
428    }
429}
430
431// SERIALIZATION / DESERIALIZATION
432// ================================================================================================
433
434impl Serializable for SecretKey {
435    fn write_into<W: ByteWriter>(&self, target: &mut W) {
436        target.write_bytes(&self.0);
437    }
438}
439
440impl Deserializable for SecretKey {
441    fn read_from<R: ByteReader>(source: &mut R) -> Result<Self, DeserializationError> {
442        let inner = read_sensitive_array::<SK_SIZE_BYTES, _>(source)?;
443
444        Ok(SecretKey(*inner))
445    }
446}
447
448impl Serializable for Nonce {
449    fn write_into<W: ByteWriter>(&self, target: &mut W) {
450        target.write_bytes(&self.inner);
451    }
452}
453
454impl Deserializable for Nonce {
455    fn read_from<R: ByteReader>(source: &mut R) -> Result<Self, DeserializationError> {
456        let inner: [u8; NONCE_SIZE_BYTES] = source.read_array()?;
457
458        Ok(Nonce { inner: inner.into() })
459    }
460}
461
462impl Serializable for EncryptedData {
463    fn write_into<W: ByteWriter>(&self, target: &mut W) {
464        target.write_u8(self.data_type as u8);
465        target.write_usize(self.ciphertext.len());
466        target.write_bytes(&self.ciphertext);
467        target.write_bytes(&self.nonce.inner);
468    }
469}
470
471impl Deserializable for EncryptedData {
472    fn read_from<R: ByteReader>(source: &mut R) -> Result<Self, DeserializationError> {
473        let data_type_value: u8 = source.read_u8()?;
474        let data_type = data_type_value.try_into().map_err(|_| {
475            DeserializationError::InvalidValue("invalid data type value".to_string())
476        })?;
477
478        let ciphertext = Vec::<u8>::read_from(source)?;
479
480        let inner: [u8; NONCE_SIZE_BYTES] = source.read_array()?;
481
482        Ok(Self {
483            ciphertext,
484            nonce: Nonce { inner: inner.into() },
485            data_type,
486        })
487    }
488}