-
Notifications
You must be signed in to change notification settings - Fork 72
/
randomstring.js
92 lines (76 loc) · 2.12 KB
/
randomstring.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
"use strict";
var randomBytes = require('randombytes');
var Charset = require('./charset.js');
function safeRandomBytes(length) {
while (true) {
try {
return randomBytes(length);
} catch(e) {
continue;
}
}
}
function processString(buf, initialString, chars, reqLen, maxByte) {
var string = initialString;
for (var i = 0; i < buf.length && string.length < reqLen; i++) {
var randomByte = buf.readUInt8(i);
if (randomByte < maxByte) {
string += chars.charAt(randomByte % chars.length);
}
}
return string;
}
function getAsyncString(string, chars, length, maxByte, cb) {
randomBytes(length, function(err, buf) {
if (err) {
// Since it is waiting for entropy, errors are legit and we shouldn't just keep retrying
cb(err);
}
var generatedString = processString(buf, string, chars, length, maxByte);
if (generatedString.length < length) {
getAsyncString(generatedString, chars, length, maxByte, cb);
} else {
cb(null, generatedString);
}
})
}
exports.generate = function(options, cb) {
var charset = new Charset();
var length, chars, capitalization, string = '';
// Handle options
if (typeof options === 'object') {
length = options.length || 32;
if (options.charset) {
charset.setType(options.charset);
}
else {
charset.setType('alphanumeric');
}
if (options.capitalization) {
charset.setcapitalization(options.capitalization);
}
if (options.readable) {
charset.removeUnreadable();
}
charset.removeDuplicates();
}
else if (typeof options === 'number') {
length = options;
charset.setType('alphanumeric');
}
else {
length = 32;
charset.setType('alphanumeric');
}
// Generate the string
var charsLen = charset.chars.length;
var maxByte = 256 - (256 % charsLen);
if (!cb) {
while (string.length < length) {
var buf = safeRandomBytes(Math.ceil(length * 256 / maxByte));
string = processString(buf, string, charset.chars, length, maxByte);
}
return string;
}
getAsyncString(string, charset.chars, length, maxByte, cb);
};