srt-runtime 0.13.0

SRT (Secure Reliable Transport, draft-sharabayko-srt-01) packet codecs, sans-IO HSv5 handshakes, a one-connection link engine, ARQ, TSBPD, LiveCC/FileCC congestion control, optional payload crypto and an optional tokio UDP adapter; no_std core.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
//! SRT payload encryption — `draft-sharabayko-srt-01` §6 ("Encryption").
//!
//! Spec grounding: `private/specs-verified/rules/srt-crypto.md` (curated §6, external-algorithm
//! references grep-verified against RFC 3394 / RFC 8018 / RFC 2104 / FIPS 197
//! / NIST SP 800-38A). Cross-refs: `private/specs-verified/rules/srt-rules.md` §"Key Material
//! message — §3.2.2" (wire layout of `Salt`/`ICV`/`xSEK`/`oSEK`/`KLen`, all
//! carried opaquely by [`crate::packet::KeyMaterial`]) and §"Data packet —
//! §3.1" (`KK` field, [`crate::packet::EncryptionKeyField`]).
//!
//! This module adds the crypto *primitives* §6 names but does not restate:
//!
//! - **AES-CTR** payload encrypt/decrypt ([`aes_ctr_apply`]) — §6.2.2/§6.3.2.
//! - **RFC 3394 AES key wrap/unwrap** of the SEK ([`wrap_sek`]/[`unwrap_sek`])
//!   — §6.1.5/§6.2.1/§6.3.1.
//! - **PBKDF2 (HMAC-SHA1) KEK derivation** from a passphrase
//!   ([`derive_kek`]) — §6.1.4/§6.2.1/§6.3.1.
//!
//! Gated behind the `crypto` feature; the default/no_std packet-codec core
//! (this crate's `--no-default-features` build) pulls none of these
//! dependencies.
//!
//! # ⚠ The draft's two IV formulas (srt-crypto.md, "Conflicting IV formula")
//!
//! `draft-sharabayko-srt-01` gives **two different, unreconciled** formulas
//! for the AES-CTR IV:
//!
//! - §6.1.2 (Overview): build a 128-bit `{80 zero bits | 32-bit packet index
//!   | 16-bit block counter}` word and XOR its upper 112 bits with `IV =
//!   MSB(112, Salt)`.
//! - §6.2.2 (Encryption Process) / §6.3.2 (Decryption Process), verbatim and
//!   identical in both places: `IV = (MSB(112, Salt) << 2) XOR (PktSeqNo)`.
//!
//! These are not algebraically the same construction, and the draft never
//! reconciles them. No sample ciphertext exists anywhere in the draft to
//! disambiguate by reproduction (`srt-crypto.md`, "No test vectors" note), so
//! this module resolves it against a **real SRT peer** instead: the counter is
//! built as §6.1.2 describes — `{80 zero bits | 32-bit packet index | 16-bit
//! block counter}` with `MSB(112, Salt)` XORed across the top 112 bits — with
//! **no** `<< 2` shift. The §6.2.2/§6.3.2 `<< 2` is a draft-text artifact;
//! implementing it literally yields a keystream no real SRT peer can decrypt,
//! which `tests/it/libsrt_crypto_interop.rs` shows by having a genuine
//! `srt-live-transmit` decrypt this crate's payloads and this crate decrypt its
//! own. [`packet_counter`] therefore follows the §6.1.2 layout, pinned
//! byte-for-byte by a known-answer test.

use aes::cipher::{KeyIvInit, StreamCipher};
use aes::{Aes128, Aes192, Aes256};
use aes_kw::{KeyInit, KwAes128, KwAes192, KwAes256};
use alloc::vec;
use alloc::vec::Vec;
use broadcast_core::error::InvalidField;
use core::result::Result::{Err, Ok};
use ctr::Ctr128BE;
use hmac::Hmac;
use pbkdf2::pbkdf2;
use sha1::Sha1;
use zeroize::Zeroizing;

use crate::error::{Error, Result};
use crate::packet::EncryptionKeyField;

