Skip to content

Commit

Permalink
Merge branch 'haavardw-master'
Browse files Browse the repository at this point in the history
  • Loading branch information
markbao committed Dec 17, 2015
2 parents c58fb5a + c5f97c6 commit b2931ab
Show file tree
Hide file tree
Showing 2 changed files with 37 additions and 6 deletions.
32 changes: 26 additions & 6 deletions lib/speakeasy.js
Expand Up @@ -91,13 +91,8 @@ speakeasy.hotp = function(options) {
|(digest_bytes[offset+2] & 0xff) << 8
|(digest_bytes[offset+3] & 0xff);

bin_code = bin_code.toString();
var code = speakeasy.bin_to_string(bin_code, length);

// get the chars at position bin_code - length through length chars
var sub_start = bin_code.length - length;
var code = bin_code.substr(sub_start, length);

// we now have a code with `length` number of digits, so return it
return(code);
};

Expand Down Expand Up @@ -140,6 +135,31 @@ speakeasy.totp = function(options) {
return(code);
};

// speakeasy.bin_to_string(bin, length)
//
// helper function to convert a number to a string of given length.
//
speakeasy.bin_to_string = function(bin, length) {
var bin_str = bin.toString();

if (bin_str.length < length) {
// pad with 0's
var pad = '';
var padLength = length - bin_str.length;
for (var j = 0; j < padLength; ++j) {
pad += '0';
}

return pad + bin_str;
} else {
// get the chars at position bin_code - length through length chars
var sub_start = bin_str.length - length;
var code = bin_str.substr(sub_start, length);

return code;
}
}

// speakeasy.hex_to_ascii(key)
//
// helper function to convert a hex key to ascii.
Expand Down
11 changes: 11 additions & 0 deletions test/test_hotp.js
Expand Up @@ -56,4 +56,15 @@ vows.describe('HOTP Counter-Based Algorithm Test').addBatch({
assert.equal(topic, '338314');
}
},

'Test 0-padding encoding with key = \'h/,Iv]ET34!].kfNUU^Nf!I#gp1bNT1C\' at counter 3 and length = 8': {
topic: function() {
return speakeasy.hotp({key: 'h/,Iv]ET34!].kfNUU^Nf!I#gp1bNT1C', length: 8, counter: 3});
},

'correct one-time password returned': function(topic) {
assert.equal(topic, '05314231');
}
},

}).exportTo(module);

0 comments on commit b2931ab

Please sign in to comment.