capsule_core/crypto/keys/master.rs
1//! The account master key: the single backed-up root of the hierarchy.
2//!
3//! It does **not** encrypt assets directly. Its jobs are (1) to wrap the per-device
4//! identity private keys and (2) to anchor the encrypted backup that escrows album keys.
5//! It also derives one *identifier* — the [default album]'s `album_id` — via HKDF with a
6//! dedicated label, so any device can recompute the default album from the master key
7//! alone after recovery (SSoT: [Cryptography — Keys § Key Chain]).
8//!
9//! [default album]: https://docs/design/organization/#the-default-album
10//! [Cryptography — Keys § Key Chain]: https://docs/design/cryptography/keys/#key-chain
11
12use aes_gcm::aead::{Aead, KeyInit};
13use aes_gcm::{Aes256Gcm, Key, Nonce};
14use uuid::Uuid;
15
16use crate::crypto::primitives::info;
17use crate::crypto::{CryptoError, kdf, rng};
18
19const NONCE_LEN: usize = 12;
20
21/// A 32-byte account master key.
22#[derive(Clone)]
23pub struct MasterKey([u8; 32]);
24
25impl MasterKey {
26 /// Generate a fresh master key from the OS CSPRNG (client-side at account creation).
27 pub fn generate() -> Self {
28 Self(rng::random_array::<32>())
29 }
30
31 /// Wrap raw key bytes (e.g. after unwrapping the escrow blob).
32 pub fn from_bytes(bytes: [u8; 32]) -> Self {
33 Self(bytes)
34 }
35
36 /// Borrow the raw key bytes (for escrow wrapping).
37 pub fn as_bytes(&self) -> &[u8; 32] {
38 &self.0
39 }
40
41 /// Derive the default album's `album_id` deterministically. This derives an *ID*,
42 /// never a key — the default album has its own random per-epoch AMK like any album.
43 pub fn derive_default_album_id(&self) -> Uuid {
44 let okm = kdf::hkdf_sha512(&self.0, b"", info::DEFAULT_ALBUM_ID_V1, 16);
45 let mut b = [0u8; 16];
46 b.copy_from_slice(&okm);
47 // A v8 (custom) UUID: deterministic, unguessable before creation, recomputable.
48 uuid::Builder::from_custom_bytes(b).into_uuid()
49 }
50
51 /// Symmetrically seal `plaintext` under the master key (AES-256-GCM, random nonce).
52 /// Used to wrap device identity private keys. Output is `nonce(12) ‖ ciphertext+tag`.
53 pub fn seal(&self, plaintext: &[u8]) -> Vec<u8> {
54 let nonce = rng::random_array::<NONCE_LEN>();
55 let cipher = Aes256Gcm::new(Key::<Aes256Gcm>::from_slice(&self.0));
56 let ct = cipher
57 .encrypt(Nonce::from_slice(&nonce), plaintext)
58 .expect("AES-256-GCM seal is infallible for a valid key/nonce");
59 let mut out = Vec::with_capacity(NONCE_LEN + ct.len());
60 out.extend_from_slice(&nonce);
61 out.extend_from_slice(&ct);
62 out
63 }
64
65 /// Open a blob produced by [`seal`](Self::seal). Returns [`CryptoError::Auth`] on a
66 /// wrong key or tampered ciphertext.
67 pub fn open(&self, blob: &[u8]) -> Result<Vec<u8>, CryptoError> {
68 if blob.len() < NONCE_LEN {
69 return Err(CryptoError::Malformed("sealed blob shorter than nonce"));
70 }
71 let (nonce, ct) = blob.split_at(NONCE_LEN);
72 let cipher = Aes256Gcm::new(Key::<Aes256Gcm>::from_slice(&self.0));
73 cipher
74 .decrypt(Nonce::from_slice(nonce), ct)
75 .map_err(|_| CryptoError::Auth("master-key unseal failed"))
76 }
77}
78
79impl std::fmt::Debug for MasterKey {
80 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
81 // Never print key material.
82 f.write_str("MasterKey(****)")
83 }
84}
85
86#[cfg(test)]
87mod tests;