forge
Explore
Log in

Don't you dare go Hollow

im

Clone
★ 0

0 watching0 forksRustAGPL-3.0542.8 KiBb9f0726Tahinli27 days ago34 commits

token.rs62 lines, 2.2 KiBHistoryRawDownload
1//! Random tokens, codes, and the hashing and comparison rules that go with them.
2//!
3//! A token is 32 random bytes in base64url. Only its SHA-256 (hex) is stored, so a database leak
4//! does not reveal live tokens. Codes typed by people use a readable alphabet with no look-alike
5//! characters.
6
7use base64::prelude::{BASE64_URL_SAFE_NO_PAD, Engine as _};
8use sha2::{Digest, Sha256};
9use subtle::ConstantTimeEq;
10
11/// Alphabet for codes typed by people: lowercase letters and the digits 2 to 9, without `l`, `o`,
12/// `0` and `1`, which are easy to confuse. It has exactly 32 symbols, so the low five bits of a
13/// random byte pick one uniformly, with no modulo bias.
14pub const READABLE_ALPHABET: &[u8; 32] = b"abcdefghijkmnpqrstuvwxyz23456789";
15
16/// A fresh token: 32 random bytes, base64url without padding (43 characters).
17pub fn generate_token() -> String {
18 BASE64_URL_SAFE_NO_PAD.encode(random_32())
19}
20
21/// `len` random characters from [`READABLE_ALPHABET`].
22pub fn random_readable(len: usize) -> String {
23 let mut buf = vec![0u8; len];
24 rand::fill(buf.as_mut_slice());
25 buf.iter()
26 .map(|b| char::from(READABLE_ALPHABET[usize::from(b & 31)]))
27 .collect()
28}
29
30/// The hex SHA-256 of `token`. This is what the database stores in place of the token.
31pub fn hash_token(token: &str) -> String {
32 hex::encode(Sha256::digest(token.as_bytes()))
33}
34
35/// Compares two byte strings in time that does not depend on where they first differ.
36///
37/// Different lengths return false at once; the length of a secret is not itself secret here,
38/// because every token of a kind has the same length.
39pub fn constant_time_eq(a: &[u8], b: &[u8]) -> bool {
40 a.ct_eq(b).into()
41}
42
43/// 32 random bytes from the thread RNG, which is seeded from the operating system. It cannot fail,
44/// so callers need no error path.
45pub(crate) fn random_32() -> [u8; 32] {
46 let mut buf = [0u8; 32];
47 rand::fill(&mut buf);
48 buf
49}
50
51#[cfg(test)]
52mod tests {
53 use super::*;
54
55 #[test]
56 fn constant_time_eq_matches_plain_equality() {
57 assert!(constant_time_eq(b"same", b"same"));
58 assert!(!constant_time_eq(b"same", b"diff"));
59 assert!(!constant_time_eq(b"short", b"longer"));
60 assert!(constant_time_eq(b"", b""));
61 }
62}