revault_lockbox_api 0.0.2

reVault lockbox API to create and manage lockboxes
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
use chacha20poly1305::aead::{Aead, KeyInit};
use chacha20poly1305::{ChaCha20Poly1305, Key, Nonce};
use hkdf::Hkdf;
use ml_kem::kem::{Decapsulate, Encapsulate, Kem, KeyExport};
use ml_kem::MlKem768;
use sha2::Sha256;
use x25519_dalek::{PublicKey as X25519PublicKey, StaticSecret as X25519SecretKey};
use zeroize::Zeroize;

use crate::{secret_vec::SecretVec, Error, Result};

const PUBLIC_MAGIC: &[u8; 8] = b"LBX1HPUB";
const PRIVATE_MAGIC: &[u8; 8] = b"LBX1HPRV";
const HYBRID_KEY_VERSION: u16 = 1;
const HYBRID_ALGORITHM_X25519_MLKEM768: u16 = 1;
const X25519_KEY_LEN: usize = 32;

/// Hybrid X25519 + ML-KEM-768 contact keypair.
///
/// The private material is stored as a versioned Lockbox binary record in
/// `SecretVec`. The public contact key is cached separately for wrapping new
/// content keys.
pub struct ContactKeyPair {
    private_key_bytes: SecretVec,
    x25519_public_key: [u8; X25519_KEY_LEN],
    mlkem_encapsulation_key: ml_kem::EncapsulationKey768,
}

/// Public hybrid X25519 + ML-KEM-768 contact key.
///
/// This key can be shared with a lockbox creator. It can wrap a lockbox content
/// key for the holder of the matching `ContactKeyPair`, but it cannot open a
/// lockbox by itself.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct ContactPublicKey {
    x25519_public_key: [u8; X25519_KEY_LEN],
    mlkem_encapsulation_key: ml_kem::EncapsulationKey768,
}

/// Content key wrapped to a hybrid X25519 + ML-KEM-768 contact.
#[derive(Debug, Clone)]
pub struct ContactWrappedKey {
    x25519_ephemeral_public_key: [u8; X25519_KEY_LEN],
    mlkem_ciphertext: ml_kem::Ciphertext<MlKem768>,
    encrypted_key: Vec<u8>,
}

impl ContactKeyPair {
    /// Generate a fresh hybrid X25519 + ML-KEM-768 keypair.
    ///
    /// Returns `Error::SecurityLimitExceeded` if the private record cannot be
    /// stored in secure memory.
    pub fn generate() -> Result<Self> {
        let mut x25519_secret_bytes = [0_u8; X25519_KEY_LEN];
        getrandom::fill(&mut x25519_secret_bytes).map_err(|err| Error::Io(err.to_string()))?;
        let x25519_secret_key = X25519SecretKey::from(x25519_secret_bytes);
        let x25519_public_key = X25519PublicKey::from(&x25519_secret_key).to_bytes();
        x25519_secret_bytes.zeroize();

        let (mlkem_decapsulation_key, mlkem_encapsulation_key) = MlKem768::generate_keypair();
        let mut mlkem_seed = mlkem_decapsulation_key.to_bytes();
        let private_key_bytes =
            encode_private_key(&x25519_secret_key.to_bytes(), mlkem_seed.as_ref())?;
        mlkem_seed.zeroize();

        Ok(Self {
            private_key_bytes,
            x25519_public_key,
            mlkem_encapsulation_key,
        })
    }

    /// Encrypt a content key to this keypair's public contact key.
    ///
    /// Returns `Error::InvalidKey` if authenticated wrapping fails.
    pub fn encrypt(&self, content_key: &[u8]) -> Result<ContactWrappedKey> {
        self.public_key().encrypt(content_key)
    }

    /// Decrypt a content key previously encrypted for this keypair.
    ///
    /// Returns `Error::InvalidKey` if authenticated decrypt fails,
    /// `Error::InvalidKeyMaterial` if the stored private key cannot be decoded,
    /// or `Error::SecurityLimitExceeded` if secure memory access fails.
    pub fn decrypt(&self, wrapped: &ContactWrappedKey) -> Result<Vec<u8>> {
        self.private_key_bytes.with_bytes(|bytes| {
            let decoded = decode_private_key(bytes)?;
            let x25519_secret_key = X25519SecretKey::from(decoded.x25519_secret_key);
            let peer = X25519PublicKey::from(wrapped.x25519_ephemeral_public_key);
            let x25519_secret = x25519_secret_key.diffie_hellman(&peer);

            let seed = ml_kem::Seed::try_from(decoded.mlkem_seed.as_slice()).map_err(|_| {
                Error::InvalidKeyMaterial("ML-KEM private seed has the wrong length".to_string())
            })?;
            let mlkem_decapsulation_key = ml_kem::DecapsulationKey768::from_seed(seed);
            let mlkem_secret = mlkem_decapsulation_key.decapsulate(&wrapped.mlkem_ciphertext);

            let mut wrapping_key =
                derive_wrapping_key(x25519_secret.as_bytes(), mlkem_secret.as_ref())?;
            let cipher = ChaCha20Poly1305::new(&Key::from(wrapping_key));
            let key = cipher
                .decrypt(&Nonce::from([0_u8; 12]), wrapped.encrypted_key.as_ref())
                .map_err(|_| Error::InvalidKey);
            wrapping_key.zeroize();
            key
        })?
    }

