summaryrefslogtreecommitdiff
path: root/src/auth/mod.rs
blob: 723427cf96521c12d3a9b4b3c0792a2d725d9cf0 (plain)
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
extern crate base64;

use crypto::bcrypt_pbkdf::bcrypt_pbkdf;

#[derive(Debug, PartialEq, Eq)]
pub struct HashedPassword {
    pub salt: String,
    pub enc: String,
}

// TODO: Configurable number of iterations.
pub fn encode(salt: &str, pw: &str) -> HashedPassword {
    let mut enc = vec!(0; 32);
    let encrypted = bcrypt_pbkdf(pw.as_bytes(), salt.as_bytes(), 10, &mut enc);
    HashedPassword {
        salt: salt.to_string(),
        enc: base64::encode(&enc),
    }
}

pub fn validate(pw: &str, enc: &HashedPassword) -> bool {
    encode(enc.salt.as_str(), pw) == *enc
}

#[cfg(test)]
mod tests {
    use super::*;
    #[test]
    fn it_validates() {
        assert_eq!(false,
                   validate("hello",
                            &HashedPassword {
                                salt: String::from("123"),
                                enc: String::from("123"),
                            }));
        assert_eq!(true, validate("123", &encode("hello", "123")));
    }
}