Skip to main content

srt_runtime/
crypto.rs

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