crypto-random-string
Advanced tools
Comparing version 2.0.0 to 3.0.0
@@ -0,6 +1,59 @@ | ||
import {MergeExclusive} from 'type-fest'; | ||
interface BaseOptions { | ||
/** | ||
Length of the returned string. | ||
*/ | ||
length: number; | ||
} | ||
interface TypeOption { | ||
/** | ||
Use only characters from a predefined set of allowed characters. | ||
Cannot be set at the same time as the `characters` option. | ||
@default 'hex' | ||
@example | ||
``` | ||
cryptoRandomString({length: 10}); | ||
//=> '87fc70e2b9' | ||
cryptoRandomString({length: 10, type:'base64'}); | ||
//=> 'mhsX7xmIv/' | ||
cryptoRandomString({length: 10, type:'url-safe'}); | ||
//=> 'VEjfNW3Yej' | ||
``` | ||
*/ | ||
type?: 'hex' | 'base64' | 'url-safe'; | ||
} | ||
interface CharactersOption { | ||
/** | ||
Use only characters from a custom set of allowed characters. | ||
Cannot be set at the same time as the `type` option. | ||
Minimum length: `1` | ||
Maximum length: `65536` | ||
@example | ||
``` | ||
cryptoRandomString({length: 10, characters:'0123456789'}); | ||
//=> '8796225811' | ||
``` | ||
*/ | ||
characters?: string; | ||
} | ||
declare namespace cryptoRandomString { | ||
type Options = BaseOptions & MergeExclusive<TypeOption, CharactersOption>; | ||
} | ||
/** | ||
Generate a [cryptographically strong](https://en.m.wikipedia.org/wiki/Strong_cryptography) random string. | ||
Generate a [cryptographically strong](https://en.wikipedia.org/wiki/Strong_cryptography) random string. | ||
@param length - Length of the returned string. | ||
@returns A [`hex`](https://en.wikipedia.org/wiki/Hexadecimal) string. | ||
@returns A randomized string. | ||
@@ -11,8 +64,8 @@ @example | ||
cryptoRandomString(10); | ||
cryptoRandomString({length: 10}); | ||
//=> '2cf05d94db' | ||
``` | ||
*/ | ||
declare function cryptoRandomString(length: number): string; | ||
declare function cryptoRandomString(options?: cryptoRandomString.Options): string; | ||
export = cryptoRandomString; |
76
index.js
'use strict'; | ||
const crypto = require('crypto'); | ||
module.exports = length => { | ||
const urlSafeCharacters = 'abcdefjhijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-._~'.split(''); | ||
const generateForCustomCharacters = (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 = crypto.randomBytes(entropyLength); | ||
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 allowedTypes = [ | ||
undefined, | ||
'hex', | ||
'base64', | ||
'url-safe' | ||
]; | ||
module.exports = ({length, type, characters}) => { | ||
if (!Number.isFinite(length)) { | ||
@@ -9,3 +45,39 @@ throw new TypeError('Expected a finite number'); | ||
return crypto.randomBytes(Math.ceil(length / 2)).toString('hex').slice(0, length); | ||
if (type !== undefined && characters !== undefined) { | ||
throw new TypeError('Expected either type or characters'); | ||
} | ||
if (characters !== undefined && typeof characters !== 'string') { | ||
throw new TypeError('Expected characters to be string'); | ||
} | ||
if (!allowedTypes.includes(type)) { | ||
throw new TypeError(`Unknown type: ${type}`); | ||
} | ||
if (type === undefined && characters === undefined) { | ||
type = 'hex'; | ||
} | ||
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 | ||
} | ||
if (type === 'base64') { | ||
return crypto.randomBytes(Math.ceil(length * 0.75)).toString('base64').slice(0, length); // Need 0.75 byte of entropy per character | ||
} | ||
if (type === 'url-safe') { | ||
return generateForCustomCharacters(length, urlSafeCharacters); | ||
} | ||
if (characters.length === 0) { | ||
throw new TypeError('Expected `characters` string length to be greater than or equal to 1'); | ||
} | ||
if (characters.length > 0x10000) { | ||
throw new TypeError('Expected `characters` string length to be less or equal to 65536'); | ||
} | ||
return generateForCustomCharacters(length, characters.split('')); | ||
}; |
{ | ||
"name": "crypto-random-string", | ||
"version": "2.0.0", | ||
"version": "3.0.0", | ||
"description": "Generate a cryptographically strong random string", | ||
@@ -35,2 +35,5 @@ "license": "MIT", | ||
], | ||
"dependencies": { | ||
"type-fest": "^0.4.1" | ||
}, | ||
"devDependencies": { | ||
@@ -37,0 +40,0 @@ "ava": "^1.4.1", |
# crypto-random-string [![Build Status](https://travis-ci.org/sindresorhus/crypto-random-string.svg?branch=master)](https://travis-ci.org/sindresorhus/crypto-random-string) | ||
> Generate a [cryptographically strong](https://en.m.wikipedia.org/wiki/Strong_cryptography) random string | ||
> Generate a [cryptographically strong](https://en.wikipedia.org/wiki/Strong_cryptography) random string | ||
@@ -20,4 +20,13 @@ Can be useful for creating an identifier, slug, salt, fixture, etc. | ||
cryptoRandomString(10); | ||
cryptoRandomString({length: 10}); | ||
//=> '2cf05d94db' | ||
cryptoRandomString({length: 10, type: 'base64'}); | ||
//=> 'YMiMbaQl6I' | ||
cryptoRandomString({length: 10, type: 'url-safe'}); | ||
//=> 'YN-tqc8pOw' | ||
cryptoRandomString({length: 10, characters: '1234567890'}); | ||
//=> '1791935639' | ||
``` | ||
@@ -28,8 +37,13 @@ | ||
### cryptoRandomString(length) | ||
### cryptoRandomString(options) | ||
Returns a [`hex`](https://en.wikipedia.org/wiki/Hexadecimal) string. | ||
Returns a randomized string. [Hex](https://en.wikipedia.org/wiki/Hexadecimal) by default. | ||
#### length | ||
#### options | ||
Type: `object` | ||
##### length | ||
*Required*<br> | ||
Type: `number` | ||
@@ -39,3 +53,23 @@ | ||
##### type | ||
Type: `string`<br> | ||
Default: `'hex'`<br> | ||
Values: `'hex'` `'base64'` `'url-safe'` | ||
Use only characters from a predefined set of allowed characters. | ||
Cannot be set at the same time as the `characters` option. | ||
##### characters | ||
Type: `string`<br> | ||
Minimum length: `1`<br> | ||
Maximum length: `65536` | ||
Use only characters from a custom set of allowed characters. | ||
Cannot be set at the same time as the `type` option. | ||
## Related | ||
@@ -42,0 +76,0 @@ |
8133
117
86
1
+ Addedtype-fest@^0.4.1
+ Addedtype-fest@0.4.1(transitive)