forge
Explore
Log in

Don't you dare go Hollow

in

Clone
★ 0

0 watching0 forksRustAGPL-3.0528.7 KiB9215377Tahinli27 days ago37 commits

token.rs56 lines, 2.0 KiBHistoryRawDownload
1//! Random tokens, readable codes and constant-time comparison. Tokens are shown to the user once and
2//! stored only as their SHA-256 hash, so a leaked database does not reveal a usable token.
3
4use base64::prelude::{BASE64_URL_SAFE_NO_PAD, Engine as _};
5use sha2::{Digest, Sha256};
6use subtle::ConstantTimeEq;
7
8/// Alphabet for codes that people type: lowercase letters and the digits 2 to 9, without look-alikes
9/// such as `l`, `o`, `0` and `1`. It has exactly 32 symbols, so the low five bits of a random byte
10/// pick one with no bias.
11pub const READABLE_ALPHABET: &[u8; 32] = b"abcdefghijkmnpqrstuvwxyz23456789";
12
13/// A session or share token: 32 random bytes, base64url without padding (43 characters).
14pub fn generate_token() -> String {
15 let mut buf = [0u8; 32];
16 rand::fill(&mut buf);
17 BASE64_URL_SAFE_NO_PAD.encode(buf)
18}
19
20/// `len` random characters from [`READABLE_ALPHABET`].
21pub fn random_readable(len: usize) -> String {
22 let mut buf = vec![0u8; len];
23 rand::fill(buf.as_mut_slice());
24 buf.iter()
25 .map(|b| char::from(READABLE_ALPHABET[usize::from(b & 31)]))
26 .collect()
27}
28
29/// Lowercase hex SHA-256 of `token`. This is what the database stores.
30pub fn hash_token(token: &str) -> String {
31 hex::encode(Sha256::digest(token.as_bytes()))
32}
33
34/// Compares two byte strings in time that does not depend on where they first differ. Different
35/// lengths are unequal; the length itself is not hidden.
36pub fn constant_time_eq(a: &[u8], b: &[u8]) -> bool {
37 a.ct_eq(b).into()
38}
39
40#[cfg(test)]
41mod tests {
42 use super::*;
43
44 #[test]
45 fn constant_time_eq_matches_ordinary_equality() {
46 assert!(constant_time_eq(b"same", b"same"));
47 assert!(!constant_time_eq(b"same", b"diff"));
48 assert!(!constant_time_eq(b"short", b"longer"));
49 assert!(constant_time_eq(b"", b""));
50 // Known vector: SHA-256 of "abc".
51 assert_eq!(
52 hash_token("abc"),
53 "ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad"
54 );
55 }
56}