Skip to main content

cas_lib/password_hashers/
bcrypt.rs

1
2
3use bcrypt::{hash, verify, DEFAULT_COST};
4
5use crate::error::{CasError, CasResult};
6
7pub struct CASBCrypt;
8
9impl CASBCrypt {
10    /// Hashes a password using bcrypt with a customized cost.
11    /// Parameters:
12    /// - password_to_hash: The password to be hashed.
13    /// - cost: The cost parameter for bcrypt (default is 12 and max is 31).
14    /// Returns the hashed password as a string.
15    pub fn hash_password_customized(password_to_hash: String, cost: u32) -> CasResult<String> {
16        hash(password_to_hash, cost).map_err(|_| CasError::PasswordHashingFailed)
17    }
18
19    /// Hashes a password using bcrypt.
20    /// Returns the hashed password as a string.
21    pub fn hash_password(password_to_hash: String) -> CasResult<String> {
22        hash(password_to_hash, DEFAULT_COST).map_err(|_| CasError::PasswordHashingFailed)
23    }
24
25    /// Verifies a password against a hashed password using bcrypt.
26    /// Returns `Ok(true)` if the password matches, `Ok(false)` if it does not, and
27    /// an error if the stored hash could not be parsed.
28    pub fn verify_password(hashed_password: String, password_to_verify: String) -> CasResult<bool> {
29        verify(password_to_verify, &hashed_password).map_err(|_| CasError::PasswordHashingFailed)
30    }
31}