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

message-digests.mddocs/

Message Digests and HMAC

Cryptographic hash functions (MD5, SHA-1, SHA-256, SHA-512) and HMAC for message authentication. Node-forge provides pure JavaScript implementations of standard hash algorithms with consistent API patterns.

Capabilities

Message Digest Interface

All hash algorithms implement a consistent message digest interface.

interface MessageDigest {
  /** Algorithm name (e.g., 'md5', 'sha1', 'sha256', 'sha512') */
  algorithm: string;
  /** Block size in bytes for the algorithm */
  blockLength: number;
  /** Digest output length in bytes */
  digestLength: number;
  /** Current message length processed */
  messageLength: number;
  
  /**
   * Start or restart the digest computation
   * @returns This digest object for chaining
   */
  start(): MessageDigest;
  
  /**
   * Update the digest with message data
   * @param message - Data to hash as string
   * @param encoding - Encoding format ('raw' or 'utf8', default: 'raw')
   * @returns This digest object for chaining
   */
  update(message: string, encoding?: 'raw' | 'utf8'): MessageDigest;
  
  /**
   * Complete the digest computation and return result
   * @returns ByteStringBuffer containing the digest
   */
  digest(): ByteStringBuffer;
}

SHA-256 Hash Function

SHA-256 produces 256-bit (32-byte) hash values and is recommended for new applications.

/**
 * Create SHA-256 message digest
 * @returns SHA-256 digest object
 */
forge.md.sha256.create(): MessageDigest;

// Also available as:
forge.sha256.create(): MessageDigest;

Usage Examples:

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

// Basic SHA-256 hashing
const md = forge.md.sha256.create();
md.update('Hello World');
const hash = md.digest().toHex();
console.log('SHA-256:', hash);

// Chained operations
const hash2 = forge.md.sha256.create()
  .update('Hello')
  .update(' ')
  .update('World')
  .digest()
  .toHex();

// Hash binary data
const binaryData = forge.util.hexToBytes('48656c6c6f');
const binaryHash = forge.md.sha256.create()
  .update(binaryData)
  .digest()
  .toHex();

// Hash UTF-8 text
const utf8Hash = forge.md.sha256.create()
  .update('Hello 世界', 'utf8')
  .digest()
  .toHex();

SHA-1 Hash Function

SHA-1 produces 160-bit (20-byte) hash values. Consider SHA-256 for new applications.

/**
 * Create SHA-1 message digest
 * @returns SHA-1 digest object
 */
forge.md.sha1.create(): MessageDigest;

// Also available as:
forge.sha1.create(): MessageDigest;

Usage Examples:

// SHA-1 hashing
const sha1 = forge.md.sha1.create();
sha1.update('message to hash');
const sha1Hash = sha1.digest().toHex();
console.log('SHA-1:', sha1Hash);

SHA-512 Hash Function

SHA-512 produces 512-bit (64-byte) hash values for high security applications.

/**
 * Create SHA-512 message digest
 * @returns SHA-512 digest object
 */
forge.md.sha512.create(): MessageDigest;

// Also available as:
forge.sha512.create(): MessageDigest;

Usage Examples:

// SHA-512 hashing
const sha512 = forge.md.sha512.create();
sha512.update('secure message');
const sha512Hash = sha512.digest().toHex();
console.log('SHA-512:', sha512Hash);

SHA-384 Hash Function

SHA-384 produces 384-bit (48-byte) hash values as a truncated version of SHA-512.

/**
 * Create SHA-384 message digest
 * @returns SHA-384 digest object
 */
forge.md.sha384.create(): MessageDigest;

// Also available as:
forge.sha384.create(): MessageDigest;

Usage Examples:

// SHA-384 hashing  
const sha384 = forge.md.sha384.create();
sha384.update('message for sha384');
const sha384Hash = sha384.digest().toHex();
console.log('SHA-384:', sha384Hash);

MD5 Hash Function

MD5 produces 128-bit (16-byte) hash values. Use only for legacy compatibility.

/**
 * Create MD5 message digest
 * @returns MD5 digest object
 */
forge.md.md5.create(): MessageDigest;

// Also available as:
forge.md5.create(): MessageDigest;

Usage Examples:

// MD5 hashing (not recommended for security-critical applications)
const md5 = forge.md.md5.create();
md5.update('legacy data');
const md5Hash = md5.digest().toHex();
console.log('MD5:', md5Hash);

HMAC (Hash-based Message Authentication Code)

HMAC provides message authentication using a secret key and a hash function.

/**
 * Create HMAC context
 * @returns HMAC object for authentication
 */
forge.hmac.create(): HMACContext;

interface HMACContext {
  /**
   * Start HMAC with hash algorithm and key
   * @param md - Hash algorithm name or MessageDigest object
   * @param key - Secret key as string, bytes, or ByteStringBuffer
   */
  start(md: string | MessageDigest, key: string | ByteStringBuffer): void;
  
  /**
   * Update HMAC with message data
   * @param bytes - Message data to authenticate
   */
  update(bytes: string): void;
  
  /**
   * Get the HMAC result
   * @returns ByteStringBuffer containing the HMAC
   */
  getMac(): ByteStringBuffer;
  
  /**
   * Get HMAC result as hex string
   * @returns HMAC as hexadecimal string
   */
  digest(): any;
}

