CtrlK
BlogDocsLog inGet started
Tessl Logo

tessl/npm-node-forge

JavaScript implementations of network transports, cryptography, ciphers, PKI, message digests, and various utilities.

Pending
Quality

Pending

Does it follow best practices?

Impact

Pending

No eval scenarios have been run

SecuritybySnyk

Pending

The risk profile of this skill

Overview
Eval results
Files

random.mddocs/

Random Number Generation

Secure random number generation for cryptographic operations including key generation and IV creation. Node-forge provides cross-platform secure random number generation with multiple entropy sources and PRNG implementations.

Capabilities

Basic Random Number Generation

Generate cryptographically secure random bytes for keys, IVs, and salts.

/**
 * Generate random bytes synchronously
 * @param count - Number of bytes to generate
 * @returns Random bytes as binary string
 */
forge.random.getBytesSync(count: number): string;

/**
 * Generate random bytes asynchronously
 * @param count - Number of bytes to generate
 * @param callback - Callback function to receive bytes
 */
forge.random.getBytes(count: number, callback?: (err: Error | null, bytes: string) => void): string | void;

Usage Examples:

const forge = require('node-forge');

// Generate random key material
const aesKey = forge.random.getBytesSync(32);    // 256-bit AES key
const iv = forge.random.getBytesSync(16);        // 128-bit IV
const salt = forge.random.getBytesSync(16);      // 128-bit salt

console.log('AES Key (hex):', forge.util.bytesToHex(aesKey));
console.log('IV (hex):', forge.util.bytesToHex(iv));
console.log('Salt (hex):', forge.util.bytesToHex(salt));

// Asynchronous generation (for non-blocking operation)
forge.random.getBytes(32, (err, bytes) => {
  if (err) {
    console.error('Random generation failed:', err);
    return;
  }
  console.log('Async random bytes:', forge.util.bytesToHex(bytes));
});

// Generate multiple random values
const sessionId = forge.random.getBytesSync(16);
const nonce = forge.random.getBytesSync(12);     // 96-bit nonce for GCM
const challenge = forge.random.getBytesSync(32); // Random challenge

PRNG (Pseudo-Random Number Generator)

Create and manage pseudo-random number generator instances with custom seeds.

/**
 * Create PRNG instance
 * @param plugin - PRNG plugin/algorithm
 * @returns PRNG context
 */
forge.prng.create(plugin: any): PRNGContext;

/**
 * Create random number generator instance
 * @returns Random generator instance
 */
forge.random.createInstance(): RandomGenerator;

interface PRNGContext {
  /** PRNG plugin */
  plugin: any;
  /** Internal state */
  key: any;
  /** Seed the PRNG */
  seed: string;
  
  /**
   * Generate random bytes
   * @param count - Number of bytes
   * @returns Random bytes
   */
  generate(count: number): string;
}

interface RandomGenerator {
  /**
   * Generate random bytes synchronously
   * @param count - Number of bytes
   * @returns Random bytes as binary string
   */
  getBytesSync(count: number): string;
  
  /**
   * Generate random bytes asynchronously
   * @param count - Number of bytes
   * @param callback - Callback for result
   */
  getBytes(count: number, callback: (err: Error | null, bytes: string) => void): void;
  
  /**
   * Seed the random generator
   * @param seed - Seed data
   */
  seedFileSync(seed: string): void;
}

Usage Examples:

// Create custom random generator instance
const rng = forge.random.createInstance();

// Seed with custom entropy
const customSeed = forge.util.encodeUtf8('custom-entropy-source') + 
                   Date.now().toString() + 
                   Math.random().toString();
rng.seedFileSync(customSeed);

// Generate random bytes with custom instance
const customRandom = rng.getBytesSync(32);
console.log('Custom random:', forge.util.bytesToHex(customRandom));

// Asynchronous generation with custom instance
rng.getBytes(16, (err, bytes) => {
  if (!err) {
    console.log('Custom async random:', forge.util.bytesToHex(bytes));
  }
});

