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.

JavascriptAuth Jwt

Code

javascriptsnippet
1 line
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, crypto will 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

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.