Skip to main content

wae_authentication/password/
hasher.rs

1//! 密码哈希器实现
2
3use zeroize::Zeroize;
4
5use crate::password::{PasswordHashConfig, PasswordHashError, PasswordHashResult};
6
7/// 密码哈希器
8#[derive(Debug, Clone)]
9pub struct PasswordHasherService {
10    config: PasswordHashConfig,
11}
12
13impl PasswordHasherService {
14    /// 创建新的密码哈希器
15    ///
16    /// # Arguments
17    /// * `config` - 密码哈希配置
18    pub fn new(config: PasswordHashConfig) -> Self {
19        Self { config }
20    }
21
22    /// 使用默认配置创建密码哈希器
23    pub fn default() -> Self {
24        Self::new(PasswordHashConfig::default())
25    }
26
27    /// 哈希密码
28    ///
29    /// # Arguments
30    /// * `password` - 明文密码
31    pub fn hash_password(&self, password: &str) -> PasswordHashResult<String> {
32        let mut password_bytes = password.as_bytes().to_vec();
33
34        let result = self.hash_bcrypt(&password_bytes);
35
36        password_bytes.zeroize();
37        result
38    }
39
40    /// 验证密码
41    ///
42    /// # Arguments
43    /// * `password` - 明文密码
44    /// * `hash` - 密码哈希
45    pub fn verify_password(&self, password: &str, hash: &str) -> PasswordHashResult<bool> {
46        let mut password_bytes = password.as_bytes().to_vec();
47
48        let result = self.verify_bcrypt(&password_bytes, hash);
49
50        password_bytes.zeroize();
51        result
52    }
53
54    /// 使用 bcrypt 哈希密码
55    fn hash_bcrypt(&self, password: &[u8]) -> PasswordHashResult<String> {
56        bcrypt::hash(password, self.config.bcrypt_cost).map_err(|_| PasswordHashError::HashFailed)
57    }
58
59    /// 使用 bcrypt 验证密码
60    fn verify_bcrypt(&self, password: &[u8], hash: &str) -> PasswordHashResult<bool> {
61        bcrypt::verify(password, hash).map_err(|_| PasswordHashError::VerifyFailed)
62    }
63}
64
65impl Default for PasswordHasherService {
66    fn default() -> Self {
67        Self::new(PasswordHashConfig::default())
68    }
69}