A time-based one-time password (TOTP) is a short code, usually six digits, that an authenticator app calculates from a secret key and the current time. The server holds the same secret and does the same calculation, so it can check the code without any message being sent to the user. A new code appears every 30 seconds by default. TOTP is defined in RFC 6238 and powers apps such as Google Authenticator, Microsoft Authenticator and Authy.
TOTP stops password-only attacks and is stronger than SMS codes, but it doesn’t stop phishing: NIST SP 800-63B-4 states that OTP authentication is not phishing-resistant, because a user can type the code into a fake site. This guide covers how TOTP works, a worked example you can check against the RFC, the server-side rules that matter, and where TOTP fits next to passkeys.
In this article:
How TOTP Works
TOTP turns time into a counter and feeds that counter, with the shared secret, into an HMAC. Both sides compute the same result as long as their clocks roughly agree.
- Enrollment. The server generates a random secret for the user and shows it as a QR code. The user’s authenticator app scans it and stores the secret.
- Time step. At sign-in, the app computes T = floor((current Unix time − T0) / X). RFC 6238 sets the defaults to T0 = 0 (the Unix epoch) and X = 30 seconds, so T increases by one every 30 seconds.
- HMAC. The app computes HMAC-SHA-1 of T, written as an 8-byte number, using the secret as the key. RFC 6238 also allows HMAC-SHA-256 and HMAC-SHA-512.
- Truncation. It takes four bytes from the HMAC at an offset given by the last byte (the dynamic truncation from RFC 4226 section 5.3), clears the top bit, and takes the result modulo 106 to get six digits.
- Verification. The user types the code. The server repeats the calculation with its copy of the secret and compares the results.
A worked example you can verify
This Python implementation reproduces the test vectors published in RFC 6238 appendix B. With the RFC’s test secret (the ASCII string 12345678901234567890, shown here in Base32) at Unix time 59, it returns the RFC’s expected 8-digit code, 94287082. The verify function adds the server-side rules covered in the checklist below; start last_used_step at -1 for a user who has never signed in, and store the accepted step after each success.
import base64
import hashlib
import hmac
import struct
import time
def totp(secret: bytes, unix_time: int, digits: int = 6, period: int = 30, algorithm=hashlib.sha1) -> str:
time_step = unix_time // period
digest = hmac.new(secret, struct.pack(">Q", time_step), algorithm).digest()
offset = digest[-1] & 0x0F
truncated = struct.unpack(">I", digest[offset:offset + 4])[0] & 0x7FFFFFFF
return str(truncated % 10 ** digits).zfill(digits)
def verify(secret: bytes, submitted_code: str, last_used_step: int, digits: int = 6, period: int = 30,
algorithm=hashlib.sha1, allowed_drift_steps: int = 1):
if len(submitted_code) != digits or not submitted_code.isascii() or not submitted_code.isdigit():
return None
current_step = int(time.time()) // period
for step in range(current_step - allowed_drift_steps, current_step + allowed_drift_steps + 1):
if step <= last_used_step:
continue
expected = totp(secret, step * period, digits=digits, period=period, algorithm=algorithm)
if hmac.compare_digest(expected, submitted_code):
return step
return None
rfc_test_secret = base64.b32decode("GEZDGNBVGY3TQOJQGEZDGNBVGY3TQOJQ")
print(totp(rfc_test_secret, 59, digits=8))
current_code = totp(rfc_test_secret, int(time.time()))
accepted_step = verify(rfc_test_secret, current_code, last_used_step=-1)
print(accepted_step is not None, verify(rfc_test_secret, current_code, last_used_step=accepted_step))
TOTP parameters
| Parameter | Common value | Notes |
|---|---|---|
| Time step (period) | 30 seconds | RFC 6238 default and recommendation |
| Digits | 6 | HOTP requires at least 6; 8 is allowed |
| Algorithm | HMAC-SHA-1 | SHA-256 and SHA-512 are allowed, but not every app supports them |
| Secret length | 160 bits (20 bytes) | RFC 4226 requires at least 128 bits and recommends 160 |
| Accepted drift | ±1 time step | RFC 6238 recommends allowing at most one step for network delay |
The otpauth:// URI behind the QR code
The QR code shown at enrollment encodes a URI in the format Google documented for its authenticator, which most apps follow:
otpauth://totp/Acme:jane@acme.com?secret=JBSWY3DPEHPK3PXP&issuer=Acme&algorithm=SHA1&digits=6&period=30
The label (Acme:jane@acme.com) names the account, issuer names your service, and the secret is Base32 without padding. Also show the secret as text next to the QR code for users who can’t scan it. Stick to the defaults (SHA-1, 6 digits, 30 seconds): Google’s Key URI documentation, now archived, noted that Google Authenticator ignored the algorithm and period parameters, and the digits parameter on Android, so non-default values can produce codes your server rejects.
TOTP vs. HOTP vs. SMS Codes
TOTP uses the time, HOTP uses a counter, and SMS codes are sent by the server; none of them is phishing-resistant. TOTP grew out of HOTP, the counter-based one-time password in RFC 4226, and both are generated on the user’s device. SMS codes travel over the phone network, where they can be intercepted or redirected by SIM swapping, which makes them the weakest of the three.
| TOTP | HOTP | SMS one-time code | |
|---|---|---|---|
| Moving factor | Current time | A counter that increases with each use | Random code from the server |
| Code lifetime | One time step, usually 30 seconds | Until used or a newer code is accepted | Set by the server, often minutes |
| Needs network at sign-in | No | No | Yes, mobile network |
| Main weakness | Phishing; clock drift | Phishing; counter desynchronization | Phishing, SIM swapping, interception |
| Phishing-resistant | No | No | No |
For phishing resistance you need passkeys or other FIDO2/WebAuthn authenticators, which bind each login to the real website. See our guide to MFA types for the full comparison.
Tips from the expert
Anthony Dombrowski is a product manager and developer advocate with expertise in developer experience, cybersecurity, and product strategy. He has led initiatives at Ping Identity and DevNetwork to enhance developer tools, authentication processes, and user experiences.
- Adopt phishing-resistant second-factor options alongside TOTPs: TOTPs alone can be vulnerable to real-time phishing attacks. Complement them with methods like FIDO2/WebAuthn-based authentication to ensure phishing-resistant second factors for high-security applications.
- Secure secret sharing during enrollment: During TOTP setup, ensure the secret key (seed) is delivered to the client securely.
- Implement device binding: Bind TOTPs to a specific device through unique identifiers and secure storage (e.g., a secure enclave) to mitigate risks of TOTP keys being extracted or transferred to unauthorized devices.
- Use adaptive authentication with TOTPs: Step-up from TOTP authentication with risk-aware steps. For example, flag and prompt for additional verification if a TOTP login occurs from an unusual location, device, or time.
- Protect TOTP seeds with encryption and HSMs: Store server-side TOTP seeds (the shared secret) using encryption and in hardware security modules (HSMs). Ensure secrets are accessible only to authentication processes and not to general application layers.
Security Benefits of TOTP
TOTP adds a factor an attacker can’t get from a password leak, at almost no cost to users:
- Stolen passwords aren’t enough. Credential stuffing with leaked passwords fails without the current code.
- Short-lived codes. A captured code is useless after its time step, and a correct server rejects it even within the step once it has been used.
- Nothing to intercept in transit. Unlike SMS, the code is computed on the device, so SIM swapping and SMS interception don’t apply.
- Works offline and is free. Users need only an authenticator app, and there is no per-message cost for you.
Security Risks of TOTP
TOTP’s weaknesses come from the code being typed by a person and the secret being shared between two places.
Real-time phishing
A phishing site can ask for the password and the current code, then replay both to the real site within seconds. Adversary-in-the-middle phishing kits automate this. It is why NIST classifies OTP as not phishing-resistant and why high-risk accounts should use passkeys or security keys instead.
Stolen shared secrets
The server stores every user’s secret. If that database leaks, an attacker can generate valid codes for every account. Encrypt secrets at rest, keep the key in a key management service or hardware security module, and restrict which services can read them.
Brute force
A six-digit code has one million possible values, so guessing is practical without limits. RFC 4226 recommends throttling and says any delay or lockout must apply across login sessions, and NIST SP 800-63B-4 requires limiting consecutive failed attempts on one account to no more than 100. In practice, set a much lower limit with increasing delays.
Clock drift and lost devices
If a device clock drifts, codes start failing; RFC 6238 suggests tracking each token’s drift to resynchronize. Users also lose or replace phones, and a recovery process that is weaker than TOTP itself, such as an email link, becomes the easiest way in.
TOTP Implementation Checklist
Follow these rules on the server:
- Generate secrets with a cryptographically secure random generator, 160 bits (20 bytes) per user, unique per enrollment.
- Confirm enrollment with a first code before activating TOTP, so a mistyped or partly scanned secret doesn’t lock the user out.
- Accept one time step either side, no more. RFC 6238 recommends allowing at most one step for network delay.
- Reject reused codes. Store the last accepted time step per user, update it with an atomic compare-and-set so two simultaneous submissions can’t both succeed, and refuse any code at or before it. RFC 6238 says the verifier must not accept a second attempt after a successful validation, and NIST requires each OTP to be accepted only once while it is valid.
- Rate-limit failed attempts per account, across sessions and IP addresses, and alert the user after repeated failures.
- Compare codes in constant time to avoid timing leaks.
- Encrypt stored secrets and never log them or return them after enrollment.
- Issue recovery codes at enrollment, store them hashed, make each single-use, and protect account recovery as strongly as sign-in.
- Offer a phishing-resistant option, such as passkeys, and require it for administrators and other high-risk roles.
Implementing TOTP Securely with Frontegg
Frontegg includes authenticator-app MFA, so you don’t build enrollment, verification or recovery yourself. According to Frontegg’s MFA documentation:
- Five MFA methods. Authenticator apps, SMS, built-in authenticators, security keys and email, so you can offer TOTP alongside phishing-resistant options.
- QR enrollment. Users scan a QR code or copy the key manually, and receive a recovery code when they set up MFA.
- Enforcement policies. You can leave MFA optional, force it, or force it except for users who sign in through enterprise SSO. Your customers’ account admins can set stricter MFA rules for their own accounts.
- Remembered devices. A remembered device can skip MFA, while adaptive MFA can still prompt when a sign-in looks risky.
Sign up for free and try Frontegg today.
Put this into practice with Frontegg
Frontegg is customer identity and access management (CIAM) for B2B SaaS. It's free up to 7,500 monthly active users, including 5 SSO/SCIM connections.
Start for freeThe Complete Guide to SaaS Multi-Tenant Architecture
Read the guide