use crate::error::{Error, Result};
use std::fmt::Write;
pub fn random_hex(bytes: usize) -> Result<String> {
let mut buf = vec![0u8; bytes];
getrandom::getrandom(&mut buf)
.map_err(|e| Error::Config(format!("cannot read OS randomness: {e}")))?;
let mut out = String::with_capacity(bytes * 2);
for b in buf {
let _ = write!(out, "{b:02x}");
}
Ok(out)
}
pub fn generate() -> Result<String> {
random_hex(32)
}
pub fn constant_time_eq(a: &str, b: &str) -> bool {
let (a, b) = (a.as_bytes(), b.as_bytes());
let mut diff = a.len() ^ b.len();
for i in 0..a.len().max(b.len()) {
diff |= usize::from(a.get(i).copied().unwrap_or(0) ^ b.get(i).copied().unwrap_or(0));
}
diff == 0
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn tokens_are_hex_and_distinct() {
let (a, b) = (generate().unwrap(), generate().unwrap());
assert_eq!(a.len(), 64);
assert!(a.chars().all(|c| c.is_ascii_hexdigit()));
assert_ne!(a, b);
assert_eq!(random_hex(4).unwrap().len(), 8);
}
#[test]
fn constant_time_eq_matches_normal_equality() {
assert!(constant_time_eq("abc", "abc"));
assert!(!constant_time_eq("abc", "abd"));
assert!(!constant_time_eq("abc", "abcd"));
assert!(!constant_time_eq("", "a"));
assert!(constant_time_eq("", ""));
}
}