/// PBKDF2 iteration count mandated by the draft (`Iter = 2048`,
/// §6.1.4/§6.2.1/§6.3.1 — identical value at every citation).
pub const PBKDF2_ITERATIONS: u32 = 2048;

/// Length of the 128-bit Key Material `Salt` field in bytes (`SLen/4 = 4`
/// words — the only salt length the draft defines, `srt-rules.md` §3.2.2).
pub const SALT_LEN: usize = 16;

/// Bytes of RFC 3394's default initial value (the wrap ICV).
pub const WRAP_ICV_LEN: usize = 8;

/// Number of least-significant bytes of the 128-bit `Salt` fed to PBKDF2 as
/// its salt argument (`LSB(64,Salt)`, §6.2.1/§6.3.1: 64 bits = 8 bytes). The
/// remaining (most-significant) bytes of `Salt` feed the AES-CTR IV instead
/// (§6.1.2/§6.2.2/§6.3.2).
const PBKDF2_SALT_LEN: usize = 8;

/// Number of most-significant bytes of the 128-bit `Salt` used to build the
/// AES-CTR IV (`MSB(112, Salt)`, §6.1.2/§6.2.2/§6.3.2: 112 bits = 14 bytes).
const IV_SALT_LEN: usize = 14;

/// AES block size in bytes (FIPS 197) — also the AES-CTR counter width
/// (§6.1.2: "The counter for AES-CTR is the size of the cipher's block, i.e.
/// 128 bits").
pub const AES_BLOCK_LEN: usize = 16;

/// A key length not one of AES-128/192/256's 16/24/32 bytes (`KLen/4` ∈
/// `{4,6,8}`, `srt-rules.md` §3.2.2).
fn invalid_key_length(what: &'static str) -> Error {
    Error::InvalidField(InvalidField::new(
        what,
        "length must be 16, 24, or 32 bytes (AES-128/192/256)",
    ))
}

// ---------------------------------------------------------------------------
// RFC 8018 PBKDF2 (HMAC-SHA1) — lowest-level entry point.
// ---------------------------------------------------------------------------

/// Run PBKDF2-HMAC-SHA1 (RFC 8018 §5.2 with the HMAC-SHA-1 PRF of
/// Appendix B.1.1) with a caller-supplied salt and iteration count. This is
/// the lowest-level `srt-runtime` function that performs PBKDF2-HMAC-SHA1;
/// [`derive_kek`] is a thin wrapper that fixes the salt to `LSB(64, Salt)`
/// and the iteration count to [`PBKDF2_ITERATIONS`].
///
/// `output`'s length determines `dkLen`; any non-negative length up to
/// `(2^32 - 1) * 20` is accepted by the underlying primitive.
pub fn pbkdf2_hmac_sha1(password: &[u8], salt: &[u8], iterations: u32, output: &mut [u8]) {
    let (Ok(()) | Err(_)) = pbkdf2::<Hmac<Sha1>>(password, salt, iterations, output);
}

// ---------------------------------------------------------------------------
// §6.1.4/§6.2.1/§6.3.1 — KEK derivation (passphrase path).
// ---------------------------------------------------------------------------

/// Derive the Key Encrypting Key (KEK) from the pre-shared passphrase
/// (`draft-sharabayko-srt-01` §6.1.4, §6.2.1 sender / §6.3.1 receiver —
/// identical formula both sides):
///
/// ```text
/// KEK = PBKDF2(passphrase, LSB(64,Salt), Iter=2048, KLen)
/// ```
///
/// `salt` is the Key Material message's 128-bit `Salt` field; `klen` is the
/// desired KEK length in bytes (16/24/32, matching the handshake's
/// Encryption Field / the Key Material message's `KLen/4` — "the KEK has to
/// be at least as long as the SEK", §6.1.4).
///
/// The KEK is returned in a [`Zeroizing`] buffer, wiped when dropped.
///
/// # Errors
/// [`Error::InvalidField`] if `klen` is not 16, 24, or 32.
pub fn derive_kek(
    passphrase: &[u8],
    salt: &[u8; SALT_LEN],
    klen: usize,
) -> Result<Zeroizing<Vec<u8>>> {
    if !crate::AES_KEY_LENS.contains(&klen) {
        return Err(invalid_key_length("KLen"));
    }
    // LSB(64, Salt): the low/least-significant 8 bytes of the 128-bit,
    // big-endian-wire Salt.
    let pbkdf2_salt = &salt[SALT_LEN - PBKDF2_SALT_LEN..];
    let mut kek = Zeroizing::new(vec![0u8; klen]);
    pbkdf2_hmac_sha1(passphrase, pbkdf2_salt, PBKDF2_ITERATIONS, &mut kek[..]);
    Ok(kek)
}

