Skip to main content

openmls/treesync/node/
encryption_keys.rs

1use std::fmt::Debug;
2
3use openmls_traits::{
4    crypto::OpenMlsCrypto,
5    random::OpenMlsRand,
6    storage::{StorageProvider as StorageProviderTrait, CURRENT_VERSION},
7    types::{Ciphersuite, HpkeCiphertext, HpkeKeyPair},
8};
9use serde::{Deserialize, Serialize};
10use tls_codec::{TlsDeserialize, TlsDeserializeBytes, TlsSerialize, TlsSize, VLBytes};
11
12use crate::{
13    ciphersuite::{hpke, HpkePrivateKey, HpkePublicKey, Secret},
14    error::LibraryError,
15    storage::{OpenMlsProvider, StorageProvider},
16};
17
18/// [`EncryptionKey`] contains an HPKE public key that allows the encryption of
19/// path secrets in MLS commits.
20#[derive(
21    Debug,
22    Clone,
23    Serialize,
24    Deserialize,
25    TlsSerialize,
26    TlsDeserialize,
27    TlsDeserializeBytes,
28    TlsSize,
29    PartialEq,
30    Eq,
31    Hash,
32)]
33pub struct EncryptionKey {
34    key: HpkePublicKey,
35}
36
37impl EncryptionKey {
38    /// Return the internal [`HpkePublicKey`].
39    pub(crate) fn key(&self) -> &HpkePublicKey {
40        &self.key
41    }
42
43    /// Return the internal [`HpkePublicKey`] as slice.
44    pub(crate) fn as_slice(&self) -> &[u8] {
45        self.key.as_slice()
46    }
47
48    /// Encrypt to this HPKE public key.
49    pub(crate) fn encrypt(
50        &self,
51        crypto: &impl OpenMlsCrypto,
52        ciphersuite: Ciphersuite,
53        context: &[u8],
54        plaintext: &[u8],
55    ) -> Result<HpkeCiphertext, LibraryError> {
56        hpke::encrypt_with_label(
57            self.as_slice(),
58            "UpdatePathNode",
59            context,
60            plaintext,
61            ciphersuite,
62            crypto,
63        )
64        .map_err(|_| LibraryError::custom("Encryption failed. A serialization issue really"))
65    }
66}
67
68#[cfg(feature = "targeted-messages-draft")]
69impl EncryptionKey {
70    pub(crate) fn seal_psk(
71        &self,
72        params: hpke::PskEncryptParams,
73        aad: &[u8],
74        plaintext: &[u8],
75        crypto: &impl OpenMlsCrypto,
76    ) -> Result<HpkeCiphertext, LibraryError> {
77        hpke::seal_psk(self.as_slice(), params, aad, plaintext, crypto)
78    }
79}
80
81impl From<Vec<u8>> for EncryptionKey {
82    fn from(key: Vec<u8>) -> Self {
83        Self { key: key.into() }
84    }
85}
86
87#[derive(
88    Clone, Serialize, Deserialize, TlsDeserialize, TlsDeserializeBytes, TlsSerialize, TlsSize,
89)]
90#[cfg_attr(any(test, feature = "test-utils"), derive(PartialEq, Eq))]
91pub struct EncryptionPrivateKey {
92    key: HpkePrivateKey,
93}
94
95impl Debug for EncryptionPrivateKey {
96    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
97        let mut ds = f.debug_struct("EncryptionPrivateKey");
98
99        #[cfg(feature = "crypto-debug")]
100        ds.field("key", &self.key);
101        #[cfg(not(feature = "crypto-debug"))]
102        ds.field("key", &"***");
103
104        ds.finish()
105    }
106}
107
108impl From<Vec<u8>> for EncryptionPrivateKey {
109    fn from(key: Vec<u8>) -> Self {
110        Self { key: key.into() }
111    }
112}
113
114impl From<HpkePrivateKey> for EncryptionPrivateKey {
115    fn from(key: HpkePrivateKey) -> Self {
116        Self { key }
117    }
118}
119
120impl EncryptionPrivateKey {
121    /// Decrypt a given `HpkeCiphertext` using this [`EncryptionPrivateKey`] and
122    /// `group_context`.
123    ///
124    /// Returns the decrypted [`Secret`]. Returns an error if the decryption was
125    /// unsuccessful.
126    pub(crate) fn decrypt(
127        &self,
128        crypto: &impl OpenMlsCrypto,
129        ciphersuite: Ciphersuite,
130        ciphertext: &HpkeCiphertext,
131        group_context: &[u8],
132    ) -> Result<Secret, hpke::Error> {
133        // ValSem203: Path secrets must decrypt correctly
134        hpke::decrypt_with_label(
135            &self.key,
136            "UpdatePathNode",
137            group_context,
138            ciphertext,
139            ciphersuite,
140            crypto,
141        )
142        .map(|secret_bytes| Secret::from_slice(&secret_bytes))
143    }
144
145    #[cfg(feature = "targeted-messages-draft")]
146    pub(crate) fn open_psk(
147        &self,
148        params: hpke::PskEncryptParams,
149        aad: &[u8],
150        ciphertext: &HpkeCiphertext,
151        crypto: &impl OpenMlsCrypto,
152    ) -> Result<Vec<u8>, hpke::Error> {
153        hpke::open_psk(&self.key, params, aad, ciphertext, crypto)
154    }
155}
156
157#[cfg(any(test, feature = "test-utils"))]
158impl EncryptionPrivateKey {
159    pub(crate) fn key(&self) -> &HpkePrivateKey {
160        &self.key
161    }
162}
163
164impl From<HpkePublicKey> for EncryptionKey {
165    fn from(key: HpkePublicKey) -> Self {
166        Self { key }
167    }
168}
169
170#[derive(
171    Debug, Clone, Serialize, Deserialize, TlsDeserialize, TlsDeserializeBytes, TlsSerialize, TlsSize,
172)]
173#[cfg_attr(any(test, feature = "test-utils"), derive(PartialEq, Eq))]
174pub(crate) struct EncryptionKeyPair {
175    public_key: EncryptionKey,
176    private_key: EncryptionPrivateKey,
177}
178
179impl EncryptionKeyPair {
180    /// Write the [`EncryptionKeyPair`] to the store of the `provider`.
181    ///
182    /// This must only be used for encryption key pairs that are generated for
183    /// update leaf nodes. All other encryption key pairs are stored as part
184    /// of the key package or the epoch encryption key pairs.
185    #[openmls_traits::maybe_async]
186    pub(crate) async fn write<Storage: StorageProvider>(
187        &self,
188        store: &Storage,
189    ) -> Result<(), Storage::Error> {
190        store
191            .write_encryption_key_pair(self.public_key(), self)
192            .await
193    }
194
195    /// Read the [`EncryptionKeyPair`] from the key store of the `provider`. This
196    /// function is meant to read standalone keypairs, not ones that are
197    /// already in use with an MLS group.
198    ///
199    /// This must only be used for encryption key pairs that are generated for
200    /// update leaf nodes. All other encryption key pairs are stored as part
201    /// of the key package or the epoch encryption key pairs.
202    ///
203    /// Returns `None` if the keypair cannot be read from the store.
204    #[openmls_traits::maybe_async]
205    pub(crate) async fn read(
206        provider: &impl OpenMlsProvider,
207        encryption_key: &EncryptionKey,
208    ) -> Option<EncryptionKeyPair> {
209        provider
210            .storage()
211            .encryption_key_pair(encryption_key)
212            .await
213            .ok()
214            .flatten()
215    }
216
217    /// Delete the [`EncryptionKeyPair`] from the store of the `provider`.
218    ///
219    /// This must only be used for encryption key pairs that are generated for
220    /// update leaf nodes. All other encryption key pairs are stored as part
221    /// of the key package or the epoch encryption key pairs.
222    #[openmls_traits::maybe_async]
223    pub(crate) async fn delete<Storage: StorageProviderTrait<CURRENT_VERSION>>(
224        &self,
225        store: &Storage,
226    ) -> Result<(), Storage::Error> {
227        store.delete_encryption_key_pair(self.public_key()).await
228    }
229
230    pub(crate) fn public_key(&self) -> &EncryptionKey {
231        &self.public_key
232    }
233
234    pub(crate) fn private_key(&self) -> &EncryptionPrivateKey {
235        &self.private_key
236    }
237
238    pub(crate) fn random(
239        rand: &impl OpenMlsRand,
240        crypto: &impl OpenMlsCrypto,
241        ciphersuite: Ciphersuite,
242    ) -> Result<Self, LibraryError> {
243        let ikm =
244            Secret::random(ciphersuite, rand).map_err(LibraryError::unexpected_crypto_error)?;
245        Ok(crypto
246            .derive_hpke_keypair(ciphersuite.hpke_config(), ikm.as_slice())
247            .map_err(LibraryError::unexpected_crypto_error)?
248            .into())
249    }
250}
251
252#[cfg(feature = "test-utils")]
253pub mod test_utils {
254    use super::*;
255
256    #[openmls_traits::maybe_async]
257    pub async fn read_keys_from_key_store(
258        provider: &impl OpenMlsProvider,
259        encryption_key: &EncryptionKey,
260    ) -> HpkeKeyPair {
261        let keys = EncryptionKeyPair::read(provider, encryption_key)
262            .await
263            .unwrap();
264
265        HpkeKeyPair {
266            private: keys.private_key.key,
267            public: keys.public_key.key.as_slice().to_vec(),
268        }
269    }
270
271    #[openmls_traits::maybe_async]
272    pub async fn write_keys_from_key_store(
273        provider: &impl OpenMlsProvider,
274        encryption_key: HpkeKeyPair,
275    ) {
276        let keypair = EncryptionKeyPair::from(encryption_key);
277
278        keypair.write(provider.storage()).await.unwrap();
279    }
280}
281
282#[cfg(test)]
283impl EncryptionKeyPair {
284    /// Build a key pair from raw bytes for testing.
285    pub(crate) fn from_raw(public_key: Vec<u8>, private_key: Vec<u8>) -> Self {
286        Self {
287            public_key: EncryptionKey {
288                key: public_key.into(),
289            },
290            private_key: EncryptionPrivateKey {
291                key: private_key.into(),
292            },
293        }
294    }
295}
296
297impl From<(HpkePublicKey, HpkePrivateKey)> for EncryptionKeyPair {
298    fn from((public_key, private_key): (HpkePublicKey, HpkePrivateKey)) -> Self {
299        Self {
300            public_key: public_key.into(),
301            private_key: private_key.into(),
302        }
303    }
304}
305
306impl From<HpkeKeyPair> for EncryptionKeyPair {
307    fn from(hpke_keypair: HpkeKeyPair) -> Self {
308        let public_bytes: VLBytes = hpke_keypair.public.into();
309        let private_bytes = hpke_keypair.private;
310        Self {
311            public_key: public_bytes.into(),
312            private_key: private_bytes.into(),
313        }
314    }
315}
316
317impl From<(EncryptionKey, EncryptionPrivateKey)> for EncryptionKeyPair {
318    fn from((public_key, private_key): (EncryptionKey, EncryptionPrivateKey)) -> Self {
319        Self {
320            public_key,
321            private_key,
322        }
323    }
324}