    /// Return the public contact key for this keypair.
    pub fn public_key(&self) -> ContactPublicKey {
        ContactPublicKey {
            x25519_public_key: self.x25519_public_key,
            mlkem_encapsulation_key: self.mlkem_encapsulation_key.clone(),
        }
    }

    /// Construct a keypair by taking ownership of a private key record buffer.
    ///
    /// Returns `Error::InvalidKeyMaterial` if the bytes do not encode a
    /// supported Lockbox hybrid contact private key, or
    /// `Error::SecurityLimitExceeded` if secure memory access fails.
    pub fn from_private_key_record(private_key_bytes: SecretVec) -> Result<Self> {
        let (x25519_public_key, mlkem_encapsulation_key) =
            private_key_bytes.with_bytes(|bytes| {
                let decoded = decode_private_key(bytes)?;
                let x25519_secret_key = X25519SecretKey::from(decoded.x25519_secret_key);
                let x25519_public_key = X25519PublicKey::from(&x25519_secret_key).to_bytes();
                let seed = ml_kem::Seed::try_from(decoded.mlkem_seed.as_slice()).map_err(|_| {
                    Error::InvalidKeyMaterial(
                        "ML-KEM private seed has the wrong length".to_string(),
                    )
                })?;
                let mlkem_decapsulation_key = ml_kem::DecapsulationKey768::from_seed(seed);
                Ok::<_, Error>((
                    x25519_public_key,
                    mlkem_decapsulation_key.encapsulation_key().clone(),
                ))
            })??;
        Ok(Self {
            private_key_bytes,
            x25519_public_key,
            mlkem_encapsulation_key,
        })
    }

    /// Clone the private key record into a new `SecretVec`.
    ///
    /// Returns `Error::SecurityLimitExceeded` if secure memory allocation
    /// fails.
    pub fn private_key_record(&self) -> Result<SecretVec> {
        self.private_key_bytes.try_clone().map_err(Into::into)
    }
}

impl ContactPublicKey {
    /// Decode a public contact key from its versioned Lockbox byte
    /// representation.
    ///
    /// Returns `Error::InvalidKeyMaterial` if the bytes do not encode a
    /// supported hybrid contact public key.
    pub fn from_bytes(bytes: &[u8]) -> Result<Self> {
        decode_public_key(bytes)
    }

    /// Encode this public contact key as versioned Lockbox bytes.
    pub fn to_bytes(&self) -> Vec<u8> {
        encode_public_key(self)
    }

    /// Wrap a content key for this contact.
    ///
    /// Returns `Error::InvalidKey` if authenticated wrapping fails.
    pub fn encrypt(&self, content_key: &[u8]) -> Result<ContactWrappedKey> {
        let mut ephemeral_secret_bytes = [0_u8; X25519_KEY_LEN];
        getrandom::fill(&mut ephemeral_secret_bytes).map_err(|err| Error::Io(err.to_string()))?;
        let ephemeral_secret = X25519SecretKey::from(ephemeral_secret_bytes);
        ephemeral_secret_bytes.zeroize();
        let x25519_ephemeral_public_key = X25519PublicKey::from(&ephemeral_secret).to_bytes();
        let peer = X25519PublicKey::from(self.x25519_public_key);
        let x25519_secret = ephemeral_secret.diffie_hellman(&peer);

        let (mlkem_ciphertext, mlkem_secret) = self.mlkem_encapsulation_key.encapsulate();

        let mut wrapping_key =
            derive_wrapping_key(x25519_secret.as_bytes(), mlkem_secret.as_ref())?;
        let cipher = ChaCha20Poly1305::new(&Key::from(wrapping_key));
        let encrypted_key = cipher
            .encrypt(&Nonce::from([0_u8; 12]), content_key)
            .map_err(|_| Error::InvalidKey)?;
        wrapping_key.zeroize();
        Ok(ContactWrappedKey {
            x25519_ephemeral_public_key,
            mlkem_ciphertext,
            encrypted_key,
        })
    }
}