/// One-entry cache for [`derive_kek`], keyed by the Key Material `Salt` and
/// the requested `KLen` (the passphrase is fixed for the life of a
/// connection). A peer can re-send the same Key Material message, and deriving
/// the KEK costs a full 2048-iteration PBKDF2 run every time; the cache makes
/// a repeat cost a comparison instead (#2840).
#[derive(Default)]
pub(crate) struct KekCache {
    entry: Option<CachedKek>,
    /// Derivation count, so a test can prove a repeat is served from the
    /// cache.
    derivations: u64,
}

struct CachedKek {
    salt: [u8; SALT_LEN],
    klen: usize,
    kek: Zeroizing<Vec<u8>>,
}

impl KekCache {
    pub(crate) const fn new() -> Self {
        KekCache {
            entry: None,
            derivations: 0,
        }
    }

    /// The KEK for `(salt, klen)`, derived once and reused for an identical
    /// request.
    ///
    /// # Errors
    /// The same as [`derive_kek`].
    pub(crate) fn derive(
        &mut self,
        passphrase: &[u8],
        salt: &[u8; SALT_LEN],
        klen: usize,
    ) -> Result<Zeroizing<Vec<u8>>> {
        if let Some(entry) = &self.entry
            && entry.salt == *salt
            && entry.klen == klen
        {
            return Ok(entry.kek.clone());
        }
        let kek = derive_kek(passphrase, salt, klen)?;
        self.entry = Some(CachedKek {
            salt: *salt,
            klen,
            kek: kek.clone(),
        });
        self.derivations = self.derivations.saturating_add(1);
        Ok(kek)
    }

    /// How many PBKDF2 derivations this cache has performed.
    #[cfg(test)]
    pub(crate) fn derivations(&self) -> u64 {
        self.derivations
    }
}

// ---------------------------------------------------------------------------
// §6.1.5/§6.2.1/§6.3.1 — RFC 3394 AES key wrap/unwrap of the SEK.
// ---------------------------------------------------------------------------

/// Wrap one or two SEKs with the KEK (RFC 3394 AES key wrap, external
/// algorithm — `draft-sharabayko-srt-01` §6.1.5/§6.2.1: `Wrap = AESkw(KEK,
/// SEK)`).
///
/// `plaintext_keys` is the concatenation of the SEK(s) being wrapped — one
/// SEK's worth of bytes (Key Material `KK` = even/odd) or two concatenated
/// SEKs (`KK` = both), per the Wrap-field length formula `n*KLen + 8` in
/// `srt-rules.md` §"Key Material message — §3.2.2". Returns `(icv, wrapped)`
/// to match [`crate::packet::KeyMaterial`]'s `icv`/`x_sek`/`o_sek` fields —
/// RFC 3394's first 8-byte output block *is* the wrap's Integrity Check
/// Vector (the encrypted default IV, RFC 3394 §2.2.3.1), and the remaining
/// bytes are the wrapped key material, the same length as the input.
///
/// # Errors
/// [`Error::InvalidField`] if `kek.len()` is not 16, 24, or 32, or if
/// `plaintext_keys.len()` is not a multiple of 8 bytes (RFC 3394 operates on
/// 64-bit semiblocks).
pub fn wrap_sek(kek: &[u8], plaintext_keys: &[u8]) -> Result<([u8; WRAP_ICV_LEN], Vec<u8>)> {
    let mut out = vec![0u8; plaintext_keys.len() + WRAP_ICV_LEN];
    match kek.len() {
        16 => KwAes128::new_from_slice(kek)
            .map_err(|_| invalid_key_length("KEK"))?
            .wrap_key(plaintext_keys, &mut out)
            .map(|_| ()),
        24 => KwAes192::new_from_slice(kek)
            .map_err(|_| invalid_key_length("KEK"))?
            .wrap_key(plaintext_keys, &mut out)
            .map(|_| ()),
        32 => KwAes256::new_from_slice(kek)
            .map_err(|_| invalid_key_length("KEK"))?
            .wrap_key(plaintext_keys, &mut out)
            .map(|_| ()),
        _ => return Err(invalid_key_length("KEK")),
    }
    .map_err(|_| {
        Error::InvalidField(InvalidField::new(
            "SEK",
            "length must be a multiple of 8 bytes (RFC 3394 semiblocks)",
        ))
    })?;
    let mut icv = [0u8; WRAP_ICV_LEN];
    icv.copy_from_slice(&out[..WRAP_ICV_LEN]);
    Ok((icv, out[WRAP_ICV_LEN..].to_vec()))
}

