cas_lib/password_hashers/
scrypt.rs

1
2
3
4
5use scrypt::{
6    password_hash::{rand_core::OsRng, PasswordHash, PasswordHasher, PasswordVerifier, SaltString},
7    Scrypt, Params
8};
9
10pub struct CASScrypt;
11
12impl CASScrypt {
13    /// Hashes a passwith using Scrypt with custom params.
14    /// Parameters:
15    /// - password_to_hash: The password to be hashed.
16    /// - cpu_memory_cost: logâ‚‚ of the Scrypt parameter `N`, the work factor.
17    /// - block_size: `r` parameter: resource usage.
18    /// - parallelism: `p` parameter: parallelization.
19    pub fn hash_password_customized(password_to_hash: String, cpu_memory_cost: u8, block_size: u32, parallelism: u32) -> String {
20        let salt = SaltString::generate(&mut OsRng);
21        let params = Params::new(cpu_memory_cost, block_size, parallelism, 32).unwrap();
22        return Scrypt.hash_password_customized(password_to_hash.as_bytes(), None, None, params, &salt).unwrap().to_string();
23    }
24
25    /// Hashes a password using Scrypt.
26    /// Returns the hashed password as a string.
27    pub fn hash_password(password_to_hash: String) -> String {
28        let salt = SaltString::generate(&mut OsRng);
29        return Scrypt
30            .hash_password(password_to_hash.as_bytes(), &salt)
31            .unwrap()
32            .to_string();
33    }
34
35    /// Verifies a password against a hashed password using Scrypt.
36    /// Returns true if the password matches the hashed password, false otherwise.
37    pub fn verify_password(hashed_password: String, password_to_verify: String) -> bool {
38        let parsed_hash = PasswordHash::new(&hashed_password).unwrap();
39        return Scrypt
40            .verify_password(password_to_verify.as_bytes(), &parsed_hash)
41            .is_ok();
42    }
43}