TOTP Two Factor Generate And Verify
Generate TOTP codes from a shared secret with time step and digit parameters and verify with window tolerance for clock skew.
Code
export async function generateTOTP(secret,{step=30,digits=6,t=Date.now()/1000}={}){const counter=Math.floor(t/step);const key=await crypto.subtle.importKey('raw',base32Decode(secret),{name:'HMAC',hash:'SHA-1'},false,['sign']);const msg=new ArrayBuffer(8);new DataView(msg).setBigUint64(0,BigInt(counter));const sig=new Uint8Array(await crypto.subtle.sign('HMAC',key,msg));const offset=sig[sig.length-1]&0xf;const code=((sig[offset]&0x7f)<<24|sig[offset+1]<<16|sig[offset+2]<<8|sig[offset+3])%10**digits;return code.toString().padStart(digits,'0');}export async function verifyTOTP(secret,code,{window=1}={}){for(let i=-window;i<=window;i++)if(await generateTOTP(secret,{t:(Date.now()/1000)+i*30})===code)return true;return false;}How the snippet works
Count the functions code, generateTOTP and verifyTOTP as the entire surface area of TOTP Two Factor Generate And Verify.
Asynchronous boundaries use await, so failures surface as rejected promises at the call site instead of being swallowed.
What to watch for
- This is browser-side code —
window,cryptowill not resolve in Node.
Using it
The primary signature is export async function generateTOTP(secret,{step=30,digits=6,t=Date.now()
The surface worth importing is generateTOTP; the helpers around it are private to the snippet.
Interactive Tools for This Topic
Basic & Bearer Auth Header ToolEncode and decode HTTP Authorization Basic and Bearer headers locally with UTF-8 Base64 validation and automatic JWT claim and expiry inspection.JWT Expiry CalculatorDecode a JWT payload and convert its exp, iat, and nbf claims into UTC ISO timestamps, with an expired-or-valid verdict.TOTP URI Builder & Code GeneratorBuild valid otpauth://totp QR provisioning URIs and compute RFC 6238 HMAC-SHA1, SHA-256, or SHA-512 verification codes locally using Web Crypto.JWT Token DecoderDecode JSON Web Token (JWT) headers and payloads safely in the browser. Inspect expiration, issuer, and claims without sending tokens to any external server.
FAQ
- Does TOTP Two Factor Generate And Verify run in plain Node.js?
- No — it touches `window`, which exist only in the browser. Run it in a page (or the DevTools console) instead of a bare Node process.
Report a problem with this exampleOpens a pre-filled issue on GitHub.