Skip to main content

sew_e2ee/
code.rs

1//! The 30-digit security code: derived from the **active** epoch's
2//! `epoch_authenticator()` (RFC 9420 §8.7). Six groups of five digits: group `i` is the
3//! big-endian integer of authenticator bytes `[5i, 5i+5)` mod 100,000, zero-padded. Identical on
4//! every member of one active epoch; changes every epoch; never modal; not secret, but
5//! never logged.
6
7use std::fmt;
8
9/// A security code (6 × 5 digits).
10#[derive(Clone, PartialEq, Eq)]
11pub struct SecurityCode([u32; 6]);
12
13impl SecurityCode {
14    /// The code of an epoch authenticator (at least 30 bytes; SHA-256 suites give 32).
15    pub fn from_authenticator(auth: &[u8]) -> Option<SecurityCode> {
16        if auth.len() < 30 {
17            return None;
18        }
19        let mut groups = [0u32; 6];
20        for (i, g) in groups.iter_mut().enumerate() {
21            let mut v: u64 = 0;
22            for b in &auth[5 * i..5 * i + 5] {
23                v = (v << 8) | u64::from(*b);
24            }
25            *g = (v % 100_000) as u32;
26        }
27        Some(SecurityCode(groups))
28    }
29
30    /// The six groups.
31    pub fn groups(&self) -> [u32; 6] {
32        self.0
33    }
34
35    /// `"01234 56789 …"`.
36    pub fn display(&self) -> String {
37        self.0
38            .iter()
39            .map(|g| format!("{g:05}"))
40            .collect::<Vec<_>>()
41            .join(" ")
42    }
43
44    /// The 30 digits without spaces.
45    pub fn digits(&self) -> String {
46        self.0.iter().map(|g| format!("{g:05}")).collect()
47    }
48}
49
50impl fmt::Debug for SecurityCode {
51    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
52        // Not secret, but kept out of logs.
53        f.write_str("SecurityCode(…)")
54    }
55}
56
57#[cfg(test)]
58mod tests {
59    use super::*;
60
61    #[test]
62    fn groups_are_five_digits() {
63        let auth = [0xffu8; 32];
64        let c = SecurityCode::from_authenticator(&auth).unwrap_or(SecurityCode([0; 6]));
65        // 0xffffffffff = 1099511627775 → mod 100000 = 27775
66        assert_eq!(c.groups(), [27_775; 6]);
67        assert_eq!(c.digits().len(), 30);
68        assert!(SecurityCode::from_authenticator(&[0; 29]).is_none());
69    }
70}