1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
use bcrypt::{hash, verify};
use lightspeed_core::error::LightSpeedError;

#[derive(Clone)]
pub struct PasswordCodecService {
    hash_cost: u32,
}

impl PasswordCodecService {
    /// Cost needs to be between 4 and 31
    /// Java bcrypt lib uses 10 by default
    pub fn new(hash_cost: u32) -> Self {
        PasswordCodecService { hash_cost }
    }

    pub fn verify_match(&self, plain_password: &str, hash: &str) -> Result<bool, LightSpeedError> {
        verify(plain_password, hash).map_err(|err| LightSpeedError::PasswordEncryptionError {
            message: format!("{}", err),
        })
    }

    pub fn hash_password(&self, plain_password: &str) -> Result<String, LightSpeedError> {
        hash(plain_password, self.hash_cost).map_err(|err| {
            LightSpeedError::PasswordEncryptionError {
                message: format!("{}", err),
            }
        })
    }
}

#[cfg(test)]
pub mod test {

    use super::*;

    #[test]
    fn should_encrypt_and_decrypt() -> Result<(), LightSpeedError> {
        let password_codec = PasswordCodecService::new(4);
        let plain_pass = "wrwdsdfast346n534dfsg5353";
        let hash = password_codec.hash_password(plain_pass)?;

        assert!(password_codec.verify_match(plain_pass, &hash)?);
        assert!(!password_codec
            .verify_match(plain_pass, &password_codec.hash_password("asfasfasxcva")?)?);

        Ok(())
    }

    #[test]
    fn should_decrypt_admin() -> Result<(), LightSpeedError> {
        let password_codec = PasswordCodecService::new(4);
        let plain_pass = "admin";
        let hash = &password_codec.hash_password(plain_pass)?;
        let java_bcrypt_hash = r#"$2a$10$TkWSZIawgD9tjkmAV2GjGOt30FQktiTlpZTIHbxatakOHf4G0.aA."#;

        assert!(password_codec.verify_match(plain_pass, hash)?);
        assert!(password_codec.verify_match(plain_pass, java_bcrypt_hash)?);

        Ok(())
    }
}