cas_lib/password_hashers/
argon2.rs

1use argon2::{
2    password_hash::{rand_core::OsRng, SaltString},
3    Argon2, PasswordHash, PasswordHasher, PasswordVerifier, Params
4};
5use rand::RngCore;
6
7
8pub struct CASArgon;
9
10impl CASArgon {
11
12    /// Hashes a password using Argon2 with custom parameters.
13    /// Returns the hashed password as a string.
14    /// Parameters:
15    /// - memory_cost: Memory cost in kibibytes.
16    /// - iterations: Number of iterations.
17    /// - parallelism: Degree of parallelism.
18    /// - password_to_hash: The password to be hashed.
19    pub fn hash_password_parameters(memory_cost: u32, iterations: u32, parallelism: u32, password_to_hash: String) -> String {
20        let params = Params::new(memory_cost * 1024, iterations, parallelism, None).unwrap();
21        let argon2 = Argon2::new(argon2::Algorithm::Argon2id, argon2::Version::V0x13, params);
22        let salt = SaltString::generate(&mut OsRng);
23        let hash = argon2.hash_password(password_to_hash.as_bytes(), &salt).unwrap();
24        hash.to_string()
25    }
26    /// Derives a 128-bit AES key from a password using Argon2.
27    /// Returns the derived key as a vector of bytes.
28    pub fn derive_aes_128_key(password: Vec<u8>) -> Vec<u8> {
29        let mut rng = OsRng;
30        let mut salt: [u8; 16] = [0; 16];
31        rng.fill_bytes(&mut salt);
32
33        let mut key = Box::new([0u8; 16]);
34        Argon2::default().hash_password_into(password.as_ref(), &salt, &mut *key).unwrap();
35        key.to_vec()
36    }
37
38    /// Derives a 256-bit AES key from a password using Argon2.
39    /// Returns the derived key as a vector of bytes.
40    pub fn derive_aes_256_key(password: Vec<u8>) -> Vec<u8> {
41        let mut rng = OsRng;
42        let mut salt: [u8; 16] = [0; 16];
43        rng.fill_bytes(&mut salt);
44
45        let mut key = Box::new([0u8; 32]);
46        Argon2::default().hash_password_into(password.as_ref(), &salt, &mut *key).unwrap();
47        key.to_vec()
48    }
49
50    /// Hashes a password using Argon2.
51    /// Returns the hashed password as a string.
52    pub fn hash_password(password_to_hash: String) -> String {
53        let salt = SaltString::generate(&mut OsRng);
54        let argon2 = Argon2::default();
55        let hashed_password = argon2
56            .hash_password(password_to_hash.as_bytes(), &salt)
57            .unwrap()
58            .to_string();
59        return hashed_password;
60    }
61
62    /// Verifies a password against a hashed password using Argon2.
63    /// Returns true if the password matches the hashed password, false otherwise.
64    pub fn verify_password(hashed_password: String, password_to_verify: String) -> bool {
65        let hashed_password = PasswordHash::new(&hashed_password).unwrap();
66        return Argon2::default()
67            .verify_password(password_to_verify.as_bytes(), &hashed_password)
68            .is_ok();
69    }
70}