Skip to main content

spoolframe_protocol/
fingerprint.rs

1//! A server key's fingerprint (P1-21, ARCHITECTURE §19): a short code a
2//! person can compare between the server's terminal and a client's screen
3//! before the client pins the key.
4//!
5//! SHA-256 over a fixed label and the 32-byte `EndpointId`, the first 80
6//! bits, in Crockford base32, as four groups of four: `K7QX-3MPA-9TRD-WF2H`.
7//! 80 bits puts making a key with a given fingerprint out of reach; a
8//! six-digit code could be matched by generating keys for a few seconds.
9//! Crockford's alphabet has no I, L, O or U, so the code reads aloud
10//! without confusion. The server and every client compute it here, so they
11//! always agree.
12
13use sha2::{Digest, Sha256};
14
15/// Changing it changes every fingerprint; a new scheme gets a new label.
16const LABEL: &[u8] = b"spoolframe fingerprint v1";
17
18const CROCKFORD: &[u8; 32] = b"0123456789ABCDEFGHJKMNPQRSTVWXYZ";
19
20/// The fingerprint of the `EndpointId` whose 32 bytes are `key`.
21pub fn fingerprint(key: &[u8; 32]) -> String {
22    let digest = Sha256::new()
23        .chain_update(LABEL)
24        .chain_update(key)
25        .finalize();
26    let mut bits = [0u8; 16];
27    bits[6..].copy_from_slice(&digest[..10]);
28    let n = u128::from_be_bytes(bits);
29    let mut out = String::with_capacity(19);
30    for i in 0..16 {
31        if i > 0 && i % 4 == 0 {
32            out.push('-');
33        }
34        let digit = (n >> (5 * (15 - i))) & 31;
35        out.push(char::from(CROCKFORD[digit as usize]));
36    }
37    out
38}
39
40/// The fingerprint of an `EndpointId` written as iroh prints it (64 hex
41/// digits); `None` if it is not one.
42pub fn of_hex(endpoint_id: &str) -> Option<String> {
43    if endpoint_id.len() != 64 {
44        return None;
45    }
46    let mut key = [0u8; 32];
47    for (i, byte) in key.iter_mut().enumerate() {
48        *byte = u8::from_str_radix(endpoint_id.get(2 * i..2 * i + 2)?, 16).ok()?;
49    }
50    Some(fingerprint(&key))
51}
52
53/// A fingerprint as a person typed it, read back from another screen or
54/// aloud: in the form [`fingerprint`] writes it, or `None` if it is not
55/// one. Case, spaces and dashes do not matter, and the letters Crockford
56/// reads as digits are read so (`O` as `0`, `I` and `L` as `1`); anything
57/// else, and any length but sixteen characters, is not a fingerprint.
58pub fn parse(typed: &str) -> Option<String> {
59    let mut digits = String::with_capacity(16);
60    for c in typed.chars() {
61        let c = match c.to_ascii_uppercase() {
62            '-' | ' ' => continue,
63            'O' => '0',
64            'I' | 'L' => '1',
65            c if c.is_ascii() && CROCKFORD.contains(&(c as u8)) => c,
66            _ => return None,
67        };
68        digits.push(c);
69    }
70    if digits.len() != 16 {
71        return None;
72    }
73    let mut out = String::with_capacity(19);
74    for (i, c) in digits.chars().enumerate() {
75        if i > 0 && i % 4 == 0 {
76            out.push('-');
77        }
78        out.push(c);
79    }
80    Some(out)
81}
82
83/// Keys and their fingerprints, computed apart from this code (Python's
84/// hashlib), so the format cannot drift. The server's and the SDK's tests
85/// check them too.
86pub const TEST_VECTORS: [(&str, &str); 3] = [
87    (
88        "0000000000000000000000000000000000000000000000000000000000000000",
89        "PGJA-BHZ1-F68M-DFSE",
90    ),
91    (
92        "0102030405060708090a0b0c0d0e0f101112131415161718191a1b1c1d1e1f20",
93        "QAJ7-XQG9-2MDW-AN9H",
94    ),
95    (
96        "ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff",
97        "NWXF-HYJ0-Y9VH-1R2M",
98    ),
99];
100
101#[cfg(test)]
102mod tests {
103    use super::*;
104
105    #[test]
106    fn the_test_vectors_hold() {
107        for (key, expected) in TEST_VECTORS {
108            assert_eq!(of_hex(key).as_deref(), Some(expected), "{key}");
109        }
110    }
111
112    #[test]
113    fn only_crockford_letters_are_used() {
114        let code = of_hex(TEST_VECTORS[1].0).unwrap();
115        assert_eq!(code.len(), 19);
116        assert!(!code.contains(['I', 'L', 'O', 'U']));
117    }
118
119    #[test]
120    fn a_string_that_is_not_a_key_has_no_fingerprint() {
121        assert_eq!(of_hex("abc"), None);
122        assert_eq!(of_hex(&"zz".repeat(32)), None);
123    }
124
125    #[test]
126    fn a_typed_fingerprint_is_read_in_the_written_form() {
127        let written = TEST_VECTORS[1].1;
128        for typed in [
129            written,
130            "qaj7-xqg9-2mdw-an9h",
131            "QAJ7 XQG9 2MDW AN9H",
132            "QAJ7XQG92MDWAN9H",
133        ] {
134            assert_eq!(parse(typed).as_deref(), Some(written), "{typed}");
135        }
136        assert_eq!(
137            parse("PGJA-BHZI-F68M-DFSE").as_deref(),
138            Some(TEST_VECTORS[0].1)
139        );
140        assert_eq!(
141            parse("NWXF-HYJO-Y9VH-LR2M").as_deref(),
142            Some(TEST_VECTORS[2].1)
143        );
144    }
145
146    #[test]
147    fn what_is_not_a_fingerprint_is_not_read_as_one() {
148        for typed in [
149            "",
150            "QAJ7-XQG9-2MDW",
151            "QAJ7-XQG9-2MDW-AN9H-0",
152            "QAJ7-XQG9-2MDW-AN9U",
153            "QAJ7_XQG9_2MDW_AN9H",
154            "QAJ7-XQG9-2MDW-AN9É",
155        ] {
156            assert_eq!(parse(typed), None, "{typed}");
157        }
158    }
159}