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
extern crate chrono;
extern crate md5;
use chrono::{DateTime, Utc};
pub const DEFAULT_OTP_VALID_PERIOD: u8 = 30;
#[cfg(test)]
mod tests {
use super::{check_otp, create_otp};
#[test]
fn it_really_works() {
let otp = create_otp("0123456789abcdef", "0000");
assert!(check_otp(&otp, "0123456789abcdef", "0000"));
}
}
pub fn create_otp(secret: &str, pin: &str) -> String {
let now: DateTime<Utc> = Utc::now();
let to_hash = format!("{}{}{}", now.timestamp() / 10, secret, pin);
let hash = format!("{:x}", md5::compute(to_hash));
let s = String::from(&hash[0..6]);
s
}
pub fn check_otp(code: &str, secret: &str, pin: &str, valid_period: u8) -> bool {
let now = Utc::now().timestamp();
let mut past_limit = now - valid_period as i64 / 2;
let future_limit = now + valid_period as i64 / 2;
while past_limit < future_limit {
let current_code = create_otp(secret, pin);
if current_code == code {
return true;
}
past_limit = past_limit + 1;
}
false
}