Better random string generation #28

Closed
wants to merge 4 commits into
from
View
@@ -161,20 +161,6 @@ speakeasy.hex_to_ascii = function(str) {
return ascii_string;
}
-// speakeasy.ascii_to_hex(key)
-//
-// helper function to convert an ascii key to hex.
-//
-speakeasy.ascii_to_hex = function(str) {
- var hex_string = '';
-
- for (var i = 0; i < str.length; i++) {
- hex_string += str.charCodeAt(i).toString(16);
- }
-
- return hex_string;
-}
-
// speakeasy.generate_key(options)
//
// Generates a random key with the set A-Z a-z 0-9 and symbols, of any length
@@ -185,7 +171,7 @@ speakeasy.ascii_to_hex = function(str) {
// generate a link to a special QR code for use with the Google Authenticator
// app, for which you can also specify a name.
//
-// options.length(=32) length of key
+// options.length(=32) length of hex key
// .symbols(=true) include symbols in the key
// .qr_codes(=false) generate links to QR codes
// .google_auth_qr(=false) generate a link to a QR code to scan
@@ -207,13 +193,13 @@ speakeasy.generate_key = function(options) {
}
// generate an ascii key
- var key = this.generate_key_ascii(length, symbols);
+ var key = this.generate_random_key(length);
// return a SecretKey with ascii, hex, and base32
var SecretKey = {};
- SecretKey.ascii = key;
- SecretKey.hex = this.ascii_to_hex(key);
- SecretKey.base32 = base32.encode(key).replace(/=/g,'');
+ SecretKey.hex = key.toString('hex');
+ SecretKey.ascii = parseInt(SecretKey.hex, 16).toString(36);
+ SecretKey.base32 = base32.encode(key).toString().replace(/=/g,'');
// generate some qr codes if requested
if (qr_codes) {
@@ -233,28 +219,18 @@ speakeasy.generate_key = function(options) {
return SecretKey;
}
-// speakeasy.generate_key_ascii(length, symbols)
+// speakeasy.generate_random_key(length)
//
-// Generates a random key, of length `length` (default 32).
-// Also choose whether you want symbols, default false.
+// Generates a random key, of length/2 `length` (default 16, generates 32 chars).
// speakeasy.generate_key() wraps around this.
//
-speakeasy.generate_key_ascii = function(length, symbols) {
- if (!length) length = 32;
-
- var set = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXTZabcdefghiklmnopqrstuvwxyz';
-
- if (symbols) {
- set += '!@#$%^&*()<>?/[]{},.:;';
- }
-
- var key = '';
-
- for(var i=0; i < length; i++) {
- key += set.charAt(Math.floor(Math.random() * set.length));
+speakeasy.generate_random_key = function(length) {
+ if (!length) length = 32
+ try {
+ return crypto.randomBytes(length/2);
+ } catch (error) {
+ throw new Error(error);
}
-
- return key;
}
// alias, not the TV show
View
@@ -14,7 +14,7 @@
},
"dependencies": {
"ezcrypto": "0.0.3",
- "thirty-two": "0.0.1"
+ "thirty-two": "0.0.2"
},
"keywords": ["two-factor", "authentication", "hotp", "totp", "multi-factor", "hmac", "one-time password", "passwords"],
"devDependencies": {