|
1 |
| -import {promisify} from 'util'; |
2 |
| -import crypto from 'crypto'; |
| 1 | +import {promisify} from 'node:util'; |
| 2 | +import crypto from 'node:crypto'; |
| 3 | +import {createStringGenerator, createAsyncStringGenerator} from './core.js'; |
3 | 4 |
|
4 | 5 | const randomBytesAsync = promisify(crypto.randomBytes);
|
5 | 6 |
|
6 |
| -const urlSafeCharacters = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-._~'.split(''); |
7 |
| -const numericCharacters = '0123456789'.split(''); |
8 |
| -const distinguishableCharacters = 'CDEHKMPRTUWXY012458'.split(''); |
9 |
| -const asciiPrintableCharacters = '!"#$%&\'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`abcdefghijklmnopqrstuvwxyz{|}~'.split(''); |
10 |
| -const alphanumericCharacters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789'.split(''); |
11 |
| - |
12 |
| -const generateForCustomCharacters = (length, characters) => { |
13 |
| - // Generating entropy is faster than complex math operations, so we use the simplest way |
14 |
| - const characterCount = characters.length; |
15 |
| - const maxValidSelector = (Math.floor(0x10000 / characterCount) * characterCount) - 1; // Using values above this will ruin distribution when using modular division |
16 |
| - const entropyLength = 2 * Math.ceil(1.1 * length); // Generating a bit more than required so chances we need more than one pass will be really low |
17 |
| - let string = ''; |
18 |
| - let stringLength = 0; |
19 |
| - |
20 |
| - while (stringLength < length) { // In case we had many bad values, which may happen for character sets of size above 0x8000 but close to it |
21 |
| - const entropy = crypto.randomBytes(entropyLength); |
22 |
| - let entropyPosition = 0; |
23 |
| - |
24 |
| - while (entropyPosition < entropyLength && stringLength < length) { |
25 |
| - const entropyValue = entropy.readUInt16LE(entropyPosition); |
26 |
| - entropyPosition += 2; |
27 |
| - if (entropyValue > maxValidSelector) { // Skip values which will ruin distribution when using modular division |
28 |
| - continue; |
29 |
| - } |
30 |
| - |
31 |
| - string += characters[entropyValue % characterCount]; |
32 |
| - stringLength++; |
33 |
| - } |
34 |
| - } |
35 |
| - |
36 |
| - return string; |
37 |
| -}; |
38 |
| - |
39 |
| -const generateForCustomCharactersAsync = async (length, characters) => { |
40 |
| - // Generating entropy is faster than complex math operations, so we use the simplest way |
41 |
| - const characterCount = characters.length; |
42 |
| - const maxValidSelector = (Math.floor(0x10000 / characterCount) * characterCount) - 1; // Using values above this will ruin distribution when using modular division |
43 |
| - const entropyLength = 2 * Math.ceil(1.1 * length); // Generating a bit more than required so chances we need more than one pass will be really low |
44 |
| - let string = ''; |
45 |
| - let stringLength = 0; |
46 |
| - |
47 |
| - while (stringLength < length) { // In case we had many bad values, which may happen for character sets of size above 0x8000 but close to it |
48 |
| - const entropy = await randomBytesAsync(entropyLength); // eslint-disable-line no-await-in-loop |
49 |
| - let entropyPosition = 0; |
50 |
| - |
51 |
| - while (entropyPosition < entropyLength && stringLength < length) { |
52 |
| - const entropyValue = entropy.readUInt16LE(entropyPosition); |
53 |
| - entropyPosition += 2; |
54 |
| - if (entropyValue > maxValidSelector) { // Skip values which will ruin distribution when using modular division |
55 |
| - continue; |
56 |
| - } |
57 |
| - |
58 |
| - string += characters[entropyValue % characterCount]; |
59 |
| - stringLength++; |
60 |
| - } |
61 |
| - } |
62 |
| - |
63 |
| - return string; |
64 |
| -}; |
65 |
| - |
66 |
| -const generateRandomBytes = (byteLength, type, length) => crypto.randomBytes(byteLength).toString(type).slice(0, length); |
67 |
| - |
68 |
| -const generateRandomBytesAsync = async (byteLength, type, length) => { |
| 7 | +const cryptoRandomString = createStringGenerator((byteLength, type, length) => crypto.randomBytes(byteLength).toString(type).slice(0, length), crypto.randomBytes); |
| 8 | +cryptoRandomString.async = createAsyncStringGenerator(async (byteLength, type, length) => { |
69 | 9 | const buffer = await randomBytesAsync(byteLength);
|
70 | 10 | return buffer.toString(type).slice(0, length);
|
71 |
| -}; |
72 |
| - |
73 |
| -const allowedTypes = new Set([ |
74 |
| - undefined, |
75 |
| - 'hex', |
76 |
| - 'base64', |
77 |
| - 'url-safe', |
78 |
| - 'numeric', |
79 |
| - 'distinguishable', |
80 |
| - 'ascii-printable', |
81 |
| - 'alphanumeric' |
82 |
| -]); |
83 |
| - |
84 |
| -const createGenerator = (generateForCustomCharacters, generateRandomBytes) => ({length, type, characters}) => { |
85 |
| - if (!(length >= 0 && Number.isFinite(length))) { |
86 |
| - throw new TypeError('Expected a `length` to be a non-negative finite number'); |
87 |
| - } |
88 |
| - |
89 |
| - if (type !== undefined && characters !== undefined) { |
90 |
| - throw new TypeError('Expected either `type` or `characters`'); |
91 |
| - } |
92 |
| - |
93 |
| - if (characters !== undefined && typeof characters !== 'string') { |
94 |
| - throw new TypeError('Expected `characters` to be string'); |
95 |
| - } |
96 |
| - |
97 |
| - if (!allowedTypes.has(type)) { |
98 |
| - throw new TypeError(`Unknown type: ${type}`); |
99 |
| - } |
100 |
| - |
101 |
| - if (type === undefined && characters === undefined) { |
102 |
| - type = 'hex'; |
103 |
| - } |
104 |
| - |
105 |
| - if (type === 'hex' || (type === undefined && characters === undefined)) { |
106 |
| - return generateRandomBytes(Math.ceil(length * 0.5), 'hex', length); // Need 0.5 byte entropy per character |
107 |
| - } |
108 |
| - |
109 |
| - if (type === 'base64') { |
110 |
| - return generateRandomBytes(Math.ceil(length * 0.75), 'base64', length); // Need 0.75 byte of entropy per character |
111 |
| - } |
112 |
| - |
113 |
| - if (type === 'url-safe') { |
114 |
| - return generateForCustomCharacters(length, urlSafeCharacters); |
115 |
| - } |
116 |
| - |
117 |
| - if (type === 'numeric') { |
118 |
| - return generateForCustomCharacters(length, numericCharacters); |
119 |
| - } |
120 |
| - |
121 |
| - if (type === 'distinguishable') { |
122 |
| - return generateForCustomCharacters(length, distinguishableCharacters); |
123 |
| - } |
124 |
| - |
125 |
| - if (type === 'ascii-printable') { |
126 |
| - return generateForCustomCharacters(length, asciiPrintableCharacters); |
127 |
| - } |
128 |
| - |
129 |
| - if (type === 'alphanumeric') { |
130 |
| - return generateForCustomCharacters(length, alphanumericCharacters); |
131 |
| - } |
132 |
| - |
133 |
| - if (characters.length === 0) { |
134 |
| - throw new TypeError('Expected `characters` string length to be greater than or equal to 1'); |
135 |
| - } |
136 |
| - |
137 |
| - if (characters.length > 0x10000) { |
138 |
| - throw new TypeError('Expected `characters` string length to be less or equal to 65536'); |
139 |
| - } |
140 |
| - |
141 |
| - return generateForCustomCharacters(length, characters.split('')); |
142 |
| -}; |
143 |
| - |
144 |
| -const cryptoRandomString = createGenerator(generateForCustomCharacters, generateRandomBytes); |
145 |
| - |
146 |
| -cryptoRandomString.async = createGenerator(generateForCustomCharactersAsync, generateRandomBytesAsync); |
| 11 | +}, randomBytesAsync); |
147 | 12 |
|
148 | 13 | export default cryptoRandomString;
|
0 commit comments