summaryrefslogtreecommitdiff
path: root/src/auth/mod.rs
blob: 2f4c3130fa3e8e4250df2d0b6a2a2c7b7c0d2bfe (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
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 {
    // let cs = enc.split('$');
    // println("{:?}", cs.len());
    // let enc_pw = cs[3];
    encode(enc.salt.as_str(), pw) == *enc
}

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