//! Random tokens, codes, and the hashing and comparison rules that go with them. //! //! A token is 32 random bytes in base64url. Only its SHA-256 (hex) is stored, so a database leak //! does not reveal live tokens. Codes typed by people use a readable alphabet with no look-alike //! characters. use base64::prelude::{BASE64_URL_SAFE_NO_PAD, Engine as _}; use sha2::{Digest, Sha256}; use subtle::ConstantTimeEq; /// Alphabet for codes typed by people: lowercase letters and the digits 2 to 9, without `l`, `o`, /// `0` and `1`, which are easy to confuse. It has exactly 32 symbols, so the low five bits of a /// random byte pick one uniformly, with no modulo bias. pub const READABLE_ALPHABET: &[u8; 32] = b"abcdefghijkmnpqrstuvwxyz23456789"; /// A fresh token: 32 random bytes, base64url without padding (43 characters). pub fn generate_token() -> String { BASE64_URL_SAFE_NO_PAD.encode(random_32()) } /// `len` random characters from [`READABLE_ALPHABET`]. pub fn random_readable(len: usize) -> String { let mut buf = vec![0u8; len]; rand::fill(buf.as_mut_slice()); buf.iter() .map(|b| char::from(READABLE_ALPHABET[usize::from(b & 31)])) .collect() } /// The hex SHA-256 of `token`. This is what the database stores in place of the token. pub fn hash_token(token: &str) -> String { hex::encode(Sha256::digest(token.as_bytes())) } /// Compares two byte strings in time that does not depend on where they first differ. /// /// Different lengths return false at once; the length of a secret is not itself secret here, /// because every token of a kind has the same length. pub fn constant_time_eq(a: &[u8], b: &[u8]) -> bool { a.ct_eq(b).into() } /// 32 random bytes from the thread RNG, which is seeded from the operating system. It cannot fail, /// so callers need no error path. pub(crate) fn random_32() -> [u8; 32] { let mut buf = [0u8; 32]; rand::fill(&mut buf); buf } #[cfg(test)] mod tests { use super::*; #[test] fn constant_time_eq_matches_plain_equality() { assert!(constant_time_eq(b"same", b"same")); assert!(!constant_time_eq(b"same", b"diff")); assert!(!constant_time_eq(b"short", b"longer")); assert!(constant_time_eq(b"", b"")); } }