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
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
//! Key Material message — `draft-sharabayko-srt-01` §3.2.2, Figures 10-11.
//!
//! Carried either as a Handshake Extension (§3.2.1.2, `Extension Type`
//! `SRT_CMD_KMREQ`/`SRT_CMD_KMRSP`) or as the CIF of a User-Defined control
//! packet (`Subtype` `SRT_CMD_KMREQ`/`SRT_CMD_KMRSP`, §3.2.2).
//!
//! ```text
//! word0   S(1) V(3) PT(4) | Sign(16) | Resv1(6) KK(2)
//! word1   KEKI(32)
//! word2   Cipher(8) Auth(8) SE(8) Resv2(8)
//! word3   Resv3(16) SLen/4(8) KLen/4(8)
//! ..      Salt (SLen bytes)
//! ..      ICV (8 bytes) | xSEK (KLen bytes) | [oSEK (KLen bytes)]
//! ```
//!
//! `S`, `V`, `PT`, `Sign`, `Resv1`, `Resv2`, `Resv3` are fixed-value fields
//! (the spec gives each a mandated `value = {..}`); they are validated on
//! parse and not stored (matching the crate's reserved-bit policy — see the
//! crate root docs), except `PT`, which acts as this struct's discriminating
//! magic number (must be `2`, "Keying Material Message").
//!
//! This module only carries the wrapped-key *bytes* — it performs no AES
//! key-wrap/unwrap. Actual encryption/decryption is an explicit follow-up
//! (see the crate root docs).

use super::{Error, Result, put_be32};
use broadcast_core::error::BufferTooShort;
use broadcast_core::len::{need_in, need_out};

const S_FIXED: u8 = 0;
const V_FIXED: u8 = 1;
const PT_KEYING_MATERIAL: u8 = 2;
const SIGN_FIXED: u16 = 0x2029; // 'HAI' PnP Vendor ID, big-endian.
const RESV1_FIXED: u8 = 0;
const RESV2_FIXED: u8 = 0;
const RESV3_FIXED: u16 = 0;

/// Bytes of the Key Material message's fixed header, and of the 4-byte block
/// `SLen`/`KLen` are counted in (§3.2.2, Figure 7).
const FIXED_HEADER_LEN: usize = 16;
/// Bytes of the Key Material message's ICV, the first half of a wrapped block
/// (§3.2.2, Figure 7; RFC 3394 §2.2.3.1).
pub const ICV_LEN: usize = 8;
const KEY_BLOCK_LEN: usize = 4;

/// Keys a message with `KK = 11b` carries: the even and the odd SEK.
const KEY_COUNT_BOTH: usize = 2;

/// Byte offsets of the fixed header's words.
const KEKI_OFFSET: usize = 4;
const FLAGS_OFFSET: usize = 8;
const LENGTHS_OFFSET: usize = 12;

/// Shifts and masks of the first word's fields (§3.2.2, Figure 7).
const S_SHIFT: u32 = 31;
const V_SHIFT: u32 = 28;
const V_MASK: u32 = 0b111;
const PT_SHIFT: u32 = 24;
const PT_MASK: u32 = 0b1111;
const SIGN_SHIFT: u32 = 8;
const SIGN_MASK: u32 = 0xFFFF;
const RESV1_SHIFT: u32 = 2;
const RESV1_MASK: u32 = 0b0011_1111;
const KK_MASK: u32 = 0b11;

/// Shifts and masks of the second and third words' fields.
const CIPHER_SHIFT: u32 = 24;
const AUTH_SHIFT: u32 = 16;
const SE_SHIFT: u32 = 8;
const RESV2_MASK: u32 = 0xFF;
const RESV3_SHIFT: u32 = 16;
const SLEN_SHIFT: u32 = 8;
const LEN_MASK: u32 = 0xFF;

/// Mask of a 2-bit `KK` value decoded from a byte.
const KK_FIELD_MASK: u8 = 0b11;

/// `KK` wire values of the Key Material message (§3.2.2). Distinct from the
/// data-packet `KK` field ([`super::EncryptionKeyField`]) — same 2-bit shape,
/// different meaning.
pub const KM_KK_NO_SEK: u8 = 0b00;
/// Even key provided.
pub const KM_KK_EVEN: u8 = 0b01;
/// Odd key provided.
pub const KM_KK_ODD: u8 = 0b10;
/// Both keys provided.
pub const KM_KK_BOTH: u8 = 0b11;

/// `KK`: which SEK(s) (odd/even) this Key Material message provides
/// (`draft-sharabayko-srt-01` §3.2.2).
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
#[cfg_attr(feature = "serde", derive(serde::Serialize))]
#[non_exhaustive]
pub enum KmKeyFlag {
    /// `00b`: no SEK provided (spec: "invalid extension format") — decodable
    /// from the 2-bit field, but [`KeyMaterial::parse`] and
    /// [`KeyMaterial::serialize_into`] both refuse a message carrying it.
    NoSek,
    /// `01b`: even key provided.
    Even,
    /// `10b`: odd key provided.
    Odd,
    /// `11b`: both even and odd keys provided.
    Both,
}