Entropy Collection

Methods for collecting entropy from various sources to seed random generators.

/**
 * Collect entropy from browser/environment
 * @param callback - Callback with collected entropy
 */
forge.random.collect(callback: (bytes: string) => void): void;

/**
 * Register entropy collector
 * @param collector - Collector function
 */
forge.random.registerCollector(collector: () => string): void;

/**
 * Start collecting entropy continuously
 */
forge.random.startCollecting(): void;

/**
 * Stop collecting entropy
 */
forge.random.stopCollecting(): void;

Usage Examples:

// Collect additional entropy (browser environment)
if (typeof window !== 'undefined') {
  forge.random.collect((bytes) => {
    console.log('Collected entropy:', bytes.length, 'bytes');
  });
  
  // Register custom entropy collector
  forge.random.registerCollector(() => {
    return Date.now().toString() + 
           navigator.userAgent + 
           Math.random().toString() +
           (performance.now ? performance.now().toString() : '');
  });
  
  // Start continuous entropy collection
  forge.random.startCollecting();
}

// Node.js entropy collection
if (typeof process !== 'undefined') {
  const crypto = require('crypto');
  
  // Register Node.js crypto as entropy source
  forge.random.registerCollector(() => {
    return crypto.randomBytes(32).toString('binary');
  });
}

Random Number Utilities

Utility functions for working with random data in different formats.

/**
 * Generate random integer in range
 * @param min - Minimum value (inclusive)
 * @param max - Maximum value (exclusive)
 * @returns Random integer
 */
function randomInt(min: number, max: number): number;

/**
 * Generate random hex string
 * @param length - Length in bytes
 * @returns Random hex string
 */
function randomHex(length: number): string;

/**
 * Generate random base64 string
 * @param length - Length in bytes
 * @returns Random base64 string
 */
function randomBase64(length: number): string;

/**
 * Shuffle array randomly
 * @param array - Array to shuffle
 * @returns Shuffled array
 */
function shuffleArray<T>(array: T[]): T[];

Usage Examples:

// Utility functions for random data
function randomInt(min, max) {
  const range = max - min;
  const bytes = forge.random.getBytesSync(4);
  const value = forge.util.createBuffer(bytes).getInt32();
  return min + Math.abs(value) % range;
}

function randomHex(length) {
  const bytes = forge.random.getBytesSync(length);
  return forge.util.bytesToHex(bytes);
}

function randomBase64(length) {
  const bytes = forge.random.getBytesSync(length);
  return forge.util.encode64(bytes);
}

function shuffleArray(array) {
  const shuffled = [...array];
  for (let i = shuffled.length - 1; i > 0; i--) {
    const j = randomInt(0, i + 1);
    [shuffled[i], shuffled[j]] = [shuffled[j], shuffled[i]];
  }
  return shuffled;
}

// Usage examples
const randomId = randomHex(16);              // 32-character hex ID
const sessionToken = randomBase64(24);       // Base64 session token
const randomPort = randomInt(8000, 9000);    // Random port number
const shuffledItems = shuffleArray(['a', 'b', 'c', 'd', 'e']);

Secure Random Practices

Best practices for secure random number generation in different scenarios.

Key Generation:

// Generate cryptographic keys with proper lengths
const keys = {
  aes128: forge.random.getBytesSync(16),    // 128-bit AES
  aes192: forge.random.getBytesSync(24),    // 192-bit AES
  aes256: forge.random.getBytesSync(32),    // 256-bit AES
  hmacKey: forge.random.getBytesSync(32),   // 256-bit HMAC key
  salt: forge.random.getBytesSync(16)       // 128-bit salt (minimum)
};

// Generate IVs for different algorithms
const ivs = {
  aes_cbc: forge.random.getBytesSync(16),   // 128-bit IV for AES-CBC
  aes_gcm: forge.random.getBytesSync(12),   // 96-bit IV for AES-GCM (recommended)
  des: forge.random.getBytesSync(8)         // 64-bit IV for DES
};

