Skip to main content

capsule_core/crypto/encryption/
blob.rs

1//! Standalone AEAD for metadata blobs — a single contiguous byte string with a fixed
2//! wire format. Used for the encrypted CBOR sidecar / metadata blob the server stores.
3//!
4//! **Implementations MUST produce and consume exactly this layout** so two correct
5//! implementations compute identical content hashes byte-for-byte:
6//!
7//! ```text
8//! +---------------------+------------------+----------------------+----------------+
9//! | crypto_suite_id (2) | nonce (12 bytes) | ciphertext (variable)| tag (16 bytes) |
10//! | big-endian u16      | fresh CSPRNG     | AES-256-GCM(plaintext)| GCM tag        |
11//! +---------------------+------------------+----------------------+----------------+
12//! ```
13//!
14//! The key is derived per blob via [`crate::crypto::keys::Amk::derive_blob_key`]. The
15//! `ciphertext_hash` committed to by the manifest is computed over the **full** byte
16//! string. SSoT: [Cryptography — Encryption § Metadata Blob Wire Format].
17//!
18//! [Cryptography — Encryption § Metadata Blob Wire Format]: https://docs/design/cryptography/encryption/#metadata-blob-wire-format
19
20use aes_gcm::aead::{Aead, KeyInit};
21use aes_gcm::{Aes256Gcm, Key, Nonce};
22
23use crate::crypto::hash::{self, Hash32};
24use crate::crypto::primitives::{CRYPTO_SUITE_ID, SuiteId};
25use crate::crypto::{CryptoError, rng};
26
27const SUITE_LEN: usize = 2;
28/// Length of the per-blob AES-256-GCM nonce (fresh CSPRNG draw per seal).
29pub const NONCE_LEN: usize = 12;
30const TAG_LEN: usize = 16;
31/// Minimum valid blob length: header + nonce + empty ciphertext + tag.
32pub const MIN_BLOB_LEN: usize = SUITE_LEN + NONCE_LEN + TAG_LEN;
33
34/// Seal `plaintext` (canonical CBOR) into the metadata-blob wire format under `blob_key`,
35/// tagging it with the current `crypto_suite_id`. A fresh nonce is drawn per call.
36///
37/// This is the nonce-agnostic AEAD primitive (also used for the KEM-DEM drop wrap and the
38/// share-scope wrap, whose keys are not blob-id-derived). Metadata-blob writers that fold
39/// the nonce into a derived key go through [`super::rekey::seal_metadata_blob`].
40pub fn seal_blob(blob_key: &[u8; 32], plaintext: &[u8]) -> Vec<u8> {
41    seal_blob_with_nonce(blob_key, rng::random_array::<NONCE_LEN>(), plaintext)
42}
43
44/// [`seal_blob`] with an explicit `nonce`, so a metadata-blob writer can fold that same
45/// nonce into the derived `blob_key` salt before sealing (the salt depends on the nonce).
46pub fn seal_blob_with_nonce(
47    blob_key: &[u8; 32],
48    nonce: [u8; NONCE_LEN],
49    plaintext: &[u8],
50) -> Vec<u8> {
51    let cipher = Aes256Gcm::new(Key::<Aes256Gcm>::from_slice(blob_key));
52    let ct_and_tag = cipher
53        .encrypt(Nonce::from_slice(&nonce), plaintext)
54        .expect("AES-256-GCM seal is infallible for a valid key/nonce");
55
56    let mut out = Vec::with_capacity(SUITE_LEN + NONCE_LEN + ct_and_tag.len());
57    out.extend_from_slice(&CRYPTO_SUITE_ID.to_be_bytes());
58    out.extend_from_slice(&nonce);
59    out.extend_from_slice(&ct_and_tag);
60    out
61}
62
63/// The 12-byte nonce a blob carries in its header, needed to re-derive the folded
64/// `blob_key` before opening. `None` if the wire is shorter than the fixed prefix.
65pub fn blob_nonce(wire: &[u8]) -> Option<[u8; NONCE_LEN]> {
66    wire.get(SUITE_LEN..SUITE_LEN + NONCE_LEN)?.try_into().ok()
67}
68
69/// Open a metadata-blob wire string under `blob_key`. Rejects an unknown `crypto_suite_id`
70/// (fail-closed) before attempting decryption, and rejects tampered ciphertext.
71pub fn open_blob(blob_key: &[u8; 32], wire: &[u8]) -> Result<Vec<u8>, CryptoError> {
72    if wire.len() < MIN_BLOB_LEN {
73        return Err(CryptoError::Malformed("metadata blob shorter than minimum"));
74    }
75    let suite = u16::from_be_bytes([wire[0], wire[1]]);
76    if SuiteId::from_u16(suite).is_none() {
77        return Err(CryptoError::UnknownSuite(suite));
78    }
79    let nonce = &wire[SUITE_LEN..SUITE_LEN + NONCE_LEN];
80    let ct_and_tag = &wire[SUITE_LEN + NONCE_LEN..];
81    let cipher = Aes256Gcm::new(Key::<Aes256Gcm>::from_slice(blob_key));
82    cipher
83        .decrypt(Nonce::from_slice(nonce), ct_and_tag)
84        .map_err(|_| CryptoError::Auth("metadata blob authentication failed"))
85}
86
87/// The content hash of a metadata blob: SHA-256 over the **full** wire byte string
88/// (header ‖ nonce ‖ ciphertext ‖ tag). This is the value the manifest commits to.
89pub fn blob_ciphertext_hash(wire: &[u8]) -> Hash32 {
90    hash::hash_bytes(wire)
91}
92
93/// The `crypto_suite_id` declared in a blob's header, without decrypting.
94pub fn blob_suite_id(wire: &[u8]) -> Option<u16> {
95    (wire.len() >= SUITE_LEN).then(|| u16::from_be_bytes([wire[0], wire[1]]))
96}
97
98#[cfg(test)]
99mod tests;