/// Unwrap the SEK(s) with the KEK (inverse RFC 3394 AES key wrap —
/// `draft-sharabayko-srt-01` §6.1.5/§6.3.1: `SEK = AESkuw(KEK, Wrap)`).
///
/// `icv`/`wrapped` are [`crate::packet::KeyMaterial`]'s `icv`/`x_sek` (or
/// `o_sek`) fields. A wrap-integrity failure — wrong KEK (wrong passphrase)
/// or corrupt wire data — is the spec's "it does not have the SEK" case
/// (§6.1.5, L3799-3803/L3820-3823): a structured error, never a panic or
/// silently-wrong plaintext.
///
/// # Errors
/// [`Error::InvalidField`] if `kek.len()` is not 16, 24, or 32, if
/// `wrapped.len()` is not a multiple of 8 bytes, or if the RFC 3394
/// integrity check fails.
///
/// The plaintext SEK(s) come back in a [`Zeroizing`] buffer, wiped when
/// dropped.
pub fn unwrap_sek(
    kek: &[u8],
    icv: &[u8; WRAP_ICV_LEN],
    wrapped: &[u8],
) -> Result<Zeroizing<Vec<u8>>> {
    let mut input = Vec::with_capacity(WRAP_ICV_LEN + wrapped.len());
    input.extend_from_slice(icv);
    input.extend_from_slice(wrapped);
    let mut out = Zeroizing::new(vec![0u8; wrapped.len()]);
    let bad_wrap = || {
        Error::InvalidField(InvalidField::new(
            "AES key wrap",
            "integrity check failed (wrong KEK / passphrase, or corrupt wire data)",
        ))
    };
    match kek.len() {
        16 => KwAes128::new_from_slice(kek)
            .map_err(|_| invalid_key_length("KEK"))?
            .unwrap_key(&input, &mut out[..])
            .map(|_| ()),
        24 => KwAes192::new_from_slice(kek)
            .map_err(|_| invalid_key_length("KEK"))?
            .unwrap_key(&input, &mut out[..])
            .map(|_| ()),
        32 => KwAes256::new_from_slice(kek)
            .map_err(|_| invalid_key_length("KEK"))?
            .unwrap_key(&input, &mut out[..])
            .map(|_| ()),
        _ => return Err(invalid_key_length("KEK")),
    }
    .map_err(|_| bad_wrap())?;
    Ok(out)
}

// ---------------------------------------------------------------------------
// §6.1.2/§6.2.2/§6.3.2 — AES-CTR payload encrypt/decrypt.
// ---------------------------------------------------------------------------

