Skip to main content

larastvel_core/hash/
mod.rs

1const BCRYPT_COST: u32 = 12;
2
3#[derive(Debug, thiserror::Error)]
4pub enum HashError {
5    #[error("Hashing failed: {0}")]
6    Failed(String),
7}
8
9pub fn make(password: &str) -> Result<String, HashError> {
10    bcrypt::hash(password, BCRYPT_COST).map_err(|e| HashError::Failed(e.to_string()))
11}
12
13pub fn check(password: &str, hash: &str) -> bool {
14    bcrypt::verify(password, hash).unwrap_or(false)
15}
16
17pub fn needs_rehash(hash: &str) -> bool {
18    if !is_hashed(hash) {
19        return true;
20    }
21    let parts: Vec<&str> = hash.split('$').collect();
22    if parts.len() >= 4 {
23        if let Ok(cost) = parts[2].parse::<u32>() {
24            return cost < BCRYPT_COST;
25        }
26    }
27    true
28}
29
30pub fn is_hashed(value: &str) -> bool {
31    value.starts_with("$2y$") || value.starts_with("$2b$") || value.starts_with("$2a$")
32}
33
34pub fn make_with_cost(password: &str, cost: u32) -> Result<String, HashError> {
35    bcrypt::hash(password, cost).map_err(|e| HashError::Failed(e.to_string()))
36}
37
38#[cfg(test)]
39mod tests {
40    use super::*;
41
42    #[test]
43    fn test_hash_make_and_check() {
44        let hash = make("password123").unwrap();
45        assert!(check("password123", &hash));
46        assert!(!check("wrong", &hash));
47    }
48
49    #[test]
50    fn test_hash_needs_rehash() {
51        let strong = make_with_cost("test", 12).unwrap();
52        assert!(!needs_rehash(&strong));
53
54        let weak = make_with_cost("test", 4).unwrap();
55        assert!(needs_rehash(&weak));
56    }
57
58    #[test]
59    fn test_hash_needs_rehash_invalid() {
60        assert!(needs_rehash("not-a-hash"));
61        assert!(needs_rehash(""));
62    }
63
64    #[test]
65    fn test_is_hashed() {
66        let hash = make("test").unwrap();
67        assert!(is_hashed(&hash));
68        assert!(!is_hashed("plaintext"));
69    }
70
71    #[test]
72    fn test_hash_different_passwords() {
73        let h1 = make("abc").unwrap();
74        let h2 = make("abc").unwrap();
75        assert_ne!(h1, h2);
76        assert!(check("abc", &h1));
77        assert!(check("abc", &h2));
78    }
79
80    #[test]
81    fn test_hash_make_with_cost() {
82        let hash = make_with_cost("test", 8).unwrap();
83        assert!(check("test", &hash));
84        let parts: Vec<&str> = hash.split('$').collect();
85        assert_eq!(parts[2], "08");
86    }
87
88    #[test]
89    fn test_hash_empty_password() {
90        let hash = make("").unwrap();
91        assert!(check("", &hash));
92    }
93}