CtrlK
BlogDocsLog inGet started
Tessl Logo

tessl/npm-crypto-random-string

Generate a cryptographically strong random string with multiple output formats

Pending

Quality

Pending

Does it follow best practices?

Impact

Pending

No eval scenarios have been run

Overview
Eval results
Files

Crypto Random String

Crypto Random String is a JavaScript library that generates cryptographically strong random strings. It provides multiple output formats including hex, base64, URL-safe, numeric, and custom character sets, with both synchronous and asynchronous APIs that work in Node.js and browser environments.

Package Information

  • Package Name: crypto-random-string
  • Package Type: npm
  • Language: JavaScript (with TypeScript definitions)
  • Installation: npm install crypto-random-string

Core Imports

import cryptoRandomString from 'crypto-random-string';

For the async version:

import { cryptoRandomStringAsync } from 'crypto-random-string';

For CommonJS:

const cryptoRandomString = require('crypto-random-string');
const { cryptoRandomStringAsync } = require('crypto-random-string');

Basic Usage

import cryptoRandomString from 'crypto-random-string';

// Generate hex string (default)
cryptoRandomString({length: 10});
//=> '2cf05d94db'

// Generate base64 string
cryptoRandomString({length: 10, type: 'base64'});
//=> 'YMiMbaQl6I'

// Generate numeric string
cryptoRandomString({length: 8, type: 'numeric'});
//=> '83146591'

// Generate string with custom characters
cryptoRandomString({length: 10, characters: 'abc'});
//=> 'abaaccabac'

Architecture

Crypto Random String uses platform-specific entropy sources for cryptographic security:

  • Node.js: Uses crypto.randomBytes() for high-quality entropy
  • Browser: Uses crypto.getRandomValues() Web Crypto API
  • Universal API: Same function signatures across both platforms
  • Entropy Management: Handles browser entropy limits (65,536 bytes) automatically
  • Character Distribution: Uses mathematically sound techniques to ensure uniform distribution

Capabilities

Synchronous Random String Generation

Generate cryptographically strong random strings synchronously with various output formats.

/**
 * Generate a cryptographically strong random string synchronously
 * @param options - Configuration options for string generation
 * @returns A cryptographically strong random string
 */
function cryptoRandomString(options: Options): string;

interface Options {
  /** Length of the returned string (required) */
  length: number;
  /** Predefined character type (optional, default: 'hex') */
  type?: 'hex' | 'base64' | 'url-safe' | 'numeric' | 'distinguishable' | 'ascii-printable' | 'alphanumeric';
  /** Custom character set (optional, mutually exclusive with type) */
  characters?: string;
}

Usage Examples:

import cryptoRandomString from 'crypto-random-string';

// Hex format (default)
cryptoRandomString({length: 10});
//=> '87fc70e2b9'

// Base64 format  
cryptoRandomString({length: 10, type: 'base64'});
//=> 'mhsX7xmIv/'

// URL-safe format
cryptoRandomString({length: 10, type: 'url-safe'});
//=> 'VEjfNW3Yej'

// Numeric format
cryptoRandomString({length: 10, type: 'numeric'});
//=> '8314659141'

// Distinguishable characters (non-confusing uppercase)
cryptoRandomString({length: 6, type: 'distinguishable'});
//=> 'CDEHKM'

// ASCII printable characters
cryptoRandomString({length: 10, type: 'ascii-printable'});
//=> '`#Rt8$IK>B'

// Alphanumeric characters
cryptoRandomString({length: 10, type: 'alphanumeric'});
//=> 'DMuKL8YtE7'

// Custom character set
cryptoRandomString({length: 10, characters: '0123456789'});
//=> '8796225811'

Asynchronous Random String Generation

Generate cryptographically strong random strings asynchronously. Generally not needed as entropy generation is very fast, but available for special use cases.

/**
 * Generate a cryptographically strong random string asynchronously
 * @param options - Configuration options for string generation
 * @returns Promise that resolves to a cryptographically strong random string
 */
function cryptoRandomStringAsync(options: Options): Promise<string>;

Usage Examples:

import { cryptoRandomStringAsync } from 'crypto-random-string';

// Async hex generation
const hexString = await cryptoRandomStringAsync({length: 10});
//=> '2cf05d94db'