/// Compute the 128-bit AES-CTR initial counter for one data packet.
///
/// This follows the §6.1.2 layout, which is what real SRT peers use on the wire
/// (`private/specs-verified/rules/srt-crypto.md`):
///
/// ```text
/// all 16 bytes zeroed
/// 32-bit packet index at bytes [10..14]
/// MSB(112, Salt) XORed across the top 14 bytes
/// bytes [14..16] = per-packet AES-block counter, starts 0
///
///  byte:  0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
/// //        +-----------------------+-----------+-----+
/// //        |          0s           |    pki    | ctr |
/// //        +-----------------------+-----------+-----+
/// ```
///
/// **On the draft's `IV = (MSB(112, Salt) << 2) XOR PktSeqNo` (§6.2.2/§6.3.2):**
/// the `<< 2` is a draft-text artifact — a real SRT peer applies no left shift.
/// Implementing the `<< 2` literally produces a keystream no real SRT peer can
/// decrypt, so this function follows §6.1.2's field layout: packet index in bits
/// `[47:16]`, block counter in `[15:0]`. See the module doc's "conflicting IV
/// formula" note.
///
/// The low 16 bits (`counter[14..16]`) are the per-packet AES-block counter,
/// left at `0` here — a standard 128-bit big-endian CTR increments the whole
/// counter per block, which only touches these low bits as long as a single
/// packet's payload stays under `2^16` AES blocks (1 MiB); every SRT payload
/// (bounded by a UDP datagram) is far smaller.
///
/// `pkt_seq_no` is the data packet's 31-bit Packet Sequence Number
/// (`draft-sharabayko-srt-01` §3.1); bit 31 (the `F` header bit) is never part
/// of it.
pub fn packet_counter(salt: &[u8; SALT_LEN], pkt_seq_no: u32) -> [u8; AES_BLOCK_LEN] {
    let mut counter = [0u8; AES_BLOCK_LEN];
    // 32-bit packet index at bytes [10..14].
    counter[10..14].copy_from_slice(&pkt_seq_no.to_be_bytes());
    // XOR MSB(112, Salt) — the top 14 bytes of the Salt — across bytes [0..14]
    // No left shift.
    for i in 0..IV_SALT_LEN {
        counter[i] ^= salt[i];
    }
    // counter[14..16] stays 0 — the block counter starts at 0 for this packet.
    counter
}

/// AES-CTR encrypt/decrypt one data packet's payload **in place**
/// (`draft-sharabayko-srt-01` §6.2.2/§6.3.2). CTR mode is its own inverse —
/// `EncryptedPayload = AES_CTR_Encrypt(SEK, IV, UnencryptedPayload)` and
/// `DecryptedPayload = AES_CTR_Encrypt(SEK, IV, EncryptedPayload)` are the
/// same operation (XOR with the same keystream), so this one function serves
/// both directions.
///
/// `sek` selects AES-128/192/256 by its length (16/24/32 bytes); `salt` and
/// `pkt_seq_no` feed [`packet_counter`]. No padding is applied or expected —
/// CTR is a stream cipher (§6.1.1).
///
/// # Errors
/// [`Error::InvalidField`] if `sek.len()` is not 16, 24, or 32.
pub fn aes_ctr_apply(
    sek: &[u8],
    salt: &[u8; SALT_LEN],
    pkt_seq_no: u32,
    data: &mut [u8],
) -> Result<()> {
    let counter = packet_counter(salt, pkt_seq_no);
    match sek.len() {
        16 => {
            let mut cipher =
                Ctr128BE::<Aes128>::new_from_slices(sek, &counter).map_err(|_| bad_sek())?;
            cipher.apply_keystream(data);
        }
        24 => {
            let mut cipher =
                Ctr128BE::<Aes192>::new_from_slices(sek, &counter).map_err(|_| bad_sek())?;
            cipher.apply_keystream(data);
        }
        32 => {
            let mut cipher =
                Ctr128BE::<Aes256>::new_from_slices(sek, &counter).map_err(|_| bad_sek())?;
            cipher.apply_keystream(data);
        }
        _ => return Err(bad_sek()),
    }
    Ok(())
}

fn bad_sek() -> Error {
    invalid_key_length("SEK")
}

// ---------------------------------------------------------------------------
// §3.1 `KK` — select the active SEK by odd/even parity.
// ---------------------------------------------------------------------------

