BLAKE3 Cryptographic Hash Function

repository·master·Indexed 41 days ago

https://github.com/connor4312/blake3

A high-performance implementation of the BLAKE3 cryptographic hash function for Node.js (native) and browser (WASM/web) environments. It provides capabilities for standard hashing, keyed hashing for MAC applications, and key derivation (KDF) via deriveKey(). The library includes a NodeHash class that extends Node.js Transform streams and an IHashReader interface for efficient hash data traversal.

Tokens
5.5K
Snippets
26
Records
29
Agent score
47%

What's inside BLAKE3

  1. Use NodeHash as a Transform stream

    master

    The NodeHash class extends Node.js Transform. This allows you to pipe data directly into the hasher and receive the digest as the output of the stream. When the stream is flushed, it emits the digest.

    import { createHash } from 'blake3-wasm/src/node/hash-instance';
    import { Readable } from 'stream';
    
    const hasher = createHash();
    const source = Readable.from(['chunk1', 'chunk2']);
    
    source
      .pipe(hasher)
      .on('data', (digest: Buffer) => {
        console.log('Hash:', digest.toString('hex'));
      });
  2. Import the correct blake3 version for your environment

    master

    The blake3 package provides different entry points depending on your target environment. If you are building for a browser environment and attempt to import from the default blake3 entry point, the build will fail with a verbose error to prevent runtime issues and poor tree-shaking performance.

    • For Node.js/Native environments: Use import { ... } from 'blake3';
    • For Browser environments: Use import { ... } from 'blake3/browser';
    // Incorrect for browser builds:
    import { hash } from 'blake3';
    
    // Correct for browser builds:
    import { hash } from 'blake3/browser';
  3. Initialize the BLAKE3 WASM module with load()

    master

    Before performing any hashing operations using the blake3-wasm package, you must call the asynchronous load() function. This function loads the WebAssembly hashing engine and initializes the internal state. Failure to call load() before using hashing methods will result in errors.

    import { load, hash } from 'blake3-wasm';
    
    async function run() {
      await load();
      const digest = hash(new Uint8Array([1, 2, 3]));
      console.log(digest);
    }
    
    run();
  4. Import the correct blake3 version for browser environments

    master

    The blake3 package detects if it is being bundled for a browser environment via the process.browser flag. If you attempt to import the default Node.js build (import ... from 'blake3') into a browser bundle, the library will throw an error to prevent runtime issues and poor tree-shaking performance.

    To fix this, use the dedicated browser entrypoint instead of the default import.

    // ❌ Avoid this in browser bundles:
    import { hash } from 'blake3';
    
    // ✅ Use this for browser bundles:
    import { hash } from 'blake3/browser';
  5. Create a keyed BLAKE3 hash instance

    master

    Use createKeyed(key: HashInput) to initialize a BLAKE3 keyed hash instance. This is used for MAC (Message Authentication Code) applications where a secret key is required.

    import { createKeyed } from 'blake3-native';
    
    const key = Buffer.alloc(32, 'secret-key');
    const keyedHash = createKeyed(key);
    keyedHash.update(Buffer.from('data to authenticate'));
    const digest = keyedHash.digest();
  6. Configure digest encoding and options in NodeHash

    master

    The digest method on NodeHash supports multiple overloads to return either a Buffer or a formatted string (e.g., hex or base64) with optional BLAKE3 hash options.

    • To get a Buffer: Call digest() or digest(undefined, options).
    • To get a string: Call digest(encoding) where encoding is a BufferEncoding (like 'hex').
    • To get a string with options: Call digest(encoding, options).
    const hash = createHash();
    hash.update('data');
    
    // Returns Buffer
    const buffer = hash.digest(); 
    
    // Returns hex string
    const hex = hash.digest('hex');
    
    // Returns hex string with specific BLAKE3 options
    const custom = hash.digest('hex', { /* IBaseHashOptions */ });
  7. Digest hash results with encoding in BrowserHasher

    master

    The digest() method on a BrowserHasher can return either a raw Hash object or a formatted string based on the arguments provided:

    1. Return a Hash object: Call digest() with no arguments or with IBaseHashOptions.
    2. Return an encoded string: Pass a BrowserEncoding as the first argument (e.g., hex or base64). If you pass an encoding, the second argument should be the IBaseHashOptions.

    Supported overloads:

    • digest(options?: IBaseHashOptions): Hash
    • digest(encoding: undefined, options: IBaseHashOptions): Hash
    • digest(encoding: BrowserEncoding, options?: IBaseHashOptions): string
    // Returns a Hash object
    const hashObj = hasher.digest();
    
    // Returns a hex string
    const hexString = hasher.digest('hex');
    
    // Returns a hex string with specific options
    const hexStringWithOpts = hasher.digest('hex', { /* options */ });
  8. Use exported BLAKE3 functions and instances from blake3-native

    master
    The blake3-native package re-exports all public members from @c4312/blake3-internal, as well as specific hashing functions from ./hash-fn and hash instance logic from ./hash-instance. This provides a unified entrypoint for accessing the native BLAKE3 implementation.
  9. Create a keyed hasher with createKeyed()

    master

    Use createKeyed(key: HashInput) to instantiate a BrowserHasher configured for keyed hashing. The key provided will be used as the secret key for the BLAKE3 keyed mode.

    import { createHash, createKeyed } from 'blake3-wasm';
    
    const key = new Uint8Array([0, 1, 2, 3]); // Example key
    const hasher = createKeyed(key);
    const result = hasher.update(data).digest();
  10. Compute a keyed hash with keyedHash()

    master

    The keyedHash function implements the BLAKE3 keyed hash mode. It uses a key to hash the provided input. This mode is intended for use in MAC (Message Authentication Code) applications.

    Parameters:

    • key: A HashInput containing the cryptographic key.
    • input: A HashInput containing the data to be hashed.
    • options: An object containing length (defaults to defaultHashLength).
    import { keyedHash } from './hash-fn';
    
    const key = Buffer.from('0123456789abcdef0123456789abcdef'); // 32-byte key
    const data = Buffer.from('message to authenticate');
    
    const mac = keyedHash(key, data);
  11. Create a BLAKE3 key derivation instance

    master

    Use createDeriveKey(material: HashInput) to initialize a BLAKE3 key derivation instance. This is used to derive new keys from input material.

    import { createDeriveKey } from 'blake3-native';
    
    const material = Buffer.from('input-material');
    const deriveHash = createDeriveKey(material);
    deriveHash.update(Buffer.from('additional-context'));
    const derivedKey = deriveHash.digest();