1use crate::error::{Error, Result};
4use std::fmt::Write;
5
6pub fn random_hex(bytes: usize) -> Result<String> {
8 let mut buf = vec![0u8; bytes];
9 getrandom::getrandom(&mut buf)
10 .map_err(|e| Error::Config(format!("cannot read OS randomness: {e}")))?;
11 let mut out = String::with_capacity(bytes * 2);
12 for b in buf {
13 let _ = write!(out, "{b:02x}");
14 }
15 Ok(out)
16}
17
18pub fn generate() -> Result<String> {
20 random_hex(32)
21}
22
23pub fn constant_time_eq(a: &str, b: &str) -> bool {
25 let (a, b) = (a.as_bytes(), b.as_bytes());
26 let mut diff = a.len() ^ b.len();
27 for i in 0..a.len().max(b.len()) {
28 diff |= usize::from(a.get(i).copied().unwrap_or(0) ^ b.get(i).copied().unwrap_or(0));
29 }
30 diff == 0
31}
32
33#[cfg(test)]
34mod tests {
35 use super::*;
36
37 #[test]
38 fn tokens_are_hex_and_distinct() {
39 let (a, b) = (generate().unwrap(), generate().unwrap());
40 assert_eq!(a.len(), 64);
41 assert!(a.chars().all(|c| c.is_ascii_hexdigit()));
42 assert_ne!(a, b);
43 assert_eq!(random_hex(4).unwrap().len(), 8);
44 }
45
46 #[test]
47 fn constant_time_eq_matches_normal_equality() {
48 assert!(constant_time_eq("abc", "abc"));
49 assert!(!constant_time_eq("abc", "abd"));
50 assert!(!constant_time_eq("abc", "abcd"));
51 assert!(!constant_time_eq("", "a"));
52 assert!(constant_time_eq("", ""));
53 }
54}