/// Select the SEK to use for a data packet from its `KK` field
/// (`draft-sharabayko-srt-01` §3.1/§6.1.6): `even`/`odd` are the two SEKs
/// currently held (both may be live during the `±`KM-Pre-Announcement-Period`
/// rekey transition window, §6.1.6).
///
/// # Errors
/// [`Error::InvalidField`] if the packet is unencrypted (`KK = NotEncrypted`)
/// or carries the control-packet-only reserved value, or if the selected
/// parity's SEK is not currently held (e.g. not yet unwrapped, or already
/// decommissioned — §6.3, step 11: such packets "must be dropped").
pub fn select_sek<'a>(
    key_flag: EncryptionKeyField,
    even: Option<&'a [u8]>,
    odd: Option<&'a [u8]>,
) -> Result<&'a [u8]> {
    let no_sek = |parity: &'static str| {
        Error::InvalidField(InvalidField::new(
            "SEK",
            match parity {
                "even" => "even key not currently held",
                _ => "odd key not currently held",
            },
        ))
    };
    match key_flag {
        EncryptionKeyField::Even => even.ok_or_else(|| no_sek("even")),
        EncryptionKeyField::Odd => odd.ok_or_else(|| no_sek("odd")),
        EncryptionKeyField::NotEncrypted => Err(Error::InvalidField(InvalidField::new(
            "KK",
            "packet is not encrypted (KK=00b)",
        ))),
        EncryptionKeyField::Reserved(_) => Err(Error::InvalidField(InvalidField::new(
            "KK",
            "reserved value (11b) is control-packet-only, not valid on a data packet",
        ))),
    }
}

#[cfg(test)]
mod tests {
    use broadcast_core::error::InvalidField;

    use super::*;

    // -----------------------------------------------------------------
    // RFC 3394 §4.1 — "Wrap 128 bits of Key Data with a 128-bit KEK".
    // <https://datatracker.ietf.org/doc/html/rfc3394#section-4.1>
    // -----------------------------------------------------------------
    const RFC3394_KEK_128: [u8; 16] = [
        0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0A, 0x0B, 0x0C, 0x0D, 0x0E,
        0x0F,
    ];
    const RFC3394_KEY_DATA_128: [u8; 16] = [
        0x00, 0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77, 0x88, 0x99, 0xAA, 0xBB, 0xCC, 0xDD, 0xEE,
        0xFF,
    ];
    const RFC3394_WRAPPED_128: [u8; 24] = [
        0x1F, 0xA6, 0x8B, 0x0A, 0x81, 0x12, 0xB4, 0x47, 0xAE, 0xF3, 0x4B, 0xD8, 0xFB, 0x5A, 0x7B,
        0x82, 0x9D, 0x3E, 0x86, 0x23, 0x71, 0xD2, 0xCF, 0xE5,
    ];

    #[test]
    fn rfc3394_wrap_matches_worked_vector() {
        let (icv, wrapped) = wrap_sek(&RFC3394_KEK_128, &RFC3394_KEY_DATA_128).unwrap();
        assert_eq!(&icv[..], &RFC3394_WRAPPED_128[..8]);
        assert_eq!(wrapped.as_slice(), &RFC3394_WRAPPED_128[8..]);
    }

    // -----------------------------------------------------------------
    // packet_counter known-answer, hand-derived from the §6.1.2 layout:
    //   zero 16 bytes; packet index at [10..14]; iv[0..14] ^= salt[0..14];
    // For salt = 01 02 … 10 and pki = 0x11223344:
    //   [0..10]  = salt[0..10]                = 01 02 03 04 05 06 07 08 09 0A
    //   [10]     = salt[10]^0x11 = 0x0B^0x11  = 1A
    //   [11]     = salt[11]^0x22 = 0x0C^0x22  = 2E
    //   [12]     = salt[12]^0x33 = 0x0D^0x33  = 3E
    //   [13]     = salt[13]^0x44 = 0x0E^0x44  = 4A
    //   [14..16] = 00 00                        (block counter, salt[14..] unused)
    // The old `MSB(112,Salt) << 2` construction gives byte[0]=0x04 (not 0x01)
    // and different [10..14] — this test BITES against that regression.
    // -----------------------------------------------------------------
    #[test]
    fn packet_counter_follows_the_section_6_1_2_layout() {
        let salt: [u8; SALT_LEN] = [
            0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0A, 0x0B, 0x0C, 0x0D, 0x0E,
            0x0F, 0x10,
        ];
        let expected: [u8; AES_BLOCK_LEN] = [
            0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0A, 0x1A, 0x2E, 0x3E, 0x4A,
            0x00, 0x00,
        ];
        let got = packet_counter(&salt, 0x1122_3344);
        assert_eq!(
            got, expected,
            "counter must follow the §6.1.2 layout (no <<2)"
        );
        // Explicit guard against the buggy left-shift construction.
        assert_eq!(got[0], 0x01, "byte 0 is pure salt, not the <<2 value 0x04");
    }

