Last active
October 28, 2020 04:05
-
-
Save thameera/4fb64dcb5f65c482817581085dac71bc to your computer and use it in GitHub Desktop.
TOTP generator
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const base32 = require('base32.js') | |
const crypto = require('crypto') | |
const secret = 'MFA_SECRET_GOES_HERE' | |
// Example secret: JRKTI3COHQ7HKOL3GBJF2MK6HBMG2S3H | |
const hotp = (counter) => { | |
const counterHex = counter.toString(16).padStart(16, '0') | |
// Calculate digest | |
const decSecret = base32.decode(secret) | |
const hmac = crypto.createHmac('sha1', decSecret) | |
const digest = hmac.update(Buffer.from(counterHex, 'hex')).digest() | |
// Calculate HOTP offset | |
const offset = digest[digest.length - 1] & 0xf; | |
// Calculate binary code | |
const binCode = (digest[offset] & 0x7f) << 24 | | |
(digest[offset + 1] & 0xff) << 16 | | |
(digest[offset + 2] & 0xff) << 8 | | |
(digest[offset + 3] & 0xff); | |
const code = ('000000' + binCode.toString(10)).substr(-6) | |
return code | |
} | |
const totp = () => { | |
const counter = Math.floor(Date.now() / 30 / 1000) | |
return hotp(counter) | |
} | |
console.log(totp()) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment