//! Random tokens and their hashes. A token is shown once; only its SHA-256 hex is stored, and //! comparisons use `subtle` so that timing does not reveal matching prefixes. use base64::prelude::{BASE64_URL_SAFE_NO_PAD, Engine as _}; use sha2::{Digest, Sha256}; use subtle::ConstantTimeEq; /// A fresh token: 32 random bytes as unpadded base64url (43 characters). pub fn generate_token() -> String { let mut buf = [0u8; 32]; rand::fill(&mut buf); BASE64_URL_SAFE_NO_PAD.encode(buf) } /// Lowercase hex SHA-256 of the 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 depends only on their lengths. pub fn constant_time_eq(a: &[u8], b: &[u8]) -> bool { a.ct_eq(b).into() } #[cfg(test)] mod tests { use super::*; #[test] fn token_is_43_url_safe_characters_and_fresh() { let t = generate_token(); assert_eq!(t.len(), 43); assert!( t.bytes() .all(|b| b.is_ascii_alphanumeric() || b == b'-' || b == b'_') ); assert_ne!(t, generate_token()); } #[test] fn hash_is_hex_sha256_and_compare_matches_eq() { assert_eq!( hash_token("abc"), "ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad" ); assert!(constant_time_eq(b"same", b"same")); assert!(!constant_time_eq(b"same", b"diff")); assert!(!constant_time_eq(b"short", b"longer")); } }