The 30-Second Time Counter Math
TOTP is built on HMAC-based One-Time Passwords (HOTP, RFC 4226). While HOTP increments an event counter on every login, TOTP derives its counter directly from the current Unix epoch time in seconds: Counter = floor(UnixTime / 30).
Because both your smartphone and the authentication server have internal quartz clocks synchronized to UTC, both parties calculate the identical integer counter at any given second without needing to communicate over the network.
HMAC-SHA1 and Dynamic Truncation
The counter integer (packed as an 8-byte big-endian buffer) and your Base32-decoded secret key are fed into an HMAC-SHA1 algorithm, yielding a 20-byte cryptographic hash.
Dynamic truncation takes the last 4 bits of the hash as an offset, extracts a 31-bit unsigned integer from that offset, and computes integer modulo 1,000,000 to produce the final 6-digit verification code.
Step-by-Step Tutorial
Read Current Unix Timestamp
Divide Math.floor(Date.now() / 1000) by 30 to calculate the current time counter window.
Compute HMAC-SHA1 Digest
Hash the 8-byte counter buffer with your shared Base32 secret using Web Crypto API.
Extract 6-Digit Verification Code
Perform 4-byte dynamic truncation and take modulo 10^6 to display the live 6-digit code.
Ready to Try It Yourself?
DocSwift processes everything directly on your device. Fast, safe, and completely free forever.
How helpful was this guide?
Rated 4.9 / 5 by 3,420+ users worldwide
Share with Colleagues & Friends
Help others protect their document privacy
Frequently Asked Questions
Why does TOTP work without an internet connection on my phone?
Because the calculation requires only the shared secret seed and the current Unix timestamp from your device hardware clock. No network communication is involved.
What happens if my device clock is slightly out of sync?
RFC 6238 servers routinely evaluate the previous counter window (-30s) and next window (+30s) to tolerate minor client clock drifts of ±1 minute.