HOW-TO

How to verify a TOTP code

Verify a 6-digit TOTP code against a shared secret, with a drift window. Step-by-step, plus a free tool to test it.

Verifying a TOTP code means recomputing the expected code from the shared secret and current time and comparing it to what the user entered — allowing a small window for clock drift. Here is how, and how to test it free.

Allow for clock drift

The user’s phone and your server clocks are never perfectly in sync. Standard practice is to accept the code for the current 30-second window plus one step on each side, so a code from a slightly-off clock still passes. Widen the window only as much as you must — each extra step slightly enlarges the guessing surface.

Prevent reuse

To stop a captured code being replayed within its window, record the last accepted time-step per user and reject a code from a step you have already accepted. Test your implementation with our TOTP tool, which shows the live code and verifies pasted codes.

Step by step

1

Load the user’s stored Base32 secret.

2

Compute the expected TOTP for the current 30-second step (HMAC-SHA1, 6 digits).

3

Compare against the submitted code, also checking ±1 step for clock drift.

4

Record the accepted step to reject replays within the window.

5

Test the whole flow with our TOTP generator/verifier before shipping.

Try it now — free, no signup

Use the TOTP verifier in your browser. Then, when you need it at scale with an API key and higher limits, grab the full Eveses API.

FAQ

Why do valid codes sometimes fail?›
Clock drift. Accept ±1 time step and make sure server time is synced via NTP.
How big should the drift window be?›
One step on each side (±30s) is typical. Larger windows are more forgiving but slightly less secure.

Related