s2n_quic_core/packet/
key_phase.rs

1// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
2// SPDX-License-Identifier: Apache-2.0
3
4use super::Tag;
5use crate::event::IntoEvent;
6
7//= https://www.rfc-editor.org/rfc/rfc9000#section-17.3.1
8//# Key Phase:  The next bit (0x04) of byte 0 indicates the key phase,
9//# which allows a recipient of a packet to identify the packet
10//# protection keys that are used to protect the packet.
11
12const KEY_PHASE_MASK: u8 = 0x04;
13
14#[derive(Clone, Copy, Debug, PartialEq)]
15pub struct ProtectedKeyPhase;
16
17#[derive(Clone, Copy, Debug, PartialEq)]
18#[cfg_attr(
19    any(test, feature = "bolero-generator"),
20    derive(bolero_generator::TypeGenerator)
21)]
22pub enum KeyPhase {
23    Zero,
24    One,
25}
26
27impl Default for KeyPhase {
28    #[inline]
29    fn default() -> Self {
30        Self::Zero
31    }
32}
33
34const PHASES: [KeyPhase; 2] = [KeyPhase::Zero, KeyPhase::One];
35impl From<u8> for KeyPhase {
36    #[inline]
37    fn from(v: u8) -> Self {
38        // Will only be 0 or 1. Invalid phases may result in a failed decryption, still in constant
39        // time.
40        PHASES[(v & 0x01) as usize]
41    }
42}
43
44impl KeyPhase {
45    #[inline]
46    pub fn from_tag(tag: Tag) -> Self {
47        let phase = (tag & KEY_PHASE_MASK) >> 2;
48        PHASES[phase as usize]
49    }
50
51    #[inline]
52    pub fn into_packet_tag_mask(self) -> u8 {
53        match self {
54            Self::One => KEY_PHASE_MASK,
55            Self::Zero => 0,
56        }
57    }
58
59    #[must_use]
60    #[inline]
61    pub fn next_phase(self) -> Self {
62        PHASES[(((self as u8) + 1) % 2) as usize]
63    }
64}
65
66impl IntoEvent<u8> for KeyPhase {
67    fn into_event(self) -> u8 {
68        match self {
69            KeyPhase::Zero => 0,
70            KeyPhase::One => 1,
71        }
72    }
73}
74
75#[cfg(test)]
76mod tests {
77    use super::*;
78
79    #[test]
80    fn test_keyphase_from_tag() {
81        for i in 0..255 {
82            let phase = KeyPhase::from_tag(i);
83            assert_eq!(phase.into_packet_tag_mask(), i & KEY_PHASE_MASK);
84        }
85    }
86
87    #[test]
88    fn test_next_phase() {
89        for i in 0..254 {
90            let phase = KeyPhase::from(i);
91            let next_phase = KeyPhase::from(i + 1);
92            assert_eq!(phase.next_phase(), next_phase);
93        }
94    }
95}