impl ContactWrappedKey {
    /// Reconstruct a wrapped key from serialized hybrid ciphertext components.
    ///
    /// Returns `Error::InvalidKeyMaterial` if the component bytes are invalid.
    pub fn from_parts(
        x25519_ephemeral_public_key: Vec<u8>,
        mlkem_ciphertext: Vec<u8>,
        encrypted_key: Vec<u8>,
    ) -> Result<Self> {
        if x25519_ephemeral_public_key.len() != X25519_KEY_LEN {
            return Err(Error::InvalidKeyMaterial(
                "X25519 public key bytes have the wrong length".to_string(),
            ));
        }
        let mut x25519_public = [0_u8; X25519_KEY_LEN];
        x25519_public.copy_from_slice(&x25519_ephemeral_public_key);
        let mlkem_ciphertext = ml_kem::Ciphertext::<MlKem768>::try_from(
            mlkem_ciphertext.as_slice(),
        )
        .map_err(|_| {
            Error::InvalidKeyMaterial("ML-KEM ciphertext bytes have the wrong length".to_string())
        })?;
        Ok(Self {
            x25519_ephemeral_public_key: x25519_public,
            mlkem_ciphertext,
            encrypted_key,
        })
    }

    /// Return the ephemeral X25519 public key bytes.
    pub fn x25519_ephemeral_public_key(&self) -> &[u8; X25519_KEY_LEN] {
        &self.x25519_ephemeral_public_key
    }

    /// Return the ML-KEM ciphertext bytes.
    pub fn ciphertext_bytes(&self) -> &[u8] {
        self.mlkem_ciphertext.as_ref()
    }

    /// Return the encrypted content-key bytes.
    pub fn encrypted_key(&self) -> &[u8] {
        &self.encrypted_key
    }
}

struct DecodedPrivateKey {
    x25519_secret_key: [u8; X25519_KEY_LEN],
    mlkem_seed: Vec<u8>,
}

fn encode_public_key(key: &ContactPublicKey) -> Vec<u8> {
    let mlkem_public = key.mlkem_encapsulation_key.to_bytes();
    let mut out = Vec::with_capacity(16 + X25519_KEY_LEN + 4 + mlkem_public.len());
    out.extend_from_slice(PUBLIC_MAGIC);
    put_u16(&mut out, HYBRID_KEY_VERSION);
    put_u16(&mut out, HYBRID_ALGORITHM_X25519_MLKEM768);
    out.extend_from_slice(&key.x25519_public_key);
    put_bytes(&mut out, mlkem_public.as_ref());
    out
}

fn decode_public_key(bytes: &[u8]) -> Result<ContactPublicKey> {
    let mut reader = Reader::new(bytes);
    reader.magic(PUBLIC_MAGIC)?;
    reader.version()?;
    reader.algorithm()?;
    let x25519_public = reader.x25519_key()?;
    let mlkem_public = reader.bytes()?;
    reader.done()?;
    let key = ml_kem::kem::Key::<ml_kem::EncapsulationKey768>::try_from(mlkem_public.as_slice())
        .map_err(|_| {
            Error::InvalidKeyMaterial("ML-KEM public key bytes have the wrong length".to_string())
        })?;
    let mlkem_encapsulation_key = ml_kem::EncapsulationKey768::new(&key).map_err(|_| {
        Error::InvalidKeyMaterial("ML-KEM public key bytes are invalid".to_string())
    })?;
    Ok(ContactPublicKey {
        x25519_public_key: x25519_public,
        mlkem_encapsulation_key,
    })
}

fn encode_private_key(
    x25519_secret: &[u8; X25519_KEY_LEN],
    mlkem_seed: &[u8],
) -> Result<SecretVec> {
    let mut out = SecretVec::new();
    out.try_extend_from_slice(PRIVATE_MAGIC)?;
    out.try_extend_from_slice(&HYBRID_KEY_VERSION.to_le_bytes())?;
    out.try_extend_from_slice(&HYBRID_ALGORITHM_X25519_MLKEM768.to_le_bytes())?;
    out.try_extend_from_slice(x25519_secret)?;
    out.try_extend_from_slice(&(mlkem_seed.len() as u32).to_le_bytes())?;
    out.try_extend_from_slice(mlkem_seed)?;
    Ok(out)
}

