Skip to main content

wae_authentication/password/
hasher.rs

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