Skip to main content

karbon_framework/security/
crypto.rs

1use base64::{engine::general_purpose::URL_SAFE_NO_PAD, Engine};
2use rand::RngExt;
3use sha2::{Sha256, Digest};
4
5/// Cryptographic helpers
6pub struct Crypto;
7
8impl Crypto {
9    /// Generate a random token (URL-safe base64)
10    pub fn random_token(length: usize) -> String {
11        let mut bytes = vec![0u8; length];
12        rand::rng().fill(&mut bytes[..]);
13        URL_SAFE_NO_PAD.encode(&bytes)
14    }
15
16    /// Hash a token with SHA-256 (for storing refresh tokens)
17    pub fn hash_token(token: &str) -> String {
18        let mut hasher = Sha256::new();
19        hasher.update(token.as_bytes());
20        let result = hasher.finalize();
21        result.iter().map(|b| format!("{b:02x}")).collect()
22    }
23
24    /// Generate a short alphanumeric code (e.g. for email verification)
25    pub fn random_code(length: usize) -> String {
26        const CHARSET: &[u8] = b"ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
27        let mut rng = rand::rng();
28        (0..length)
29            .map(|_| {
30                let idx = rng.random_range(0..CHARSET.len());
31                CHARSET[idx] as char
32            })
33            .collect()
34    }
35}