Skip to main content

gbp_sframe/
kdf.rs

1use gbp_mls::MlsContext;
2use hkdf::Hkdf;
3use sha2::Sha256;
4
5use crate::error::SFrameError;
6
7/// SFrame ciphersuite selection.
8///
9/// `Aes128Gcm` is the standard choice; `Aes256Gcm` is available for
10/// high-assurance deployments.
11#[derive(Clone, Copy, Debug, PartialEq, Eq)]
12pub enum CipherSuite {
13    /// AES-128-GCM: 16-byte key, 12-byte nonce.
14    Aes128Gcm,
15    /// AES-256-GCM: 32-byte key, 12-byte nonce.
16    Aes256Gcm,
17}
18
19impl CipherSuite {
20    /// Key length in bytes.
21    pub(crate) fn key_len(self) -> usize {
22        match self {
23            Self::Aes128Gcm => 16,
24            Self::Aes256Gcm => 32,
25        }
26    }
27
28    /// Numeric discriminant used in the FFI (`0` = AES-128, `1` = AES-256).
29    pub fn from_u8(v: u8) -> Option<Self> {
30        match v {
31            0 => Some(Self::Aes128Gcm),
32            1 => Some(Self::Aes256Gcm),
33            _ => None,
34        }
35    }
36
37    /// Numeric discriminant.
38    pub fn as_u8(self) -> u8 {
39        match self {
40            Self::Aes128Gcm => 0,
41            Self::Aes256Gcm => 1,
42        }
43    }
44}
45
46/// Derived key material for one participant in one epoch.
47pub(crate) struct ParticipantKeys {
48    /// AES key: 16 bytes for AES-128-GCM, 32 bytes for AES-256-GCM.
49    pub key: Vec<u8>,
50    /// 12-byte base nonce (XOR'd with the per-frame counter to produce each frame nonce).
51    pub base_nonce: [u8; 12],
52}
53
54/// Derives the 32-byte SFrame base key from the MLS `ExportSecret`.
55///
56/// `label` is the application-defined export label
57/// (e.g. `"gbp/sframe v1"`).
58/// `epoch` is passed as an 8-byte big-endian context to bind the key to the
59/// current MLS epoch.
60pub fn derive_base_key(mls: &MlsContext, label: &str, epoch: u64) -> Result<[u8; 32], SFrameError> {
61    let context = epoch.to_be_bytes();
62    let raw = mls
63        .export_raw(label, &context, 32)
64        .map_err(|e| SFrameError::MlsExport(e.to_string()))?;
65    let mut out = [0u8; 32];
66    out.copy_from_slice(&raw);
67    Ok(out)
68}
69
70// Protocol-defined HKDF domain-separation labels (public constants, not secret values).
71// HKDF-Expand takes an `info` parameter that is intentionally a well-known, fixed label;
72// the *output* is the derived key material, which is cryptographically bound to `base_key`.
73const HKDF_LABEL_KEY: &[u8] = b"gbp sframe key ";
74const HKDF_LABEL_NONCE: &[u8] = b"gbp sframe salt ";
75
76/// Derives the encryption key and base nonce for participant `leaf_index`.
77///
78/// Uses HKDF-Expand (SHA-256) over the epoch's `base_key` with
79/// deterministic domain labels so every member can reproduce any sender's
80/// key material.
81pub(crate) fn derive_participant(
82    base_key: &[u8; 32],
83    leaf_index: u32,
84    suite: CipherSuite,
85) -> ParticipantKeys {
86    // SAFETY: base_key is 32 bytes = SHA-256 HashLen, so from_prk never panics.
87    let hk =
88        Hkdf::<Sha256>::from_prk(base_key).expect("base_key is exactly SHA-256 HashLen (32 bytes)");
89
90    let leaf_be = leaf_index.to_be_bytes();
91
92    let mut label = HKDF_LABEL_KEY.to_vec();
93    label.extend_from_slice(&leaf_be);
94    let mut key = vec![0u8; suite.key_len()];
95    hk.expand(&label, &mut key)
96        .expect("key length is well within 255 * HashLen");
97
98    let mut label = HKDF_LABEL_NONCE.to_vec();
99    label.extend_from_slice(&leaf_be);
100    let mut base_nonce: [u8; 12] = Default::default();
101    hk.expand(&label, &mut base_nonce)
102        .expect("nonce length (12) is well within 255 * HashLen");
103
104    ParticipantKeys { key, base_nonce }
105}
106
107/// Constructs the 12-byte per-frame nonce:
108/// `participant_salt XOR (CTR_LE64 || 0x00_00_00_00)`.
109pub(crate) fn make_nonce(salt: &[u8; 12], ctr: u64) -> [u8; 12] {
110    let mut nonce = *salt;
111    let ctr_le = ctr.to_le_bytes(); // 8 bytes little-endian
112    for i in 0..8 {
113        nonce[i] ^= ctr_le[i];
114    }
115    nonce
116}