Various Hash Functions (SHA1, SHA256, HMAC)

1.1.7 · abandoned · verified Sun Apr 19

hash.js is a lightweight JavaScript library providing implementations for various cryptographic hash functions, including SHA1, SHA224, SHA256, SHA512, and HMAC, designed to run consistently in both browser and Node.js environments. The current stable version is 1.1.7. This package distinguishes itself by offering pure JavaScript implementations, making it suitable for environments where native cryptographic modules are unavailable or undesirable. However, its last significant update was approximately seven years ago, meaning it is largely unmaintained. Due to its age, it does not officially support ES Modules directly and may not benefit from modern cryptographic optimizations or security reviews that more actively developed libraries or Node.js's native `crypto` module receive. Developers should exercise caution and critically evaluate its suitability for new security-sensitive applications.

Common errors

Warnings

Install

Imports

Quickstart

Demonstrates how to import and use various hash functions (SHA256, SHA512, HMAC) from `hash.js`, including both main and selective module imports, in a TypeScript environment.

import * as hash from 'hash.js';
import { sha512 } from 'hash.js/lib/hash/sha/512';

// Example 1: Using the main hash.js export for SHA256
const dataToHash1 = 'Hello, Checklist Day!';
const sha256Hash = hash.sha256().update(dataToHash1).digest('hex');
console.log(`SHA256 Hash of '${dataToHash1}': ${sha256Hash}`);

// Example 2: Using selective import for SHA512
const dataToHash2 = 'Another piece of text to hash securely.';
const sha512Hash = sha512().update(dataToHash2).digest('hex');
console.log(`SHA512 Hash of '${dataToHash2}': ${sha512Hash}`);

// Example 3: Using HMAC with SHA256
const secretKey = 'my-super-secret-key';
const message = 'The quick brown fox jumps over the lazy dog';
const hmacSha256 = hash.hmac(hash.sha256, secretKey).update(message).digest('hex');
console.log(`HMAC-SHA256 of '${message}' with key '${secretKey}': ${hmacSha256}`);

// For demonstration purposes with environment variable (e.g., for API keys)
const apiKey = process.env.API_KEY ?? 'default-fallback-api-key';
const sensitiveData = `User info: ${apiKey}`;
const hashOfSensitiveData = hash.sha1().update(sensitiveData).digest('hex');
console.log(`SHA1 Hash of sensitive data (using API_KEY): ${hashOfSensitiveData.substring(0, 20)}...`);

view raw JSON →