impl KmKeyFlag {
    /// Decode the 2-bit `KK` field.
    pub fn from_bits(v: u8) -> Self {
        match v & KK_FIELD_MASK {
            KM_KK_EVEN => KmKeyFlag::Even,
            KM_KK_ODD => KmKeyFlag::Odd,
            KM_KK_BOTH => KmKeyFlag::Both,
            _ => KmKeyFlag::NoSek,
        }
    }

    /// The 2-bit wire value.
    pub fn to_bits(self) -> u8 {
        match self {
            KmKeyFlag::NoSek => KM_KK_NO_SEK,
            KmKeyFlag::Even => KM_KK_EVEN,
            KmKeyFlag::Odd => KM_KK_ODD,
            KmKeyFlag::Both => KM_KK_BOTH,
        }
    }

    /// Number of SEKs this flag indicates (`n` in the Wrap-field length
    /// formula, §3.2.2: `n = (KK + 1) / 2`).
    pub fn key_count(self) -> u8 {
        match self {
            KmKeyFlag::NoSek => 0,
            KmKeyFlag::Even | KmKeyFlag::Odd => 1,
            KmKeyFlag::Both => 2,
        }
    }

    /// Spec label.
    pub fn name(&self) -> &'static str {
        match self {
            KmKeyFlag::NoSek => "no SEK",
            KmKeyFlag::Even => "even key",
            KmKeyFlag::Odd => "odd key",
            KmKeyFlag::Both => "both keys",
        }
    }
}

broadcast_core::impl_spec_display!(KmKeyFlag);

/// `Cipher` wire values (§3.2.2).
pub const CIPHER_NONE: u8 = 0;
/// AES-CTR.
pub const CIPHER_AES_CTR: u8 = 2;

/// `Cipher`: encryption cipher and mode (`draft-sharabayko-srt-01` §3.2.2).
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
#[cfg_attr(feature = "serde", derive(serde::Serialize))]
#[non_exhaustive]
pub enum Cipher {
    /// `0`: none, or a KEKI-indexed crypto context.
    None,
    /// `2`: AES-CTR (SP800-38A).
    AesCtr,
    /// A value not defined above (includes `1`).
    Reserved(u8),
}

impl Cipher {
    /// Decode the 8-bit `Cipher` field.
    pub fn from_bits(v: u8) -> Self {
        match v {
            CIPHER_NONE => Cipher::None,
            CIPHER_AES_CTR => Cipher::AesCtr,
            other => Cipher::Reserved(other),
        }
    }

    /// The wire value.
    pub fn to_bits(self) -> u8 {
        match self {
            Cipher::None => CIPHER_NONE,
            Cipher::AesCtr => CIPHER_AES_CTR,
            Cipher::Reserved(v) => v,
        }
    }

    /// Spec label.
    pub fn name(&self) -> &'static str {
        match self {
            Cipher::None => "none / KEKI-indexed",
            Cipher::AesCtr => "AES-CTR",
            Cipher::Reserved(_) => "reserved",
        }
    }
}

broadcast_core::impl_spec_display!(Cipher, Reserved);

/// `Authentication` wire values (§3.2.2).
pub const KM_AUTH_NONE: u8 = 0;

/// `Authentication`: message authentication code algorithm
/// (`draft-sharabayko-srt-01` §3.2.2).
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
#[cfg_attr(feature = "serde", derive(serde::Serialize))]
#[non_exhaustive]
pub enum KmAuth {
    /// `0`: none, or a KEKI-indexed crypto context (the only defined value).
    None,
    /// A value not defined above.
    Reserved(u8),
}

impl KmAuth {
    /// Decode the 8-bit `Auth` field.
    pub fn from_bits(v: u8) -> Self {
        match v {
            KM_AUTH_NONE => KmAuth::None,
            other => KmAuth::Reserved(other),
        }
    }

    /// The wire value.
    pub fn to_bits(self) -> u8 {
        match self {
            KmAuth::None => KM_AUTH_NONE,
            KmAuth::Reserved(v) => v,
        }
    }

    /// Spec label.
    pub fn name(&self) -> &'static str {
        match self {
            KmAuth::None => "none / KEKI-indexed",
            KmAuth::Reserved(_) => "reserved",
        }
    }
}

broadcast_core::impl_spec_display!(KmAuth, Reserved);

/// `SE` (Stream Encapsulation) wire values (§3.2.2).
pub const STREAM_ENCAP_UNSPECIFIED: u8 = 0;
/// MPEG-TS/UDP.
pub const STREAM_ENCAP_MPEG_TS_UDP: u8 = 1;
/// MPEG-TS/SRT.
pub const STREAM_ENCAP_MPEG_TS_SRT: u8 = 2;