Usage Examples:

// HMAC-SHA256
const hmac = forge.hmac.create();
hmac.start('sha256', 'secret-key');
hmac.update('message to authenticate');
const mac = hmac.getMac().toHex();
console.log('HMAC-SHA256:', mac);

// HMAC with different algorithms
const hmacSha1 = forge.hmac.create();
hmacSha1.start('sha1', 'another-key');
hmacSha1.update('authenticated message');
const mac1 = hmacSha1.getMac().toHex();

// HMAC with MessageDigest object
const hmacCustom = forge.hmac.create();
hmacCustom.start(forge.md.sha512.create(), 'strong-key');
hmacCustom.update('high-security message');
const macCustom = hmacCustom.getMac().toHex();

// Key from bytes
const keyBytes = forge.random.getBytesSync(32); // 256-bit key
const hmacBytes = forge.hmac.create();
hmacBytes.start('sha256', keyBytes);
hmacBytes.update('message with random key');
const macBytes = hmacBytes.getMac().toHex();

Hash Algorithm Registry

Access to the hash algorithm registry for dynamic algorithm selection.

/**
 * Registry of all message digest algorithms
 */
forge.md.algorithms: {
  md5: () => MessageDigest;
  sha1: () => MessageDigest;
  sha256: () => MessageDigest;
  sha384: () => MessageDigest;
  sha512: () => MessageDigest;
};

Usage Examples:

// Dynamic algorithm selection
function hashWithAlgorithm(message, algorithm) {
  if (!(algorithm in forge.md.algorithms)) {
    throw new Error(`Unsupported algorithm: ${algorithm}`);
  }
  
  const md = forge.md.algorithms[algorithm]();
  md.update(message);
  return md.digest().toHex();
}

const sha256Hash = hashWithAlgorithm('test', 'sha256');
const sha1Hash = hashWithAlgorithm('test', 'sha1');

Hash Function Properties

Key properties of each hash algorithm for selection guidance.

// Algorithm Properties
interface HashAlgorithmProperties {
  MD5: {
    digestLength: 16;    // 128 bits
    blockLength: 64;     // 512 bits
    security: 'broken';  // Cryptographically broken
  };
  SHA1: {
    digestLength: 20;    // 160 bits  
    blockLength: 64;     // 512 bits
    security: 'weak';    // Collision attacks exist
  };
  SHA256: {
    digestLength: 32;    // 256 bits
    blockLength: 64;     // 512 bits
    security: 'strong';  // Currently secure
  };
  SHA384: {
    digestLength: 48;    // 384 bits
    blockLength: 128;    // 1024 bits
    security: 'strong';  // Currently secure
  };
  SHA512: {
    digestLength: 64;    // 512 bits
    blockLength: 128;    // 1024 bits  
    security: 'strong';  // Currently secure
  };
}

Performance Considerations

Optimize hash operations for different use cases.

Usage Examples:

// Efficient hashing of large data
function hashLargeData(dataChunks) {
  const md = forge.md.sha256.create();
  
  for (const chunk of dataChunks) {
    md.update(chunk);
  }
  
  return md.digest().toHex();
}

// Streaming hash computation
function createStreamingHasher(algorithm = 'sha256') {
  const md = forge.md[algorithm].create();
  
  return {
    update: (data) => md.update(data),
    finalize: () => md.digest().toHex(),
    reset: () => md.start()
  };
}

const hasher = createStreamingHasher('sha256');
hasher.update('chunk 1');
hasher.update('chunk 2');
const result = hasher.finalize();

Security Best Practices

Guidelines for secure hash function usage.

// Recommended algorithms for different use cases
const RECOMMENDED_ALGORITHMS = {
  // For general purpose hashing
  general: 'sha256',
  
  // For password hashing (use PBKDF2 or bcrypt instead)
  passwords: 'DO_NOT_USE_PLAIN_HASH',
  
  // For digital signatures
  signatures: 'sha256', // or 'sha512'
  
  // For HMAC
  hmac: 'sha256',
  
  // For integrity checking
  integrity: 'sha256'
};

// Secure HMAC key generation
const hmacKey = forge.random.getBytesSync(32); // 256-bit key
const hmac = forge.hmac.create();
hmac.start('sha256', hmacKey);

// Constant-time HMAC verification (approximate)
function verifyHMAC(message, key, expectedMac) {
  const hmac = forge.hmac.create();
  hmac.start('sha256', key);
  hmac.update(message);
  const computedMac = hmac.getMac().toHex();
  
  // Note: This is not truly constant-time in JavaScript
  // For production, use a dedicated constant-time comparison library
  return computedMac === expectedMac;
}

Error Handling

Handle common errors in hash operations.

try {
  const md = forge.md.sha256.create();
  md.update(message);
  const hash = md.digest().toHex();
  
} catch (error) {
  // Handle errors:
  // - Invalid encoding specified
  // - Memory allocation failures for very large inputs
  // - Invalid algorithm names for HMAC
  console.error('Hashing failed:', error.message);
}

// HMAC error handling
try {
  const hmac = forge.hmac.create();
  hmac.start('invalid-algorithm', 'key'); // Will throw error
  
} catch (error) {
  console.error('HMAC initialization failed:', error.message);
}

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