tourze/blake3-php

A PHP implementation of the BLAKE3 cryptographic hash function

Installs: 56

Dependents: 0

Suggesters: 0

Security: 0

Stars: 0

Watchers: 1

Forks: 0

Open Issues: 0

pkg:composer/tourze/blake3-php

0.0.1 2025-05-24 17:08 UTC

This package is auto-updated.

Last update: 2025-10-31 04:07:06 UTC


README

English | 中文

Latest Version Total Downloads License PHP Version Build Status Coverage Status

A pure PHP implementation of the BLAKE3 cryptographic hash function, providing high-security hashing capabilities with support for standard hashing, keyed hashing, and key derivation.

Table of Contents

Features

  • Pure PHP Implementation - Following the official BLAKE3 specification
  • Multiple Modes - Standard hashing, keyed hashing, and key derivation
  • Streaming API - Process large files with low memory usage
  • Variable Output Length - Support for custom output sizes
  • Low Memory Mode - Optimized memory usage for constrained environments
  • PSR-4 & PSR-12 Compliant - Following PHP community standards
  • Comprehensive Test Suite - Thoroughly tested against official test vectors

Installation

Install via Composer:

composer require tourze/blake3-php

Requirements

  • PHP 8.1 or higher
  • Composer for dependency management

Quick Start

Basic Hashing

use Tourze\Blake3\Blake3;

// Create a new hasher instance
$hasher = Blake3::newInstance();

// Update with data
$hasher->update('hello ');
$hasher->update('world');

// Get the hash (default 32 bytes)
$hash = $hasher->finalize();
echo bin2hex($hash); // Output as hex string

Keyed Hashing (MAC)

use Tourze\Blake3\Blake3;

// Create a 32-byte key
$key = random_bytes(32); // Use a secure random key in production

// Create a keyed hasher
$hasher = Blake3::newKeyedInstance($key);
$hasher->update('message to authenticate');
$mac = $hasher->finalize();

Key Derivation

use Tourze\Blake3\Blake3;

// Derive keys from a context string
$hasher = Blake3::newKeyDerivationInstance('my-app 2024-01-01 user-key');
$hasher->update($inputKeyMaterial);

// Derive a 32-byte key
$derivedKey = $hasher->finalize(32);

Hashing Files with Streaming

use Tourze\Blake3\Blake3;

// Enable low memory mode for large files
$hasher = Blake3::newInstance(lowMemoryMode: true);

// Stream file in chunks
$handle = fopen('large-file.bin', 'rb');
while (!feof($handle)) {
    $chunk = fread($handle, 8192); // 8KB chunks
    $hasher->update($chunk);
}
fclose($handle);

$hash = $hasher->finalize();

Variable Output Length

use Tourze\Blake3\Blake3;

$hasher = Blake3::newInstance();
$hasher->update('data');

// Get different output lengths
$hash256bit = $hasher->finalize(32);  // 256-bit (default)
$hash512bit = $hasher->finalize(64);  // 512-bit
$hash1024bit = $hasher->finalize(128); // 1024-bit

Configuration

The library works out of the box without additional configuration. However, you can optimize performance for specific use cases:

Memory Usage

For large file processing, enable low memory mode:

$hasher = Blake3::newInstance(lowMemoryMode: true);

Buffer Size Management

The library automatically optimizes buffer sizes based on data characteristics. For manual control:

use Tourze\Blake3\Util\BufferSizeManager;

// Configure custom buffer size
$bufferManager = new BufferSizeManager();
$optimalSize = $bufferManager->getOptimalBufferSize($dataSize);

Performance Considerations

This is a pure PHP implementation prioritizing compatibility and ease of deployment over raw performance. Based on our benchmarks:

  • Speed: Significantly slower than PHP's built-in hash functions (SHA256, MD5)
  • Memory: Efficient memory usage, especially in low memory mode
  • Use Cases: Best suited for applications requiring BLAKE3's specific features rather than maximum throughput