/// `SE`: stream encapsulation (`draft-sharabayko-srt-01` §3.2.2).
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
#[cfg_attr(feature = "serde", derive(serde::Serialize))]
#[non_exhaustive]
pub enum StreamEncapsulation {
    /// `0`: unspecified, or a KEKI-indexed crypto context.
    Unspecified,
    /// `1`: MPEG-TS/UDP.
    MpegTsUdp,
    /// `2`: MPEG-TS/SRT.
    MpegTsSrt,
    /// A value not defined above.
    Reserved(u8),
}

impl StreamEncapsulation {
    /// Decode the 8-bit `SE` field.
    pub fn from_bits(v: u8) -> Self {
        match v {
            STREAM_ENCAP_UNSPECIFIED => StreamEncapsulation::Unspecified,
            STREAM_ENCAP_MPEG_TS_UDP => StreamEncapsulation::MpegTsUdp,
            STREAM_ENCAP_MPEG_TS_SRT => StreamEncapsulation::MpegTsSrt,
            other => StreamEncapsulation::Reserved(other),
        }
    }

    /// The wire value.
    pub fn to_bits(self) -> u8 {
        match self {
            StreamEncapsulation::Unspecified => STREAM_ENCAP_UNSPECIFIED,
            StreamEncapsulation::MpegTsUdp => STREAM_ENCAP_MPEG_TS_UDP,
            StreamEncapsulation::MpegTsSrt => STREAM_ENCAP_MPEG_TS_SRT,
            StreamEncapsulation::Reserved(v) => v,
        }
    }

    /// Spec label.
    pub fn name(&self) -> &'static str {
        match self {
            StreamEncapsulation::Unspecified => "unspecified / KEKI-indexed",
            StreamEncapsulation::MpegTsUdp => "MPEG-TS/UDP",
            StreamEncapsulation::MpegTsSrt => "MPEG-TS/SRT",
            StreamEncapsulation::Reserved(_) => "reserved",
        }
    }
}

broadcast_core::impl_spec_display!(StreamEncapsulation, Reserved);

/// Key Material message (`draft-sharabayko-srt-01` §3.2.2, Figures 10-11).
///
/// [`core::fmt::Debug`] prints only the lengths of the wrapped keys and the
/// ICV: with the Salt they are exactly what an offline attack on the
/// passphrase needs, so they must not reach a log by way of `{:?}`
/// (issue #1142).
#[derive(Clone, PartialEq, Eq, Hash)]
#[cfg_attr(feature = "serde", derive(serde::Serialize))]
pub struct KeyMaterial<'a> {
    /// Which SEK(s) [`Self::x_sek`] / [`Self::o_sek`] carry.
    pub kk: KmKeyFlag,
    /// Key Encryption Key Index (big-endian; `0` = default stream key).
    pub keki: u32,
    /// Encryption cipher and mode.
    pub cipher: Cipher,
    /// Message authentication code algorithm.
    pub auth: KmAuth,
    /// Stream encapsulation.
    pub se: StreamEncapsulation,
    /// Salt / IV (`SLen` bytes; `0` if absent, else 16 bytes / 128 bits per
    /// the only length the spec defines). Not serialized by the `serde`
    /// feature (with the wrapped keys it permits an offline passphrase
    /// attack), nor shown by `Debug`.
    #[cfg_attr(feature = "serde", serde(skip))]
    pub salt: &'a [u8],
    /// 64-bit AES key-wrap Integrity Check Vector. Not serialized by `serde`.
    #[cfg_attr(feature = "serde", serde(skip))]
    pub icv: [u8; ICV_LEN],
    /// The (even or odd, per [`Self::kk`]) SEK, wrapped. `KLen` bytes
    /// (16/24/32, matching the handshake's `Encryption Field`). Not serialized
    /// by `serde`.
    #[cfg_attr(feature = "serde", serde(skip))]
    pub x_sek: &'a [u8],
    /// The odd SEK, wrapped, present only when [`Self::kk`] is
    /// [`KmKeyFlag::Both`] (same length as [`Self::x_sek`]). Not serialized by
    /// `serde`.
    #[cfg_attr(feature = "serde", serde(skip))]
    pub o_sek: Option<&'a [u8]>,
}

impl core::fmt::Debug for KeyMaterial<'_> {
    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
        f.debug_struct("KeyMaterial")
            .field("kk", &self.kk)
            .field("keki", &self.keki)
            .field("cipher", &self.cipher)
            .field("auth", &self.auth)
            .field("se", &self.se)
            .field(
                "salt",
                &format_args!("<redacted, {} bytes>", self.salt.len()),
            )
            .field("icv", &format_args!("<redacted, {} bytes>", self.icv.len()))
            .field(
                "x_sek",
                &format_args!("<redacted, {} bytes>", self.x_sek.len()),
            )
            .field(
                "o_sek",
                &format_args!("<redacted, {} bytes>", self.o_sek.map_or(0, <[u8]>::len)),
            )
            .finish()
    }
}

