crypto-random-string
Advanced tools
Comparing version 3.2.0 to 3.3.0
@@ -20,2 +20,6 @@ import {MergeExclusive} from 'type-fest'; | ||
The `ascii-printable` set contains all [printable ASCII characters](https://en.wikipedia.org/wiki/ASCII#ASCII_printable_characters): ``!"#$%&\'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`abcdefghijklmnopqrstuvwxyz{|}~`` Useful for generating passwords where all possible ASCII characters should be used. | ||
The `alphanumeric` set contains uppercase letters, lowercase letters, and digits: `ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789`. Useful for generating [nonce](https://developer.mozilla.org/en-US/docs/Web/API/HTMLOrForeignElement/nonce) values. | ||
@example | ||
@@ -37,5 +41,11 @@ ``` | ||
//=> 'CDEHKM' | ||
cryptoRandomString({length: 10, type: 'ascii-printable'}); | ||
//=> '`#Rt8$IK>B' | ||
cryptoRandomString({length: 10, type: 'alphanumeric'}); | ||
//=> 'DMuKL8YtE7' | ||
``` | ||
*/ | ||
type?: 'hex' | 'base64' | 'url-safe' | 'numeric' | 'distinguishable'; | ||
type?: 'hex' | 'base64' | 'url-safe' | 'numeric' | 'distinguishable' | 'ascii-printable' | 'alphanumeric'; | ||
} | ||
@@ -65,17 +75,34 @@ | ||
/** | ||
Generate a [cryptographically strong](https://en.wikipedia.org/wiki/Strong_cryptography) random string. | ||
declare const cryptoRandomString: { | ||
/** | ||
Generate a [cryptographically strong](https://en.wikipedia.org/wiki/Strong_cryptography) random string. | ||
@returns A randomized string. | ||
@returns A randomized string. | ||
@example | ||
``` | ||
import cryptoRandomString = require('crypto-random-string'); | ||
@example | ||
``` | ||
import cryptoRandomString = require('crypto-random-string'); | ||
cryptoRandomString({length: 10}); | ||
//=> '2cf05d94db' | ||
``` | ||
*/ | ||
declare function cryptoRandomString(options?: cryptoRandomString.Options): string; | ||
cryptoRandomString({length: 10}); | ||
//=> '2cf05d94db' | ||
``` | ||
*/ | ||
(options?: cryptoRandomString.Options): string; | ||
/** | ||
Asynchronously generate a [cryptographically strong](https://en.wikipedia.org/wiki/Strong_cryptography) random string. | ||
@returns A promise which resolves to a randomized string. | ||
@example | ||
``` | ||
import cryptoRandomString = require('crypto-random-string'); | ||
await cryptoRandomString.async({length: 10}); | ||
//=> '2cf05d94db' | ||
``` | ||
*/ | ||
async(options?: cryptoRandomString.Options): Promise<string>; | ||
} | ||
export = cryptoRandomString; |
60
index.js
'use strict'; | ||
const {promisify} = require('util'); | ||
const crypto = require('crypto'); | ||
const randomBytesAsync = promisify(crypto.randomBytes); | ||
const urlSafeCharacters = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-._~'.split(''); | ||
const numericCharacters = '0123456789'.split(''); | ||
const distinguishableCharacters = 'CDEHKMPRTUWXY012458'.split(''); | ||
const asciiPrintableCharacters = '!"#$%&\'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`abcdefghijklmnopqrstuvwxyz{|}~'.split(''); | ||
const alphanumericCharacters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789'.split(''); | ||
@@ -35,2 +40,36 @@ const generateForCustomCharacters = (length, characters) => { | ||
const generateForCustomCharactersAsync = async (length, characters) => { | ||
// Generating entropy is faster than complex math operations, so we use the simplest way | ||
const characterCount = characters.length; | ||
const maxValidSelector = (Math.floor(0x10000 / characterCount) * characterCount) - 1; // Using values above this will ruin distribution when using modular division | ||
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 | ||
let string = ''; | ||
let stringLength = 0; | ||
while (stringLength < length) { // In case we had many bad values, which may happen for character sets of size above 0x8000 but close to it | ||
const entropy = await randomBytesAsync(entropyLength); // eslint-disable-line no-await-in-loop | ||
let entropyPosition = 0; | ||
while (entropyPosition < entropyLength && stringLength < length) { | ||
const entropyValue = entropy.readUInt16LE(entropyPosition); | ||
entropyPosition += 2; | ||
if (entropyValue > maxValidSelector) { // Skip values which will ruin distribution when using modular division | ||
continue; | ||
} | ||
string += characters[entropyValue % characterCount]; | ||
stringLength++; | ||
} | ||
} | ||
return string; | ||
}; | ||
const generateRandomBytes = (byteLength, type, length) => crypto.randomBytes(byteLength).toString(type).slice(0, length); | ||
const generateRandomBytesAsync = async (byteLength, type, length) => { | ||
const buffer = await randomBytesAsync(byteLength); | ||
return buffer.toString(type).slice(0, length); | ||
}; | ||
const allowedTypes = [ | ||
@@ -42,6 +81,8 @@ undefined, | ||
'numeric', | ||
'distinguishable' | ||
'distinguishable', | ||
'ascii-printable', | ||
'alphanumeric' | ||
]; | ||
module.exports = ({length, type, characters}) => { | ||
const createGenerator = (generateForCustomCharacters, generateRandomBytes) => ({length, type, characters}) => { | ||
if (!(length >= 0 && Number.isFinite(length))) { | ||
@@ -68,7 +109,7 @@ throw new TypeError('Expected a `length` to be a non-negative finite number'); | ||
if (type === 'hex' || (type === undefined && characters === undefined)) { | ||
return crypto.randomBytes(Math.ceil(length * 0.5)).toString('hex').slice(0, length); // Need 0.5 byte entropy per character | ||
return generateRandomBytes(Math.ceil(length * 0.5), 'hex', length); // Need 0.5 byte entropy per character | ||
} | ||
if (type === 'base64') { | ||
return crypto.randomBytes(Math.ceil(length * 0.75)).toString('base64').slice(0, length); // Need 0.75 byte of entropy per character | ||
return generateRandomBytes(Math.ceil(length * 0.75), 'base64', length); // Need 0.75 byte of entropy per character | ||
} | ||
@@ -88,2 +129,10 @@ | ||
if (type === 'ascii-printable') { | ||
return generateForCustomCharacters(length, asciiPrintableCharacters); | ||
} | ||
if (type === 'alphanumeric') { | ||
return generateForCustomCharacters(length, alphanumericCharacters); | ||
} | ||
if (characters.length === 0) { | ||
@@ -99,1 +148,4 @@ throw new TypeError('Expected `characters` string length to be greater than or equal to 1'); | ||
}; | ||
module.exports = createGenerator(generateForCustomCharacters, generateRandomBytes); | ||
module.exports.async = createGenerator(generateForCustomCharactersAsync, generateRandomBytesAsync); |
{ | ||
"name": "crypto-random-string", | ||
"version": "3.2.0", | ||
"version": "3.3.0", | ||
"description": "Generate a cryptographically strong random string", | ||
@@ -5,0 +5,0 @@ "license": "MIT", |
@@ -33,2 +33,8 @@ # crypto-random-string [![Build Status](https://travis-ci.org/sindresorhus/crypto-random-string.svg?branch=master)](https://travis-ci.org/sindresorhus/crypto-random-string) | ||
cryptoRandomString({length: 10, type: 'ascii-printable'}); | ||
//=> '`#Rt8$IK>B' | ||
cryptoRandomString({length: 10, type: 'alphanumeric'}); | ||
//=> 'DMuKL8YtE7' | ||
cryptoRandomString({length: 10, characters: 'abc'}); | ||
@@ -44,2 +50,6 @@ //=> 'abaaccabac' | ||
### cryptoRandomString.async(options) | ||
Returns a promise which resolves to a randomized string. [Hex](https://en.wikipedia.org/wiki/Hexadecimal) by default. | ||
#### options | ||
@@ -60,3 +70,3 @@ | ||
Default: `'hex'`\ | ||
Values: `'hex' | 'base64' | 'url-safe' | 'numeric' | 'distinguishable'` | ||
Values: `'hex' | 'base64' | 'url-safe' | 'numeric' | 'distinguishable' | 'ascii-printable' | 'alphanumeric'` | ||
@@ -69,2 +79,6 @@ Use only characters from a predefined set of allowed characters. | ||
The `ascii-printable` set contains all [printable ASCII characters](https://en.wikipedia.org/wiki/ASCII#ASCII_printable_characters): ``!"#$%&\'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`abcdefghijklmnopqrstuvwxyz{|}~`` Useful for generating passwords where all possible ASCII characters should be used. | ||
The `alphanumeric` set contains uppercase letters, lowercase letters, and digits: `ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789`. Useful for generating [nonce](https://developer.mozilla.org/en-US/docs/Web/API/HTMLOrForeignElement/nonce) values. | ||
##### characters | ||
@@ -71,0 +85,0 @@ |
License Policy Violation
LicenseThis package is not allowed per your license policy. Review the package's license to ensure compliance.
Found 1 instance in 1 package
License Policy Violation
LicenseThis package is not allowed per your license policy. Review the package's license to ensure compliance.
Found 1 instance in 1 package
14460
194
111