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

snippet
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;}