Skip to main content

rtci_sframe/
key_id.rs

1//! The KID layouts of the two key-management schemes RFC 9605 describes: sender keys (section
2//! 5.1) and MLS (section 5.2).
3
4use crate::error::{Error, Result};
5
6/// The low `bits` bits set; all 64 when `bits` is 64 or more.
7const fn mask(bits: u32) -> u64 {
8    if bits >= 64 {
9        u64::MAX
10    } else {
11        (1u64 << bits) - 1
12    }
13}
14
15/// `value << bits`, 0 when that shifts everything out.
16const fn shl(value: u64, bits: u32) -> u64 {
17    if bits >= 64 { 0 } else { value << bits }
18}
19
20/// `value >> bits`, 0 when that shifts everything out.
21const fn shr(value: u64, bits: u32) -> u64 {
22    if bits >= 64 { 0 } else { value >> bits }
23}
24
25/// The KID layout of the sender-keys scheme (RFC 9605 section 5.1, Figure 7).
26///
27/// ```text
28///      64-R bits         R bits
29///  <---------------> <------------>
30/// +-----------------+--------------+
31/// | Key Generation  | Ratchet Step |
32/// +-----------------+--------------+
33/// ```
34///
35/// `KID = (key_generation << R) + (ratchet_step % (1 << R))`. `R` is set by the application;
36/// every receiver of a sender has to know the sender's `R`.
37#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
38pub struct SenderKeyIdLayout {
39    ratchet_bits: u32,
40}
41
42impl SenderKeyIdLayout {
43    /// A layout with `ratchet_bits` (`R`) bits of ratchet step: 0 to 64.
44    pub fn new(ratchet_bits: u32) -> Result<Self> {
45        if ratchet_bits > 64 {
46            return Err(Error::KeyIdLayout);
47        }
48        Ok(Self { ratchet_bits })
49    }
50
51    /// `R`: the number of low-order bits that carry the ratchet step.
52    #[must_use]
53    pub const fn ratchet_bits(&self) -> u32 {
54        self.ratchet_bits
55    }
56
57    /// The KID of `key_generation` at `ratchet_step`. Only the low `R` bits of the step are
58    /// sent; the generation has to fit the remaining `64 - R`.
59    pub fn key_id(&self, key_generation: u64, ratchet_step: u64) -> Result<u64> {
60        if key_generation > mask(64 - self.ratchet_bits) {
61            return Err(Error::KeyIdLayout);
62        }
63        Ok(self.compose(key_generation, ratchet_step))
64    }
65
66    /// The KID of a generation known to fit its field.
67    pub(crate) const fn compose(&self, key_generation: u64, ratchet_step: u64) -> u64 {
68        shl(key_generation, self.ratchet_bits) | (ratchet_step & mask(self.ratchet_bits))
69    }
70
71    /// The key generation and the low `R` bits of the ratchet step a KID carries.
72    #[must_use]
73    pub const fn split(&self, kid: u64) -> SenderKeyId {
74        SenderKeyId {
75            key_generation: shr(kid, self.ratchet_bits),
76            ratchet_step: kid & mask(self.ratchet_bits),
77        }
78    }
79
80    /// How many ratchet steps lie from a key at `from_step` to the one a KID with
81    /// `ratchet_step` in its low bits names, counting forward modulo `1 << R`.
82    #[must_use]
83    pub const fn steps_between(&self, from_step: u64, ratchet_step: u64) -> u64 {
84        ratchet_step.wrapping_sub(from_step) & mask(self.ratchet_bits)
85    }
86}
87
88/// The parts of a sender-keys KID.
89#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
90pub struct SenderKeyId {
91    /// How many keys the sender had distributed before this one.
92    pub key_generation: u64,
93    /// The low `R` bits of how often the sender has ratcheted this key forward.
94    pub ratchet_step: u64,
95}
96
97/// The KID layout of an MLS-keyed session (RFC 9605 section 5.2, Figure 8).
98///
99/// ```text
100///   64-S-E bits   S bits   E bits
101///  <-----------> <------> <------>
102/// +-------------+--------+-------+
103/// | Context ID  | Index  | Epoch |
104/// +-------------+--------+-------+
105/// ```
106///
107/// `KID = (context << (S + E)) + (sender_index << E) + (epoch % (1 << E))`. `E` is set by the
108/// application and bounds how many epochs can be active at once; `S` is the number of bits a
109/// member index of the group needs.
110#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
111pub struct MlsKeyIdLayout {
112    epoch_bits: u32,
113    sender_bits: u32,
114}
115
116impl MlsKeyIdLayout {
117    /// A layout with `epoch_bits` (`E`) and `sender_bits` (`S`); together at most 64.
118    pub fn new(epoch_bits: u32, sender_bits: u32) -> Result<Self> {
119        if epoch_bits > 64 || sender_bits > 64 - epoch_bits {
120            return Err(Error::KeyIdLayout);
121        }
122        Ok(Self {
123            epoch_bits,
124            sender_bits,
125        })
126    }
127
128    /// A layout for a group of `group_size` members: `S` is the smallest value such that
129    /// `group_size <= (1 << S)`.
130    pub fn for_group_size(epoch_bits: u32, group_size: u64) -> Result<Self> {
131        let sender_bits = match group_size {
132            0 | 1 => 0,
133            size => 64 - (size - 1).leading_zeros(),
134        };
135        Self::new(epoch_bits, sender_bits)
136    }
137
138    /// `E`: the number of low-order bits that carry the epoch.
139    #[must_use]
140    pub const fn epoch_bits(&self) -> u32 {
141        self.epoch_bits
142    }
143
144    /// `S`: the number of bits that carry the sender's member index.
145    #[must_use]
146    pub const fn sender_bits(&self) -> u32 {
147        self.sender_bits
148    }
149
150    /// The number of bits left for the sender's context value: `64 - S - E`.
151    #[must_use]
152    pub const fn context_bits(&self) -> u32 {
153        64 - self.sender_bits - self.epoch_bits
154    }
155
156    /// The low `E` bits of `epoch`: what a KID carries of it, and what two epochs must differ
157    /// in to be active together.
158    #[must_use]
159    pub const fn epoch_slot(&self, epoch: u64) -> u64 {
160        epoch & mask(self.epoch_bits)
161    }
162
163    /// The KID a member at `sender_index` uses in `epoch` for its `context` (0 gives the
164    /// shortest KID). The index and the context have to fit their fields.
165    pub fn key_id(&self, epoch: u64, sender_index: u64, context: u64) -> Result<u64> {
166        if sender_index > mask(self.sender_bits) || context > mask(self.context_bits()) {
167            return Err(Error::KeyIdLayout);
168        }
169        Ok(shl(context, self.sender_bits + self.epoch_bits)
170            | shl(sender_index, self.epoch_bits)
171            | self.epoch_slot(epoch))
172    }
173
174    /// The context, the sender index and the low `E` epoch bits a KID carries.
175    #[must_use]
176    pub const fn split(&self, kid: u64) -> MlsKeyId {
177        MlsKeyId {
178            context: shr(kid, self.sender_bits + self.epoch_bits),
179            sender_index: shr(kid, self.epoch_bits) & mask(self.sender_bits),
180            epoch: kid & mask(self.epoch_bits),
181        }
182    }
183}
184
185/// The parts of an MLS KID.
186#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
187pub struct MlsKeyId {
188    /// The value the sender chose, for instance to tell its streams apart.
189    pub context: u64,
190    /// The sender's member index in the MLS group.
191    pub sender_index: u64,
192    /// The low `E` bits of the MLS epoch.
193    pub epoch: u64,
194}