Skip to main content

rustauth_core/crypto/
random.rs

1//! Secure random string generation.
2
3use rand::rngs::OsRng;
4use rand::RngCore;
5
6const RUSTAUTH_CHARSET: &[u8; 64] =
7    b"abcdefghijklmnopqrstuvwxyz0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ-_";
8
9/// Generate a cryptographically random string using RustAuth's URL-safe charset.
10pub fn generate_random_string(length: usize) -> String {
11    let mut output = String::with_capacity(length);
12    let mut random = vec![0_u8; length];
13    OsRng.fill_bytes(&mut random);
14
15    for byte in random {
16        let index = usize::from(byte & 0b0011_1111);
17        output.push(char::from(RUSTAUTH_CHARSET[index]));
18    }
19
20    output
21}