Skip to content

Commit

Permalink
Added bufferizeSecret
Browse files Browse the repository at this point in the history
  • Loading branch information
DoctorMcKay committed Nov 20, 2015
1 parent 3746988 commit da79828
Showing 1 changed file with 16 additions and 10 deletions.
26 changes: 16 additions & 10 deletions index.js
Original file line number Diff line number Diff line change
Expand Up @@ -7,23 +7,15 @@ var Crypto = require('crypto');
* @returns {string}
*/
exports.generateAuthCode = function(secret, timeOffset) {
if(typeof secret === 'string') {
// Check if it's hex
if(secret.match(/[0-9a-f]{40}/i)) {
secret = new Buffer(secret, 'hex');
} else {
// Looks like it's base64
secret = new Buffer(secret, 'base64');
}
}
secret = bufferizeSecret(secret);

var time = Math.floor(Date.now() / 1000) + (timeOffset || 0);

var buffer = new Buffer(8);
buffer.writeUInt32BE(0, 0); // This will stop working in 2038!
buffer.writeUInt32BE(Math.floor(time / 30), 4);

var hmac = require('crypto').createHmac('sha1', secret);
var hmac = Crypto.createHmac('sha1', secret);
hmac = hmac.update(buffer).digest();

var start = hmac[19] & 0x0F;
Expand All @@ -41,3 +33,17 @@ exports.generateAuthCode = function(secret, timeOffset) {

return code;
};

function bufferizeSecret(secret) {
if(typeof secret === 'string') {
// Check if it's hex
if(secret.match(/[0-9a-f]{40}/i)) {
return new Buffer(secret, 'hex');
} else {
// Looks like it's base64
return new Buffer(secret, 'base64');
}
}

return secret;
}

0 comments on commit da79828

Please sign in to comment.