aboutsummaryrefslogtreecommitdiffstats
path: root/src/password.rs
blob: 020fa5847e7d803388394d38b813801daf59cadc (plain) (blame)
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
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
// checkpw - Check passwords against pwnedpasswords.com
// Copyright (C) 2018  Harald Eilertsen <haraldei@anduin.net>
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program.  If not, see <https://www.gnu.org/licenses/>.

use crate::k_anon::to_k_anon;
use ring::digest;

pub struct Password {
    pub range: String,
    pub rest: String,
}

impl Password {
    pub fn new(pw: &str) -> Password {
        let (range, rest) = to_k_anon(digest::digest(&digest::SHA1, &pw.as_bytes()));

        Password { range, rest }
    }

    pub fn is_pwned(&self, hashes: &str) -> usize {
        if let Some(pos) = hashes.find(&self.rest) {
            if let Some(res) = hashes[pos..].lines().take(1).collect::<Vec<_>>().pop() {
                return res
                    .split(':')
                    .skip(1)
                    .collect::<Vec<_>>()
                    .pop()
                    .unwrap()
                    .parse()
                    .unwrap();
            }
        }

        0
    }
}

#[test]
fn test_creating_new_password() {
    let pw = Password::new("Passw0rd");
    assert_eq!(&pw.range, "EBFC7");
    assert_eq!(&pw.rest, "910077770C8340F63CD2DCA2AC1F120444F");
}

#[test]
fn test_matching_response_with_no_matches() {
    let pw = Password::new("Passw0rd");
    let hashes = "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA:42";

    assert_eq!(0, pw.is_pwned(&hashes));
}

#[test]
fn test_matching_response_with_one_match() {
    let pw = Password::new("Passw0rd");
    let hashes = "910077770C8340F63CD2DCA2AC1F120444F:42";

    assert_eq!(42, pw.is_pwned(&hashes));
}

#[test]
fn test_matching_response_with_multiple_matches() {
    let pw = Password::new("Passw0rd");
    let hashes = "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA:3\n910077770C8340F63CD2DCA2AC1F120444F:42\n00000000000000000000:1";

    assert_eq!(42, pw.is_pwned(&hashes));
}