Skip to main content

wae_authentication/password/
config.rs

1//! 密码哈希配置
2
3use wae_crypto::PasswordAlgorithm;
4
5/// 密码哈希算法类型
6#[derive(Debug, Clone, Copy, PartialEq, Eq)]
7pub enum PasswordHashAlgorithm {
8    /// bcrypt 算法
9    Bcrypt,
10    /// Argon2 算法
11    Argon2,
12}
13
14/// 密码哈希配置
15#[derive(Debug, Clone)]
16pub struct PasswordHashConfig {
17    /// 使用的哈希算法
18    pub algorithm: PasswordHashAlgorithm,
19    /// bcrypt 成本因子(4-31,推荐 12)
20    pub bcrypt_cost: u32,
21    /// argon2 内存成本(KB)
22    pub argon2_memory_cost: u32,
23    /// argon2 时间成本
24    pub argon2_time_cost: u32,
25    /// argon2 并行度
26    pub argon2_parallelism: u32,
27}
28
29impl Default for PasswordHashConfig {
30    fn default() -> Self {
31        Self {
32            algorithm: PasswordHashAlgorithm::Bcrypt,
33            bcrypt_cost: 12,
34            argon2_memory_cost: 19456,
35            argon2_time_cost: 2,
36            argon2_parallelism: 1,
37        }
38    }
39}
40
41impl PasswordHashConfig {
42    /// 创建新的密码哈希配置
43    ///
44    /// # Arguments
45    /// * `algorithm` - 使用的哈希算法
46    pub fn new(algorithm: PasswordHashAlgorithm) -> Self {
47        Self { algorithm, ..Default::default() }
48    }
49
50    /// 设置 bcrypt 成本因子
51    ///
52    /// # Arguments
53    /// * `cost` - 成本因子(4-31)
54    pub fn with_bcrypt_cost(mut self, cost: u32) -> Self {
55        self.bcrypt_cost = cost.clamp(4, 31);
56        self
57    }
58
59    /// 设置 argon2 内存成本
60    ///
61    /// # Arguments
62    /// * `cost` - 内存成本(KB)
63    pub fn with_argon2_memory_cost(mut self, cost: u32) -> Self {
64        self.argon2_memory_cost = cost;
65        self
66    }
67
68    /// 设置 argon2 时间成本
69    ///
70    /// # Arguments
71    /// * `cost` - 时间成本
72    pub fn with_argon2_time_cost(mut self, cost: u32) -> Self {
73        self.argon2_time_cost = cost;
74        self
75    }
76
77    /// 设置 argon2 并行度
78    ///
79    /// # Arguments
80    /// * `parallelism` - 并行度
81    pub fn with_argon2_parallelism(mut self, parallelism: u32) -> Self {
82        self.argon2_parallelism = parallelism;
83        self
84    }
85}
86
87impl From<PasswordHashAlgorithm> for PasswordAlgorithm {
88    fn from(algo: PasswordHashAlgorithm) -> Self {
89        match algo {
90            PasswordHashAlgorithm::Bcrypt => PasswordAlgorithm::Bcrypt,
91            PasswordHashAlgorithm::Argon2 => PasswordAlgorithm::Argon2,
92        }
93    }
94}
95
96impl From<&PasswordHashConfig> for wae_crypto::PasswordHasherConfig {
97    fn from(config: &PasswordHashConfig) -> Self {
98        wae_crypto::PasswordHasherConfig {
99            algorithm: config.algorithm.into(),
100            bcrypt_cost: config.bcrypt_cost,
101            argon2_memory_cost: config.argon2_memory_cost,
102            argon2_time_cost: config.argon2_time_cost,
103            argon2_parallelism: config.argon2_parallelism,
104        }
105    }
106}