baichun_framework_core/
security.rs1use 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
12pub struct PasswordUtils;
14
15impl PasswordUtils {
16 pub fn hash_password(password: &str) -> Result<String> {
18 hash(password, DEFAULT_COST).map_err(|e| Error::System(e.to_string()))
19 }
20
21 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 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
36pub struct TokenUtils;
38
39impl TokenUtils {
40 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 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 pub fn generate_uuid() -> String {
60 Uuid::new_v4().to_string()
61 }
62
63 pub fn current_timestamp() -> i64 {
65 SystemTime::now()
66 .duration_since(UNIX_EPOCH)
67 .unwrap()
68 .as_secs() as i64
69 }
70}
71
72pub struct CryptoUtils;
74
75impl CryptoUtils {
76 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 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 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 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}