forge
Explore
Log in

Don't you dare go Hollow

forge

Clone
★ 0

0 watching0 forksRustAGPL-3.09.7 MiB37e985dTahinli2 hours ago363 commits

token.rs83 lines, 2.1 KiBHistoryRawDownload
1use base64::prelude::{BASE64_URL_SAFE_NO_PAD, Engine as _};
2use sha2::{Digest, Sha256};
3use subtle::ConstantTimeEq;
4
5pub(crate) fn random_32() -> [u8; 32] {
6 let mut buf = [0u8; 32];
7 rand::fill(&mut buf);
8 buf
9}
10
11pub const READABLE_ALPHABET: &[u8; 32] = b"abcdefghijkmnpqrstuvwxyz23456789";
12
13pub fn random_readable(len: usize) -> String {
14 let mut buf = vec![0u8; len];
15 rand::fill(buf.as_mut_slice());
16 buf.iter()
17 .map(|b| char::from(READABLE_ALPHABET[usize::from(b & 31)]))
18 .collect()
19}
20
21pub fn random_b64url() -> String {
22 BASE64_URL_SAFE_NO_PAD.encode(random_32())
23}
24
25pub fn generate_token() -> String {
26 format!("forge_{}", random_b64url())
27}
28
29pub fn hash_token(token: &str) -> String {
30 hex::encode(Sha256::digest(token.as_bytes()))
31}
32
33pub fn sha256_reader(mut reader: impl std::io::Read) -> std::io::Result<(u64, String)> {
34 let mut hasher = Sha256::new();
35 let mut buf = vec![0u8; 64 * 1024];
36 let mut total = 0u64;
37 loop {
38 let n = reader.read(&mut buf)?;
39 if n == 0 {
40 break;
41 }
42 hasher.update(&buf[..n]);
43 total += n as u64;
44 }
45 Ok((total, hex::encode(hasher.finalize())))
46}
47
48pub fn constant_time_eq(a: &[u8], b: &[u8]) -> bool {
49 a.ct_eq(b).into()
50}
51
52#[cfg(test)]
53mod tests {
54 use super::*;
55
56 #[test]
57 fn token_has_prefix_and_43_char_body() {
58 let t = generate_token();
59 let body = t.strip_prefix("forge_").unwrap();
60 assert_eq!(body.len(), 43);
61 assert!(
62 body.bytes()
63 .all(|b| b.is_ascii_alphanumeric() || b == b'-' || b == b'_')
64 );
65 assert_ne!(t, generate_token());
66 }
67
68 #[test]
69 fn hash_is_hex_sha256() {
70 assert_eq!(
71 hash_token("abc"),
72 "ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad"
73 );
74 }
75
76 #[test]
77 fn constant_time_eq_behaves_like_eq() {
78 assert!(constant_time_eq(b"same", b"same"));
79 assert!(!constant_time_eq(b"same", b"diff"));
80 assert!(!constant_time_eq(b"short", b"longer"));
81 assert!(constant_time_eq(b"", b""));
82 }
83}