Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Remove bias when generating secrets #92

Open
wants to merge 2 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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