Skip to main content

srt_runtime/
crypto.rs

1//! SRT payload encryption — `draft-sharabayko-srt-01` §6 ("Encryption").
2//!
3//! Spec grounding: `private/specs-verified/rules/srt-crypto.md` (curated §6, external-algorithm
4//! references grep-verified against RFC 3394 / RFC 8018 / RFC 2104 / FIPS 197
5//! / NIST SP 800-38A). Cross-refs: `private/specs-verified/rules/srt-rules.md` §"Key Material
6//! message — §3.2.2" (wire layout of `Salt`/`ICV`/`xSEK`/`oSEK`/`KLen`, all
7//! carried opaquely by [`crate::packet::KeyMaterial`]) and §"Data packet —
8//! §3.1" (`KK` field, [`crate::packet::EncryptionKeyField`]).
9//!
10//! This module adds the crypto *primitives* §6 names but does not restate:
11//!
12//! - **AES-CTR** payload encrypt/decrypt ([`aes_ctr_apply`]) — §6.2.2/§6.3.2.
13//! - **RFC 3394 AES key wrap/unwrap** of the SEK ([`wrap_sek`]/[`unwrap_sek`])
14//!   — §6.1.5/§6.2.1/§6.3.1.
15//! - **PBKDF2 (HMAC-SHA1) KEK derivation** from a passphrase
16//!   ([`derive_kek`]) — §6.1.4/§6.2.1/§6.3.1.
17//!
18//! Gated behind the `crypto` feature; the default/no_std packet-codec core
19//! (this crate's `--no-default-features` build) pulls none of these
20//! dependencies.
21//!
22//! # ⚠ The draft's two IV formulas (srt-crypto.md, "Conflicting IV formula")
23//!
24//! `draft-sharabayko-srt-01` gives **two different, unreconciled** formulas
25//! for the AES-CTR IV:
26//!
27//! - §6.1.2 (Overview): build a 128-bit `{80 zero bits | 32-bit packet index
28//!   | 16-bit block counter}` word and XOR its upper 112 bits with `IV =
29//!   MSB(112, Salt)`.
30//! - §6.2.2 (Encryption Process) / §6.3.2 (Decryption Process), verbatim and
31//!   identical in both places: `IV = (MSB(112, Salt) << 2) XOR (PktSeqNo)`.
32//!
33//! These are not algebraically the same construction, and the draft never
34//! reconciles them. No sample ciphertext exists anywhere in the draft to
35//! disambiguate by reproduction (`srt-crypto.md`, "No test vectors" note), so
36//! this module resolves it against the **reference implementation** instead:
37//! `libsrt` (`haivision/srt`) `haicrypt/hcrypt.h` `hcrypt_SetCtrIV` builds the
38//! counter as §6.1.2 describes — `{80 zero bits | 32-bit packet index | 16-bit
39//! block counter}` with `MSB(112, Salt)` XORed across the top 112 bits — and
40//! performs **no** `<< 2` shift. The §6.2.2/§6.3.2 `<< 2` is a draft-text
41//! artifact; implementing it literally yields a keystream no real SRT peer can
42//! decrypt. [`packet_counter`] therefore follows `hcrypt_SetCtrIV` (≡ the
43//! §6.1.2 layout), verified byte-for-byte against that macro in the tests.
44
45use aes::cipher::{KeyIvInit, StreamCipher};
46use aes::{Aes128, Aes192, Aes256};
47use aes_kw::{KeyInit, KwAes128, KwAes192, KwAes256};
48use alloc::vec;
49use alloc::vec::Vec;
50use broadcast_common::error::InvalidField;
51use ctr::Ctr128BE;
52use hmac::Hmac;
53use pbkdf2::pbkdf2;
54use sha1::Sha1;
55use zeroize::Zeroizing;
56
57use crate::error::{Error, Result};
58use crate::packet::EncryptionKeyField;
59
60/// PBKDF2 iteration count mandated by the draft (`Iter = 2048`,
61/// §6.1.4/§6.2.1/§6.3.1 — identical value at every citation).
62pub const PBKDF2_ITERATIONS: u32 = 2048;
63
64/// Length of the 128-bit Key Material `Salt` field in bytes (`SLen/4 = 4`
65/// words — the only salt length the draft defines, `srt-rules.md` §3.2.2).
66pub const SALT_LEN: usize = 16;
67
68/// Number of least-significant bytes of the 128-bit `Salt` fed to PBKDF2 as
69/// its salt argument (`LSB(64,Salt)`, §6.2.1/§6.3.1: 64 bits = 8 bytes). The
70/// remaining (most-significant) bytes of `Salt` feed the AES-CTR IV instead
71/// (§6.1.2/§6.2.2/§6.3.2).
72const PBKDF2_SALT_LEN: usize = 8;
73
74/// Number of most-significant bytes of the 128-bit `Salt` used to build the
75/// AES-CTR IV (`MSB(112, Salt)`, §6.1.2/§6.2.2/§6.3.2: 112 bits = 14 bytes).
76const IV_SALT_LEN: usize = 14;
77
78/// AES block size in bytes (FIPS 197) — also the AES-CTR counter width
79/// (§6.1.2: "The counter for AES-CTR is the size of the cipher's block, i.e.
80/// 128 bits").
81const AES_BLOCK_LEN: usize = 16;
82
83/// A key length not one of AES-128/192/256's 16/24/32 bytes (`KLen/4` ∈
84/// `{4,6,8}`, `srt-rules.md` §3.2.2).
85fn invalid_key_length(what: &'static str) -> Error {
86    Error::InvalidField(InvalidField {
87        field: what,
88        reason: "length must be 16, 24, or 32 bytes (AES-128/192/256)",
89    })
90}
91
92// ---------------------------------------------------------------------------
93// RFC 8018 PBKDF2 (HMAC-SHA1) — lowest-level entry point.
94// ---------------------------------------------------------------------------
95
96/// Run PBKDF2-HMAC-SHA1 (RFC 8018 §5.2 with the HMAC-SHA-1 PRF of
97/// Appendix B.1.1) with a caller-supplied salt and iteration count. This is
98/// the lowest-level `srt-runtime` function that performs PBKDF2-HMAC-SHA1;
99/// [`derive_kek`] is a thin wrapper that fixes the salt to `LSB(64, Salt)`
100/// and the iteration count to [`PBKDF2_ITERATIONS`].
101///
102/// `output`'s length determines `dkLen`; any non-negative length up to
103/// `(2^32 - 1) * 20` is accepted by the underlying primitive.
104pub fn pbkdf2_hmac_sha1(password: &[u8], salt: &[u8], iterations: u32, output: &mut [u8]) {
105    pbkdf2::<Hmac<Sha1>>(password, salt, iterations, output)
106        .expect("HMAC-SHA1 accepts any key length, so PBKDF2 cannot fail here");
107}
108
109// ---------------------------------------------------------------------------
110// §6.1.4/§6.2.1/§6.3.1 — KEK derivation (passphrase path).
111// ---------------------------------------------------------------------------
112
113/// Derive the Key Encrypting Key (KEK) from the pre-shared passphrase
114/// (`draft-sharabayko-srt-01` §6.1.4, §6.2.1 sender / §6.3.1 receiver —
115/// identical formula both sides):
116///
117/// ```text
118/// KEK = PBKDF2(passphrase, LSB(64,Salt), Iter=2048, KLen)
119/// ```
120///
121/// `salt` is the Key Material message's 128-bit `Salt` field; `klen` is the
122/// desired KEK length in bytes (16/24/32, matching the handshake's
123/// Encryption Field / the Key Material message's `KLen/4` — "the KEK has to
124/// be at least as long as the SEK", §6.1.4).
125///
126/// The KEK is returned in a [`Zeroizing`] buffer, wiped when dropped.
127///
128/// # Errors
129/// [`Error::InvalidField`] if `klen` is not 16, 24, or 32.
130pub fn derive_kek(
131    passphrase: &[u8],
132    salt: &[u8; SALT_LEN],
133    klen: usize,
134) -> Result<Zeroizing<Vec<u8>>> {
135    if !matches!(klen, 16 | 24 | 32) {
136        return Err(invalid_key_length("KLen"));
137    }
138    // LSB(64, Salt): the low/least-significant 8 bytes of the 128-bit,
139    // big-endian-wire Salt.
140    let pbkdf2_salt = &salt[SALT_LEN - PBKDF2_SALT_LEN..];
141    let mut kek = Zeroizing::new(vec![0u8; klen]);
142    pbkdf2_hmac_sha1(passphrase, pbkdf2_salt, PBKDF2_ITERATIONS, &mut kek[..]);
143    Ok(kek)
144}
145
146// ---------------------------------------------------------------------------
147// §6.1.5/§6.2.1/§6.3.1 — RFC 3394 AES key wrap/unwrap of the SEK.
148// ---------------------------------------------------------------------------
149
150/// Wrap one or two SEKs with the KEK (RFC 3394 AES key wrap, external
151/// algorithm — `draft-sharabayko-srt-01` §6.1.5/§6.2.1: `Wrap = AESkw(KEK,
152/// SEK)`).
153///
154/// `plaintext_keys` is the concatenation of the SEK(s) being wrapped — one
155/// SEK's worth of bytes (Key Material `KK` = even/odd) or two concatenated
156/// SEKs (`KK` = both), per the Wrap-field length formula `n*KLen + 8` in
157/// `srt-rules.md` §"Key Material message — §3.2.2". Returns `(icv, wrapped)`
158/// to match [`crate::packet::KeyMaterial`]'s `icv`/`x_sek`/`o_sek` fields —
159/// RFC 3394's first 8-byte output block *is* the wrap's Integrity Check
160/// Vector (the encrypted default IV, RFC 3394 §2.2.3.1), and the remaining
161/// bytes are the wrapped key material, the same length as the input.
162///
163/// # Errors
164/// [`Error::InvalidField`] if `kek.len()` is not 16, 24, or 32, or if
165/// `plaintext_keys.len()` is not a multiple of 8 bytes (RFC 3394 operates on
166/// 64-bit semiblocks).
167pub fn wrap_sek(kek: &[u8], plaintext_keys: &[u8]) -> Result<([u8; 8], Vec<u8>)> {
168    let mut out = vec![0u8; plaintext_keys.len() + 8];
169    match kek.len() {
170        16 => KwAes128::new_from_slice(kek)
171            .map_err(|_| invalid_key_length("KEK"))?
172            .wrap_key(plaintext_keys, &mut out)
173            .map(|_| ()),
174        24 => KwAes192::new_from_slice(kek)
175            .map_err(|_| invalid_key_length("KEK"))?
176            .wrap_key(plaintext_keys, &mut out)
177            .map(|_| ()),
178        32 => KwAes256::new_from_slice(kek)
179            .map_err(|_| invalid_key_length("KEK"))?
180            .wrap_key(plaintext_keys, &mut out)
181            .map(|_| ()),
182        _ => return Err(invalid_key_length("KEK")),
183    }
184    .map_err(|_| {
185        Error::InvalidField(InvalidField {
186            field: "SEK",
187            reason: "length must be a multiple of 8 bytes (RFC 3394 semiblocks)",
188        })
189    })?;
190    let mut icv = [0u8; 8];
191    icv.copy_from_slice(&out[..8]);
192    Ok((icv, out[8..].to_vec()))
193}
194
195/// Unwrap the SEK(s) with the KEK (inverse RFC 3394 AES key wrap —
196/// `draft-sharabayko-srt-01` §6.1.5/§6.3.1: `SEK = AESkuw(KEK, Wrap)`).
197///
198/// `icv`/`wrapped` are [`crate::packet::KeyMaterial`]'s `icv`/`x_sek` (or
199/// `o_sek`) fields. A wrap-integrity failure — wrong KEK (wrong passphrase)
200/// or corrupt wire data — is the spec's "it does not have the SEK" case
201/// (§6.1.5, L3799-3803/L3820-3823): a structured error, never a panic or
202/// silently-wrong plaintext.
203///
204/// # Errors
205/// [`Error::InvalidField`] if `kek.len()` is not 16, 24, or 32, if
206/// `wrapped.len()` is not a multiple of 8 bytes, or if the RFC 3394
207/// integrity check fails.
208///
209/// The plaintext SEK(s) come back in a [`Zeroizing`] buffer, wiped when
210/// dropped.
211pub fn unwrap_sek(kek: &[u8], icv: &[u8; 8], wrapped: &[u8]) -> Result<Zeroizing<Vec<u8>>> {
212    let mut input = Vec::with_capacity(8 + wrapped.len());
213    input.extend_from_slice(icv);
214    input.extend_from_slice(wrapped);
215    let mut out = Zeroizing::new(vec![0u8; wrapped.len()]);
216    let bad_wrap = || {
217        Error::InvalidField(InvalidField {
218            field: "AES key wrap",
219            reason: "integrity check failed (wrong KEK / passphrase, or corrupt wire data)",
220        })
221    };
222    match kek.len() {
223        16 => KwAes128::new_from_slice(kek)
224            .map_err(|_| invalid_key_length("KEK"))?
225            .unwrap_key(&input, &mut out[..])
226            .map(|_| ()),
227        24 => KwAes192::new_from_slice(kek)
228            .map_err(|_| invalid_key_length("KEK"))?
229            .unwrap_key(&input, &mut out[..])
230            .map(|_| ()),
231        32 => KwAes256::new_from_slice(kek)
232            .map_err(|_| invalid_key_length("KEK"))?
233            .unwrap_key(&input, &mut out[..])
234            .map(|_| ()),
235        _ => return Err(invalid_key_length("KEK")),
236    }
237    .map_err(|_| bad_wrap())?;
238    Ok(out)
239}
240
241// ---------------------------------------------------------------------------
242// §6.1.2/§6.2.2/§6.3.2 — AES-CTR payload encrypt/decrypt.
243// ---------------------------------------------------------------------------
244
245/// Compute the 128-bit AES-CTR initial counter for one data packet.
246///
247/// This follows the **reference SRT construction** (`libsrt` `haicrypt/hcrypt.h`,
248/// `hcrypt_SetCtrIV`), which is what real SRT peers use on the wire:
249///
250/// ```text
251/// memset(iv, 0, 16);              // all 16 bytes zeroed
252/// memcpy(&iv[10], &pki, 4);       // 32-bit packet index at bytes [10..14]
253/// iv[0..14] ^= salt[0..14];       // XOR MSB(112, Salt) across the top 14 bytes
254/// // iv[14..16] = per-packet AES-block counter, starts 0
255/// //
256/// //  byte:  0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
257/// //        +-----------------------+-----------+-----+
258/// //        |          0s           |    pki    | ctr |
259/// //        +-----------------------+-----------+-----+
260/// ```
261///
262/// **On the draft's `IV = (MSB(112, Salt) << 2) XOR PktSeqNo` (§6.2.2/§6.3.2):**
263/// the `<< 2` is a known artifact/typo of the draft text — the reference
264/// implementation does **no** left shift. Implementing the `<< 2` literally
265/// produces a keystream no real SRT peer can decrypt, so this function follows
266/// `hcrypt_SetCtrIV` (which is equivalent to §6.1.2's field layout: packet index
267/// in bits `[47:16]`, block counter in `[15:0]`). See the module doc's
268/// "conflicting IV formula" note.
269///
270/// The low 16 bits (`counter[14..16]`) are the per-packet AES-block counter,
271/// left at `0` here — a standard 128-bit big-endian CTR increments the whole
272/// counter per block, which only touches these low bits as long as a single
273/// packet's payload stays under `2^16` AES blocks (1 MiB); every SRT payload
274/// (bounded by a UDP datagram) is far smaller.
275///
276/// `pkt_seq_no` is the data packet's 31-bit Packet Sequence Number
277/// (`draft-sharabayko-srt-01` §3.1); bit 31 (the `F` header bit) is never part
278/// of it.
279pub fn packet_counter(salt: &[u8; SALT_LEN], pkt_seq_no: u32) -> [u8; AES_BLOCK_LEN] {
280    let mut counter = [0u8; AES_BLOCK_LEN];
281    // 32-bit packet index at bytes [10..14] (hcrypt.h: `memcpy(&iv[10], pki, 4)`).
282    counter[10..14].copy_from_slice(&pkt_seq_no.to_be_bytes());
283    // XOR MSB(112, Salt) — the top 14 bytes of the Salt — across bytes [0..14]
284    // (hcrypt.h: `hcrypt_XorStream(&iv[0], nonce, 112/8)`). No left shift.
285    for i in 0..IV_SALT_LEN {
286        counter[i] ^= salt[i];
287    }
288    // counter[14..16] stays 0 — the block counter starts at 0 for this packet.
289    counter
290}
291
292/// AES-CTR encrypt/decrypt one data packet's payload **in place**
293/// (`draft-sharabayko-srt-01` §6.2.2/§6.3.2). CTR mode is its own inverse —
294/// `EncryptedPayload = AES_CTR_Encrypt(SEK, IV, UnencryptedPayload)` and
295/// `DecryptedPayload = AES_CTR_Encrypt(SEK, IV, EncryptedPayload)` are the
296/// same operation (XOR with the same keystream), so this one function serves
297/// both directions.
298///
299/// `sek` selects AES-128/192/256 by its length (16/24/32 bytes); `salt` and
300/// `pkt_seq_no` feed [`packet_counter`]. No padding is applied or expected —
301/// CTR is a stream cipher (§6.1.1).
302///
303/// # Errors
304/// [`Error::InvalidField`] if `sek.len()` is not 16, 24, or 32.
305pub fn aes_ctr_apply(
306    sek: &[u8],
307    salt: &[u8; SALT_LEN],
308    pkt_seq_no: u32,
309    data: &mut [u8],
310) -> Result<()> {
311    let counter = packet_counter(salt, pkt_seq_no);
312    match sek.len() {
313        16 => {
314            let mut cipher =
315                Ctr128BE::<Aes128>::new_from_slices(sek, &counter).map_err(|_| bad_sek())?;
316            cipher.apply_keystream(data);
317        }
318        24 => {
319            let mut cipher =
320                Ctr128BE::<Aes192>::new_from_slices(sek, &counter).map_err(|_| bad_sek())?;
321            cipher.apply_keystream(data);
322        }
323        32 => {
324            let mut cipher =
325                Ctr128BE::<Aes256>::new_from_slices(sek, &counter).map_err(|_| bad_sek())?;
326            cipher.apply_keystream(data);
327        }
328        _ => return Err(bad_sek()),
329    }
330    Ok(())
331}
332
333fn bad_sek() -> Error {
334    invalid_key_length("SEK")
335}
336
337// ---------------------------------------------------------------------------
338// §3.1 `KK` — select the active SEK by odd/even parity.
339// ---------------------------------------------------------------------------
340
341/// Select the SEK to use for a data packet from its `KK` field
342/// (`draft-sharabayko-srt-01` §3.1/§6.1.6): `even`/`odd` are the two SEKs
343/// currently held (both may be live during the `±`KM-Pre-Announcement-Period`
344/// rekey transition window, §6.1.6).
345///
346/// # Errors
347/// [`Error::InvalidField`] if the packet is unencrypted (`KK = NotEncrypted`)
348/// or carries the control-packet-only reserved value, or if the selected
349/// parity's SEK is not currently held (e.g. not yet unwrapped, or already
350/// decommissioned — §6.3, step 11: such packets "must be dropped").
351pub fn select_sek<'a>(
352    key_flag: EncryptionKeyField,
353    even: Option<&'a [u8]>,
354    odd: Option<&'a [u8]>,
355) -> Result<&'a [u8]> {
356    let no_sek = |parity: &'static str| {
357        Error::InvalidField(InvalidField {
358            field: "SEK",
359            reason: match parity {
360                "even" => "even key not currently held",
361                _ => "odd key not currently held",
362            },
363        })
364    };
365    match key_flag {
366        EncryptionKeyField::Even => even.ok_or_else(|| no_sek("even")),
367        EncryptionKeyField::Odd => odd.ok_or_else(|| no_sek("odd")),
368        EncryptionKeyField::NotEncrypted => Err(Error::InvalidField(InvalidField {
369            field: "KK",
370            reason: "packet is not encrypted (KK=00b)",
371        })),
372        EncryptionKeyField::Reserved(_) => Err(Error::InvalidField(InvalidField {
373            field: "KK",
374            reason: "reserved value (11b) is control-packet-only, not valid on a data packet",
375        })),
376    }
377}
378
379#[cfg(test)]
380mod tests {
381    use broadcast_common::error::InvalidField;
382
383    use super::*;
384
385    // -----------------------------------------------------------------
386    // RFC 3394 §4.1 — "Wrap 128 bits of Key Data with a 128-bit KEK".
387    // <https://datatracker.ietf.org/doc/html/rfc3394#section-4.1>
388    // -----------------------------------------------------------------
389    const RFC3394_KEK_128: [u8; 16] = [
390        0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0A, 0x0B, 0x0C, 0x0D, 0x0E,
391        0x0F,
392    ];
393    const RFC3394_KEY_DATA_128: [u8; 16] = [
394        0x00, 0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77, 0x88, 0x99, 0xAA, 0xBB, 0xCC, 0xDD, 0xEE,
395        0xFF,
396    ];
397    const RFC3394_WRAPPED_128: [u8; 24] = [
398        0x1F, 0xA6, 0x8B, 0x0A, 0x81, 0x12, 0xB4, 0x47, 0xAE, 0xF3, 0x4B, 0xD8, 0xFB, 0x5A, 0x7B,
399        0x82, 0x9D, 0x3E, 0x86, 0x23, 0x71, 0xD2, 0xCF, 0xE5,
400    ];
401
402    #[test]
403    fn rfc3394_wrap_matches_worked_vector() {
404        let (icv, wrapped) = wrap_sek(&RFC3394_KEK_128, &RFC3394_KEY_DATA_128).unwrap();
405        assert_eq!(&icv[..], &RFC3394_WRAPPED_128[..8]);
406        assert_eq!(wrapped.as_slice(), &RFC3394_WRAPPED_128[8..]);
407    }
408
409    // -----------------------------------------------------------------
410    // packet_counter known-answer, hand-derived from libsrt
411    // haicrypt/hcrypt.h `hcrypt_SetCtrIV`:
412    //   memset(iv,0,16); memcpy(&iv[10], pki, 4); iv[0..14] ^= salt[0..14];
413    // For salt = 01 02 … 10 and pki = 0x11223344:
414    //   [0..10]  = salt[0..10]                = 01 02 03 04 05 06 07 08 09 0A
415    //   [10]     = salt[10]^0x11 = 0x0B^0x11  = 1A
416    //   [11]     = salt[11]^0x22 = 0x0C^0x22  = 2E
417    //   [12]     = salt[12]^0x33 = 0x0D^0x33  = 3E
418    //   [13]     = salt[13]^0x44 = 0x0E^0x44  = 4A
419    //   [14..16] = 00 00                        (block counter, salt[14..] unused)
420    // The old `MSB(112,Salt) << 2` construction gives byte[0]=0x04 (not 0x01)
421    // and different [10..14] — this test BITES against that regression.
422    // -----------------------------------------------------------------
423    #[test]
424    fn packet_counter_matches_libsrt_hcrypt_setctriv() {
425        let salt: [u8; SALT_LEN] = [
426            0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0A, 0x0B, 0x0C, 0x0D, 0x0E,
427            0x0F, 0x10,
428        ];
429        let expected: [u8; AES_BLOCK_LEN] = [
430            0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0A, 0x1A, 0x2E, 0x3E, 0x4A,
431            0x00, 0x00,
432        ];
433        let got = packet_counter(&salt, 0x1122_3344);
434        assert_eq!(got, expected, "counter must match hcrypt_SetCtrIV (no <<2)");
435        // Explicit guard against the buggy left-shift construction.
436        assert_eq!(got[0], 0x01, "byte 0 is pure salt, not the <<2 value 0x04");
437    }
438
439    #[test]
440    fn rfc3394_unwrap_matches_worked_vector() {
441        let mut icv = [0u8; 8];
442        icv.copy_from_slice(&RFC3394_WRAPPED_128[..8]);
443        let recovered = unwrap_sek(&RFC3394_KEK_128, &icv, &RFC3394_WRAPPED_128[8..]).unwrap();
444        assert_eq!(recovered.as_slice(), &RFC3394_KEY_DATA_128[..]);
445    }
446
447    #[test]
448    fn rfc3394_unwrap_rejects_wrong_kek() {
449        let mut icv = [0u8; 8];
450        icv.copy_from_slice(&RFC3394_WRAPPED_128[..8]);
451        let mut wrong_kek = RFC3394_KEK_128;
452        wrong_kek[0] ^= 0xFF;
453        assert!(matches!(
454            unwrap_sek(&wrong_kek, &icv, &RFC3394_WRAPPED_128[8..]),
455            Err(crate::error::Error::InvalidField(..))
456        ));
457    }
458
459    // -----------------------------------------------------------------
460    // SRT §6 payload round-trip (no spec test vectors exist for this —
461    // srt-crypto.md's "No test vectors" note — so this exercises the crate's
462    // own packet_counter + aes_ctr_apply against each other, not an
463    // external ground truth).
464    // -----------------------------------------------------------------
465
466    #[test]
467    fn srt_payload_round_trips_and_wrong_sek_does_not_recover() {
468        let sek = [0x42u8; 16];
469        let salt = [0x99u8; SALT_LEN];
470        let pkt_seq_no = 0x0123_4567u32;
471        let plaintext = b"SRT payload encryption round trip test vector.".to_vec();
472
473        let mut encrypted = plaintext.clone();
474        aes_ctr_apply(&sek, &salt, pkt_seq_no, &mut encrypted).unwrap();
475        assert_ne!(encrypted, plaintext, "encryption must change the bytes");
476
477        let mut decrypted = encrypted.clone();
478        aes_ctr_apply(&sek, &salt, pkt_seq_no, &mut decrypted).unwrap();
479        assert_eq!(
480            decrypted, plaintext,
481            "correct SEK must recover the plaintext"
482        );
483
484        let wrong_sek = [0x43u8; 16];
485        let mut wrongly_decrypted = encrypted;
486        aes_ctr_apply(&wrong_sek, &salt, pkt_seq_no, &mut wrongly_decrypted).unwrap();
487        assert_ne!(
488            wrongly_decrypted, plaintext,
489            "wrong SEK must not recover the plaintext"
490        );
491    }
492
493    #[test]
494    fn different_seq_no_gives_different_keystream() {
495        let sek = [0x11u8; 24];
496        let salt = [0x22u8; SALT_LEN];
497        let plaintext = [0u8; 32];
498
499        let mut a = plaintext;
500        aes_ctr_apply(&sek, &salt, 1, &mut a).unwrap();
501        let mut b = plaintext;
502        aes_ctr_apply(&sek, &salt, 2, &mut b).unwrap();
503        assert_ne!(a, b);
504    }
505
506    #[test]
507    fn kek_derivation_all_sizes_and_deterministic() {
508        for klen in [16usize, 24, 32] {
509            let salt = [0xABu8; SALT_LEN];
510            let kek1 = derive_kek(b"correct horse battery staple", &salt, klen).unwrap();
511            let kek2 = derive_kek(b"correct horse battery staple", &salt, klen).unwrap();
512            assert_eq!(kek1.len(), klen);
513            assert_eq!(kek1, kek2, "PBKDF2 is deterministic for the same inputs");
514
515            let different_salt = [0xACu8; SALT_LEN];
516            let kek3 = derive_kek(b"correct horse battery staple", &different_salt, klen).unwrap();
517            assert_ne!(kek1, kek3, "different salt must give a different KEK");
518        }
519    }
520
521    #[test]
522    fn invalid_klen_errs_without_panic() {
523        let salt = [0u8; SALT_LEN];
524        assert!(matches!(
525            derive_kek(b"pw", &salt, 20),
526            Err(crate::error::Error::InvalidField(..))
527        ));
528        assert!(matches!(
529            wrap_sek(&[0u8; 20], &[0u8; 16]),
530            Err(crate::error::Error::InvalidField(..))
531        ));
532        assert!(matches!(
533            aes_ctr_apply(&[0u8; 20], &salt, 0, &mut [0u8; 4]),
534            Err(crate::error::Error::InvalidField(..))
535        ));
536    }
537
538    #[test]
539    fn select_sek_picks_correct_parity_and_rejects_bad_flags() {
540        let even = [1u8; 16];
541        let odd = [2u8; 16];
542        assert_eq!(
543            select_sek(EncryptionKeyField::Even, Some(&even), Some(&odd)).unwrap(),
544            &even[..]
545        );
546        assert_eq!(
547            select_sek(EncryptionKeyField::Odd, Some(&even), Some(&odd)).unwrap(),
548            &odd[..]
549        );
550        assert!(matches!(
551            select_sek(EncryptionKeyField::Even, None, Some(&odd)),
552            Err(Error::InvalidField(..))
553        ));
554        assert!(matches!(
555            select_sek(EncryptionKeyField::NotEncrypted, Some(&even), Some(&odd)),
556            Err(Error::InvalidField(InvalidField { field: "KK", .. }))
557        ));
558        assert!(matches!(
559            select_sek(EncryptionKeyField::Reserved(0b11), Some(&even), Some(&odd)),
560            Err(Error::InvalidField(InvalidField { field: "KK", .. }))
561        ));
562    }
563
564    #[test]
565    fn both_seks_wrap_unwrap_round_trip() {
566        // KK=Both: two concatenated SEKs wrapped under one KEK/ICV, matching
567        // the Wrap-field length formula `n*KLen + 8` (`srt-rules.md` §3.2.2).
568        let kek = [0x77u8; 16];
569        let even_sek = [0xAAu8; 16];
570        let odd_sek = [0xBBu8; 16];
571        let mut plaintext = Vec::new();
572        plaintext.extend_from_slice(&even_sek);
573        plaintext.extend_from_slice(&odd_sek);
574
575        let (icv, wrapped) = wrap_sek(&kek, &plaintext).unwrap();
576        assert_eq!(wrapped.len(), 32);
577        let recovered = unwrap_sek(&kek, &icv, &wrapped).unwrap();
578        assert_eq!(&recovered[..], &plaintext[..]);
579        assert_eq!(&recovered[..16], &even_sek[..]);
580        assert_eq!(&recovered[16..], &odd_sek[..]);
581    }
582}