Skip to content

Instantly share code, notes, and snippets.

@nvssks
Last active July 9, 2021 11:42
Show Gist options
  • Save nvssks/3e7aef955c4fd05f417d661f330d63d9 to your computer and use it in GitHub Desktop.
Save nvssks/3e7aef955c4fd05f417d661f330d63d9 to your computer and use it in GitHub Desktop.
topt-generator using crypto-js library (for use in postman)
/*
Code borrowed from the following library and modified to work with crypto-js (for use in postman):
https://github.com/bellstrand/totp-generator/blob/master/LICENSE
Install requirements:
npm i crypto-js
Run:
node otp_script.js {{GOOGLE AUTH KEY}}
*/
let CryptoJS = require("crypto-js");
function hex2dec(s) {
return parseInt(s, 16);
}
function dec2hex(s) {
return (s < 15.5 ? '0' : '') + Math.round(s).toString(16);
}
function base32tohex(base32) {
let base32chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ234567',
bits = '',
hex = '';
base32 = base32.replace(/=+$/, '');
for(let i = 0; i < base32.length; i++) {
let val = base32chars.indexOf(base32.charAt(i).toUpperCase());
if (val === -1) throw new Error("Invalid base32 character in key");
bits += leftpad(val.toString(2), 5, '0');
}
for(let i = 0; i + 8 <= bits.length; i += 8) {
let chunk = bits.substr(i, 8);
hex = hex + leftpad(parseInt(chunk, 2).toString(16), 2, '0');
}
return hex;
}
function leftpad(str, len, pad) {
if(len + 1 >= str.length) {
str = Array(len + 1 - str.length).join(pad) + str;
}
return str;
}
function getToken(key, options) {
options = options || {};
let epoch, time, shaObj, hmac, offset, otp;
options.period = options.period || 30;
options.algorithm = options.algorithm || 'SHA-1';
options.digits = options.digits || 6;
key = base32tohex(key);
epoch = Math.round(Date.now() / 1000.0);
time = leftpad(dec2hex(Math.floor(epoch / options.period)), 16, '0');
shaObj = CryptoJS.algo.HMAC.create(CryptoJS.algo.SHA1, CryptoJS.enc.Hex.parse(key));
shaObj.update(CryptoJS.enc.Hex.parse(time));
hmac = shaObj.finalize().toString(CryptoJS.enc.Hex);
offset = hex2dec(hmac.substring(hmac.length - 1));
otp = (hex2dec(hmac.substr(offset * 2, 8)) & hex2dec('7fffffff')) + '';
otp = otp.substr(otp.length - options.digits, options.digits);
return otp;
}
console.log(getToken(process.argv[2]))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment