@h0llyw00dzz/crypto-rand
Version:
Cryptographically secure random utilities for Node.js and browsers
224 lines (223 loc) • 10.4 kB
TypeScript
/**
* Cryptographically secure random utilities
* Uses crypto module to replace Math.random() and Math.floor() for security.
* Math.random() is not suitable for security-sensitive operations because it is not truly random and can be predictable.
* This class provides methods that utilize cryptographic randomness, ensuring unpredictability and security.
*/
export declare class Crypto {
/**
* Check if running in browser environment
*/
private static isBrowser;
/**
* Check if Web Crypto API is available with getRandomValues
*/
private static hasWebCrypto;
/**
* Throw error for Node.js-only methods when running in browser
*/
private static throwBrowserError;
/**
* Generate a cryptographically secure random float between 0 and 1.
* Replacement for Math.random().
*/
static rand(): number;
/**
* Generate a cryptographically secure random integer between min (inclusive) and max (exclusive).
* Replacement for Math.floor(Math.random() * (max - min)) + min.
*/
static randInt(min?: number, max?: number): number;
/**
* Generate a cryptographically secure random integer between 0 and max (exclusive).
* Direct replacement for Math.floor(Math.random() * max).
*/
static randN(max: number): number;
/**
* Generate random array index.
* Replacement for Math.floor(Math.random() * array.length).
*/
static randIndex<T>(array: T[]): number;
/**
* Pick random element from array.
*/
static randChoice<T>(array: T[]): T;
/**
* Generate weighted random choice.
*/
static randWeighted<T>(items: T[], weights: number[]): T;
/**
* Shuffle array using [Fisher-Yates algorithm](https://en.wikipedia.org/wiki/Fisher%E2%80%93Yates_shuffle) with crypto random.
*/
static shuffle<T>(array: T[]): T[];
/**
* Generate cryptographically secure random string.
*/
static randString(length: number, charset?: string): string;
/**
* Generate random hex string.
* Note: Only available in Node.js environment.
*/
static randHex(length: number): string;
/**
* Generate random base64 string.
* Note: Only available in Node.js environment.
*/
static randBase64(length: number): string;
/**
* Generate random boolean with optional probability.
*/
static randBool(probability?: number): boolean;
/**
* Generate random bytes.
*/
static randBytes(size: number): Uint8Array | Buffer;
/**
* Generate UUID v4.
*/
static randUUID(): string;
/**
* Generate random numbers for sensor data format.
*/
static randFormat(count?: number, maxValue?: number, delimiter?: string): string;
/**
* Generate cryptographically secure seed.
* Note: Only available in Node.js environment.
*/
static randSeed(): number;
/**
* Generate random version string (44 characters base64-like).
* Note: Only available in Node.js environment.
*/
static randVersion(): string;
/**
* Generate random float in range.
*/
static randFloat(min?: number, max?: number): number;
/**
* Generate random number with normal distribution using [Box-Muller transform](https://en.wikipedia.org/wiki/Box%E2%80%93Muller_transform).
*
* This method is similar to randGaussian but ensures that the logarithm function
* never receives zero by converting [0,1) to (0,1).
*
* Steps:
*
* 1. Generate two independent uniform random numbers:
* - (u) is adjusted to be in the interval (0, 1) by using 1 - Crypto.rand().
* - (v) is a standard uniform random number in [0, 1).
* 2. Apply the [Box-Muller transform](https://en.wikipedia.org/wiki/Box%E2%80%93Muller_transform):
* - Compute z = √(-2 × ln(u)) × cos(2π × v)
* - This gives z, a standard normally distributed random number (mean = 0, std dev = 1).
* 3. Scale and shift z to have the desired mean and standard deviation:
* - Return z × stdDev + mean
*/
static randNormal(mean?: number, stdDev?: number): number;
/**
* Secure replacement for Math.random() with seed support.
* Note: Seeded functionality only available in Node.js environment.
*/
static randSeeded(seed?: number): number;
/**
* Check if current environment supports all features.
*/
static isFullySupported(): boolean;
/**
* Get list of methods that are not supported in current environment.
*/
static getUnsupportedMethods(): string[];
/**
* Get environment info.
*/
static getEnvironmentInfo(): {
isBrowser: boolean;
hasWebCrypto: boolean;
hasRandomUUID: boolean;
supportedMethods: string[];
unsupportedMethods: string[];
};
/**
* Generate a random subset of a given size from an array.
*/
static randSubset<T>(array: T[], size: number): T[];
/**
* Generate random number with Gaussian distribution using [Box-Muller transform](https://en.wikipedia.org/wiki/Box%E2%80%93Muller_transform).
*
* Steps:
*
* 1. Generate two independent uniform random numbers (u₁) and (u₂) in the interval [0, 1).
* 2. Apply the [Box-Muller transform](https://en.wikipedia.org/wiki/Box%E2%80%93Muller_transform):
* - Compute z₀ = √(-2 × ln(u₁)) × cos(2π × u₂)
* - This gives z₀, a standard normally distributed random number (mean = 0, std dev = 1).
* 3. Scale and shift z₀ to have the desired mean and standard deviation:
* - Return z₀ × stdDev + mean
*/
static randGaussian(mean?: number, stdDev?: number): number;
/**
* Generate random walk sequence.
*/
static randWalk(steps: number, stepSize?: number): number[];
/**
* Generate cryptographically secure password with configurable requirements.
*
* Note: This method is different from randString as it focuses specifically on password generation
* with built-in character type controls, password-specific features like excluding similar-looking
* characters (0O1lI), and ensuring proper character distribution for strong passwords.
* While randString is a general-purpose string generator, randPassword is optimized for creating
* secure passwords with common password policy requirements.
*/
static randPassword(options: {
length: number;
includeUppercase?: boolean;
includeLowercase?: boolean;
includeNumbers?: boolean;
includeSymbols?: boolean;
excludeSimilar?: boolean;
customChars?: string;
}): string;
/**
* Pre-calculated constant for the square root of 2π.
*
* This constant is a component of the normalization factor for the Gaussian probability density function (PDF),
* and is used in calculating the standard deviation for Gaussian error in lattice-based cryptography.
*/
private static readonly SQRT_2PI;
/**
* Generate cryptographically secure random number using lattice-based mathematical operations.
* It uses lattice operations combined with Gaussian error distribution to produce cryptographically secure randomness.
*
* **Note:** This method is currently only available in Node.js environment due to its
* dependency on the native crypto module for secure random number generation.
*/
static randLattice(dimension?: number, modulus?: number): number;
/**
* Generate a cryptographically secure random prime number within a specified bit length.
*
* This method uses the [Miller-Rabin primality test](https://en.wikipedia.org/wiki/Miller%E2%80%93Rabin_primality_test) to verify that the generated number is prime.
* The implementation follows cryptographic best practices for generating prime numbers securely.
*
* **Note:** This method is currently only available in Node.js environment due to its
* dependency on the native crypto module for secure random number generation.
*
* @param bits - The bit length of the prime number to generate (default: 1024)
* @param iterations - The number of iterations for the [Miller-Rabin primality test](https://en.wikipedia.org/wiki/Miller%E2%80%93Rabin_primality_test) (default: 10)
* @returns A bigint representing a probable prime number of the specified bit length
*/
static randPrime(bits?: number, iterations?: number): bigint;
/**
* Generate a cryptographically secure random bigint with a specified bit length.
*
* This method generates a random bigint with exactly the specified number of bits.
* It ensures the most significant bit is set to 1 and the least significant bit is set to 1 (making it odd).
*
* **Note:** This method is currently only available in Node.js environment due to its
* dependency on the native crypto module for secure random number generation.
*
* @param bits - The bit length of the bigint to generate (default: 1024)
* @returns A bigint with the specified bit length
*/
static randBigInt(bits?: number): bigint;
/**
* Generate random number with exponential distribution
*/
static randExponential(lambda?: number): number;
}
export declare const rand: typeof Crypto.rand, randInt: typeof Crypto.randInt, randN: typeof Crypto.randN, randIndex: typeof Crypto.randIndex, randChoice: typeof Crypto.randChoice, randWeighted: typeof Crypto.randWeighted, shuffle: typeof Crypto.shuffle, randString: typeof Crypto.randString, randHex: typeof Crypto.randHex, randBase64: typeof Crypto.randBase64, randBool: typeof Crypto.randBool, randBytes: typeof Crypto.randBytes, randUUID: typeof Crypto.randUUID, randFormat: typeof Crypto.randFormat, randSeed: typeof Crypto.randSeed, randVersion: typeof Crypto.randVersion, randFloat: typeof Crypto.randFloat, randNormal: typeof Crypto.randNormal, randSeeded: typeof Crypto.randSeeded, randSubset: typeof Crypto.randSubset, randGaussian: typeof Crypto.randGaussian, randWalk: typeof Crypto.randWalk, randPassword: typeof Crypto.randPassword, randLattice: typeof Crypto.randLattice, randPrime: typeof Crypto.randPrime, randBigInt: typeof Crypto.randBigInt, randExponential: typeof Crypto.randExponential;