summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorVineet Kumar <git@vineetk.net>2026-05-22 14:50:42 -0400
committerVineet Kumar <git@vineetk.net>2026-05-22 14:50:42 -0400
commitf503c45b7156ef47afed0ab6bf98dc1067e79aa7 (patch)
tree18e236e086fc71b6dca7965038eb923235bb0a34
parentfc307ad821becea95353db58a7133bd5317856c1 (diff)
slightly simplify totp code
-rw-r--r--kasi-totp.el15
1 files changed, 5 insertions, 10 deletions
diff --git a/kasi-totp.el b/kasi-totp.el
index 3d197d6..d14e00a 100644
--- a/kasi-totp.el
+++ b/kasi-totp.el
@@ -5,7 +5,6 @@
5(require 'bindat) 5(require 'bindat)
6(require 'gnutls) 6(require 'gnutls)
7(require 'hexl) 7(require 'hexl)
8(require 'auth-source)
9 8
10(defconst base32-alphabet 9(defconst base32-alphabet
11 (let ((tbl (make-char-table nil))) 10 (let ((tbl (make-char-table nil)))
@@ -44,21 +43,17 @@ required for HMAC-TOTP."
44 (seq-map (lambda (s) (hexl-htoi (aref s 0) (aref s 1))) 43 (seq-map (lambda (s) (hexl-htoi (aref s 0) (aref s 1)))
45 (seq-partition string 2)))) 44 (seq-partition string 2))))
46 45
47(defun totp (string &optional time digits) 46(defun totp (string)
48 "Return a TOTP token using the secret hex STRING and current time. 47 "Return a TOTP token using the secret hex STRING and current time."
49TIME is used as counter value instead of current time, if non-nil.
50DIGITS is the number of pin digits and defaults to 6."
51 (let* ((key-bytes (totp--hex-decode-string (upcase string))) 48 (let* ((key-bytes (totp--hex-decode-string (upcase string)))
52 (counter (truncate (/ (or time (time-to-seconds)) 30))) 49 (counter (truncate (/ (time-to-seconds) 30)))
53 (digits (or digits 6))
54 (format-string (format "%%0%dd" digits))
55 ;; we have to manually split the 64 bit number (u64 not supported in Emacs 27.2) 50 ;; we have to manually split the 64 bit number (u64 not supported in Emacs 27.2)
56 (counter-bytes (bindat-pack '((:high u32) (:low u32)) 51 (counter-bytes (bindat-pack '((:high u32) (:low u32))
57 `((:high . ,(ash counter -32)) (:low . ,(logand counter #xffffffff))))) 52 `((:high . ,(ash counter -32)) (:low . ,(logand counter #xffffffff)))))
58 (mac (gnutls-hash-mac 'SHA1 key-bytes counter-bytes)) 53 (mac (gnutls-hash-mac 'SHA1 key-bytes counter-bytes))
59 (offset (logand (bindat-get-field (bindat-unpack '((:offset u8)) mac 19) :offset) #xf))) 54 (offset (logand (bindat-get-field (bindat-unpack '((:offset u8)) mac 19) :offset) #xf)))
60 (format format-string 55 (format "%06d"
61 (mod 56 (mod
62 (logand (bindat-get-field (bindat-unpack '((:totp-pin u32)) mac offset) :totp-pin) 57 (logand (bindat-get-field (bindat-unpack '((:totp-pin u32)) mac offset) :totp-pin)
63 #x7fffffff) 58 #x7fffffff)
64 (expt 10 digits))))) 59 (expt 10 6)))))