impl<'a> KeyMaterial<'a> {
    /// Parse a Key Material message from `bytes` (exactly the message —
    /// either a handshake extension's contents or a User-Defined control
    /// packet's CIF).
    pub fn parse(bytes: &'a [u8]) -> Result<Self> {
        need_in(bytes, FIXED_HEADER_LEN, "key material fixed header")?;
        let word0 = broadcast_core::wire::Reader::at(bytes, 0).u32("word0")?;
        let s = (word0 >> S_SHIFT) as u8;
        let v = ((word0 >> V_SHIFT) & V_MASK) as u8;
        let pt = ((word0 >> PT_SHIFT) & PT_MASK) as u8;
        let sign = ((word0 >> SIGN_SHIFT) & SIGN_MASK) as u16;
        let resv1 = ((word0 >> RESV1_SHIFT) & RESV1_MASK) as u8;
        let kk_bits = (word0 & KK_MASK) as u8;

        if s != S_FIXED {
            return Err(Error::InvalidKeyMaterial {
                field: "S",
                reason: "must be 0",
            });
        }
        if v != V_FIXED {
            return Err(Error::InvalidKeyMaterial {
                field: "V",
                reason: "must be 1",
            });
        }
        if pt != PT_KEYING_MATERIAL {
            return Err(Error::InvalidKeyMaterial {
                field: "PT",
                reason: "must be 2 (Keying Material Message)",
            });
        }
        if sign != SIGN_FIXED {
            return Err(Error::InvalidKeyMaterial {
                field: "Sign",
                reason: "must be 0x2029 ('HAI' PnP Vendor ID)",
            });
        }
        if resv1 != RESV1_FIXED {
            return Err(Error::InvalidKeyMaterial {
                field: "Resv1",
                reason: "must be 0",
            });
        }
        let kk = KmKeyFlag::from_bits(kk_bits);
        if kk == KmKeyFlag::NoSek {
            // §3.2.2: `KK` = `00b` "No SEK is provided", which the draft
            // itself calls an invalid extension format. Accepting it would
            // admit a value `serialize_into` (which needs a `KLen`-sized
            // xSEK) cannot reproduce — a parse the round-trip invariant
            // cannot honour — so it is refused here and in serialize.
            return Err(Error::InvalidKeyMaterial {
                field: "KK",
                reason: "00b (no SEK provided) is an invalid Key Material message (§3.2.2)",
            });
        }

        let keki = broadcast_core::wire::Reader::at(bytes, KEKI_OFFSET).u32("keki")?;

        let word2 = broadcast_core::wire::Reader::at(bytes, FLAGS_OFFSET).u32("word2")?;
        let cipher = Cipher::from_bits((word2 >> CIPHER_SHIFT) as u8);
        let auth = KmAuth::from_bits((word2 >> AUTH_SHIFT) as u8);
        let se = StreamEncapsulation::from_bits((word2 >> SE_SHIFT) as u8);
        let resv2 = (word2 & RESV2_MASK) as u8;
        if resv2 != RESV2_FIXED {
            return Err(Error::InvalidKeyMaterial {
                field: "Resv2",
                reason: "must be 0",
            });
        }

        let word3 = broadcast_core::wire::Reader::at(bytes, LENGTHS_OFFSET).u32("word3")?;
        let resv3 = (word3 >> RESV3_SHIFT) as u16;
        let slen4 = ((word3 >> SLEN_SHIFT) & LEN_MASK) as usize;
        let klen4 = (word3 & LEN_MASK) as usize;
        if resv3 != RESV3_FIXED {
            return Err(Error::InvalidKeyMaterial {
                field: "Resv3",
                reason: "must be 0",
            });
        }

        let slen = slen4 * KEY_BLOCK_LEN;
        let klen = klen4 * KEY_BLOCK_LEN;
        if !crate::AES_KEY_LENS.contains(&klen) {
            return Err(Error::InvalidKeyMaterial {
                field: "KLen",
                reason: "must be 16, 24, or 32 bytes (AES-128/192/256)",
            });
        }

        let mut offset = FIXED_HEADER_LEN;
        let salt = bytes
            .get(offset..offset + slen)
            .ok_or(Error::BufferTooShort(BufferTooShort::new(
                offset + slen,
                bytes.len(),
                "key material salt",
            )))?;
        offset += slen;

        let n = usize::from(kk.key_count());
        let wrap_len = ICV_LEN + n * klen;
        let wrap = bytes
            .get(offset..offset + wrap_len)
            .ok_or(Error::BufferTooShort(BufferTooShort::new(
                offset + wrap_len,
                bytes.len(),
                "key material wrap field",
            )))?;
        offset += wrap_len;

        if offset != bytes.len() {
            return Err(Error::UnexpectedTrailingBytes {
                what: "key material message",
                extra: bytes.len() - offset,
            });
        }

        let mut icv = [0u8; ICV_LEN];
        icv.copy_from_slice(&wrap[0..ICV_LEN]);
        // `KK` is not `NoSek` (refused above), so there is always an xSEK.
        let x_sek = &wrap[ICV_LEN..ICV_LEN + klen];
        let o_sek = if n == KEY_COUNT_BOTH {
            Some(&wrap[ICV_LEN + klen..ICV_LEN + n * klen])
        } else {
            None
        };

        Ok(KeyMaterial {
            kk,
            keki,
            cipher,
            auth,
            se,
            salt,
            icv,
            x_sek,
            o_sek,
        })
    }

