auth_framework/utils/
crypto.rs

1//! Cryptographic utility functions for the AuthFramework.
2
3use crate::errors::Result;
4use rand::{Rng, rng};
5
6/// Generate a random alphanumeric token of specified length
7pub fn generate_token(length: usize) -> String {
8    const CHARSET: &[u8] = b"ABCDEFGHIJKLMNOPQRSTUVWXYZ\
9                             abcdefghijklmnopqrstuvwxyz\
10                             0123456789";
11    (0..length)
12        .map(|_| {
13            let idx = rng().random_range(0..CHARSET.len());
14            CHARSET[idx] as char
15        })
16        .collect()
17}
18
19/// Generate a cryptographically secure random string
20pub fn generate_secure_token(length: usize) -> Result<String> {
21    const CHARSET: &[u8] = b"ABCDEFGHIJKLMNOPQRSTUVWXYZ\
22                             abcdefghijklmnopqrstuvwxyz\
23                             0123456789";
24    let token: String = (0..length)
25        .map(|_| {
26            let idx = rng().random_range(0..CHARSET.len());
27            CHARSET[idx] as char
28        })
29        .collect();
30
31    Ok(token)
32}
33/// Generate a hex-encoded random token
34pub fn generate_hex_token(byte_length: usize) -> Result<String> {
35    let mut bytes = vec![0u8; byte_length];
36    rng().fill(&mut bytes[..]);
37    Ok(hex::encode(bytes))
38}
39
40#[cfg(test)]
41mod tests {
42    use super::*;
43
44    #[test]
45    fn test_generate_token() {
46        let token = generate_token(32);
47        assert_eq!(token.len(), 32);
48        assert!(token.chars().all(|c| c.is_alphanumeric()));
49    }
50
51    #[test]
52    fn test_generate_secure_token() {
53        let token = generate_secure_token(32).unwrap();
54        assert_eq!(token.len(), 32);
55        assert!(token.chars().all(|c| c.is_alphanumeric()));
56    }
57
58    #[test]
59    fn test_generate_hex_token() {
60        let token = generate_hex_token(16).unwrap();
61        assert_eq!(token.len(), 32); // 16 bytes = 32 hex chars
62        assert!(token.chars().all(|c| c.is_ascii_hexdigit()));
63    }
64}