For performance-critical applications, consider:

  • Using PHP's built-in hash functions if BLAKE3 is not specifically required
  • Looking for a PHP extension with native BLAKE3 implementation
  • Caching hash results when processing the same data multiple times

See benchmark results for detailed performance data.

API Reference

Blake3::newInstance(bool $lowMemoryMode = false)

Creates a standard BLAKE3 hasher instance.

Blake3::newKeyedInstance(string $key)

Creates a keyed BLAKE3 hasher for MAC operations. The key must be exactly 32 bytes.

Blake3::newKeyDerivationInstance(string $context)

Creates a BLAKE3 hasher for key derivation with the given context string.

$hasher->update(string $data): self

Updates the hash state with new data. Can be called multiple times.

$hasher->finalize(int $length = 32): string

Finalizes the hash and returns the output of the specified length in bytes.

$hasher->reset(): self

Resets the hasher to its initial state, allowing reuse of the same instance.

Advanced Usage

Incremental Hashing

Process data in multiple stages:

$hasher = Blake3::newInstance();

// Process data from multiple sources
$hasher->update($header);
$hasher->update($body);
$hasher->update($footer);

$finalHash = $hasher->finalize();

Key Stretching

Use for password-based key derivation:

$password = 'user_password';
$salt = random_bytes(16);
$context = "MyApp v1.0 key derivation {$salt}";

$hasher = Blake3::newKeyDerivationInstance($context);
$hasher->update($password . $salt);
$stretchedKey = $hasher->finalize(32);

Batch Processing

Process multiple inputs efficiently:

$inputs = ['data1', 'data2', 'data3'];
$results = [];

$hasher = Blake3::newInstance();
foreach ($inputs as $input) {
    $hasher->reset();
    $hasher->update($input);
    $results[] = $hasher->finalize();
}

Security

Key Management

  • Use secure random keys: Always use random_bytes() for key generation
  • Key size: MAC keys must be exactly 32 bytes
  • Key storage: Store keys securely, never hardcode in source code
  • Key rotation: Implement regular key rotation for production systems

Best Practices

  • Constant-time operations: The implementation uses constant-time comparisons where possible
  • Memory clearing: Sensitive data is cleared from memory when possible
  • Side-channel resistance: Implementation minimizes timing-based side channels

Security Considerations

  • This is a pure PHP implementation - consider timing attacks in highly sensitive environments
  • For maximum security, use in conjunction with secure key management systems
  • Validate input sizes to prevent resource exhaustion attacks

Testing

Run the test suite:

# Run all tests (from project root)
./vendor/bin/phpunit packages/blake3-php/tests

# Run with coverage
./vendor/bin/phpunit packages/blake3-php/tests --coverage-html coverage

# Run with verbose output
./vendor/bin/phpunit packages/blake3-php/tests --testdox

Directory Structure

src/
├── Blake3.php                 # Main hasher class
├── ChunkState/               # Chunk processing logic
│   └── Blake3ChunkState.php
├── Constants/                # Algorithm constants
│   └── Blake3Constants.php
├── Exception/                # Custom exceptions
│   ├── Blake3InvalidArgumentException.php
│   └── Blake3RuntimeException.php
├── Output/                   # Output generation
│   └── Blake3Output.php
└── Util/                     # Utility functions
    ├── Blake3Util.php
    └── BufferSizeManager.php

Contributing

Contributions are welcome! Please feel free to submit a Pull Request. For major changes, please open an issue first to discuss what you would like to change.

  1. Fork the repository
  2. Create your feature branch (git checkout -b feature/amazing-feature)
  3. Commit your changes (git commit -m 'Add some amazing feature')
  4. Push to the branch (git push origin feature/amazing-feature)
  5. Open a Pull Request

Please make sure to:

  • Update tests as appropriate
  • Follow PSR-12 coding standards
  • Add documentation for new features

References

License

The MIT License (MIT). Please see License File for more information.