    /// Number of bytes [`Self::serialize_into`] will write.
    pub fn serialized_len(&self) -> usize {
        FIXED_HEADER_LEN
            + self.salt.len()
            + ICV_LEN
            + self.x_sek.len()
            + self.o_sek.map_or(0, <[u8]>::len)
    }

    /// Serialize this Key Material message into `buf`.
    pub fn serialize_into(&self, buf: &mut [u8]) -> Result<usize> {
        let len = self.serialized_len();
        need_out(buf, len, "KeyMaterial")?;
        if !self.salt.len().is_multiple_of(KEY_BLOCK_LEN) {
            return Err(Error::InvalidKeyMaterial {
                field: "Salt",
                reason: "length must be a whole number of 4-byte words",
            });
        }
        // `SLen/4` is an 8-bit wire field (§3.2.2): a salt over 1020 bytes
        // would otherwise shift into the reserved `Resv3` bits, misframing
        // the message with `Ok` (#1129). Checked in `usize` before the
        // 8-bit field is packed below.
        broadcast_core::len::fit_u8(self.salt.len() / KEY_BLOCK_LEN, "Salt length / 4 (SLen)")?;
        if !crate::AES_KEY_LENS.contains(&self.x_sek.len()) {
            return Err(Error::InvalidKeyMaterial {
                field: "xSEK",
                reason: "length must be 16, 24, or 32 bytes",
            });
        }
        if self.kk == KmKeyFlag::NoSek {
            return Err(Error::InvalidKeyMaterial {
                field: "KK",
                reason: "00b (no SEK provided) is an invalid Key Material message (§3.2.2)",
            });
        }
        let expects_both = self.kk == KmKeyFlag::Both;
        match (&self.o_sek, expects_both) {
            (Some(o), true) if o.len() == self.x_sek.len() => {}
            (None, false) => {}
            _ => {
                return Err(Error::InvalidKeyMaterial {
                    field: "KK/oSEK",
                    reason: "oSEK must be present with the same length as xSEK iff KK is Both",
                });
            }
        }

        let word0 = (u32::from(S_FIXED) << S_SHIFT)
            | (u32::from(V_FIXED) << V_SHIFT)
            | (u32::from(PT_KEYING_MATERIAL) << PT_SHIFT)
            | (u32::from(SIGN_FIXED) << SIGN_SHIFT)
            | (u32::from(RESV1_FIXED) << RESV1_SHIFT)
            | u32::from(self.kk.to_bits());
        put_be32(buf, 0, word0);
        put_be32(buf, KEKI_OFFSET, self.keki);
        let word2 = (u32::from(self.cipher.to_bits()) << CIPHER_SHIFT)
            | (u32::from(self.auth.to_bits()) << AUTH_SHIFT)
            | (u32::from(self.se.to_bits()) << SE_SHIFT)
            | u32::from(RESV2_FIXED);
        put_be32(buf, FLAGS_OFFSET, word2);
        let slen4 = (self.salt.len() / KEY_BLOCK_LEN) as u32;
        let klen4 = (self.x_sek.len() / KEY_BLOCK_LEN) as u32;
        let word3 = (u32::from(RESV3_FIXED) << RESV3_SHIFT) | (slen4 << SLEN_SHIFT) | klen4;
        put_be32(buf, LENGTHS_OFFSET, word3);

        let mut off = FIXED_HEADER_LEN;
        buf[off..off + self.salt.len()].copy_from_slice(self.salt);
        off += self.salt.len();
        buf[off..off + ICV_LEN].copy_from_slice(&self.icv);
        off += ICV_LEN;
        buf[off..off + self.x_sek.len()].copy_from_slice(self.x_sek);
        off += self.x_sek.len();
        if let Some(o) = self.o_sek {
            buf[off..off + o.len()].copy_from_slice(o);
            off += o.len();
        }
        debug_assert_eq!(off, len);
        Ok(len)
    }
}

impl<'a> broadcast_core::Parse<'a> for KeyMaterial<'a> {
    type Error = crate::Error;

    fn parse(bytes: &'a [u8]) -> core::result::Result<Self, Self::Error> {
        KeyMaterial::parse(bytes)
    }
}

