//! Random tokens, readable codes and constant-time comparison. Tokens are shown to the user once and //! stored only as their SHA-256 hash, so a leaked database does not reveal a usable token. use base64::prelude::{BASE64_URL_SAFE_NO_PAD, Engine as _}; use sha2::{Digest, Sha256}; use subtle::ConstantTimeEq; /// Alphabet for codes that people type: lowercase letters and the digits 2 to 9, without look-alikes /// such as `l`, `o`, `0` and `1`. It has exactly 32 symbols, so the low five bits of a random byte /// pick one with no bias. pub const READABLE_ALPHABET: &[u8; 32] = b"abcdefghijkmnpqrstuvwxyz23456789"; /// A session or share token: 32 random bytes, base64url without padding (43 characters). pub fn generate_token() -> String { let mut buf = [0u8; 32]; rand::fill(&mut buf); BASE64_URL_SAFE_NO_PAD.encode(buf) } /// `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() } /// Lowercase hex SHA-256 of `token`. This is what the database stores. 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 are unequal; the length itself is not hidden. pub fn constant_time_eq(a: &[u8], b: &[u8]) -> bool { a.ct_eq(b).into() } #[cfg(test)] mod tests { use super::*; #[test] fn constant_time_eq_matches_ordinary_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"")); // Known vector: SHA-256 of "abc". assert_eq!( hash_token("abc"), "ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad" ); } }