Skip to main content

gemini_adk_fluent_rs/telephony/
srtp.rs

1//! SRTP (RFC 3711) for SIP media, keyed by SDES (RFC 4568).
2//!
3//! *(feature `sip`)* A SIP trunk or softphone that offers `RTP/SAVP` with an
4//! `a=crypto` line sends its media encrypted and authenticated. This module
5//! is the packet layer: [`SrtpSession::protect`] turns an RTP packet into an
6//! SRTP packet, and [`SrtpSession::unprotect`] checks and decrypts one.
7//! [`CryptoAttribute`] parses and prints the SDP line that carries the keys.
8//!
9//! Supported: the `AES_CM_128_HMAC_SHA1_80` and `AES_CM_128_HMAC_SHA1_32`
10//! suites (the ones every SDES endpoint implements), a key derivation rate
11//! of zero, and no MKI. SRTCP is not implemented, since the agent does not
12//! send RTCP; an offer is answered for RTP only.
13//!
14//! SDES sends the keys in the SDP body, so they are only as secret as the
15//! signalling. Use SIP over TLS when the keys must not be readable on the
16//! network path.
17
18use std::collections::HashMap;
19use std::fmt;
20
21use aes::Aes128;
22use aes::cipher::{Block, BlockCipherEncrypt, KeyInit};
23use base64::Engine as _;
24use hmac::{Hmac, Mac};
25use sha1::Sha1;
26
27type HmacSha1 = Hmac<Sha1>;
28
29/// HMAC-SHA1 keyed with the session's authentication key.
30///
31/// HMAC zero-pads a key shorter than the hash's block size, so the key is
32/// handed over already padded to one full block. `Mac::new` takes exactly
33/// a block and has no length to reject, where `new_from_slice` returns a
34/// `Result` that can never be an error for HMAC.
35fn auth_mac(key: &[u8; AUTH_KEY_LEN]) -> HmacSha1 {
36    let mut block = hmac::digest::Key::<HmacSha1>::default();
37    block[..AUTH_KEY_LEN].copy_from_slice(key);
38    <HmacSha1 as hmac::digest::KeyInit>::new(&block)
39}
40
41const MASTER_KEY_LEN: usize = 16;
42const MASTER_SALT_LEN: usize = 14;
43const AUTH_KEY_LEN: usize = 20;
44/// Packets this far behind the newest one are rejected as possible replays.
45const REPLAY_WINDOW: u64 = 64;
46
47/// An SRTP crypto suite.
48#[derive(Debug, Clone, Copy, PartialEq, Eq)]
49#[non_exhaustive]
50pub enum SrtpSuite {
51    /// AES-128 counter mode, HMAC-SHA1 with an 80-bit tag.
52    AesCm128HmacSha1_80,
53    /// AES-128 counter mode, HMAC-SHA1 with a 32-bit tag.
54    AesCm128HmacSha1_32,
55}
56
57impl SrtpSuite {
58    /// The suite's SDP name.
59    pub fn name(self) -> &'static str {
60        match self {
61            Self::AesCm128HmacSha1_80 => "AES_CM_128_HMAC_SHA1_80",
62            Self::AesCm128HmacSha1_32 => "AES_CM_128_HMAC_SHA1_32",
63        }
64    }
65
66    /// The suite named `name` in SDP, when supported.
67    pub fn from_name(name: &str) -> Option<Self> {
68        match name {
69            "AES_CM_128_HMAC_SHA1_80" => Some(Self::AesCm128HmacSha1_80),
70            "AES_CM_128_HMAC_SHA1_32" => Some(Self::AesCm128HmacSha1_32),
71            _ => None,
72        }
73    }
74
75    /// Bytes of authentication tag appended to each packet.
76    pub fn tag_len(self) -> usize {
77        match self {
78            Self::AesCm128HmacSha1_80 => 10,
79            Self::AesCm128HmacSha1_32 => 4,
80        }
81    }
82}
83
84/// A master key and salt, from which the session keys are derived.
85#[derive(Clone, PartialEq, Eq)]
86pub struct MasterKey {
87    key: [u8; MASTER_KEY_LEN],
88    salt: [u8; MASTER_SALT_LEN],
89}
90
91impl MasterKey {
92    /// A key and salt from their bytes.
93    pub fn new(key: [u8; MASTER_KEY_LEN], salt: [u8; MASTER_SALT_LEN]) -> Self {
94        Self { key, salt }
95    }
96
97    /// A fresh random key and salt from the operating system's generator.
98    pub fn generate() -> std::io::Result<Self> {
99        let mut bytes = [0u8; MASTER_KEY_LEN + MASTER_SALT_LEN];
100        getrandom::fill(&mut bytes).map_err(std::io::Error::other)?;
101        Self::from_bytes(&bytes).ok_or_else(|| {
102            std::io::Error::other("generated key material is not a master key and salt long")
103        })
104    }
105
106    fn from_bytes(bytes: &[u8]) -> Option<Self> {
107        if bytes.len() != MASTER_KEY_LEN + MASTER_SALT_LEN {
108            return None;
109        }
110        Some(Self {
111            key: bytes[..MASTER_KEY_LEN].try_into().ok()?,
112            salt: bytes[MASTER_KEY_LEN..].try_into().ok()?,
113        })
114    }
115
116    /// The SDES `inline:` key parameter: base64 of key then salt.
117    pub fn to_inline(&self) -> String {
118        let mut bytes = Vec::with_capacity(MASTER_KEY_LEN + MASTER_SALT_LEN);
119        bytes.extend_from_slice(&self.key);
120        bytes.extend_from_slice(&self.salt);
121        base64::engine::general_purpose::STANDARD.encode(bytes)
122    }
123
124    /// Parse an SDES `inline:` key parameter (with or without the prefix).
125    /// A lifetime (`|2^31`) is accepted and ignored; an MKI (`|1:4`) is not
126    /// supported and fails the parse.
127    pub fn from_inline(inline: &str) -> Option<Self> {
128        let inline = inline.strip_prefix("inline:").unwrap_or(inline);
129        let mut parts = inline.split('|');
130        let key = parts.next()?;
131        for part in parts {
132            if part.contains(':') {
133                return None; // an MKI
134            }
135        }
136        let bytes = base64::engine::general_purpose::STANDARD.decode(key).ok()?;
137        Self::from_bytes(&bytes)
138    }
139}
140
141impl fmt::Debug for MasterKey {
142    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
143        f.write_str("MasterKey([redacted])")
144    }
145}
146
147/// An SDES `a=crypto` attribute (RFC 4568).
148#[derive(Debug, Clone, PartialEq, Eq)]
149pub struct CryptoAttribute {
150    /// The attribute's tag, echoed in the answer.
151    pub tag: u32,
152    /// The crypto suite.
153    pub suite: SrtpSuite,
154    /// The sender's master key.
155    pub key: MasterKey,
156}
157
158impl CryptoAttribute {
159    /// Parse the value of an `a=crypto:` line, e.g.
160    /// `1 AES_CM_128_HMAC_SHA1_80 inline:WVNfX19zZW...`. `None` for an
161    /// unsupported suite, key form or session parameter.
162    pub fn parse(value: &str) -> Option<Self> {
163        let value = value.strip_prefix("a=crypto:").unwrap_or(value);
164        let mut parts = value.split_whitespace();
165        let tag = parts.next()?.parse().ok()?;
166        let suite = SrtpSuite::from_name(parts.next()?)?;
167        let key_params = parts.next()?;
168        // One key only: several `;`-joined keys need an MKI to tell apart.
169        if key_params.contains(';') {
170            return None;
171        }
172        let key = MasterKey::from_inline(key_params)?;
173        // Session parameters (UNENCRYPTED_SRTP, KDR=.., ...) change the
174        // transform; none is supported.
175        if parts.next().is_some() {
176            return None;
177        }
178        Some(Self { tag, suite, key })
179    }
180
181    /// The attribute's value, for an `a=crypto:` line.
182    pub fn to_value(&self) -> String {
183        format!(
184            "{} {} inline:{}",
185            self.tag,
186            self.suite.name(),
187            self.key.to_inline()
188        )
189    }
190}
191
192/// Why a packet failed [`SrtpSession::unprotect`].
193#[derive(Debug, Clone, Copy, PartialEq, Eq)]
194#[non_exhaustive]
195pub enum SrtpError {
196    /// Too short, or not an RTP version 2 header.
197    Malformed,
198    /// The authentication tag does not match: altered, or keyed differently.
199    AuthenticationFailed,
200    /// This packet was already received, or is too old to tell.
201    Replayed,
202}
203
204impl fmt::Display for SrtpError {
205    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
206        f.write_str(match self {
207            Self::Malformed => "malformed SRTP packet",
208            Self::AuthenticationFailed => "SRTP authentication failed",
209            Self::Replayed => "replayed SRTP packet",
210        })
211    }
212}
213
214impl std::error::Error for SrtpError {}
215
216/// Keys derived from a master key (RFC 3711 §4.3, key derivation rate 0).
217struct SessionKeys {
218    cipher_key: [u8; MASTER_KEY_LEN],
219    salt: [u8; MASTER_SALT_LEN],
220    auth_key: [u8; AUTH_KEY_LEN],
221}
222
223impl SessionKeys {
224    fn derive(master: &MasterKey) -> Self {
225        Self {
226            cipher_key: derive(master, 0x00),
227            auth_key: derive(master, 0x01),
228            salt: derive(master, 0x02),
229        }
230    }
231}
232
233/// The AES-CM PRF over `x = label XOR master salt`, index 0: the first `N`
234/// bytes of the keystream whose block `i` is `E(key, x * 2^16 + i)`.
235fn derive<const N: usize>(master: &MasterKey, label: u8) -> [u8; N] {
236    let cipher = Aes128::new(&master.key.into());
237    let blocks: Vec<[u8; 16]> = (0..N.div_ceil(16))
238        .map(|i| {
239            let counter: [u8; 16] = std::array::from_fn(|j| match j {
240                7 => master.salt[j] ^ label,
241                j if j < MASTER_SALT_LEN => master.salt[j],
242                14 => (i >> 8) as u8,
243                _ => i as u8,
244            });
245            let mut block = Block::<Aes128>::from(counter);
246            cipher.encrypt_block(&mut block);
247            block.into()
248        })
249        .collect();
250    std::array::from_fn(|k| blocks[k / 16][k % 16])
251}
252
253/// Receive-side state of one SSRC.
254#[derive(Default)]
255struct Inbound {
256    roc: u32,
257    highest_seq: u16,
258    /// Newest accepted packet index, and which of the 64 before it arrived.
259    newest: u64,
260    seen: u64,
261}
262
263/// Send-side state of one SSRC.
264#[derive(Default)]
265struct Outbound {
266    roc: u32,
267    last_seq: Option<u16>,
268}
269
270/// One direction of an SRTP stream: protect what you send with your key,
271/// unprotect what you receive with the peer's.
272pub struct SrtpSession {
273    suite: SrtpSuite,
274    keys: SessionKeys,
275    cipher: Aes128,
276    outbound: HashMap<u32, Outbound>,
277    inbound: HashMap<u32, Inbound>,
278}
279
280impl fmt::Debug for SrtpSession {
281    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
282        f.debug_struct("SrtpSession")
283            .field("suite", &self.suite)
284            .finish_non_exhaustive()
285    }
286}
287
288impl SrtpSession {
289    /// A session keyed by `key`.
290    pub fn new(suite: SrtpSuite, key: &MasterKey) -> Self {
291        let keys = SessionKeys::derive(key);
292        let cipher = Aes128::new(&keys.cipher_key.into());
293        Self {
294            suite,
295            keys,
296            cipher,
297            outbound: HashMap::new(),
298            inbound: HashMap::new(),
299        }
300    }
301
302    /// Encrypt and authenticate an RTP packet. `None` when `rtp` is not an
303    /// RTP packet.
304    pub fn protect(&mut self, rtp: &[u8]) -> Option<Vec<u8>> {
305        let header = header_len(rtp)?;
306        let (seq, ssrc) = seq_ssrc(rtp);
307        let state = self.outbound.entry(ssrc).or_default();
308        if let Some(last) = state.last_seq
309            && seq < last
310            && last - seq > 0x8000
311        {
312            state.roc = state.roc.wrapping_add(1);
313        }
314        state.last_seq = Some(seq);
315        let roc = state.roc;
316        let index = (u64::from(roc) << 16) | u64::from(seq);
317
318        let mut packet = rtp.to_vec();
319        self.keystream(ssrc, index, &mut packet[header..]);
320        let tag = self.tag(&packet, roc);
321        packet.extend_from_slice(&tag[..self.suite.tag_len()]);
322        Some(packet)
323    }
324
325    /// Authenticate and decrypt an SRTP packet back to RTP.
326    pub fn unprotect(&mut self, srtp: &[u8]) -> Result<Vec<u8>, SrtpError> {
327        let tag_len = self.suite.tag_len();
328        if srtp.len() < tag_len {
329            return Err(SrtpError::Malformed);
330        }
331        let (authenticated, tag) = srtp.split_at(srtp.len() - tag_len);
332        let header = header_len(authenticated).ok_or(SrtpError::Malformed)?;
333        let (seq, ssrc) = seq_ssrc(authenticated);
334
335        let (roc, index) = match self.inbound.get(&ssrc) {
336            Some(state) => {
337                let roc = estimate_roc(state.roc, state.highest_seq, seq);
338                let index = (u64::from(roc) << 16) | u64::from(seq);
339                if is_replay(state, index) {
340                    return Err(SrtpError::Replayed);
341                }
342                (roc, index)
343            }
344            None => (0, u64::from(seq)),
345        };
346
347        let mut mac = auth_mac(&self.keys.auth_key);
348        mac.update(authenticated);
349        mac.update(&roc.to_be_bytes());
350        mac.verify_truncated_left(tag)
351            .map_err(|_| SrtpError::AuthenticationFailed)?;
352
353        let mut packet = authenticated.to_vec();
354        self.keystream(ssrc, index, &mut packet[header..]);
355        self.accept(ssrc, roc, seq, index);
356        Ok(packet)
357    }
358
359    /// Record an authenticated packet: advance the rollover counter and the
360    /// replay window.
361    fn accept(&mut self, ssrc: u32, roc: u32, seq: u16, index: u64) {
362        let state = self.inbound.entry(ssrc).or_insert_with(|| Inbound {
363            roc,
364            highest_seq: seq,
365            newest: index,
366            seen: 0,
367        });
368        if index > state.newest {
369            let shift = index - state.newest;
370            state.seen = if shift >= REPLAY_WINDOW {
371                0
372            } else {
373                state.seen << shift
374            };
375            state.newest = index;
376            state.roc = roc;
377            state.highest_seq = seq;
378        }
379        let behind = state.newest - index;
380        state.seen |= 1 << behind;
381    }
382
383    /// XOR the AES-CM keystream for packet `index` of `ssrc` into `data`.
384    fn keystream(&self, ssrc: u32, index: u64, data: &mut [u8]) {
385        let mut counter = [0u8; 16];
386        counter[..MASTER_SALT_LEN].copy_from_slice(&self.keys.salt);
387        for (i, b) in ssrc.to_be_bytes().iter().enumerate() {
388            counter[4 + i] ^= b;
389        }
390        for (i, b) in index.to_be_bytes()[2..].iter().enumerate() {
391            counter[8 + i] ^= b;
392        }
393        for chunk in data.chunks_mut(16) {
394            let mut block = Block::<Aes128>::from(counter);
395            self.cipher.encrypt_block(&mut block);
396            for (d, k) in chunk.iter_mut().zip(block.iter()) {
397                *d ^= k;
398            }
399            let next = u16::from_be_bytes([counter[14], counter[15]]).wrapping_add(1);
400            counter[14..].copy_from_slice(&next.to_be_bytes());
401        }
402    }
403
404    fn tag(&self, authenticated: &[u8], roc: u32) -> [u8; 20] {
405        let mut mac = auth_mac(&self.keys.auth_key);
406        mac.update(authenticated);
407        mac.update(&roc.to_be_bytes());
408        mac.finalize().into_bytes().into()
409    }
410}
411
412/// The RTP header's length, including CSRCs and an extension.
413fn header_len(packet: &[u8]) -> Option<usize> {
414    if packet.len() < 12 || packet[0] >> 6 != 2 {
415        return None;
416    }
417    let mut len = 12 + usize::from(packet[0] & 0x0F) * 4;
418    if packet[0] & 0x10 != 0 {
419        let words = packet.get(len + 2..len + 4)?;
420        len += 4 + usize::from(u16::from_be_bytes([words[0], words[1]])) * 4;
421    }
422    (len <= packet.len()).then_some(len)
423}
424
425fn seq_ssrc(packet: &[u8]) -> (u16, u32) {
426    (
427        u16::from_be_bytes([packet[2], packet[3]]),
428        u32::from_be_bytes([packet[8], packet[9], packet[10], packet[11]]),
429    )
430}
431
432/// The rollover counter a packet with `seq` most likely belongs to
433/// (RFC 3711 §3.3.1).
434fn estimate_roc(roc: u32, highest: u16, seq: u16) -> u32 {
435    if highest < 0x8000 {
436        if seq > highest && seq - highest > 0x8000 {
437            roc.wrapping_sub(1)
438        } else {
439            roc
440        }
441    } else if highest - 0x8000 > seq {
442        roc.wrapping_add(1)
443    } else {
444        roc
445    }
446}
447
448fn is_replay(state: &Inbound, index: u64) -> bool {
449    if index > state.newest {
450        return false;
451    }
452    let behind = state.newest - index;
453    behind >= REPLAY_WINDOW || state.seen & (1 << behind) != 0
454}
455
456#[cfg(test)]
457mod tests {
458    use super::*;
459
460    fn hex(s: &str) -> Vec<u8> {
461        let s: String = s.split_whitespace().collect();
462        (0..s.len())
463            .step_by(2)
464            .map(|i| u8::from_str_radix(&s[i..i + 2], 16).unwrap())
465            .collect()
466    }
467
468    fn rfc_master() -> MasterKey {
469        let bytes = hex("E1F97A0D3E018BE0D64FA32C06DE4139 0EC675AD498AFEEBB6960B3AABE6");
470        MasterKey::from_bytes(&bytes).unwrap()
471    }
472
473    /// The padded-block construction is HMAC keyed by the bare 20-byte key.
474    #[test]
475    fn auth_mac_matches_hmac_keyed_by_the_bare_key() {
476        let key: [u8; AUTH_KEY_LEN] = hex("CEBE321F6FF7716B6FD4AB49AF256A156D38BAA4")
477            .try_into()
478            .unwrap();
479        let mut padded = auth_mac(&key);
480        padded.update(b"authenticated portion");
481        let mut bare = <HmacSha1 as hmac::digest::KeyInit>::new_from_slice(&key).unwrap();
482        bare.update(b"authenticated portion");
483        assert_eq!(padded.finalize().into_bytes(), bare.finalize().into_bytes());
484    }
485
486    /// RFC 3711 Appendix B.3.
487    #[test]
488    fn key_derivation_matches_rfc_3711() {
489        let keys = SessionKeys::derive(&rfc_master());
490        assert_eq!(
491            keys.cipher_key.to_vec(),
492            hex("C61E7A93744F39EE10734AFE3FF7A087")
493        );
494        assert_eq!(keys.salt.to_vec(), hex("30CBBC08863D8C85D49DB34A9AE1"));
495        assert_eq!(
496            keys.auth_key.to_vec(),
497            hex("CEBE321F6FF7716B6FD4AB49AF256A156D38BAA4")
498        );
499    }
500
501    /// RFC 3711 Appendix B.2: the AES-CM keystream for SSRC 0, index 0.
502    #[test]
503    fn keystream_matches_rfc_3711() {
504        let key: [u8; 16] = hex("2B7E151628AED2A6ABF7158809CF4F3C").try_into().unwrap();
505        let salt: [u8; 14] = hex("F0F1F2F3F4F5F6F7F8F9FAFBFCFD").try_into().unwrap();
506        let session = SrtpSession {
507            suite: SrtpSuite::AesCm128HmacSha1_80,
508            keys: SessionKeys {
509                cipher_key: key,
510                salt,
511                auth_key: [0; AUTH_KEY_LEN],
512            },
513            cipher: Aes128::new(&key.into()),
514            outbound: HashMap::new(),
515            inbound: HashMap::new(),
516        };
517        let mut stream = [0u8; 48];
518        session.keystream(0, 0, &mut stream);
519        assert_eq!(
520            stream.to_vec(),
521            hex("E03EAD0935C95E80E166B16DD92B4EB4 \
522                 D23513162B02D0F72A43A2FE4A5F97AB \
523                 41E95B3BB0A2E8DD477901E4FCA894C0")
524        );
525    }
526
527    /// The reference packet of libsrtp's test driver: SSRC 0xCAFEBABE,
528    /// sequence 0x1234, sixteen bytes of 0xAB.
529    #[test]
530    fn protects_the_reference_packet() {
531        let plain = hex("800f1234 decafbad cafebabe abababab abababab abababab abababab");
532        let expected = hex(
533            "800f1234 decafbad cafebabe 4e55dc4c e79978d8 8ca4d215 949d2402 \
534             b78d6acc 99ea179b 8dbb",
535        );
536        let mut sender = SrtpSession::new(SrtpSuite::AesCm128HmacSha1_80, &rfc_master());
537        assert_eq!(sender.protect(&plain).unwrap(), expected);
538
539        let mut receiver = SrtpSession::new(SrtpSuite::AesCm128HmacSha1_80, &rfc_master());
540        assert_eq!(receiver.unprotect(&expected).unwrap(), plain);
541    }
542
543    fn rtp(seq: u16, payload: &[u8]) -> Vec<u8> {
544        let mut packet = vec![0x80, 0x00];
545        packet.extend_from_slice(&seq.to_be_bytes());
546        packet.extend_from_slice(&[0, 0, 0, 160]);
547        packet.extend_from_slice(&0x1234_5678u32.to_be_bytes());
548        packet.extend_from_slice(payload);
549        packet
550    }
551
552    #[test]
553    fn a_tampered_or_replayed_packet_is_refused() {
554        let key = MasterKey::generate().unwrap();
555        for suite in [
556            SrtpSuite::AesCm128HmacSha1_80,
557            SrtpSuite::AesCm128HmacSha1_32,
558        ] {
559            let mut tx = SrtpSession::new(suite, &key);
560            let mut rx = SrtpSession::new(suite, &key);
561            let packet = tx.protect(&rtp(7, b"hello")).unwrap();
562            assert_eq!(packet.len(), 12 + 5 + suite.tag_len());
563            assert_ne!(&packet[12..17], b"hello", "the payload is encrypted");
564
565            let mut tampered = packet.clone();
566            tampered[13] ^= 1;
567            assert_eq!(
568                rx.unprotect(&tampered),
569                Err(SrtpError::AuthenticationFailed)
570            );
571
572            assert_eq!(rx.unprotect(&packet).unwrap(), rtp(7, b"hello"));
573            assert_eq!(rx.unprotect(&packet), Err(SrtpError::Replayed));
574
575            let other =
576                SrtpSession::new(suite, &MasterKey::generate().unwrap()).protect(&rtp(8, b"x"));
577            assert_eq!(
578                rx.unprotect(&other.unwrap()),
579                Err(SrtpError::AuthenticationFailed),
580                "a packet under another key"
581            );
582        }
583    }
584
585    #[test]
586    fn the_rollover_counter_follows_a_sequence_wrap() {
587        let key = MasterKey::generate().unwrap();
588        let suite = SrtpSuite::AesCm128HmacSha1_80;
589        let mut tx = SrtpSession::new(suite, &key);
590        let mut rx = SrtpSession::new(suite, &key);
591        let mut seq: u16 = 65_530;
592        for n in 0..20u8 {
593            let packet = tx.protect(&rtp(seq, &[n; 4])).unwrap();
594            assert_eq!(
595                rx.unprotect(&packet).unwrap(),
596                rtp(seq, &[n; 4]),
597                "seq {seq}"
598            );
599            seq = seq.wrapping_add(1);
600        }
601        assert_eq!(tx.outbound[&0x1234_5678].roc, 1);
602        assert_eq!(rx.inbound[&0x1234_5678].roc, 1);
603
604        // A packet from before the wrap that arrives after it still
605        // authenticates, under the previous rollover count.
606        let mut tx = SrtpSession::new(suite, &key);
607        let mut rx = SrtpSession::new(suite, &key);
608        let early = tx.protect(&rtp(65_534, b"a")).unwrap();
609        let late = tx.protect(&rtp(65_535, b"b")).unwrap();
610        let wrapped = tx.protect(&rtp(0, b"c")).unwrap();
611        assert!(rx.unprotect(&early).is_ok());
612        assert!(rx.unprotect(&wrapped).is_ok());
613        assert_eq!(rx.unprotect(&late).unwrap(), rtp(65_535, b"b"));
614        assert_eq!(rx.unprotect(&late), Err(SrtpError::Replayed));
615    }
616
617    #[test]
618    fn a_crypto_line_round_trips() {
619        let line = "1 AES_CM_128_HMAC_SHA1_80 inline:4fl6DT4Bi+DWT6MsBt5BOQ7Gda1Jiv7rtpYLOqvm|2^20";
620        let attribute = CryptoAttribute::parse(line).unwrap();
621        assert_eq!(attribute.tag, 1);
622        assert_eq!(attribute.suite, SrtpSuite::AesCm128HmacSha1_80);
623        assert_eq!(attribute.key, rfc_master());
624        assert_eq!(
625            CryptoAttribute::parse(&attribute.to_value()).unwrap(),
626            attribute
627        );
628        assert!(
629            !format!("{attribute:?}").contains("4fl6DT4B"),
630            "keys never print"
631        );
632
633        assert_eq!(
634            CryptoAttribute::parse(
635                "1 F8_128_HMAC_SHA1_80 inline:4fl6DT4Bi+DWT6MsBt5BOQ7Gda1Jiv7rtpYLOqvm"
636            ),
637            None
638        );
639        assert_eq!(
640            CryptoAttribute::parse(
641                "1 AES_CM_128_HMAC_SHA1_80 inline:4fl6DT4Bi+DWT6MsBt5BOQ7Gda1Jiv7rtpYLOqvm|2^20|1:4"
642            ),
643            None,
644            "an MKI"
645        );
646        assert_eq!(
647            CryptoAttribute::parse(
648                "1 AES_CM_128_HMAC_SHA1_80 inline:4fl6DT4Bi+DWT6MsBt5BOQ7Gda1Jiv7rtpYLOqvm KDR=1"
649            ),
650            None,
651            "a session parameter"
652        );
653    }
654}