impl broadcast_core::Serialize for KeyMaterial<'_> {
    type Error = crate::Error;

    fn serialized_len(&self) -> usize {
        KeyMaterial::serialized_len(self)
    }

    fn serialize_into(&self, buf: &mut [u8]) -> core::result::Result<usize, Self::Error> {
        KeyMaterial::serialize_into(self, buf)
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    fn sample_even_only() -> KeyMaterial<'static> {
        KeyMaterial {
            kk: KmKeyFlag::Even,
            keki: 0,
            cipher: Cipher::AesCtr,
            auth: KmAuth::None,
            se: StreamEncapsulation::MpegTsSrt,
            salt: &[0xAA; 16],
            icv: [1, 2, 3, 4, 5, 6, 7, 8],
            x_sek: &[0xEE; 16],
            o_sek: None,
        }
    }

    #[test]
    fn round_trips_hand_computed_bytes() {
        let km = sample_even_only();
        let mut buf = alloc::vec![0u8; km.serialized_len()];
        let n = km.serialize_into(&mut buf).unwrap();
        assert_eq!(n, 16 + 16 + 8 + 16);

        // word0: S=0,V=1,PT=2,Sign=0x2029,Resv1=0,KK=01
        let expected_word0 = (1u32 << 28) | (2u32 << 24) | (0x2029u32 << 8) | 0b01u32;
        assert_eq!(&buf[0..4], &expected_word0.to_be_bytes());
        // word3: Resv3=0, SLen/4=4, KLen/4=4
        assert_eq!(&buf[12..16], &[0, 0, 4, 4]);
        assert_eq!(&buf[16..32], &[0xAAu8; 16][..]);
        assert_eq!(&buf[32..40], &[1, 2, 3, 4, 5, 6, 7, 8]);
        assert_eq!(&buf[40..56], &[0xEEu8; 16][..]);

        assert_eq!(KeyMaterial::parse(&buf).unwrap(), km);
    }

    #[test]
    fn both_keys_round_trip() {
        let km = KeyMaterial {
            kk: KmKeyFlag::Both,
            keki: 7,
            cipher: Cipher::AesCtr,
            auth: KmAuth::None,
            se: StreamEncapsulation::MpegTsSrt,
            salt: &[0; 16],
            icv: [0; 8],
            x_sek: &[1; 24],
            o_sek: Some(&[2; 24]),
        };
        let mut buf = alloc::vec![0u8; km.serialized_len()];
        km.serialize_into(&mut buf).unwrap();
        assert_eq!(KeyMaterial::parse(&buf).unwrap(), km);
    }

    #[test]
    fn no_salt_round_trips() {
        let km = KeyMaterial {
            kk: KmKeyFlag::Odd,
            keki: 0,
            cipher: Cipher::None,
            auth: KmAuth::None,
            se: StreamEncapsulation::Unspecified,
            salt: &[],
            icv: [9; 8],
            x_sek: &[3; 32],
            o_sek: None,
        };
        let mut buf = alloc::vec![0u8; km.serialized_len()];
        km.serialize_into(&mut buf).unwrap();
        assert_eq!(KeyMaterial::parse(&buf).unwrap(), km);
    }

    #[test]
    fn bad_signature_errs_without_panic() {
        let km = sample_even_only();
        let mut buf = alloc::vec![0u8; km.serialized_len()];
        km.serialize_into(&mut buf).unwrap();
        buf[1] = 0x00; // corrupt the Sign field
        assert!(matches!(
            KeyMaterial::parse(&buf),
            Err(Error::InvalidKeyMaterial { field: "Sign", .. })
        ));
    }

    #[test]
    fn inconsistent_kk_o_sek_errs() {
        let mut km = sample_even_only();
        km.o_sek = Some(&[0xEE; 16]); // KK=Even must not carry oSEK
        let mut buf = alloc::vec![0u8; 16 + 16 + 8 + 16 + 16];
        assert!(matches!(
            km.serialize_into(&mut buf),
            Err(Error::InvalidKeyMaterial { .. })
        ));
    }

    /// A salt of 1024 bytes (`SLen/4` = 256) cannot fit the 8-bit `SLen`
    /// wire field (max 255, i.e. 1020 bytes; #1129): unfixed, `(slen4 as u8)`
    /// (well, the packed `u32` word) wraps 256 to 0 and shifts into the
    /// reserved `Resv3` bits, misframing the message with `Ok`.
    #[test]
    fn oversized_salt_length_errors() {
        let salt = alloc::vec![0xAAu8; 1024];
        let km = KeyMaterial {
            kk: KmKeyFlag::Even,
            keki: 0,
            cipher: Cipher::AesCtr,
            auth: KmAuth::None,
            se: StreamEncapsulation::MpegTsSrt,
            salt: &salt,
            icv: [0; 8],
            x_sek: &[0xEE; 16],
            o_sek: None,
        };
        let mut buf = alloc::vec![0u8; km.serialized_len()];
        let err = km.serialize_into(&mut buf).unwrap_err();
        assert!(
            matches!(err, Error::FieldOverflow(e) if e.max == u64::from(u8::MAX)),
            "expected FieldOverflow(max=255) for SLen, got {err:?}"
        );
    }

    /// The boundary: exactly 1020 bytes (`SLen/4` = 255, the 8-bit max)
    /// still serializes and round-trips.
    #[test]
    fn max_salt_length_round_trips() {
        let salt = alloc::vec![0xAAu8; 1020];
        let km = KeyMaterial {
            kk: KmKeyFlag::Even,
            keki: 0,
            cipher: Cipher::AesCtr,
            auth: KmAuth::None,
            se: StreamEncapsulation::MpegTsSrt,
            salt: &salt,
            icv: [0; 8],
            x_sek: &[0xEE; 16],
            o_sek: None,
        };
        let mut buf = alloc::vec![0u8; km.serialized_len()];
        km.serialize_into(&mut buf).unwrap();
        let parsed = KeyMaterial::parse(&buf).unwrap();
        assert_eq!(parsed.salt, salt.as_slice());
    }

    /// r08-SRT-W13: `KK = 00b` ("no SEK provided", which §3.2.2 calls an
    /// invalid format) used to parse to an empty xSEK that `serialize_into`
    /// then refused — a parsed value that could not be re-serialized. It is
    /// now refused at both ends, so no such value exists.
    #[test]
    fn kk_no_sek_is_refused_by_parse_and_serialize() {
        let mut buf = alloc::vec![0u8; sample_even_only().serialized_len()];
        sample_even_only().serialize_into(&mut buf).unwrap();
        // Rewrite `KK` (low 2 bits of word 0) to 00b; keep the 16-byte xSEK so
        // only the flag is wrong.
        buf[3] &= !0b11;
        assert!(matches!(
            KeyMaterial::parse(&buf),
            Err(Error::InvalidKeyMaterial { field: "KK", .. })
        ));
        // The same, with no xSEK bytes at all (the shape the old parser
        // accepted): truncate to header + salt + ICV.
        let short = &buf[..16 + 16 + 8];
        assert!(matches!(
            KeyMaterial::parse(short),
            Err(Error::InvalidKeyMaterial { field: "KK", .. })
        ));

        let mut km = sample_even_only();
        km.kk = KmKeyFlag::NoSek;
        let mut out = alloc::vec![0u8; km.serialized_len()];
        assert!(matches!(
            km.serialize_into(&mut out),
            Err(Error::InvalidKeyMaterial { field: "KK", .. })
        ));
    }

    /// Every message `parse` accepts re-serializes byte-identically (the
    /// symmetry the NoSek case broke), over all `KK` values and key lengths.
    #[test]
    fn every_accepted_message_reserializes_byte_identically() {
        for kk in [KmKeyFlag::Even, KmKeyFlag::Odd, KmKeyFlag::Both] {
            for klen in [16usize, 24, 32] {
                let x = alloc::vec![0x5Au8; klen];
                let o = alloc::vec![0xA5u8; klen];
                let km = KeyMaterial {
                    kk,
                    keki: 3,
                    cipher: Cipher::AesCtr,
                    auth: KmAuth::None,
                    se: StreamEncapsulation::MpegTsSrt,
                    salt: &[7u8; 16],
                    icv: [9; 8],
                    x_sek: &x,
                    o_sek: (kk == KmKeyFlag::Both).then_some(o.as_slice()),
                };
                let mut wire = alloc::vec![0u8; km.serialized_len()];
                km.serialize_into(&mut wire).unwrap();
                let parsed = KeyMaterial::parse(&wire).unwrap();
                let mut again = alloc::vec![0u8; parsed.serialized_len()];
                parsed.serialize_into(&mut again).unwrap();
                assert_eq!(again, wire, "kk={kk:?} klen={klen}");
            }
        }
    }

    /// #1142: `{:?}` of a Key Material message shows the lengths of the wrapped
    /// keys and ICV, never their bytes (with the salt they permit an offline
    /// passphrase attack).
    #[test]
    fn debug_output_redacts_wrapped_keys() {
        let km = KeyMaterial {
            kk: KmKeyFlag::Both,
            keki: 0,
            cipher: Cipher::AesCtr,
            auth: KmAuth::None,
            se: StreamEncapsulation::MpegTsSrt,
            salt: &[0xAA; 16],
            icv: [0xBB; 8],
            x_sek: &[0xEE; 16],
            o_sek: Some(&[0xDD; 16]),
        };
        for dump in [alloc::format!("{km:?}"), alloc::format!("{km:#?}")] {
            for needle in ["238", "187", "221", "170", "0xee", "ee,"] {
                assert!(!dump.contains(needle), "{needle:?} leaked: {dump}");
            }
            assert!(
                dump.contains("x_sek: <redacted, 16 bytes>")
                    || dump.contains("x_sek: <redacted, 16 bytes>,"),
                "{dump}"
            );
            assert!(dump.contains("o_sek: <redacted, 16 bytes>"), "{dump}");
        }
    }

    /// Strings a leak of `bytes` would contain, in every form a `Debug` dump,
    /// `{:x?}` dump or JSON array would print them (the first six bytes are a
    /// long enough run to be unambiguous).
    fn needles(bytes: &[u8]) -> alloc::vec::Vec<alloc::string::String> {
        let head = &bytes[..6];
        let join = |sep: &str| {
            head.iter()
                .map(|b| alloc::format!("{b}"))
                .collect::<alloc::vec::Vec<_>>()
                .join(sep)
        };
        alloc::vec![
            join(", "),
            join(","),
            head.iter()
                .map(|b| alloc::format!("{b:x}"))
                .collect::<alloc::vec::Vec<_>>()
                .join(", "),
            head.iter().map(|b| alloc::format!("{b:02x}")).collect(),
        ]
    }

    /// Distinctive, non-repeating key material (a fixed pseudo-random run, so
    /// the needle cannot occur by chance in unrelated numbers).
    fn distinctive(seed: u8, len: usize) -> alloc::vec::Vec<u8> {
        let mut x = u32::from(seed)
            .wrapping_mul(2_654_435_761)
            .wrapping_add(12_345);
        (0..len)
            .map(|_| {
                x = x.wrapping_mul(1_664_525).wrapping_add(1_013_904_223);
                u8::try_from(x >> 24).unwrap()
            })
            .collect()
    }

    /// #1142: neither `Debug` nor serde output carries the salt, the ICV or
    /// either wrapped key.
    #[test]
    fn debug_and_serde_output_carry_no_key_bytes() {
        let salt = distinctive(1, 16);
        let x = distinctive(2, 32);
        let o = distinctive(3, 32);
        let icv: [u8; 8] = distinctive(4, 8).try_into().unwrap();
        let km = KeyMaterial {
            kk: KmKeyFlag::Both,
            keki: 0,
            cipher: Cipher::AesCtr,
            auth: KmAuth::None,
            se: StreamEncapsulation::MpegTsSrt,
            salt: &salt,
            icv,
            x_sek: &x,
            o_sek: Some(&o),
        };
        #[cfg(feature = "serde")]
        let json: Option<alloc::string::String> = {
            let json = serde_json::to_string(&km).expect("serialize");
            assert!(
                json.contains("kk"),
                "the non-secret fields are still serialized"
            );
            Some(json)
        };
        #[cfg(not(feature = "serde"))]
        let json: Option<alloc::string::String> = None;
        let dumps: alloc::vec::Vec<alloc::string::String> = [
            alloc::format!("{km:?}"),
            alloc::format!("{km:#?}"),
            alloc::format!("{km:x?}"),
        ]
        .into_iter()
        .chain(json)
        .collect();
        for (name, secret) in [
            ("salt", &salt[..]),
            ("icv", &icv[..]),
            ("x_sek", &x[..]),
            ("o_sek", &o[..]),
        ] {
            for needle in needles(secret) {
                for dump in &dumps {
                    assert!(
                        !dump.contains(&needle),
                        "{name} leaked as {needle:?} in {dump}"
                    );
                }
            }
        }
    }

    fn serialized(km: &KeyMaterial<'_>) -> alloc::vec::Vec<u8> {
        let mut buf = alloc::vec![0u8; km.serialized_len()];
        km.serialize_into(&mut buf).unwrap();
        buf
    }

    /// Each fixed-value field is checked by its own shift: a set `S` or
    /// `Resv3` bit must be rejected naming that field.
    #[test]
    fn fixed_fields_are_checked_by_their_owned_bits() {
        let km = sample_even_only();
        let mut buf = serialized(&km);
        buf[0] |= 0x80; // S = 1
        assert!(matches!(
            KeyMaterial::parse(&buf),
            Err(Error::InvalidKeyMaterial { field: "S", .. })
        ));

        let mut buf = serialized(&km);
        buf[12] = 0x01; // Resv3 = 1
        assert!(matches!(
            KeyMaterial::parse(&buf),
            Err(Error::InvalidKeyMaterial { field: "Resv3", .. })
        ));
    }

    /// A truncated salt reports the exact byte count it needs (header + the
    /// announced salt), not a product of the two.
    #[test]
    fn truncated_salt_reports_the_exact_need() {
        let buf = serialized(&sample_even_only());
        match KeyMaterial::parse(&buf[..20]) {
            Err(Error::BufferTooShort(b)) => {
                assert_eq!(b.need, 32);
                assert_eq!(b.have, 20);
            }
            other => panic!("expected BufferTooShort, got {other:?}"),
        }
    }

    /// A truncated wrap field reports the exact byte count it needs.
    #[test]
    fn truncated_wrap_field_reports_the_exact_need() {
        let buf = serialized(&sample_even_only());
        match KeyMaterial::parse(&buf[..40]) {
            Err(Error::BufferTooShort(b)) => {
                assert_eq!(b.need, 56);
                assert_eq!(b.have, 40);
            }
            other => panic!("expected BufferTooShort, got {other:?}"),
        }
    }

    /// Trailing bytes report the exact number left past the message.
    #[test]
    fn trailing_bytes_report_the_exact_extra_count() {
        let mut buf = serialized(&sample_even_only());
        buf.extend_from_slice(&[0xAA, 0xBB]);
        match KeyMaterial::parse(&buf) {
            Err(Error::UnexpectedTrailingBytes { extra, .. }) => assert_eq!(extra, 2),
            other => panic!("expected UnexpectedTrailingBytes, got {other:?}"),
        }
    }
}