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
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
use rand;
use base32;
use hmacsha1::hmac_sha1;
use std::mem;
use std::time::{SystemTime, UNIX_EPOCH};
pub struct GoogleAuthenticator{
code_len:usize,
_base32_alphabet:Vec<char>
}
impl GoogleAuthenticator{
pub fn new() -> GoogleAuthenticator{
GoogleAuthenticator{
code_len: 6,
_base32_alphabet: vec![
'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H',
'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P',
'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X',
'Y', 'Z', '2', '3', '4', '5', '6', '7',
'=',
]
}
}
pub fn create_secret(&self, length:u8) -> String{
let rand_bytes = rand::random::<[u8;32]>();
let mut secret = Vec::<char>::new();
let mut index: usize;
for i in 0 .. length {
index = (rand_bytes[i as usize] & 0x1F) as usize;
secret.push(self._base32_alphabet[ index ]);
}
secret.into_iter().collect()
}
pub fn get_code(&self, secret:&str, times_slice:u32) -> Result<String>{
if secret.len() < 16 || secret.len() > 128 {
return Err(GAError::Error("bad secret length. must be less than 128 and more than 16, recommand 32"));
}
let mut message: u32 = times_slice;
if times_slice == 0 {
message = (f64::from_bits(SystemTime::now().duration_since(UNIX_EPOCH).unwrap().as_secs()) / 30.0).floor() as u32;
}
let key = self._base32_decode(secret)?;
let msg_bytes = unsafe { mem::transmute::<u32,[u8;4]>(message.to_be()) };
let mut message_body:Vec<u8> = vec![0;4];
for msg_byte in msg_bytes.iter() {
message_body.push(*msg_byte);
}
let hash = hmac_sha1(&key, message_body.as_slice());
let offset = hash[hash.len() - 1] & 0x0F;
let mut truncated_hash:[u8;4] = Default::default();
truncated_hash.copy_from_slice(&hash[offset as usize .. (offset + 4) as usize]);
let mut code:u32 = unsafe { mem::transmute::<[u8;4], u32>(truncated_hash) };
if cfg!(target_endian = "big") {
} else {
code = u32::from_be(code);
}
code = code % 1_000_000u32;
let mut code_str = code.to_string();
for i in 0 .. (self.code_len - code_str.len()) {
code_str.insert(i,'0');
}
Ok(code_str)
}
pub fn verify_code(&self, secret:&str, code: &str, discrepancy:u32, time_slice:u32) -> Result<bool>{
let mut curr_time_slice: u32 = time_slice;
if time_slice == 0 {
curr_time_slice = (f64::from_bits(SystemTime::now().duration_since(UNIX_EPOCH).unwrap().as_secs()) / 30.0).floor() as u32;
}
if code.len() != self.code_len {
return Ok(false);
}
for _time_slice in curr_time_slice.wrapping_sub(discrepancy) .. curr_time_slice.wrapping_add(discrepancy + 1) {
if code.eq(self.get_code(secret, _time_slice)?.as_str()) {
return Ok(true);
}
}
Ok(false)
}
fn _base32_decode(&self, secret:&str) -> Result<Vec<u8>>{
match base32::decode(base32::Alphabet::RFC4648 { padding: true }, secret) {
Some(_decode_str) => Ok(_decode_str),
_ => Err(GAError::Error("secret must can decode by base32."))
}
}
}
use std::error;
use std::result;
use std::fmt;
#[derive(Debug)]
pub enum GAError {
Error(&'static str),
}
impl error::Error for GAError{
fn description(&self) -> &str {
match *self {
GAError::Error(description) =>description,
}
}
fn cause(&self) -> Option<&error::Error> {
match *self {
GAError::Error(_) => None,
}
}
}
impl fmt::Display for GAError{
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match *self {
GAError::Error(desc) => f.write_str(desc),
}
}
}
type Result<T> = result::Result<T,GAError>;