Skip to content

Commit

Permalink
Merge 9aee69d into cb58351
Browse files Browse the repository at this point in the history
  • Loading branch information
pepve committed Jul 14, 2018
2 parents cb58351 + 9aee69d commit f47dd90
Show file tree
Hide file tree
Showing 2 changed files with 11 additions and 8 deletions.
16 changes: 10 additions & 6 deletions index.js
Original file line number Diff line number Diff line change
Expand Up @@ -511,13 +511,13 @@ exports.generateSecret = function generateSecret (options) {
}

// generate an ascii key
var key = this.generateSecretASCII(length, symbols);
var keyBytes = crypto.randomBytes(length || 32);

// return a SecretKey with ascii, hex, and base32
var SecretKey = {};
SecretKey.ascii = key;
SecretKey.hex = Buffer(key, 'ascii').toString('hex');
SecretKey.base32 = base32.encode(Buffer(key)).toString().replace(/=/g, '');
SecretKey.ascii = encodeASCII(keyBytes, symbols);
SecretKey.hex = keyBytes.toString('hex');
SecretKey.base32 = base32.encode(keyBytes).toString().replace(/=/g, '');

// generate some qr codes if requested
if (qr_codes) {
Expand Down Expand Up @@ -560,14 +560,18 @@ exports.generate_key = util.deprecate(function (options) {
*/
exports.generateSecretASCII = function generateSecretASCII (length, symbols) {
var bytes = crypto.randomBytes(length || 32);
var set = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXTZabcdefghiklmnopqrstuvwxyz';
return encodeASCII(bytes, symbols);
};

function encodeASCII (bytes, symbols) {
var set = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz';
if (symbols) {
set += '!@#$%^&*()<>?/[]{},.:;';
}

var output = '';
for (var i = 0, l = bytes.length; i < l; i++) {
output += set[Math.floor(bytes[i] / 255.0 * (set.length - 1))];
output += set[Math.floor(bytes[i] / 256.0 * set.length)];
}
return output;
};
Expand Down
3 changes: 1 addition & 2 deletions test/generate.js
Original file line number Diff line number Diff line change
Expand Up @@ -23,8 +23,7 @@ describe('Generator tests', function () {
assert.isUndefined(secret.google_auth_qr, 'Google Auth QR should not be returned');

// check encodings
assert.equal(Buffer(secret.hex, 'hex').toString('ascii'), secret.ascii, 'Should have encoded correct hex string');
assert.equal(base32.decode(secret.base32).toString('ascii'), secret.ascii, 'Should have encoded correct base32 string');
assert.equal(base32.decode(secret.base32).toString('hex'), secret.hex, 'Should have encoded correct base32 string');
});

it('Generation with custom key length', function () {
Expand Down

0 comments on commit f47dd90

Please sign in to comment.