baichun_framework_core/
security.rs

1use std::time::{SystemTime, UNIX_EPOCH};
2
3use bcrypt::{hash, verify, DEFAULT_COST};
4use hmac::{Hmac, Mac};
5use jwt::{SignWithKey, VerifyWithKey};
6use rand::{distributions::Alphanumeric, Rng};
7use sha2::Sha256;
8use uuid::Uuid;
9
10use crate::error::{Error, Result};
11
12/// 密码工具
13pub struct PasswordUtils;
14
15impl PasswordUtils {
16    /// 生成密码哈希
17    pub fn hash_password(password: &str) -> Result<String> {
18        hash(password, DEFAULT_COST).map_err(|e| Error::System(e.to_string()))
19    }
20
21    /// 验证密码
22    pub fn verify_password(password: &str, hash: &str) -> Result<bool> {
23        verify(password, hash).map_err(|e| Error::System(e.to_string()))
24    }
25
26    /// 生成随机密码
27    pub fn generate_password(length: usize) -> String {
28        rand::thread_rng()
29            .sample_iter(&Alphanumeric)
30            .take(length)
31            .map(char::from)
32            .collect()
33    }
34}
35
36/// Token工具
37pub struct TokenUtils;
38
39impl TokenUtils {
40    /// 生成JWT Token
41    pub fn generate_token<T: serde::Serialize>(claims: &T, secret: &str) -> Result<String> {
42        let key: Hmac<Sha256> =
43            Hmac::new_from_slice(secret.as_bytes()).map_err(|e| Error::System(e.to_string()))?;
44        claims
45            .sign_with_key(&key)
46            .map_err(|e| Error::System(e.to_string()))
47    }
48
49    /// 验证JWT Token
50    pub fn verify_token<T: serde::de::DeserializeOwned>(token: &str, secret: &str) -> Result<T> {
51        let key: Hmac<Sha256> =
52            Hmac::new_from_slice(secret.as_bytes()).map_err(|e| Error::System(e.to_string()))?;
53        token
54            .verify_with_key(&key)
55            .map_err(|e| Error::System(e.to_string()))
56    }
57
58    /// 生成UUID
59    pub fn generate_uuid() -> String {
60        Uuid::new_v4().to_string()
61    }
62
63    /// 获取当前时间戳(秒)
64    pub fn current_timestamp() -> i64 {
65        SystemTime::now()
66            .duration_since(UNIX_EPOCH)
67            .unwrap()
68            .as_secs() as i64
69    }
70}
71
72/// 加密工具
73pub struct CryptoUtils;
74
75impl CryptoUtils {
76    /// 生成随机字符串
77    pub fn random_string(length: usize) -> String {
78        rand::thread_rng()
79            .sample_iter(&Alphanumeric)
80            .take(length)
81            .map(char::from)
82            .collect()
83    }
84
85    /// 计算SHA256哈希
86    pub fn sha256(data: &[u8]) -> Vec<u8> {
87        use sha2::Digest;
88        let mut hasher = Sha256::new();
89        hasher.update(data);
90        hasher.finalize().to_vec()
91    }
92
93    /// 生成HMAC签名
94    pub fn hmac_sign(key: &[u8], data: &[u8]) -> Result<Vec<u8>> {
95        let mut mac =
96            Hmac::<Sha256>::new_from_slice(key).map_err(|e| Error::System(e.to_string()))?;
97        mac.update(data);
98        Ok(mac.finalize().into_bytes().to_vec())
99    }
100
101    /// 验证HMAC签名
102    pub fn hmac_verify(key: &[u8], data: &[u8], signature: &[u8]) -> Result<bool> {
103        let mut mac =
104            Hmac::<Sha256>::new_from_slice(key).map_err(|e| Error::System(e.to_string()))?;
105        mac.update(data);
106        Ok(mac.verify_slice(signature).is_ok())
107    }
108}