fn decode_private_key(bytes: &[u8]) -> Result<DecodedPrivateKey> {
    let mut reader = Reader::new(bytes);
    reader.magic(PRIVATE_MAGIC)?;
    reader.version()?;
    reader.algorithm()?;
    let x25519_secret_key = reader.x25519_key()?;
    let mlkem_seed = reader.bytes()?;
    reader.done()?;
    Ok(DecodedPrivateKey {
        x25519_secret_key,
        mlkem_seed,
    })
}

fn derive_wrapping_key(x25519_secret: &[u8], mlkem_secret: &[u8]) -> Result<[u8; 32]> {
    let mut input = Vec::with_capacity(4 + x25519_secret.len() + 4 + mlkem_secret.len());
    put_bytes(&mut input, x25519_secret);
    put_bytes(&mut input, mlkem_secret);
    let hkdf = Hkdf::<Sha256>::new(Some(b"lockbox-v1-hybrid-contact-wrap"), &input);
    let mut out = [0_u8; 32];
    hkdf.expand(b"x25519-mlkem768-chacha20poly1305", &mut out)
        .map_err(|_| {
            Error::InvalidKeyMaterial("hybrid wrapping key derivation failed".to_string())
        })?;
    input.zeroize();
    Ok(out)
}

fn put_u16(out: &mut Vec<u8>, value: u16) {
    out.extend_from_slice(&value.to_le_bytes());
}

fn put_bytes(out: &mut Vec<u8>, bytes: &[u8]) {
    out.extend_from_slice(&(bytes.len() as u32).to_le_bytes());
    out.extend_from_slice(bytes);
}

struct Reader<'a> {
    bytes: &'a [u8],
    offset: usize,
}

impl<'a> Reader<'a> {
    fn new(bytes: &'a [u8]) -> Self {
        Self { bytes, offset: 0 }
    }

    fn magic(&mut self, expected: &[u8]) -> Result<()> {
        if self.bytes.get(self.offset..self.offset + expected.len()) != Some(expected) {
            return Err(Error::InvalidKeyMaterial(
                "contact key has invalid magic".to_string(),
            ));
        }
        self.offset += expected.len();
        Ok(())
    }

    fn version(&mut self) -> Result<()> {
        let version = self.u16()?;
        if version != HYBRID_KEY_VERSION {
            return Err(Error::InvalidKeyMaterial(format!(
                "contact key version {version} is not supported"
            )));
        }
        Ok(())
    }

    fn algorithm(&mut self) -> Result<()> {
        let algorithm = self.u16()?;
        if algorithm != HYBRID_ALGORITHM_X25519_MLKEM768 {
            return Err(Error::InvalidKeyMaterial(format!(
                "contact key algorithm {algorithm} is not supported"
            )));
        }
        Ok(())
    }

    fn u16(&mut self) -> Result<u16> {
        if self.offset + 2 > self.bytes.len() {
            return Err(Error::InvalidKeyMaterial(
                "contact key is truncated".to_string(),
            ));
        }
        let value = u16::from_le_bytes([self.bytes[self.offset], self.bytes[self.offset + 1]]);
        self.offset += 2;
        Ok(value)
    }

    fn x25519_key(&mut self) -> Result<[u8; X25519_KEY_LEN]> {
        if self.offset + X25519_KEY_LEN > self.bytes.len() {
            return Err(Error::InvalidKeyMaterial(
                "contact key is missing X25519 material".to_string(),
            ));
        }
        let mut out = [0_u8; X25519_KEY_LEN];
        out.copy_from_slice(&self.bytes[self.offset..self.offset + X25519_KEY_LEN]);
        self.offset += X25519_KEY_LEN;
        Ok(out)
    }

    fn bytes(&mut self) -> Result<Vec<u8>> {
        if self.offset + 4 > self.bytes.len() {
            return Err(Error::InvalidKeyMaterial(
                "contact key is truncated".to_string(),
            ));
        }
        let len = u32::from_le_bytes([
            self.bytes[self.offset],
            self.bytes[self.offset + 1],
            self.bytes[self.offset + 2],
            self.bytes[self.offset + 3],
        ]) as usize;
        self.offset += 4;
        if self.offset + len > self.bytes.len() {
            return Err(Error::InvalidKeyMaterial(
                "contact key field is truncated".to_string(),
            ));
        }
        let out = self.bytes[self.offset..self.offset + len].to_vec();
        self.offset += len;
        Ok(out)
    }

    fn done(&self) -> Result<()> {
        if self.offset != self.bytes.len() {
            return Err(Error::InvalidKeyMaterial(
                "contact key contains trailing bytes".to_string(),
            ));
        }
        Ok(())
    }
}