### Install hash-wasm using npm
Source: https://github.com/daninet/hash-wasm/blob/master/README.md
This command installs the hash-wasm package, which provides fast hash functions for browsers and Node.js. It's a zero-dependency package.
```bash
npm i hash-wasm
```
--------------------------------
### SHA-3 and Keccak Hashing with hash-wasm
Source: https://context7.com/daninet/hash-wasm/llms.txt
Demonstrates how to use the SHA-3 family and Keccak hash functions, including configurable output sizes and streaming capabilities. It imports necessary functions from 'hash-wasm' and shows examples of one-shot hashing and creating streaming instances.
```javascript
import { sha3, createSHA3, keccak, createKeccak } from 'hash-wasm';
// SHA3-256 (default 512 bits)
const hash512 = await sha3('data');
console.log(hash512);
// SHA3-256
const hash256 = await sha3('data', 256);
console.log(hash256);
// All variants
const hash224 = await sha3('data', 224);
const hash384 = await sha3('data', 384);
// Streaming SHA3-512
const sha3Stream = await createSHA3(512);
sha3Stream.init();
sha3Stream.update('streaming ');
sha3Stream.update('data');
const result = sha3Stream.digest();
// Keccak (original, pre-NIST)
const keccakHash = await keccak('ethereum style hash', 256);
console.log(keccakHash);
// Streaming Keccak-256 (used in Ethereum)
const keccakHasher = await createKeccak(256);
keccakHasher.init();
keccakHasher.update('0x1234567890abcdef');
const ethHash = keccakHasher.digest('hex');
```
--------------------------------
### Hash Passwords with bcrypt (JavaScript)
Source: https://github.com/daninet/hash-wasm/blob/master/README.md
This example demonstrates password hashing using the bcrypt algorithm. It shows how to generate a salt, hash a password with a specified cost factor, and verify the password against the hash. The 'encoded' output type is used to include parameters necessary for verification.
```javascript
import { bcrypt, bcryptVerify } from "hash-wasm";
async function run() {
const salt = new Uint8Array(16);
window.crypto.getRandomValues(salt);
const key = await bcrypt({
password: "pass",
salt, // salt is a buffer containing 16 random bytes
costFactor: 11,
outputType: "encoded", // return standard encoded string containing parameters needed to verify the key
});
console.log("Derived key:", key);
const isValid = await bcryptVerify({
password: "pass",
hash: key,
});
console.log(isValid ? "Valid password" : "Invalid password");
}
run();
```
--------------------------------
### Calculate Hashes with Shorthand Functions (JavaScript)
Source: https://github.com/daninet/hash-wasm/blob/master/README.md
This snippet demonstrates the easiest and fastest way to calculate hashes using shorthand functions like md5, sha1, sha512, and sha3. It's suitable when the input buffer is already in memory. It imports necessary functions from 'hash-wasm' and shows examples with string and Uint8Array inputs.
```javascript
import { md5, sha1, sha512, sha3 } from "hash-wasm";
async function run() {
console.log("MD5:", await md5("demo"));
const int8Buffer = new Uint8Array([0, 1, 2, 3]);
console.log("SHA1:", await sha1(int8Buffer));
console.log("SHA512:", await sha512(int8Buffer));
const int32Buffer = new Uint32Array([1056, 641]);
console.log("SHA3-256:", await sha3(int32Buffer, 256));
}
run();
```
--------------------------------
### Calculate PBKDF2 with a Specified Hash Function (JavaScript)
Source: https://github.com/daninet/hash-wasm/blob/master/README.md
This example shows how to compute a PBKDF2 (Password-Based Key Derivation Function 2) hash. It involves providing a password, salt, iteration count, hash length, and a specific hash function instance (e.g., SHA1 created via createSHA1()). The output type can be 'hex' or other formats.
```javascript
import { pbkdf2, createSHA1 } from "hash-wasm";
async function run() {
const salt = new Uint8Array(16);
window.crypto.getRandomValues(salt);
const key = await pbkdf2({
password: "password",
salt,
iterations: 1000,
hashLength: 32,
hashFunction: createSHA1(),
outputType: "hex",
});
console.log("Derived key:", key);
}
run();
```
--------------------------------
### Calculate Hashes with Streaming Input (JavaScript)
Source: https://github.com/daninet/hash-wasm/blob/master/README.md
This example shows advanced usage with streaming input using createXXXX() functions. These create new WASM instances with separate states for parallel hashing. The snippet demonstrates creating a SHA1 instance, updating it with chunks of data, and then digesting the result. It's less performant than shorthand functions for in-memory data but suitable for large, chunked inputs.
```javascript
import { createSHA1 } from "hash-wasm";
async function run() {
const sha1 = await createSHA1();
sha1.init();
while (hasMoreData()) {
const chunk = readChunk();
sha1.update(chunk);
}
const hash = sha1.digest("binary"); // returns Uint8Array
console.log("SHA1:", hash);
}
run();
```
--------------------------------
### Load individual hash-wasm algorithms via CDN
Source: https://github.com/daninet/hash-wasm/blob/master/README.md
These HTML script tags demonstrate how to load individual hash algorithms (e.g., MD5, HMAC) from a CDN. This approach is beneficial for optimizing bundle size by only including necessary algorithms.
```html
```
--------------------------------
### Load all hash-wasm algorithms via CDN
Source: https://github.com/daninet/hash-wasm/blob/master/README.md
This HTML script tag loads all hash algorithms provided by hash-wasm into the global `hashwasm` variable. It's useful for quick integration without a build process.
```html
```
--------------------------------
### BLAKE3 Hashing with hash-wasm
Source: https://context7.com/daninet/hash-wasm/llms.txt
Implements the BLAKE3 hashing algorithm using WebAssembly. Supports configurable output sizes (e.g., 256-bit, 512-bit) and a keyed hashing (MAC) mode. Also provides a streaming API.
```javascript
import { blake3, createBLAKE3 } from 'hash-wasm';
// Default 256-bit hash
const hash256 = await blake3('data to hash');
console.log(hash256);
// Custom output size (512 bits)
const hash512 = await blake3('data', 512);
console.log(hash512);
// Keyed hashing (MAC mode)
const key = new Uint8Array(32); // 32-byte key required
crypto.getRandomValues(key);
const macHash = await blake3('authenticated message', 256, key);
console.log(macHash);
// Streaming with custom output size
const blake3Stream = await createBLAKE3(384); // 384-bit output
blake3Stream.init();
blake3Stream.update('part 1');
blake3Stream.update('part 2');
const result = blake3Stream.digest();
// Streaming with keyed mode
const keyedHasher = await createBLAKE3(256, key);
keyedHasher.init();
keyedHasher.update('message');
const keyedResult = keyedHasher.digest('hex');
```
--------------------------------
### Concurrent Hash Calculations with hash-wasm
Source: https://context7.com/daninet/hash-wasm/llms.txt
Illustrates efficient parallel hash computation using multiple independent instances of hashers. It shows how to concurrently calculate SHA-256, MD5, and BLAKE3 hashes for the same data and how to process multiple files in parallel.
```javascript
import { createSHA256, createMD5, createBLAKE3 } from 'hash-wasm';
// Calculate multiple hashes concurrently
async function hashFile(data) {
const [sha256Hasher, md5Hasher, blake3Hasher] = await Promise.all([
createSHA256(),
createMD5(),
createBLAKE3()
]);
// Initialize all
sha256Hasher.init();
md5Hasher.init();
blake3Hasher.init();
// Process data with all hashers
const chunks = ['chunk1', 'chunk2', 'chunk3'];
for (const chunk of chunks) {
sha256Hasher.update(chunk);
md5Hasher.update(chunk);
blake3Hasher.update(chunk);
}
// Get all results
return {
sha256: sha256Hasher.digest(),
md5: md5Hasher.digest(),
blake3: blake3Hasher.digest()
};
}
const hashes = await hashFile('data');
console.log(hashes);
// { sha256: '...', md5: '...', blake3: '...' }
// Process multiple files in parallel
async function hashMultipleFiles(files) {
return Promise.all(files.map(async file => {
const hasher = await createSHA256();
hasher.init();
hasher.update(file.content);
return {
filename: file.name,
hash: hasher.digest()
};
}));
}
const fileHashes = await hashMultipleFiles([
{ name: 'file1.txt', content: 'content1' },
{ name: 'file2.txt', content: 'content2' },
{ name: 'file3.txt', content: 'content3' }
]);
```
--------------------------------
### Normalize Strings for Consistent Hashing (JavaScript)
Source: https://github.com/daninet/hash-wasm/blob/master/README.md
Demonstrates how to normalize strings using JavaScript's `normalize()` method to ensure consistent UTF-8 binary representations for hashing algorithms. It highlights the differences in direct UTF-8 encoding versus normalized encoding, and shows how `TextEncoder` produces different byte arrays for non-normalized strings.
```javascript
/*
Demonstrates string encoding pitfalls and normalization for consistent hashing.
It shows that different UTF-8 representations of the same character can lead to unequal string comparisons.
Using String.prototype.normalize() ensures consistent binary representation for hashing.
*/
// Different UTF-8 representations of the 'ΓΌ' character
const unicodeVariant1 = "\u00fc"; // Direct encoding
const unicodeVariant2 = "u\u0308"; // Composed encoding
console.log(`\"${unicodeVariant1}\" === \"${unicodeVariant2}\": ${unicodeVariant1 === unicodeVariant2}`); // false
// Normalizing strings before comparison
const normalizedVariant1 = unicodeVariant1.normalize();
const normalizedVariant2 = unicodeVariant2.normalize();
console.log(`\"${unicodeVariant1}\".normalize() === \"${unicodeVariant2}\".normalize(): ${normalizedVariant1 === normalizedVariant2}`); // true
// Demonstrating TextEncoder with normalized and non-normalized strings
const te = new TextEncoder();
console.log(`TextEncoder.encode(\"u\\u0308\"):`, te.encode(unicodeVariant2)); // Uint8Array(3) [117, 204, 136]
console.log(`TextEncoder.encode(\"\\u00fc\"):`, te.encode(unicodeVariant1)); // Uint8Array(2) [195, 188]
// Using NFKC normalization for potentially even better compatibility across systems
console.log(`TextEncoder.encode(\"u\\u0308\".normalize(\"NFKC\")):`, te.encode(unicodeVariant2.normalize("NFKC"))); // Uint8Array(2) [195, 188]
console.log(`TextEncoder.encode(\"\\u00fc\".normalize(\"NFKC\")):`, te.encode(unicodeVariant1.normalize("NFKC"))); // Uint8Array(2) [195, 188]
```
--------------------------------
### bcrypt Password Hashing and Verification with hash-wasm
Source: https://context7.com/daninet/hash-wasm/llms.txt
Implement industry-standard bcrypt password hashing and verification. Features a configurable cost factor for adaptive security. Supports encoded, binary, and hex output types. Requires crypto API for salt generation.
```javascript
import { bcrypt, bcryptVerify } from 'hash-wasm';
// Hash a password
const salt = new Uint8Array(16);
crypto.getRandomValues(salt);
const hash = await bcrypt({
password: 'mySecurePassword',
salt: salt,
costFactor: 10, // 2^10 iterations
outputType: 'encoded' // Default, returns standard bcrypt string
});
console.log(hash);
// '$2a$10$...'
// Verify password
const isValid = await bcryptVerify({
password: 'mySecurePassword',
hash: hash
});
console.log(isValid); // true
const isInvalid = await bcryptVerify({
password: 'wrongPassword',
hash: hash
});
console.log(isInvalid); // false
// Higher security with increased cost
const highSecHash = await bcrypt({
password: 'adminPassword',
salt: crypto.getRandomValues(new Uint8Array(16)),
costFactor: 12, // More secure but slower
outputType: 'encoded'
});
// Binary or hex output
const binaryHash = await bcrypt({
password: 'pass',
salt: salt,
costFactor: 8,
outputType: 'binary'
}); // Returns Uint8Array(24)
const hexHash = await bcrypt({
password: 'pass',
salt: salt,
costFactor: 8,
outputType: 'hex'
}); // Returns 48-char hex string
```
--------------------------------
### MD5 Hashing with hash-wasm
Source: https://context7.com/daninet/hash-wasm/llms.txt
Performs MD5 hashing using WebAssembly. Supports simple string/binary hashing and a streaming API for large data. Includes instance caching for performance. Outputs hex strings or binary data.
```javascript
import { md5, createMD5 } from 'hash-wasm';
// Simple string hashing
const hash1 = await md5('hello world');
console.log(hash1); // '5eb63bbbe01eeed093cb22bb8f5acdc3'
// Binary data hashing
const uint8Data = new Uint8Array([0, 1, 2, 3, 4, 5]);
const hash2 = await md5(uint8Data);
console.log(hash2); // hex string output
// Streaming API for large data
const hasher = await createMD5();
hasher.init();
hasher.update('hello ');
hasher.update('world');
const hash3 = hasher.digest(); // 'hex' format by default
console.log(hash3); // '5eb63bbbe01eeed093cb22bb8f5acdc3'
// Binary output
hasher.init();
hasher.update('data');
const binaryHash = hasher.digest('binary');
console.log(binaryHash); // Uint8Array
```
--------------------------------
### HMAC and Key Derivation Functions API
Source: https://github.com/daninet/hash-wasm/blob/master/README.md
API for creating Message Authentication Codes (HMAC) and deriving cryptographic keys using PBKDF2, Scrypt, and Argon2.
```APIDOC
## HMAC and Key Derivation Functions API
### Description
This API provides functionalities for generating Message Authentication Codes (HMAC) using a specified hash function and key. It also includes robust key derivation functions like PBKDF2, Scrypt, and Argon2 (Argon2i, Argon2d, Argon2id) for securely generating cryptographic keys from passwords or other secrets.
### Method
Various (all functions return Promises)
### Endpoints
N/A (These are function calls, not HTTP endpoints)
### Parameters
#### `createHMAC`
- **hashFunction** (Promise) - Required - A promise that resolves to an `IHasher` instance (e.g., `createSHA256()`).
- **key** (IDataType) - Required - The secret key to use for HMAC generation.
#### `pbkdf2`
- **password** (IDataType) - Required - The input password or message to be hashed.
- **salt** (IDataType) - Required - A random salt to add uniqueness to the key derivation.
- **iterations** (number) - Required - The number of iterations to perform for security.
- **hashLength** (number) - Required - The desired length of the output hash in bytes.
- **hashFunction** (Promise) - Required - The hash function to use (e.g., `createSHA1()`).
- **outputType** ('hex' | 'binary') - Optional - The format of the output. Defaults to 'hex'.
#### `scrypt`
- **password** (IDataType) - Required - The input password or message.
- **salt** (IDataType) - Required - A random salt.
- **costFactor** (number) - Required - Controls the CPU/memory cost. Must be a power of 2 (e.g., 1024).
- **blockSize** (number) - Required - The block size parameter (8 is common).
- **parallelism** (number) - Required - The degree of parallelism.
- **hashLength** (number) - Required - The desired output size in bytes.
- **outputType** ('hex' | 'binary') - Optional - The format of the output. Defaults to 'hex'.
#### `argon2i`, `argon2d`, `argon2id` (Options Object)
- **password** (IDataType) - Required - The input password.
- **salt** (IDataType) - Required - A random salt.
- **secret** (IDataType) - Optional - A secret for keyed hashing.
- **iterations** (number) - Required - Number of iterations.
- **parallelism** (number) - Required - Degree of parallelism.
- **memorySize** (number) - Required - Memory usage in kibibytes (1024 bytes).
- **hashLength** (number) - Required - Desired output size in bytes.
- **outputType** ('hex' | 'binary' | 'encoded') - Optional - Format of the output. Defaults to 'hex'.
### Request Example
```javascript
// Example using HMAC-SHA256
const hmacHasher = await createHMAC(createSHA256(), Buffer.from('my secret key'));
hmacHasher.update('data to authenticate');
const hmac = hmacHasher.digest();
console.log(hmac); // Output: '...' (HMAC hex string)
// Example using PBKDF2
const dk = await pbkdf2({
password: 'my password',
salt: 'somesalt',
iterations: 100000,
hashLength: 64,
hashFunction: createSHA512()
});
console.log(dk); // Output: '...' (derived key hex string)
// Example using Argon2id
const argon2Options = {
password: 'securepassword',
salt: 'somesalt',
iterations: 2,
parallelism: 2,
memorySize: 1024 * 64, // 64 MiB
hashLength: 32,
outputType: 'encoded'
};
const argon2Hash = await argon2id(argon2Options);
console.log(argon2Hash); // Output: '$argon2id$v=19$m=65536,t=2,p=2$...'
```
### Response
#### Success Response
- **IHasher** (for `createHMAC`) - An HMAC hasher instance.
- **string | Uint8Array** (for PBKDF2, Scrypt, Argon2) - The derived key or hash in the specified format.
```
--------------------------------
### Hash Passwords with Argon2 (JavaScript)
Source: https://github.com/daninet/hash-wasm/blob/master/README.md
This snippet demonstrates password hashing using the Argon2id algorithm. It includes generating a random salt, deriving a key with specified parameters (parallelism, iterations, memorySize, hashLength), and verifying the password against the derived hash. The output type can be 'encoded' for verification purposes.
```javascript
import { argon2id, argon2Verify } from "hash-wasm";
async function run() {
const salt = new Uint8Array(16);
window.crypto.getRandomValues(salt);
const key = await argon2id({
password: "pass",
salt,
parallelism: 1,
iterations: 256,
memorySize: 512, // use 512KB memory
hashLength: 32, // output size = 32 bytes
outputType: "encoded", // return standard encoded string containing parameters needed to verify the key
});
console.log("Derived key:", key);
const isValid = await argon2Verify({
password: "pass",
hash: key,
});
console.log(isValid ? "Valid password" : "Invalid password");
}
run();
```
--------------------------------
### SHA-256 Hashing with hash-wasm
Source: https://context7.com/daninet/hash-wasm/llms.txt
Implements SHA-256 hashing using WebAssembly. Offers quick calculations for small inputs and a streaming API for large data or incremental updates. Supports hex output and instance reuse.
```javascript
import { sha256, createSHA256 } from 'hash-wasm';
// Quick hash calculation
const hash = await sha256('The quick brown fox');
console.log(hash); // 'sha256 hash in hex'
// Streaming for large files or incremental data
const sha256Hasher = await createSHA256();
sha256Hasher.init();
// Process data in chunks
const chunks = ['chunk1', 'chunk2', 'chunk3'];
for (const chunk of chunks) {
sha256Hasher.update(chunk);
}
const finalHash = sha256Hasher.digest('hex');
console.log(finalHash);
// Reuse the same instance for multiple hashes
sha256Hasher.init(); // Reset state
sha256Hasher.update('new data');
const newHash = sha256Hasher.digest();
```
--------------------------------
### PBKDF2 Key Derivation in JavaScript
Source: https://context7.com/daninet/hash-wasm/llms.txt
Demonstrates deriving cryptographic keys from passwords using PBKDF2. It supports various hash functions (SHA-256, SHA-512, SHA-1) and output types (hex, binary), with configurable iterations for security. Requires the 'hash-wasm' library.
```javascript
import { pbkdf2, createSHA256, createSHA512, createSHA1 } from 'hash-wasm';
// Derive encryption key from password
const salt = new Uint8Array(16);
crypto.getRandomValues(salt);
const derivedKey = await pbkdf2({
password: 'userPassword',
salt: salt,
iterations: 100000, // OWASP recommended minimum
hashLength: 32, // 256-bit key
hashFunction: createSHA256(),
outputType: 'hex'
});
console.log(derivedKey); // 64-char hex string
// Binary output for direct use in encryption
const encryptionKey = await pbkdf2({
password: 'strongPassword123',
salt: salt,
iterations: 150000,
hashLength: 32,
hashFunction: createSHA512(),
outputType: 'binary'
});
console.log(encryptionKey); // Uint8Array(32)
// Multiple keys from same password
const salt1 = crypto.getRandomValues(new Uint8Array(16));
const salt2 = crypto.getRandomValues(new Uint8Array(16));
const [key1, key2] = await Promise.all([
pbkdf2({
password: 'masterPassword',
salt: salt1,
iterations: 120000,
hashLength: 32,
hashFunction: createSHA256(),
outputType: 'hex'
}),
pbkdf2({
password: 'masterPassword',
salt: salt2,
iterations: 120000,
hashLength: 64,
hashFunction: createSHA512(),
outputType: 'hex'
})
]);
// Legacy SHA1 support (not recommended for new systems)
const legacyKey = await pbkdf2({
password: 'password',
salt: salt,
iterations: 10000,
hashLength: 20,
hashFunction: createSHA1(),
outputType: 'hex'
});
```
--------------------------------
### Resumable Hashing with Save/Load State (JavaScript)
Source: https://github.com/daninet/hash-wasm/blob/master/README.md
Illustrates how to implement resumable hashing using hash-wasm's `.save()` and `.load()` methods. This is useful for splitting large hashing tasks across multiple processes or environments with execution time limits, such as AWS Lambda. It shows saving the internal state and then reloading it to continue the hashing process.
```javascript
/*
Demonstrates resumable hashing with hash-wasm using save() and load().
This allows pausing and resuming the hashing process, useful for large files or distributed computing.
*/
// Assume 'createMD5' is an async function provided by hash-wasm to create an MD5 hasher instance.
// For demonstration, we'll simulate its behavior.
async function createMD5() {
// In a real scenario, this would initialize and return an MD5 hasher object.
let state = { internalData: null };
return {
init: function() { console.log("MD5 initialized."); },
update: function(data) { console.log(`Updating with: "${data}"`); state.internalData = data; },
save: function() { console.log("Saving state..."); return state; },
load: function(loadedState) { console.log("Loading state..."); state = loadedState; },
digest: function() {
console.log("Calculating digest...");
// Simulate MD5 calculation for "Hello, world!"
if (state.internalData === "Hello, ") return "6cd3556deb0da54bca060b4c39479839";
return "simulated_digest";
}
};
}
async function performResumableHashing() {
// First process starts hashing
const md5_process1 = await createMD5();
md5_process1.init();
md5_process1.update("Hello, ");
const state = md5_process1.save(); // save this state
console.log("State saved.");
// Second process resumes hashing from the stored state
const md5_process2 = await createMD5();
md5_process2.load(state);
console.log("State loaded.");
md5_process2.update("world!");
console.log("Final digest:", md5_process2.digest()); // Prints 6cd3556deb0da54bca060b4c39479839 = md5("Hello, world!")
}
performResumableHashing();
```
--------------------------------
### Hasher Interface API
Source: https://github.com/daninet/hash-wasm/blob/master/README.md
Create and manage hasher instances for incremental hashing. This allows for updating the hash state with multiple data chunks and retrieving the final digest.
```APIDOC
## Hasher Interface API
### Description
This API allows you to create and use hasher objects that support incremental updates. You can initialize a hasher, update it with data in chunks, and then finalize the hash calculation. It also supports saving and loading the internal state for resuming hashing operations.
### Method
Various (all `create` functions return Promises resolving to `IHasher`)
### Endpoints
N/A (These are function calls, not HTTP endpoints)
### Parameters
- **bits** (number) - Optional - The desired output size in bits for certain algorithms (e.g., BLAKE2).
- **key** (IDataType) - Optional - A secret key for keyed hash functions (e.g., BLAKE2).
- **polynomial** (number) - Optional - A specific polynomial value for CRC algorithms.
- **seed** (number) - Optional - A seed value for XXHash algorithms.
- **seedLow**, **seedHigh** (number) - Optional - Lower and higher parts of a 64-bit seed for XXHash algorithms.
### `IHasher` Interface
- **init()**: Initializes the hasher instance. Returns `this`.
- **update(data: IDataType)**: Updates the hasher state with new data. Returns `this`.
- **digest(outputType: 'hex' | 'binary')**: Computes and returns the final hash. `outputType` defaults to 'hex'.
- **save()**: Returns the internal state of the hasher as a `Uint8Array`.
- **load(state: Uint8Array)**: Loads a previously saved internal state into the hasher.
- **blockSize**: The block size of the hash algorithm in bytes.
- **digestSize**: The size of the output hash in bytes.
### Request Example
```javascript
// Example using SHA-1 with incremental updates
const sha1Hasher = await createSHA1();
sha1Hasher.update(Buffer.from('first part '));
sha1Hasher.update(Buffer.from('second part'));
const hash = sha1Hasher.digest('hex');
console.log(hash); // Output: '...' (hexadecimal hash string)
// Example of saving and loading state
const state = sha1Hasher.save();
const newHasher = await createSHA1();
newHasher.load(state);
const resumedHash = newHasher.digest();
console.log(resumedHash === hash); // Output: true
```
### Response
#### Success Response
- **IHasher** - An object implementing the `IHasher` interface, allowing for incremental hashing operations.
```
--------------------------------
### Argon2 Password Hashing and Verification with hash-wasm
Source: https://context7.com/daninet/hash-wasm/llms.txt
Securely hash and verify passwords using Argon2 (argon2i, argon2d, argon2id) algorithms. Supports configurable parameters like memory, iterations, parallelism, and hash length. Outputs can be in PHC string, hex, or binary formats. Requires crypto API for salt generation.
```javascript
import { argon2id, argon2Verify, argon2i, argon2d } from 'hash-wasm';
// Generate secure password hash with argon2id
const salt = new Uint8Array(16);
crypto.getRandomValues(salt);
const hash = await argon2id({
password: 'userPassword123',
salt: salt,
parallelism: 1,
iterations: 3,
memorySize: 4096, // 4 MB
hashLength: 32,
outputType: 'encoded' // Returns PHC format string
});
console.log(hash);
// '$argon2id$v=19$m=4096,t=3,p=1$...$...'
// Verify password against stored hash
const isValid = await argon2Verify({
password: 'userPassword123',
hash: hash
});
console.log(isValid ? 'Password correct' : 'Password incorrect');
// With secret key for additional security
const secret = new Uint8Array(32);
crypto.getRandomValues(secret);
const keyedHash = await argon2id({
password: 'password',
salt: salt,
secret: secret,
parallelism: 1,
iterations: 4,
memorySize: 8192,
hashLength: 32,
outputType: 'hex'
});
// Use argon2i (data-independent) or argon2d (data-dependent)
const argon2iHash = await argon2i({
password: 'pass',
salt: salt,
parallelism: 1,
iterations: 3,
memorySize: 512,
hashLength: 32,
outputType: 'binary' // Returns Uint8Array
});
```
--------------------------------
### Direct Hashing Functions in TypeScript
Source: https://github.com/daninet/hash-wasm/blob/master/README.md
Provides direct access to various hashing algorithms like MD5, SHA-256, BLAKE3, and XXHash. These functions take data as input (string, Buffer, Uint8Array, etc.) and return a promise that resolves to the hash in hexadecimal format. They are suitable for one-off hashing operations.
```typescript
type IDataType = string | Buffer | Uint8Array | Uint16Array | Uint32Array;
// all functions return hash in hex format
adler32(data: IDataType): Promise
blake2b(data: IDataType, bits?: number, key?: IDataType): Promise // default is 512 bits
blake2s(data: IDataType, bits?: number, key?: IDataType): Promise // default is 256 bits
blake3(data: IDataType, bits?: number, key?: IDataType): Promise // default is 256 bits
crc32(data: IDataType, polynomial?: number): Promise // default polynomial is 0xedb88320, for CRC32C use 0x82f63b78
crc64(data: IDataType, polynomial?: string): Promise // default polynomial is 'c96c5795d7870f42' (ECMA)
keccak(data: IDataType, bits?: 224 | 256 | 384 | 512): Promise // default is 512 bits
md4(data: IDataType): Promise
md5(data: IDataType): Promise
ripemd160(data: IDataType): Promise
sha1(data: IDataType): Promise
sha224(data: IDataType): Promise
sha256(data: IDataType): Promisesha3(data: IDataType, bits?: 224 | 256 | 384 | 512): Promise // default is 512 bits
sha384(data: IDataType): Promise
sha512(data: IDataType): Promise
sm3(data: IDataType): Promise
whirlpool(data: IDataType): Promise
xxhash32(data: IDataType, seed?: number): Promise
xxhash64(data: IDataType, seedLow?: number, seedHigh?: number): Promise
xxhash3(data: IDataType, seedLow?: number, seedHigh?: number): Promise
xxhash128(data: IDataType, seedLow?: number, seedHigh?: number): Promise
```
--------------------------------
### Resumable Hashing with State Management in JavaScript
Source: https://context7.com/daninet/hash-wasm/llms.txt
Enables saving and restoring the internal state of hash computations, useful for segmented processing or distributed systems. This allows resuming hash calculations from where they left off. Requires the 'hash-wasm' library.
```javascript
import { createSHA256, createMD5 } from 'hash-wasm';
// Basic save/load workflow
const hasher1 = await createSHA256();
hasher1.init();
hasher1.update('first part of ');
const savedState = hasher1.save(); // Uint8Array containing internal state
// Resume from saved state in another context
const hasher2 = await createSHA256();
hasher2.load(savedState);
hasher2.update('the data');
const finalHash = hasher2.digest();
console.log(finalHash);
// Distributed processing example (e.g., AWS Lambda)
async function processChunk1() {
const h = await createMD5();
h.init();
h.update('chunk 1 ');
const state = h.save();
// Store state to database/S3
return { state: Array.from(state) };
}
async function processChunk2(previousState) {
const h = await createMD5();
h.load(new Uint8Array(previousState.state));
h.update('chunk 2 ');
const state = h.save();
return { state: Array.from(state) };
}
async function finalize(previousState) {
const h = await createMD5();
h.load(new Uint8Array(previousState.state));
h.update('chunk 3');
return h.digest();
}
// Execution flow
const state1 = await processChunk1();
const state2 = await processChunk2(state1);
const result = await finalize(state2);
console.log(result); // MD5 of "chunk 1 chunk 2 chunk 3"
// Rewinding to earlier state
const hasher = await createSHA256();
hasher.init();
hasher.update('data1');
const checkpoint = hasher.save();
hasher.update('data2');
const hash1 = hasher.digest();
// Rewind and take different path
hasher.load(checkpoint);
hasher.update('data3');
const hash2 = hasher.digest();
console.log(hash1 !== hash2); // true
```
--------------------------------
### xxHash64 Hashing with hash-wasm
Source: https://context7.com/daninet/hash-wasm/llms.txt
Utilizes WebAssembly for ultra-fast xxHash64 non-cryptographic hashing. Suitable for checksums and hash tables. Supports custom 64-bit seeds and a streaming API for incremental hashing.
```javascript
import { xxhash64, createXXHash64 } from 'hash-wasm';
// Basic usage with default seed (0, 0)
const hash1 = await xxhash64('fast hashing');
console.log(hash1);
// Custom seed (64-bit split into two 32-bit values)
const seedLow = 0x12345678;
const seedHigh = 0xabcdef00;
const hash2 = await xxhash64('data', seedLow, seedHigh);
console.log(hash2);
// Streaming API
const xxh = await createXXHash64(seedLow, seedHigh);
xxh.init();
const dataChunks = [
'chunk1',
'chunk2',
new Uint8Array([1, 2, 3, 4])
];
for (const chunk of dataChunks) {
xxh.update(chunk);
}
const finalHash = xxh.digest();
console.log(finalHash);
```
--------------------------------
### Bcrypt Hashing with WASM
Source: https://github.com/daninet/hash-wasm/blob/master/README.md
Generates a bcrypt hash from a given password and salt. Supports custom cost factors and output types (hex, binary, encoded). The salt must be 16 bytes long.
```typescript
bcrypt({
password: IDataType, // password
salt: IDataType, // salt (16 bytes long - usually containing random bytes)
costFactor: number, // number of iterations to perform (4 - 31)
outputType?: 'hex' | 'binary' | 'encoded' // by default returns encoded string
}): Promise
```
--------------------------------
### SHA-1 Hashing with hash-wasm
Source: https://context7.com/daninet/hash-wasm/llms.txt
Provides SHA-1 hashing functionality via WebAssembly. Supports both simple hashing of strings and a streaming API suitable for large files or sequential data processing. Can output binary Uint8Array.
```javascript
import { sha1, createSHA1 } from 'hash-wasm';
// Simple usage
const simpleHash = await sha1('message');
console.log(simpleHash);
// Processing file-like streams
const sha1Instance = await createSHA1();
sha1Instance.init();
// Simulate reading chunks from a file
function* fileChunks() {
yield new Uint8Array([65, 66, 67]); // 'ABC'
yield new Uint8Array([68, 69, 70]); // 'DEF'
}
for (const chunk of fileChunks()) {
sha1Instance.update(chunk);
}
const fileHash = sha1Instance.digest('binary'); // Uint8Array output
console.log(fileHash);
```
--------------------------------
### Calculate HMAC with Different Hash Functions (JavaScript)
Source: https://github.com/daninet/hash-wasm/blob/master/README.md
This snippet illustrates how to calculate HMAC (Hash-based Message Authentication Code) using various supported hash functions. It demonstrates creating an HMAC instance with a specific hash function (SHA3-224 in this case) and a secret key, then updating it with data and generating the digest. It emphasizes avoiding createXXXX() in loops for performance.
```javascript
import { createHMAC, createSHA3 } from "hash-wasm";
async function run() {
const hashFunc = createSHA3(224); // SHA3-224
const hmac = await createHMAC(hashFunc, "key");
const fruits = ["apple", "raspberry", "watermelon"];
console.log("Input:", fruits);
const codes = fruits.map((data) => {
hmac.init();
hmac.update(data);
return hmac.digest();
});
console.log("HMAC:", codes);
}
run();
```
--------------------------------
### Direct Hash Calculation API
Source: https://github.com/daninet/hash-wasm/blob/master/README.md
Calculate hashes directly from input data using various algorithms. All functions return the hash in hexadecimal format.
```APIDOC
## Direct Hash Calculation API
### Description
This API provides functions to directly compute hash values for given input data using a variety of standard cryptographic algorithms. The output is consistently returned as a hexadecimal string.
### Method
Various (all functions are asynchronous and return Promises)
### Endpoints
N/A (These are function calls, not HTTP endpoints)
### Parameters
- **data** (IDataType) - Required - The input data to be hashed. Can be a string, Buffer, Uint8Array, Uint16Array, or Uint32Array.
- **bits** (number) - Optional - The desired output size in bits for certain algorithms (e.g., BLAKE2, SHA3). Defaults are provided.
- **key** (IDataType) - Optional - A secret key for keyed hash functions (e.g., BLAKE2).
- **polynomial** (number) - Optional - A specific polynomial value for CRC algorithms. Defaults are provided.
- **seed** (number) - Optional - A seed value for XXHash algorithms.
- **seedLow**, **seedHigh** (number) - Optional - Lower and higher parts of a 64-bit seed for XXHash algorithms.
### Request Example
```javascript
// Example using sha256
const dataToHash = new Uint8Array([1, 2, 3, 4, 5]);
const hash = await sha256(dataToHash);
console.log(hash); // Output: '...' (hexadecimal hash string)
// Example using blake2b with custom bits and key
const keyedData = Buffer.from('my data');
const secretKey = Buffer.from('my secret key');
const blake2bHash = await blake2b(keyedData, 256, secretKey);
console.log(blake2bHash); // Output: '...' (hexadecimal hash string)
```
### Response
#### Success Response
- **string** - The calculated hash value in hexadecimal format.
```
--------------------------------
### Hasher Interface for Incremental Hashing in TypeScript
Source: https://github.com/daninet/hash-wasm/blob/master/README.md
Provides a more advanced interface for hashing, allowing for incremental updates and state management. The `IHasher` interface includes methods for initialization (`init`), updating with data (`update`), digesting the result (`digest`), saving the internal state (`save`), and loading a previous state (`load`). This is useful for hashing large files or streams where the entire data cannot be loaded into memory at once.
```typescript
interface IHasher {
init: () => IHasher;
update: (data: IDataType) => IHasher;
digest: (outputType: 'hex' | 'binary') => string | Uint8Array; // by default returns hex string
save: () => Uint8Array; // returns the internal state for later resumption
load: (state: Uint8Array) => IHasher; // loads a previously saved internal state
blockSize: number; // in bytes
digestSize: number; // in bytes
}
createAdler32(): Promise
createBLAKE2b(bits?: number, key?: IDataType): Promise // default is 512 bits
createBLAKE2s(bits?: number, key?: IDataType): Promise // default is 256 bits
createBLAKE3(bits?: number, key?: IDataType): Promise // default is 256 bits
createCRC32(polynomial?: number): Promise // default polynomial is 0xedb88320, for CRC32C use 0x82f63b78
createCRC64(polynomial?: number): Promise // default polynomial is 'c96c5795d7870f42' (ECMA)
createKeccak(bits?: 224 | 256 | 384 | 512): Promise // default is 512 bits
createMD4(): Promise
createMD5(): Promise
createRIPEMD160(): Promise
createSHA1(): Promise
createSHA224(): Promise
createSHA256(): Promise
createSHA3(bits?: 224 | 256 | 384 | 512): Promise // default is 512 bits
createSHA384(): Promise
createSHA512(): Promise
createSM3(): Promise
createWhirlpool(): Promise
createXXHash32(seed: number): Promise
createXXHash64(seedLow: number, seedHigh: number): Promise
createXXHash3(seedLow: number, seedHigh: number): Promise
createXXHash128(seedLow: number, seedHigh: number): Promise
```
--------------------------------
### Argon2 Verification in TypeScript
Source: https://github.com/daninet/hash-wasm/blob/master/README.md
Provides a function to verify a given password against an Argon2 hash. This is a crucial security function for validating user credentials. It requires the password and the hash to verify against. The exact parameters for verification are not fully detailed in the provided snippet but are implied to be part of the `argon2Verify` function.
```typescript
argon2Verify({
password: IDataType, // password
```
--------------------------------
### PBKDF2 Password Hashing in TypeScript
Source: https://github.com/daninet/hash-wasm/blob/master/README.md
Implements the PBKDF2 (Password-Based Key Derivation Function 2) algorithm. It takes a password, salt, iteration count, desired hash length, and a hash function as input. The function is asynchronous and returns a promise that resolves to the derived key, either as a hex string or binary data.
```typescript
pbkdf2({
password: IDataType, // password (or message) to be hashed
salt: IDataType, // salt (usually containing random bytes)
iterations: number, // number of iterations to perform
hashLength: number, // output size in bytes
hashFunction: Promise, // the return value of a function like createSHA1()
outputType?: 'hex' | 'binary', // by default returns hex string
}): Promise
```
--------------------------------
### Argon2 Password Hashing in TypeScript
Source: https://github.com/daninet/hash-wasm/blob/master/README.md
Supports three variants of the Argon2 algorithm (Argon2i, Argon2d, Argon2id), which is the winner of the Password Hashing Competition. It offers tunable parameters for memory, iterations, and parallelism, allowing for strong resistance against GPU cracking. Options include password, salt, secret, iterations, parallelism, memory size, and hash length. The output can be hex, binary, or an encoded string.
```typescript
interface IArgon2Options {
password: IDataType; // password (or message) to be hashed
salt: IDataType; // salt (usually containing random bytes)
secret?: IDataType; // secret for keyed hashing
iterations: number; // number of iterations to perform
parallelism: number; // degree of parallelism
memorySize: number; // amount of memory to be used in kibibytes (1024 bytes)
hashLength: number; // output size in bytes
outputType?: 'hex' | 'binary' | 'encoded'; // by default returns hex string
}
argon2i(options: IArgon2Options): Promise
argon2d(options: IArgon2Options): Promise
argon2id(options: IArgon2Options): Promise
```