    #[test]
    fn rfc3394_unwrap_matches_worked_vector() {
        let mut icv = [0u8; 8];
        icv.copy_from_slice(&RFC3394_WRAPPED_128[..8]);
        let recovered = unwrap_sek(&RFC3394_KEK_128, &icv, &RFC3394_WRAPPED_128[8..]).unwrap();
        assert_eq!(recovered.as_slice(), &RFC3394_KEY_DATA_128[..]);
    }

    #[test]
    fn rfc3394_unwrap_rejects_wrong_kek() {
        let mut icv = [0u8; 8];
        icv.copy_from_slice(&RFC3394_WRAPPED_128[..8]);
        let mut wrong_kek = RFC3394_KEK_128;
        wrong_kek[0] ^= 0xFF;
        assert!(matches!(
            unwrap_sek(&wrong_kek, &icv, &RFC3394_WRAPPED_128[8..]),
            Err(crate::error::Error::InvalidField(..))
        ));
    }

    // -----------------------------------------------------------------
    // SRT §6 payload round-trip (no spec test vectors exist for this —
    // srt-crypto.md's "No test vectors" note — so this exercises the crate's
    // own packet_counter + aes_ctr_apply against each other, not an
    // external ground truth).
    // -----------------------------------------------------------------

    #[test]
    fn srt_payload_round_trips_and_wrong_sek_does_not_recover() {
        let sek = [0x42u8; 16];
        let salt = [0x99u8; SALT_LEN];
        let pkt_seq_no = 0x0123_4567u32;
        let plaintext = b"SRT payload encryption round trip test vector.".to_vec();

        let mut encrypted = plaintext.clone();
        aes_ctr_apply(&sek, &salt, pkt_seq_no, &mut encrypted).unwrap();
        assert_ne!(encrypted, plaintext, "encryption must change the bytes");

        let mut decrypted = encrypted.clone();
        aes_ctr_apply(&sek, &salt, pkt_seq_no, &mut decrypted).unwrap();
        assert_eq!(
            decrypted, plaintext,
            "correct SEK must recover the plaintext"
        );

        let wrong_sek = [0x43u8; 16];
        let mut wrongly_decrypted = encrypted;
        aes_ctr_apply(&wrong_sek, &salt, pkt_seq_no, &mut wrongly_decrypted).unwrap();
        assert_ne!(
            wrongly_decrypted, plaintext,
            "wrong SEK must not recover the plaintext"
        );
    }

    #[test]
    fn different_seq_no_gives_different_keystream() {
        let sek = [0x11u8; 24];
        let salt = [0x22u8; SALT_LEN];
        let plaintext = [0u8; 32];

        let mut a = plaintext;
        aes_ctr_apply(&sek, &salt, 1, &mut a).unwrap();
        let mut b = plaintext;
        aes_ctr_apply(&sek, &salt, 2, &mut b).unwrap();
        assert_ne!(a, b);
    }

    #[test]
    fn kek_derivation_all_sizes_and_deterministic() {
        for klen in [16usize, 24, 32] {
            let salt = [0xABu8; SALT_LEN];
            let kek1 = derive_kek(b"correct horse battery staple", &salt, klen).unwrap();
            let kek2 = derive_kek(b"correct horse battery staple", &salt, klen).unwrap();
            assert_eq!(kek1.len(), klen);
            assert_eq!(kek1, kek2, "PBKDF2 is deterministic for the same inputs");

            let different_salt = [0xACu8; SALT_LEN];
            let kek3 = derive_kek(b"correct horse battery staple", &different_salt, klen).unwrap();
            assert_ne!(kek1, kek3, "different salt must give a different KEK");
        }
    }