// Async with specific type
const base64String = await cryptoRandomStringAsync({length: 10, type: 'base64'});
//=> 'YMiMbaQl6I'

Character Set Options

The library provides several predefined character sets optimized for different use cases:

type CharacterType = 
  | 'hex'             // Hexadecimal: 0-9, a-f (16 chars)
  | 'base64'          // Base64: A-Z, a-z, 0-9, +, / (64 chars)  
  | 'url-safe'        // URL-safe: A-Z, a-z, 0-9, -, ., _, ~ (66 chars)
  | 'numeric'         // Numeric: 0-9 (10 chars)
  | 'distinguishable' // Non-confusing uppercase: CDEHKMPRTUWXY012458 (19 chars)
  | 'ascii-printable' // All printable ASCII (94 chars)
  | 'alphanumeric';   // Letters and numbers: A-Z, a-z, 0-9 (62 chars)

Character Set Details:

  • hex: Standard hexadecimal characters (0-9, a-f). Default option.
  • base64: Standard Base64 characters including padding characters.
  • url-safe: URL-safe characters that don't require encoding in URLs.
  • numeric: Only numeric digits, useful for PIN codes or numeric IDs.
  • distinguishable: Uppercase characters that are visually distinct, reducing user input errors.
  • ascii-printable: All printable ASCII characters, useful for strong passwords.
  • alphanumeric: Letters and numbers only, useful for human-readable identifiers.

Custom Character Sets

Use custom character sets for specialized requirements:

interface CustomCharacterOptions {
  /** Length of the returned string */
  length: number;
  /** Custom character set (1-65536 characters) */
  characters: string;
}

Usage Examples:

// Custom vowels only
cryptoRandomString({length: 8, characters: 'aeiou'});
//=> 'aeuiaeoi'

// Custom binary
cryptoRandomString({length: 16, characters: '01'});
//=> '1010011001010110'

// Custom symbols for passwords
cryptoRandomString({length: 12, characters: '!@#$%^&*()_+-='});
//=> '!@#*_+@$^%!#'

Error Handling

The functions throw TypeError for invalid inputs:

// Invalid length values
cryptoRandomString({length: -1});          // Throws TypeError
cryptoRandomString({length: Infinity});    // Throws TypeError

// Conflicting options
cryptoRandomString({
  length: 10, 
  type: 'hex', 
  characters: 'abc'
});                                         // Throws TypeError

// Invalid characters option
cryptoRandomString({length: 10, characters: 42});  // Throws TypeError
cryptoRandomString({length: 10, characters: ''});  // Throws TypeError

// Unknown type
cryptoRandomString({length: 10, type: 'unknown'}); // Throws TypeError

Platform Compatibility

The library automatically detects the runtime environment and uses the appropriate entropy source:

  • Node.js (≥14.16): Uses crypto.randomBytes() from the Node.js crypto module
  • Browser: Uses crypto.getRandomValues() from the Web Crypto API
  • Browser Limitations: Automatically handles the 65,536 byte entropy limit by making multiple calls when needed

Import Behavior:

The package.json exports map automatically provides the correct implementation:

// Automatically resolves to:
// - index.js in Node.js  
// - browser.js in browsers
import cryptoRandomString from 'crypto-random-string';

Type Definitions

Complete TypeScript support with strict type checking:

import type { MergeExclusive } from 'type-fest';

interface BaseOptions {
  /** Length of the returned string */
  length: number;
}

interface TypeOption {
  /** Use only characters from a predefined set */
  type?: 'hex' | 'base64' | 'url-safe' | 'numeric' | 'distinguishable' | 'ascii-printable' | 'alphanumeric';
}

interface CharactersOption {
  /** Use only characters from a custom set (1-65536 characters) */
  characters?: string;
}

// Options type ensures type and characters are mutually exclusive
type Options = BaseOptions & MergeExclusive<TypeOption, CharactersOption>;

// Main function signatures
declare function cryptoRandomString(options: Options): string;
declare function cryptoRandomStringAsync(options: Options): Promise<string>;

Install with Tessl CLI

npx tessl i tessl/npm-crypto-random-string
Workspace
tessl
Visibility
Public
Created
Last updated
Describes
npmpkg:npm/crypto-random-string@5.0.x
Publish Source
CLI
Badge
tessl/npm-crypto-random-string badge