Skip to main content

mas_keystore/
encrypter.rs

1// Copyright 2025, 2026 Element Creations Ltd.
2// Copyright 2024, 2025 New Vector Ltd.
3// Copyright 2022-2024 The Matrix.org Foundation C.I.C.
4//
5// SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-Element-Commercial
6// Please see LICENSE files in the repository root for full details.
7
8use std::sync::Arc;
9
10use aead::Aead;
11use base64ct::{Base64, Encoding};
12use chacha20poly1305::{ChaCha20Poly1305, Key, KeyInit, Nonce};
13use thiserror::Error;
14
15/// Helps encrypting and decrypting data
16#[derive(Clone)]
17pub struct Encrypter {
18    aead: Arc<ChaCha20Poly1305>,
19}
20
21#[derive(Debug, Error)]
22#[error("Decryption error")]
23pub enum DecryptError {
24    Aead(#[from] aead::Error),
25    Base64(#[from] base64ct::Error),
26    Shape,
27}
28
29impl Encrypter {
30    /// Creates an [`Encrypter`] out of an encryption key
31    #[must_use]
32    pub fn new(key: &[u8; 32]) -> Self {
33        let aead = ChaCha20Poly1305::new(&Key::from(*key));
34        let aead = Arc::new(aead);
35        Self { aead }
36    }
37
38    /// Encrypt a payload
39    ///
40    /// # Errors
41    ///
42    /// Will return `Err` when the payload failed to encrypt
43    pub fn encrypt(&self, nonce: &[u8; 12], decrypted: &[u8]) -> Result<Vec<u8>, aead::Error> {
44        let nonce = Nonce::from(*nonce);
45        let encrypted = self.aead.encrypt(&nonce, decrypted)?;
46        Ok(encrypted)
47    }
48
49    /// Decrypts a payload
50    ///
51    /// # Errors
52    ///
53    /// Will return `Err` when the payload failed to decrypt
54    pub fn decrypt(&self, nonce: &[u8; 12], encrypted: &[u8]) -> Result<Vec<u8>, aead::Error> {
55        let nonce = Nonce::from(*nonce);
56        let encrypted = self.aead.decrypt(&nonce, encrypted)?;
57        Ok(encrypted)
58    }
59
60    /// Encrypt a payload to a self-contained base64-encoded string
61    ///
62    /// # Errors
63    ///
64    /// Will return `Err` when the payload failed to encrypt
65    pub fn encrypt_to_string(&self, decrypted: &[u8]) -> Result<String, aead::Error> {
66        let nonce = rand::random();
67        let encrypted = self.encrypt(&nonce, decrypted)?;
68        let encrypted = [&nonce[..], &encrypted].concat();
69        let encrypted = Base64::encode_string(&encrypted);
70        Ok(encrypted)
71    }
72
73    /// Decrypt a payload from a self-contained base64-encoded string
74    ///
75    /// # Errors
76    ///
77    /// Will return `Err` when the payload failed to decrypt
78    pub fn decrypt_string(&self, encrypted: &str) -> Result<Vec<u8>, DecryptError> {
79        let encrypted = Base64::decode_vec(encrypted)?;
80
81        let nonce: &[u8; 12] = encrypted
82            .get(0..12)
83            .ok_or(DecryptError::Shape)?
84            .try_into()
85            .map_err(|_| DecryptError::Shape)?;
86
87        let payload = encrypted.get(12..).ok_or(DecryptError::Shape)?;
88
89        let decrypted_client_secret = self.decrypt(nonce, payload)?;
90
91        Ok(decrypted_client_secret)
92    }
93}