1use data_encoding::{DecodeError, BASE32};
2use ring::hmac;
3use std::time::{SystemTime, SystemTimeError};
4use thiserror::Error;
5
6fn decode_base32(input: &str) -> Result<Vec<u8>, DecodeError> {
8 let input = input.trim();
9 if input.contains('=') {
10 BASE32.decode(input.as_bytes())
11 } else {
12 let mut padded = input.to_string();
15 while padded.len() % 8 != 0 {
16 padded.push('=');
17 }
18 BASE32.decode(padded.as_bytes())
19 }
20}
21
22#[derive(Debug, Error)]
23pub enum Error {
24 #[error("invalid time: {0}")]
25 InvalidTime(#[from] SystemTimeError),
26 #[error("invalid secret: {0}")]
27 DecodeError(#[from] DecodeError),
28 #[error("invalid digest length")]
29 InvalidDigestLength,
30}
31
32#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
34pub enum Algorithm {
35 #[default]
37 SHA1,
38 SHA256,
40 SHA512,
42}
43
44impl From<Algorithm> for hmac::Algorithm {
45 fn from(algo: Algorithm) -> Self {
46 match algo {
47 Algorithm::SHA1 => hmac::HMAC_SHA1_FOR_LEGACY_USE_ONLY,
48 Algorithm::SHA256 => hmac::HMAC_SHA256,
49 Algorithm::SHA512 => hmac::HMAC_SHA512,
50 }
51 }
52}
53
54#[derive(Debug, Clone)]
58pub struct HOTP {
59 secret: Vec<u8>,
60 algorithm: Algorithm,
61 digits: u32,
62}
63
64impl HOTP {
65 pub fn builder() -> HOTPBuilder {
67 HOTPBuilder::new()
68 }
69
70 pub fn new(secret: Vec<u8>, algorithm: Algorithm, digits: u32) -> Self {
72 Self {
73 secret,
74 algorithm,
75 digits,
76 }
77 }
78
79 pub fn generate(&self, counter: u64) -> u32 {
81 let key = hmac::Key::new(self.algorithm.into(), &self.secret);
82 let tag = hmac::sign(&key, &counter.to_be_bytes());
83 let digest = tag.as_ref();
84
85 let offset = (digest[digest.len() - 1] & 0xf) as usize;
86 let code_bytes: [u8; 4] = digest[offset..offset + 4].try_into().unwrap_or([0u8; 4]);
87
88 let code = u32::from_be_bytes(code_bytes);
89 (code & 0x7fffffff) % 10u32.pow(self.digits)
90 }
91
92 pub fn generate_formatted(&self, counter: u64) -> String {
94 format!(
95 "{:0width$}",
96 self.generate(counter),
97 width = self.digits as usize
98 )
99 }
100
101 pub fn verify(&self, code: u32, counter: u64) -> bool {
103 self.generate(counter) == code
104 }
105
106 pub fn verify_formatted(&self, code: &str, counter: u64) -> bool {
108 self.generate_formatted(counter) == code
109 }
110
111 #[cfg(feature = "async")]
112 pub async fn generate_async(&self, counter: u64) -> u32 {
113 self.generate(counter)
114 }
115
116 #[cfg(feature = "async")]
117 pub async fn generate_formatted_async(&self, counter: u64) -> String {
118 self.generate_formatted(counter)
119 }
120}
121
122#[derive(Debug, Default)]
124pub struct HOTPBuilder {
125 secret: Option<Vec<u8>>,
126 algorithm: Algorithm,
127 digits: u32,
128}
129
130impl HOTPBuilder {
131 pub fn new() -> Self {
133 Self {
134 secret: None,
135 algorithm: Algorithm::SHA1,
136 digits: 6,
137 }
138 }
139
140 pub fn secret(mut self, secret: Vec<u8>) -> Self {
142 self.secret = Some(secret);
143 self
144 }
145
146 pub fn base32_secret(mut self, secret: &str) -> Result<Self, DecodeError> {
151 self.secret = Some(decode_base32(secret)?);
152 Ok(self)
153 }
154
155 pub fn algorithm(mut self, algo: Algorithm) -> Self {
157 self.algorithm = algo;
158 self
159 }
160
161 pub fn digits(mut self, digits: u32) -> Self {
163 self.digits = digits;
164 self
165 }
166
167 pub fn build(self) -> Result<HOTP, String> {
172 let secret = self
173 .secret
174 .ok_or_else(|| "Secret is required".to_string())?;
175 if self.digits > 9 {
176 return Err("Digits must be between 1 and 9 for u32 output".to_string());
177 }
178 Ok(HOTP::new(secret, self.algorithm, self.digits))
179 }
180}
181
182#[derive(Debug, Clone)]
186pub struct TOTP {
187 hotp: HOTP,
188 time_step: u64,
189}
190
191impl TOTP {
192 pub fn builder() -> TOTPBuilder {
194 TOTPBuilder::new()
195 }
196
197 pub fn new(secret: Vec<u8>, algorithm: Algorithm, digits: u32, time_step: u64) -> Self {
199 Self {
200 hotp: HOTP::new(secret, algorithm, digits),
201 time_step,
202 }
203 }
204
205 pub fn generate_at(&self, timestamp: u64) -> u32 {
207 let counter = timestamp / self.time_step;
208 self.hotp.generate(counter)
209 }
210
211 pub fn generate_current(&self) -> Result<u32, Error> {
216 let now = SystemTime::now().duration_since(SystemTime::UNIX_EPOCH)?;
217 Ok(self.generate_at(now.as_secs()))
218 }
219
220 pub fn generate_formatted_at(&self, timestamp: u64) -> String {
222 format!(
223 "{:0width$}",
224 self.generate_at(timestamp),
225 width = self.hotp.digits as usize
226 )
227 }
228
229 pub fn generate_current_formatted(&self) -> Result<String, Error> {
234 let now = SystemTime::now().duration_since(SystemTime::UNIX_EPOCH)?;
235 Ok(self.generate_formatted_at(now.as_secs()))
236 }
237
238 pub fn verify_at(&self, code: u32, timestamp: u64, window: u32) -> bool {
243 let current_step = timestamp / self.time_step;
244 for i in 0..=window {
245 if self.hotp.generate(current_step.saturating_sub(i as u64)) == code {
247 return true;
248 }
249 if self.hotp.generate(current_step.saturating_add(i as u64)) == code {
251 return true;
252 }
253 }
254 false
255 }
256
257 pub fn verify_current(&self, code: u32, window: u32) -> Result<bool, Error> {
262 let now = SystemTime::now().duration_since(SystemTime::UNIX_EPOCH)?;
263 Ok(self.verify_at(code, now.as_secs(), window))
264 }
265
266 pub fn verify_current_formatted(&self, code: &str, window: u32) -> Result<bool, Error> {
271 let code_u32 = code
272 .parse::<u32>()
273 .map_err(|_| Error::InvalidDigestLength)?; self.verify_current(code_u32, window)
275 }
276
277 #[cfg(feature = "async")]
279 pub async fn generate_current_async(&self) -> Result<u32, Error> {
280 self.generate_current()
281 }
282
283 #[cfg(feature = "async")]
285 pub async fn generate_current_formatted_async(&self) -> Result<String, Error> {
286 self.generate_current_formatted()
287 }
288}
289
290pub struct TOTPBuilder {
292 secret: Option<Vec<u8>>,
293 algorithm: Algorithm,
294 digits: u32,
295 time_step: u64,
296}
297
298impl Default for TOTPBuilder {
299 fn default() -> Self {
300 Self {
301 secret: None,
302 algorithm: Algorithm::SHA1,
303 digits: 6,
304 time_step: 30,
305 }
306 }
307}
308
309impl TOTPBuilder {
310 pub fn new() -> Self {
312 Self::default()
313 }
314
315 pub fn secret(mut self, secret: Vec<u8>) -> Self {
317 self.secret = Some(secret);
318 self
319 }
320
321 pub fn base32_secret(mut self, secret: &str) -> Result<Self, DecodeError> {
326 let decoded = BASE32.decode(secret.as_bytes())?;
327 self.secret = Some(decoded);
328 Ok(self)
329 }
330
331 pub fn algorithm(mut self, algo: Algorithm) -> Self {
333 self.algorithm = algo;
334 self
335 }
336
337 pub fn digits(mut self, digits: u32) -> Self {
339 self.digits = digits;
340 self
341 }
342
343 pub fn time_step(mut self, step: u64) -> Self {
345 self.time_step = step;
346 self
347 }
348
349 pub fn build(self) -> Result<TOTP, String> {
354 let secret = self
355 .secret
356 .ok_or_else(|| "Secret is required".to_string())?;
357 if self.digits > 9 {
358 return Err("Digits must be between 1 and 9 for u32 output".to_string());
359 }
360 Ok(TOTP::new(
361 secret,
362 self.algorithm,
363 self.digits,
364 self.time_step,
365 ))
366 }
367}
368
369#[cfg(test)]
370mod tests {
371 use super::*;
372
373 #[test]
374 fn test_rfc4226_hotp() {
375 let secret = b"12345678901234567890".to_vec();
377 let hotp = HOTP::new(secret, Algorithm::SHA1, 6);
378
379 assert_eq!(hotp.generate(0), 755224);
380 assert_eq!(hotp.generate(1), 287082);
381 assert_eq!(hotp.generate(2), 359152);
382 assert_eq!(hotp.generate(3), 969429);
383 assert_eq!(hotp.generate(4), 338314);
384 assert_eq!(hotp.generate(5), 254676);
385 assert_eq!(hotp.generate(6), 287922);
386 assert_eq!(hotp.generate(7), 162583);
387 assert_eq!(hotp.generate(8), 399871);
388 assert_eq!(hotp.generate(9), 520489);
389 }
390
391 #[test]
392 fn test_rfc6238_totp_sha1() {
393 let secret = b"12345678901234567890".to_vec();
394 let totp = TOTP::new(secret, Algorithm::SHA1, 8, 30);
395
396 assert_eq!(totp.generate_formatted_at(59), "94287082");
397 assert_eq!(totp.generate_formatted_at(1111111109), "07081804");
398 assert_eq!(totp.generate_formatted_at(1111111111), "14050471");
399 assert_eq!(totp.generate_formatted_at(1234567890), "89005924");
400 assert_eq!(totp.generate_formatted_at(2000000000), "69279037");
401 assert_eq!(totp.generate_formatted_at(20000000000), "65353130");
402 }
403
404 #[test]
405 fn test_rfc6238_totp_sha256() {
406 let secret = b"12345678901234567890123456789012".to_vec();
407 let totp = TOTP::new(secret, Algorithm::SHA256, 8, 30);
408
409 assert_eq!(totp.generate_formatted_at(59), "46119246");
410 assert_eq!(totp.generate_formatted_at(1111111109), "68084774");
411 assert_eq!(totp.generate_formatted_at(1111111111), "67062674");
412 assert_eq!(totp.generate_formatted_at(1234567890), "91819424");
413 assert_eq!(totp.generate_formatted_at(2000000000), "90698825");
414 assert_eq!(totp.generate_formatted_at(20000000000), "77737706");
415 }
416
417 #[test]
418 fn test_rfc6238_totp_sha512() {
419 let secret = b"1234567890123456789012345678901234567890123456789012345678901234".to_vec();
420 let totp = TOTP::new(secret, Algorithm::SHA512, 8, 30);
421
422 assert_eq!(totp.generate_formatted_at(59), "90693936");
423 assert_eq!(totp.generate_formatted_at(1111111109), "25091201");
424 assert_eq!(totp.generate_formatted_at(1111111111), "99943326");
425 assert_eq!(totp.generate_formatted_at(1234567890), "93441116");
426 assert_eq!(totp.generate_formatted_at(2000000000), "38618901");
427 assert_eq!(totp.generate_formatted_at(20000000000), "47863826");
428 }
429
430 #[test]
431 fn test_builder() {
432 let hotp = HOTP::builder()
433 .base32_secret("GEZDGNBVGY3TQOJQGEZDGNBVGY3TQOJQ")
434 .unwrap()
435 .digits(6)
436 .build()
437 .unwrap();
438
439 assert_eq!(hotp.generate(0), 755224);
441 }
442
443 #[test]
444 fn test_unpadded_base32() {
445 let secret = "GEZDGNBVGY3TQOJQGEZDGNBVGY3TQOJQ"; let res = HOTP::builder().base32_secret(secret);
447 assert!(res.is_ok());
448
449 let secret_unpadded = "GEZDGNBVGY3TQOJQGEZDGNBV"; let res = HOTP::builder().base32_secret(secret_unpadded);
451 assert!(
452 res.is_ok(),
453 "Base32 decoding should be robust to missing padding"
454 );
455
456 let secret_very_unpadded = "GEZDG"; let res = HOTP::builder().base32_secret(secret_very_unpadded);
458 assert!(
459 res.is_ok(),
460 "Base32 decoding should handle very unpadded strings"
461 );
462 }
463
464 #[cfg(feature = "async")]
465 #[tokio::test]
466 async fn test_async() {
467 let secret = b"12345678901234567890".to_vec();
468 let hotp = HOTP::new(secret, Algorithm::SHA1, 6);
469 assert_eq!(hotp.generate_async(0).await, 755224);
470
471 let secret = b"12345678901234567890".to_vec();
472 let totp = TOTP::new(secret, Algorithm::SHA1, 6, 30);
473 assert_eq!(totp.generate_current_async().await.is_ok(), true);
474 }
475}