cas_lib/password_hashers/
scrypt.rs

1use std::sync::mpsc;
2
3
4
5use scrypt::{
6    password_hash::{rand_core::OsRng, PasswordHash, PasswordHasher, PasswordVerifier, SaltString},
7    Scrypt,
8};
9
10use super::cas_password_hasher::CASPasswordHasher;
11
12pub struct CASScrypt;
13
14impl CASPasswordHasher for CASScrypt {
15    /// Hashes a password using Scrypt.
16    /// Returns the hashed password as a string.
17    fn hash_password(password_to_hash: String) -> String {
18        let salt = SaltString::generate(&mut OsRng);
19        return Scrypt
20            .hash_password(password_to_hash.as_bytes(), &salt)
21            .unwrap()
22            .to_string();
23    }
24
25    /// Verifies a password against a hashed password using Scrypt.
26    /// Returns true if the password matches the hashed password, false otherwise.
27    fn verify_password(hashed_password: String, password_to_verify: String) -> bool {
28        let parsed_hash = PasswordHash::new(&hashed_password).unwrap();
29        return Scrypt
30            .verify_password(password_to_verify.as_bytes(), &parsed_hash)
31            .is_ok();
32    }
33
34    /// Hashes a password using Scrypt on the threadpool.
35    /// Returns the hashed password as a string.
36    fn hash_password_threadpool(password: String) -> String {
37        let (sender, receiver) = mpsc::channel();
38        rayon::spawn(move || {
39            let hash = Self::hash_password(password);
40            sender.send(hash).unwrap();
41        });
42        let hash = receiver.recv().unwrap();
43        hash
44    }
45
46    /// Verifies a password against a hashed password using Scrypt on the threadpool.
47    /// Returns true if the password matches the hashed password, false otherwise.
48    fn verify_password_threadpool(hashed_password: String, password_to_verify: String) -> bool {
49        let (sender, receiver) = mpsc::channel();
50        rayon::spawn(move || {
51            let hash = Self::verify_password(hashed_password, password_to_verify);
52            sender.send(hash).unwrap();
53        });
54        let hash = receiver.recv().unwrap();
55        hash
56    }
57}