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
#![no_std]
use core::convert::TryInto;
use hmac::crypto_mac::Output;
use hmac::{Hmac, Mac, NewMac};
use sha1::Sha1;
const TOTP: Totp = Totp::options(6, 1, 30);
pub fn generate(key: impl AsRef<[u8]>, secs: u64) -> u32 {
TOTP.generate(key.as_ref(), secs)
}
pub fn verify(key: impl AsRef<[u8]>, secs: u64, token: u32) -> bool {
TOTP.verify(key.as_ref(), secs, token)
}
#[derive(Copy, Clone, Debug)]
struct Totp {
digits: u32,
skew: u8,
step: u64,
}
impl Totp {
const fn options(digits: u32, skew: u8, step: u64) -> Totp {
Totp { digits, skew, step }
}
fn sign(&self, key: &[u8], secs: u64) -> Output<Hmac<Sha1>> {
let ctr = (secs / self.step).to_be_bytes();
let mut mac = Hmac::<Sha1>::new_varkey(key).unwrap();
mac.update(&ctr);
mac.finalize()
}
fn generate(&self, key: &[u8], secs: u64) -> u32 {
let signed = self.sign(key, secs).into_bytes();
let offset = (signed[19] & 15) as usize;
let buf = &signed[offset..offset + 4];
let buf: [u8; 4] = buf.try_into().unwrap();
let data = u32::from_be_bytes(buf) & 0x7fff_ffff;
data % 10_u32.pow(self.digits)
}
fn verify(&self, key: &[u8], secs: u64, token: u32) -> bool {
let offset = secs / self.step - self.skew as u64;
for i in 0..self.skew * 2 + 1 {
let secs = (offset + i as u64) * self.step;
if self.generate(key, secs) == token {
return true;
}
}
false
}
}
impl Default for Totp {
fn default() -> Self {
TOTP
}
}
#[cfg(test)]
mod tests {
use super::Totp;
#[test]
fn totp_8_digits() {
const TOTP: Totp = Totp::options(8, 0, 30);
assert!(TOTP.verify(b"12345678901234567890", 59, 94287082));
assert!(TOTP.verify(b"12345678901234567890", 1111111109, 7081804));
assert!(TOTP.verify(b"12345678901234567890", 1111111111, 14050471));
assert!(TOTP.verify(b"12345678901234567890", 1234567890, 89005924));
assert!(TOTP.verify(b"12345678901234567890", 2000000000, 69279037));
assert!(TOTP.verify(b"12345678901234567890", 20000000000, 65353130));
}
}