    #[test]
    fn invalid_klen_errs_without_panic() {
        let salt = [0u8; SALT_LEN];
        assert!(matches!(
            derive_kek(b"pw", &salt, 20),
            Err(crate::error::Error::InvalidField(..))
        ));
        assert!(matches!(
            wrap_sek(&[0u8; 20], &[0u8; 16]),
            Err(crate::error::Error::InvalidField(..))
        ));
        assert!(matches!(
            aes_ctr_apply(&[0u8; 20], &salt, 0, &mut [0u8; 4]),
            Err(crate::error::Error::InvalidField(..))
        ));
    }

    #[test]
    fn select_sek_picks_correct_parity_and_rejects_bad_flags() {
        let even = [1u8; 16];
        let odd = [2u8; 16];
        assert_eq!(
            select_sek(EncryptionKeyField::Even, Some(&even), Some(&odd)).unwrap(),
            &even[..]
        );
        assert_eq!(
            select_sek(EncryptionKeyField::Odd, Some(&even), Some(&odd)).unwrap(),
            &odd[..]
        );
        assert!(matches!(
            select_sek(EncryptionKeyField::Even, None, Some(&odd)),
            Err(Error::InvalidField(..))
        ));
        assert!(matches!(
            select_sek(EncryptionKeyField::NotEncrypted, Some(&even), Some(&odd)),
            Err(Error::InvalidField(InvalidField { field: "KK", .. }))
        ));
        assert!(matches!(
            select_sek(EncryptionKeyField::from_bits(0b11), Some(&even), Some(&odd)),
            Err(Error::InvalidField(InvalidField { field: "KK", .. }))
        ));
        assert!(matches!(
            select_sek(EncryptionKeyField::Even, None, Some(&odd)),
            Err(Error::InvalidField(ref e)) if e.reason.contains("even")
        ));
        assert!(matches!(
            select_sek(EncryptionKeyField::Odd, Some(&even), None),
            Err(Error::InvalidField(ref e)) if e.reason.contains("odd")
        ));
    }

    #[test]
    fn both_seks_wrap_unwrap_round_trip() {
        // KK=Both: two concatenated SEKs wrapped under one KEK/ICV, matching
        // the Wrap-field length formula `n*KLen + 8` (`srt-rules.md` §3.2.2).
        let kek = [0x77u8; 16];
        let even_sek = [0xAAu8; 16];
        let odd_sek = [0xBBu8; 16];
        let mut plaintext = Vec::new();
        plaintext.extend_from_slice(&even_sek);
        plaintext.extend_from_slice(&odd_sek);

        let (icv, wrapped) = wrap_sek(&kek, &plaintext).unwrap();
        assert_eq!(wrapped.len(), 32);
        let recovered = unwrap_sek(&kek, &icv, &wrapped).unwrap();
        assert_eq!(&recovered[..], &plaintext[..]);
        assert_eq!(&recovered[..16], &even_sek[..]);
        assert_eq!(&recovered[16..], &odd_sek[..]);
    }

    /// #2840: an identical `(Salt, KLen)` request is served from the cache,
    /// so a peer re-sending Key Material does not rerun PBKDF2. A different
    /// salt or key length misses and derives again.
    #[test]
    fn kek_cache_derives_once_per_salt_and_length() {
        let mut cache = KekCache::new();
        let salt = [0x33u8; SALT_LEN];
        let first = cache.derive(b"cache-passphrase", &salt, 16).unwrap();
        let again = cache.derive(b"cache-passphrase", &salt, 16).unwrap();
        assert_eq!(&first[..], &again[..]);
        assert_eq!(cache.derivations(), 1, "same salt and length is a hit");

        let other_salt = [0x44u8; SALT_LEN];
        let third = cache.derive(b"cache-passphrase", &other_salt, 16).unwrap();
        assert_ne!(&first[..], &third[..]);
        assert_eq!(cache.derivations(), 2, "a new salt misses");

        let longer = cache.derive(b"cache-passphrase", &salt, 24).unwrap();
        assert_eq!(longer.len(), 24);
        assert_eq!(cache.derivations(), 3, "a new length misses");
    }
}