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
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
use std::time::{Duration, SystemTime, UNIX_EPOCH};
use crate::{digest, generate, verify_delta, Algorithm, GenerationError};
pub struct Totp {
epoch_time_offset: u64,
time: u64,
step: u64,
window: u64,
digest: Vec<u8>,
}
impl Totp {
pub fn new() -> Totp {
Totp {
window: 0,
epoch_time_offset: 0,
time: 0,
step: 30,
digest: Vec::new(),
}
}
pub fn with_epoch_time_offset<'a>(&'a mut self, offset: u64) -> &'a mut Totp {
self.epoch_time_offset = offset;
self
}
pub fn with_window<'a>(&'a mut self, window: u64) -> &'a mut Totp {
self.window = window;
self
}
pub fn with_digest<'a>(&'a mut self, digest: Vec<u8>) -> &'a mut Totp {
self.digest = digest;
self
}
pub fn generate<'a>(&'a self,key: String) -> std::result::Result<String, GenerationError> {
let counter = self.get_counter() as u128;
let hash = if self.digest.is_empty() {
digest(key.clone(), counter, Algorithm::Sha1)?
} else {
self.digest.clone()
};
generate(key, counter, 6, hash)
}
pub fn verify<'a>(&'a self, token: String, key: String) -> std::result::Result<bool, GenerationError> {
let counter = self.get_counter();
let windowed_counter = (counter - self.window) as u128;
let hash = if self.digest.is_empty() {
digest(key.clone(), windowed_counter, Algorithm::Sha1)?
} else {
self.digest.clone()
};
verify_delta(
token,
key,
windowed_counter,
6,
self.window + self.window,
hash,
)
}
#[doc(hidden)]
fn get_counter<'a>(&'a self) -> u64 {
let end = if self.time == 0 {
SystemTime::now()
} else {
UNIX_EPOCH + Duration::from_secs(self.time)
};
let start = UNIX_EPOCH + Duration::from_secs(self.epoch_time_offset);
let epoch = end.duration_since(start).unwrap();
epoch.as_secs() / self.step
}
}
#[cfg(test)]
mod totp_tests {
use super::Totp;
use std::assert;
#[test]
fn assert_correct_otp() {
let key = "my secret key".to_string();
let totp = Totp::new();
let code = totp.generate(key.clone()).expect("borked");
let verified = totp.verify(code, key).expect("borked here too");
assert!(verified);
}
#[test]
fn assert_incorrect_otp() {
let key = "my secret key".to_string();
let totp = Totp::new();
let _code = totp.generate(key.clone()).expect("borked");
let verified = totp.verify("wrong".to_string(), key).expect("borked here too");
assert!(!verified);
}
}