forge
Explore
Log in

Don't you dare go Hollow

iz

Clone
★ 0

0 watching0 forksRustAGPL-3.0567.3 KiB3950aceTahinli27 days ago34 commits

token.rs50 lines, 1.5 KiBHistoryRawDownload
1//! Random tokens and their hashes. A token is shown once; only its SHA-256 hex is stored, and
2//! comparisons use `subtle` so that timing does not reveal matching prefixes.
3
4use base64::prelude::{BASE64_URL_SAFE_NO_PAD, Engine as _};
5use sha2::{Digest, Sha256};
6use subtle::ConstantTimeEq;
7
8/// A fresh token: 32 random bytes as unpadded base64url (43 characters).
9pub fn generate_token() -> String {
10 let mut buf = [0u8; 32];
11 rand::fill(&mut buf);
12 BASE64_URL_SAFE_NO_PAD.encode(buf)
13}
14
15/// Lowercase hex SHA-256 of the token. This is what the database stores.
16pub fn hash_token(token: &str) -> String {
17 hex::encode(Sha256::digest(token.as_bytes()))
18}
19
20/// Compares two byte strings in time that depends only on their lengths.
21pub fn constant_time_eq(a: &[u8], b: &[u8]) -> bool {
22 a.ct_eq(b).into()
23}
24
25#[cfg(test)]
26mod tests {
27 use super::*;
28
29 #[test]
30 fn token_is_43_url_safe_characters_and_fresh() {
31 let t = generate_token();
32 assert_eq!(t.len(), 43);
33 assert!(
34 t.bytes()
35 .all(|b| b.is_ascii_alphanumeric() || b == b'-' || b == b'_')
36 );
37 assert_ne!(t, generate_token());
38 }
39
40 #[test]
41 fn hash_is_hex_sha256_and_compare_matches_eq() {
42 assert_eq!(
43 hash_token("abc"),
44 "ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad"
45 );
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 }
50}