Session Management:

// Generate secure session identifiers
function generateSessionId() {
  return forge.util.encode64(forge.random.getBytesSync(32))
    .replace(/\+/g, '-')
    .replace(/\//g, '_')
    .replace(/=/g, ''); // URL-safe base64
}

// Generate CSRF tokens
function generateCSRFToken() {
  return forge.util.bytesToHex(forge.random.getBytesSync(32));
}

// Generate API keys
function generateAPIKey() {
  const timestamp = Date.now().toString(16);
  const randomPart = forge.util.bytesToHex(forge.random.getBytesSync(16));
  return `ak_${timestamp}_${randomPart}`;
}

Nonces and Challenges:

// Generate cryptographic nonces
function generateNonce(length = 16) {
  return forge.random.getBytesSync(length);
}

// Generate challenge-response values
function generateChallenge() {
  return {
    challenge: forge.util.encode64(forge.random.getBytesSync(32)),
    timestamp: Date.now(),
    expires: Date.now() + 300000 // 5 minutes
  };
}

Performance Considerations

Optimize random number generation for different use cases.

Batch Generation:

// Generate multiple random values efficiently
function generateBatch(count, size) {
  const totalBytes = count * size;
  const allBytes = forge.random.getBytesSync(totalBytes);
  const results = [];
  
  for (let i = 0; i < count; i++) {
    const start = i * size;
    const end = start + size;
    results.push(allBytes.slice(start, end));
  }
  
  return results;
}

// Generate multiple keys at once
const keyBatch = generateBatch(10, 32); // 10 AES-256 keys
const ivBatch = generateBatch(10, 16);  // 10 AES IVs

Caching for High-Frequency Use:

// Random pool for high-frequency operations
class RandomPool {
  constructor(poolSize = 1024) {
    this.pool = forge.random.getBytesSync(poolSize);
    this.position = 0;
    this.poolSize = poolSize;
  }
  
  getBytes(count) {
    if (this.position + count > this.poolSize) {
      // Refill pool
      this.pool = forge.random.getBytesSync(this.poolSize);
      this.position = 0;
    }
    
    const result = this.pool.slice(this.position, this.position + count);
    this.position += count;
    return result;
  }
}

const randomPool = new RandomPool();
// Use pool for frequent small random values
const quickRandom = randomPool.getBytes(16);

Error Handling

Handle random generation failures and entropy issues.

try {
  // Basic random generation
  const randomBytes = forge.random.getBytesSync(32);
  
  // Async generation with error handling
  forge.random.getBytes(32, (err, bytes) => {
    if (err) {
      console.error('Async random generation failed:', err);
      // Fallback to sync generation
      const fallbackBytes = forge.random.getBytesSync(32);
      // Use fallbackBytes...
      return;
    }
    // Use bytes...
  });
  
} catch (error) {
  // Handle errors:
  // - Insufficient entropy
  // - PRNG initialization failures
  // - Platform-specific random source failures
  console.error('Random generation failed:', error.message);
  
  // Implement fallback strategy
  console.warn('Using fallback random generation');
  const fallback = Date.now().toString() + Math.random().toString();
  const hashedFallback = forge.md.sha256.create()
    .update(fallback)
    .digest()
    .getBytes();
}

// Check for secure random availability
function isSecureRandomAvailable() {
  try {
    forge.random.getBytesSync(1);
    return true;
  } catch (error) {
    return false;
  }
}

if (!isSecureRandomAvailable()) {
  console.warn('Secure random generation not available');
  // Implement alternative strategy or warn user
}

docs

asn1.md

asymmetric-cryptography.md

index.md

logging.md

message-digests.md

network-http.md

pkcs.md

pki.md

random.md

symmetric-encryption.md

tls.md

utilities.md

web-forms.md

tile.json