Skip to content

Instantly share code, notes, and snippets.

@thameera
Last active October 28, 2020 04:05
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save thameera/4fb64dcb5f65c482817581085dac71bc to your computer and use it in GitHub Desktop.
Save thameera/4fb64dcb5f65c482817581085dac71bc to your computer and use it in GitHub Desktop.
TOTP generator
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