1use crate::primitives::hash::{sha1_hmac, sha256_hmac, sha512_hmac};
6use subtle::ConstantTimeEq;
7
8#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
14pub enum Algorithm {
15 #[default]
17 Sha1,
18 Sha256,
20 Sha512,
22}
23
24#[derive(Debug, Clone)]
28pub struct TotpOptions {
29 pub digits: u32,
34
35 pub algorithm: Algorithm,
40
41 pub period: u64,
46
47 pub timestamp: Option<u64>,
52}
53
54impl Default for TotpOptions {
55 fn default() -> Self {
56 Self {
57 digits: 6,
58 algorithm: Algorithm::Sha1,
59 period: 30,
60 timestamp: None,
61 }
62 }
63}
64
65#[derive(Debug, Clone)]
69pub struct TotpValidateOptions {
70 pub options: TotpOptions,
72
73 pub skew: u32,
82}
83
84impl Default for TotpValidateOptions {
85 fn default() -> Self {
86 Self {
87 options: TotpOptions::default(),
88 skew: 1,
89 }
90 }
91}
92
93pub struct Totp;
118
119impl Totp {
120 pub fn generate(secret: &[u8], options: Option<TotpOptions>) -> String {
154 let options = options.unwrap_or_default();
155 let timestamp = options.timestamp.unwrap_or_else(current_unix_seconds);
156 let counter = timestamp / options.period;
157 generate_hotp(secret, counter, &options)
158 }
159
160 pub fn validate(secret: &[u8], passcode: &str, options: Option<TotpValidateOptions>) -> bool {
202 let options = options.unwrap_or_default();
203 let passcode = passcode.trim();
204
205 if passcode.len() != options.options.digits as usize {
207 return false;
208 }
209
210 let timestamp = options
211 .options
212 .timestamp
213 .unwrap_or_else(current_unix_seconds);
214 let counter = timestamp / options.options.period;
215
216 let mut counters_to_check = Vec::with_capacity(1 + 2 * options.skew as usize);
219 counters_to_check.push(counter);
220
221 for i in 1..=options.skew as u64 {
222 counters_to_check.push(counter.wrapping_add(i));
223 if counter >= i {
225 counters_to_check.push(counter - i);
226 }
227 }
228
229 for check_counter in counters_to_check {
230 let expected = generate_hotp(secret, check_counter, &options.options);
231 if constant_time_eq(passcode, &expected) {
232 return true;
233 }
234 }
235
236 false
237 }
238}
239
240fn generate_hotp(secret: &[u8], counter: u64, options: &TotpOptions) -> String {
248 let counter_bytes = counter.to_be_bytes();
250
251 let hmac_result: Vec<u8> = match options.algorithm {
253 Algorithm::Sha1 => sha1_hmac(secret, &counter_bytes).to_vec(),
254 Algorithm::Sha256 => sha256_hmac(secret, &counter_bytes).to_vec(),
255 Algorithm::Sha512 => sha512_hmac(secret, &counter_bytes).to_vec(),
256 };
257
258 let offset = (hmac_result[hmac_result.len() - 1] & 0x0f) as usize;
260
261 let code_bytes = [
263 hmac_result[offset] & 0x7f, hmac_result[offset + 1],
265 hmac_result[offset + 2],
266 hmac_result[offset + 3],
267 ];
268
269 let code = u32::from_be_bytes(code_bytes);
270
271 let divisor = 10u32.pow(options.digits);
273 let truncated = code % divisor;
274
275 format!("{:0>width$}", truncated, width = options.digits as usize)
277}
278
279fn current_unix_seconds() -> u64 {
281 crate::util::time::current_time_secs()
282}
283
284fn constant_time_eq(a: &str, b: &str) -> bool {
286 if a.len() != b.len() {
287 return false;
288 }
289 a.as_bytes().ct_eq(b.as_bytes()).into()
290}
291
292#[cfg(test)]
293mod tests {
294 use super::*;
295
296 const SHA1_SECRET: &[u8] = b"12345678901234567890";
299 const SHA256_SECRET: &[u8] = b"12345678901234567890123456789012";
300 const SHA512_SECRET: &[u8] =
301 b"1234567890123456789012345678901234567890123456789012345678901234";
302
303 #[test]
305 fn test_rfc6238_sha1_time_59() {
306 let options = TotpOptions {
307 digits: 8,
308 algorithm: Algorithm::Sha1,
309 timestamp: Some(59),
310 ..Default::default()
311 };
312 let code = Totp::generate(SHA1_SECRET, Some(options));
313 assert_eq!(code, "94287082");
314 }
315
316 #[test]
317 fn test_rfc6238_sha256_time_59() {
318 let options = TotpOptions {
319 digits: 8,
320 algorithm: Algorithm::Sha256,
321 timestamp: Some(59),
322 ..Default::default()
323 };
324 let code = Totp::generate(SHA256_SECRET, Some(options));
325 assert_eq!(code, "46119246");
326 }
327
328 #[test]
329 fn test_rfc6238_sha512_time_59() {
330 let options = TotpOptions {
331 digits: 8,
332 algorithm: Algorithm::Sha512,
333 timestamp: Some(59),
334 ..Default::default()
335 };
336 let code = Totp::generate(SHA512_SECRET, Some(options));
337 assert_eq!(code, "90693936");
338 }
339
340 #[test]
341 fn test_rfc6238_sha1_time_1111111109() {
342 let options = TotpOptions {
343 digits: 8,
344 algorithm: Algorithm::Sha1,
345 timestamp: Some(1111111109),
346 ..Default::default()
347 };
348 let code = Totp::generate(SHA1_SECRET, Some(options));
349 assert_eq!(code, "07081804");
350 }
351
352 #[test]
353 fn test_rfc6238_sha256_time_1111111109() {
354 let options = TotpOptions {
355 digits: 8,
356 algorithm: Algorithm::Sha256,
357 timestamp: Some(1111111109),
358 ..Default::default()
359 };
360 let code = Totp::generate(SHA256_SECRET, Some(options));
361 assert_eq!(code, "68084774");
362 }
363
364 #[test]
365 fn test_rfc6238_sha512_time_1111111109() {
366 let options = TotpOptions {
367 digits: 8,
368 algorithm: Algorithm::Sha512,
369 timestamp: Some(1111111109),
370 ..Default::default()
371 };
372 let code = Totp::generate(SHA512_SECRET, Some(options));
373 assert_eq!(code, "25091201");
374 }
375
376 #[test]
377 fn test_rfc6238_sha1_time_1111111111() {
378 let options = TotpOptions {
379 digits: 8,
380 algorithm: Algorithm::Sha1,
381 timestamp: Some(1111111111),
382 ..Default::default()
383 };
384 let code = Totp::generate(SHA1_SECRET, Some(options));
385 assert_eq!(code, "14050471");
386 }
387
388 #[test]
389 fn test_rfc6238_sha256_time_1111111111() {
390 let options = TotpOptions {
391 digits: 8,
392 algorithm: Algorithm::Sha256,
393 timestamp: Some(1111111111),
394 ..Default::default()
395 };
396 let code = Totp::generate(SHA256_SECRET, Some(options));
397 assert_eq!(code, "67062674");
398 }
399
400 #[test]
401 fn test_rfc6238_sha512_time_1111111111() {
402 let options = TotpOptions {
403 digits: 8,
404 algorithm: Algorithm::Sha512,
405 timestamp: Some(1111111111),
406 ..Default::default()
407 };
408 let code = Totp::generate(SHA512_SECRET, Some(options));
409 assert_eq!(code, "99943326");
410 }
411
412 #[test]
413 fn test_rfc6238_sha1_time_1234567890() {
414 let options = TotpOptions {
415 digits: 8,
416 algorithm: Algorithm::Sha1,
417 timestamp: Some(1234567890),
418 ..Default::default()
419 };
420 let code = Totp::generate(SHA1_SECRET, Some(options));
421 assert_eq!(code, "89005924");
422 }
423
424 #[test]
425 fn test_rfc6238_sha256_time_1234567890() {
426 let options = TotpOptions {
427 digits: 8,
428 algorithm: Algorithm::Sha256,
429 timestamp: Some(1234567890),
430 ..Default::default()
431 };
432 let code = Totp::generate(SHA256_SECRET, Some(options));
433 assert_eq!(code, "91819424");
434 }
435
436 #[test]
437 fn test_rfc6238_sha512_time_1234567890() {
438 let options = TotpOptions {
439 digits: 8,
440 algorithm: Algorithm::Sha512,
441 timestamp: Some(1234567890),
442 ..Default::default()
443 };
444 let code = Totp::generate(SHA512_SECRET, Some(options));
445 assert_eq!(code, "93441116");
446 }
447
448 #[test]
449 fn test_rfc6238_sha1_time_2000000000() {
450 let options = TotpOptions {
451 digits: 8,
452 algorithm: Algorithm::Sha1,
453 timestamp: Some(2000000000),
454 ..Default::default()
455 };
456 let code = Totp::generate(SHA1_SECRET, Some(options));
457 assert_eq!(code, "69279037");
458 }
459
460 #[test]
461 fn test_rfc6238_sha256_time_2000000000() {
462 let options = TotpOptions {
463 digits: 8,
464 algorithm: Algorithm::Sha256,
465 timestamp: Some(2000000000),
466 ..Default::default()
467 };
468 let code = Totp::generate(SHA256_SECRET, Some(options));
469 assert_eq!(code, "90698825");
470 }
471
472 #[test]
473 fn test_rfc6238_sha512_time_2000000000() {
474 let options = TotpOptions {
475 digits: 8,
476 algorithm: Algorithm::Sha512,
477 timestamp: Some(2000000000),
478 ..Default::default()
479 };
480 let code = Totp::generate(SHA512_SECRET, Some(options));
481 assert_eq!(code, "38618901");
482 }
483
484 #[test]
485 fn test_rfc6238_sha1_time_20000000000() {
486 let options = TotpOptions {
487 digits: 8,
488 algorithm: Algorithm::Sha1,
489 timestamp: Some(20000000000),
490 ..Default::default()
491 };
492 let code = Totp::generate(SHA1_SECRET, Some(options));
493 assert_eq!(code, "65353130");
494 }
495
496 #[test]
497 fn test_rfc6238_sha256_time_20000000000() {
498 let options = TotpOptions {
499 digits: 8,
500 algorithm: Algorithm::Sha256,
501 timestamp: Some(20000000000),
502 ..Default::default()
503 };
504 let code = Totp::generate(SHA256_SECRET, Some(options));
505 assert_eq!(code, "77737706");
506 }
507
508 #[test]
509 fn test_rfc6238_sha512_time_20000000000() {
510 let options = TotpOptions {
511 digits: 8,
512 algorithm: Algorithm::Sha512,
513 timestamp: Some(20000000000),
514 ..Default::default()
515 };
516 let code = Totp::generate(SHA512_SECRET, Some(options));
517 assert_eq!(code, "47863826");
518 }
519
520 #[test]
522 fn test_6_digit_sha1_time_59() {
523 let options = TotpOptions {
524 digits: 6,
525 algorithm: Algorithm::Sha1,
526 timestamp: Some(59),
527 ..Default::default()
528 };
529 let code = Totp::generate(SHA1_SECRET, Some(options));
530 assert_eq!(code, "287082");
532 }
533
534 #[test]
535 fn test_6_digit_sha256_time_59() {
536 let options = TotpOptions {
537 digits: 6,
538 algorithm: Algorithm::Sha256,
539 timestamp: Some(59),
540 ..Default::default()
541 };
542 let code = Totp::generate(SHA256_SECRET, Some(options));
543 assert_eq!(code, "119246");
545 }
546
547 #[test]
548 fn test_6_digit_sha512_time_59() {
549 let options = TotpOptions {
550 digits: 6,
551 algorithm: Algorithm::Sha512,
552 timestamp: Some(59),
553 ..Default::default()
554 };
555 let code = Totp::generate(SHA512_SECRET, Some(options));
556 assert_eq!(code, "693936");
558 }
559
560 #[test]
562 fn test_validate_current_code() {
563 let options = TotpOptions {
564 digits: 6,
565 timestamp: Some(59),
566 ..Default::default()
567 };
568 let code = Totp::generate(SHA1_SECRET, Some(options.clone()));
569
570 let validate_options = TotpValidateOptions { options, skew: 1 };
571 assert!(Totp::validate(SHA1_SECRET, &code, Some(validate_options)));
572 }
573
574 #[test]
575 fn test_validate_rejects_invalid_code() {
576 let options = TotpOptions {
577 digits: 6,
578 timestamp: Some(59),
579 ..Default::default()
580 };
581 let validate_options = TotpValidateOptions { options, skew: 1 };
582 assert!(!Totp::validate(
583 SHA1_SECRET,
584 "000000",
585 Some(validate_options)
586 ));
587 }
588
589 #[test]
590 fn test_validate_with_skew_previous_period() {
591 let gen_options = TotpOptions {
593 digits: 6,
594 timestamp: Some(59),
595 ..Default::default()
596 };
597 let code = Totp::generate(SHA1_SECRET, Some(gen_options));
598
599 let validate_options = TotpValidateOptions {
601 options: TotpOptions {
602 digits: 6,
603 timestamp: Some(89),
604 ..Default::default()
605 },
606 skew: 1,
607 };
608 assert!(Totp::validate(SHA1_SECRET, &code, Some(validate_options)));
609 }
610
611 #[test]
612 fn test_validate_with_skew_next_period() {
613 let gen_options = TotpOptions {
615 digits: 6,
616 timestamp: Some(59),
617 ..Default::default()
618 };
619 let code = Totp::generate(SHA1_SECRET, Some(gen_options));
620
621 let validate_options = TotpValidateOptions {
623 options: TotpOptions {
624 digits: 6,
625 timestamp: Some(29),
626 ..Default::default()
627 },
628 skew: 1,
629 };
630 assert!(Totp::validate(SHA1_SECRET, &code, Some(validate_options)));
631 }
632
633 #[test]
634 fn test_validate_rejects_outside_skew() {
635 let gen_options = TotpOptions {
637 digits: 6,
638 timestamp: Some(59),
639 ..Default::default()
640 };
641 let code = Totp::generate(SHA1_SECRET, Some(gen_options));
642
643 let validate_options = TotpValidateOptions {
645 options: TotpOptions {
646 digits: 6,
647 timestamp: Some(119),
648 ..Default::default()
649 },
650 skew: 1,
651 };
652 assert!(!Totp::validate(SHA1_SECRET, &code, Some(validate_options)));
653 }
654
655 #[test]
656 fn test_validate_rejects_wrong_length() {
657 let validate_options = TotpValidateOptions {
658 options: TotpOptions {
659 digits: 6,
660 timestamp: Some(59),
661 ..Default::default()
662 },
663 skew: 1,
664 };
665
666 assert!(!Totp::validate(
668 SHA1_SECRET,
669 "12345",
670 Some(validate_options.clone())
671 ));
672
673 assert!(!Totp::validate(
675 SHA1_SECRET,
676 "1234567",
677 Some(validate_options)
678 ));
679 }
680
681 #[test]
682 fn test_validate_trims_whitespace() {
683 let options = TotpOptions {
684 digits: 6,
685 timestamp: Some(59),
686 ..Default::default()
687 };
688 let code = Totp::generate(SHA1_SECRET, Some(options.clone()));
689
690 let validate_options = TotpValidateOptions { options, skew: 1 };
691
692 let padded_code = format!(" {} ", code);
694 assert!(Totp::validate(
695 SHA1_SECRET,
696 &padded_code,
697 Some(validate_options)
698 ));
699 }
700
701 #[test]
702 fn test_60_second_period() {
703 let options_30 = TotpOptions {
704 digits: 6,
705 timestamp: Some(59),
706 period: 30,
707 ..Default::default()
708 };
709 let options_60 = TotpOptions {
710 digits: 6,
711 timestamp: Some(59),
712 period: 60,
713 ..Default::default()
714 };
715
716 let code_30 = Totp::generate(SHA1_SECRET, Some(options_30));
717 let code_60 = Totp::generate(SHA1_SECRET, Some(options_60));
718
719 assert_ne!(code_30, code_60);
722 }
723
724 #[test]
726 fn test_ts_sdk_compat_unix_epoch() {
727 let secret = hex::decode("48656c6c6f21deadbeef").unwrap();
729 let options = TotpOptions {
730 digits: 6,
731 algorithm: Algorithm::Sha1,
732 period: 30,
733 timestamp: Some(0),
734 };
735 let code = Totp::generate(&secret, Some(options));
736 assert_eq!(code, "282760");
737 }
738
739 #[test]
740 fn test_ts_sdk_compat_2016_timestamp() {
741 let secret = hex::decode("48656c6c6f21deadbeef").unwrap();
743 let options = TotpOptions {
744 digits: 6,
745 algorithm: Algorithm::Sha1,
746 period: 30,
747 timestamp: Some(1465324707),
748 };
749 let code = Totp::generate(&secret, Some(options));
750 assert_eq!(code, "341128");
751 }
752
753 #[test]
754 fn test_ts_sdk_compat_leading_zero() {
755 let secret = hex::decode("48656c6c6f21deadbeef").unwrap();
757 let options = TotpOptions {
758 digits: 6,
759 algorithm: Algorithm::Sha1,
760 period: 30,
761 timestamp: Some(1365324707),
762 };
763 let code = Totp::generate(&secret, Some(options));
764 assert_eq!(code, "089029");
765 }
766
767 #[test]
768 fn test_ts_sdk_compat_cycle_boundary_start() {
769 let secret = hex::decode("48656c6c6f21deadbeef").unwrap();
771 let options = TotpOptions {
772 digits: 6,
773 algorithm: Algorithm::Sha1,
774 period: 30,
775 timestamp: Some(1665644340),
776 };
777 let code = Totp::generate(&secret, Some(options));
778 assert_eq!(code, "886842");
779 }
780
781 #[test]
782 fn test_ts_sdk_compat_cycle_boundary_end() {
783 let secret = hex::decode("48656c6c6f21deadbeef").unwrap();
785 let options = TotpOptions {
786 digits: 6,
787 algorithm: Algorithm::Sha1,
788 period: 30,
789 timestamp: Some(1665644339),
790 };
791 let code = Totp::generate(&secret, Some(options));
792 assert_eq!(code, "134996");
793 }
794
795 #[test]
797 fn test_default_options() {
798 let code = Totp::generate(SHA1_SECRET, None);
800 assert_eq!(code.len(), 6);
801 }
802
803 #[test]
804 fn test_validate_with_none_options() {
805 let code = Totp::generate(SHA1_SECRET, None);
806 assert!(Totp::validate(SHA1_SECRET, &code, None));
807 }
808
809 #[test]
810 fn test_constant_time_eq() {
811 assert!(constant_time_eq("123456", "123456"));
812 assert!(!constant_time_eq("123456", "654321"));
813 assert!(!constant_time_eq("123", "123456"));
814 assert!(!constant_time_eq("123456", "123"));
815 }
816
817 #[test]
818 fn test_constant_time_eq_empty() {
819 assert!(constant_time_eq("", ""));
821 }
822
823 #[test]
824 fn test_counter_near_zero() {
825 let options = TotpOptions {
827 digits: 6,
828 timestamp: Some(0), ..Default::default()
830 };
831 let code = Totp::generate(SHA1_SECRET, Some(options.clone()));
832
833 let validate_options = TotpValidateOptions { options, skew: 1 };
834 assert!(Totp::validate(SHA1_SECRET, &code, Some(validate_options)));
835 }
836
837 #[test]
838 fn test_algorithm_enum_default() {
839 let algo: Algorithm = Default::default();
840 assert_eq!(algo, Algorithm::Sha1);
841 }
842
843 #[test]
844 fn test_algorithm_enum_clone_eq() {
845 let algo1 = Algorithm::Sha256;
846 let algo2 = algo1;
847 assert_eq!(algo1, algo2);
848 }
849
850 #[test]
851 fn test_totp_options_clone() {
852 let options = TotpOptions {
853 digits: 8,
854 algorithm: Algorithm::Sha512,
855 period: 60,
856 timestamp: Some(12345),
857 };
858 let cloned = options.clone();
859 assert_eq!(cloned.digits, 8);
860 assert_eq!(cloned.algorithm, Algorithm::Sha512);
861 assert_eq!(cloned.period, 60);
862 assert_eq!(cloned.timestamp, Some(12345));
863 }
864
865 #[test]
867 fn test_digits_1() {
868 let options = TotpOptions {
869 digits: 1,
870 timestamp: Some(59),
871 ..Default::default()
872 };
873 let code = Totp::generate(SHA1_SECRET, Some(options.clone()));
874 assert_eq!(code.len(), 1);
875
876 let validate_options = TotpValidateOptions { options, skew: 0 };
878 assert!(Totp::validate(SHA1_SECRET, &code, Some(validate_options)));
879 }
880
881 #[test]
882 fn test_digits_9() {
883 let options = TotpOptions {
885 digits: 9,
886 timestamp: Some(59),
887 ..Default::default()
888 };
889 let code = Totp::generate(SHA1_SECRET, Some(options.clone()));
890 assert_eq!(code.len(), 9);
891
892 let validate_options = TotpValidateOptions { options, skew: 0 };
894 assert!(Totp::validate(SHA1_SECRET, &code, Some(validate_options)));
895 }
896
897 #[test]
901 fn test_rfc4226_hotp_vectors() {
902 let expected = [
903 "755224", "287082", "359152", "969429", "338314", "254676", "287922", "162583", "399871", "520489", ];
914
915 for (counter, expected_code) in expected.iter().enumerate() {
916 let options = TotpOptions {
917 digits: 6,
918 algorithm: Algorithm::Sha1,
919 period: 1, timestamp: Some(counter as u64), };
922 let code = Totp::generate(SHA1_SECRET, Some(options));
923 assert_eq!(
924 &code, expected_code,
925 "RFC 4226 HOTP vector failed for counter {}",
926 counter
927 );
928 }
929 }
930}