PHPackages                             tourze/blake3-php - PHPackages - PHPackages  [Skip to content](#main-content)[PHPackages](/)[Directory](/)[Categories](/categories)[Trending](/trending)[Leaderboard](/leaderboard)[Changelog](/changelog)[Analyze](/analyze)[Collections](/collections)[Log in](/login)[Sign up](/register)

1. [Directory](/)
2. /
3. [Security](/categories/security)
4. /
5. tourze/blake3-php

ActiveLibrary[Security](/categories/security)

tourze/blake3-php
=================

A PHP implementation of the BLAKE3 cryptographic hash function

0.0.1(11mo ago)0520↓50%MITPHPPHP ^8.1CI passing

Since May 24Pushed 6mo ago1 watchersCompare

[ Source](https://github.com/tourze/blake3-php)[ Packagist](https://packagist.org/packages/tourze/blake3-php)[ RSS](/packages/tourze-blake3-php/feed)WikiDiscussions master Synced 1mo ago

READMEChangelog (1)Dependencies (2)Versions (2)Used By (0)

BLAKE3 PHP Implementation
=========================

[](#blake3-php-implementation)

[English](README.md) | [中文](README.zh-CN.md)

[![Latest Version](https://camo.githubusercontent.com/487bde6280dcb5a504b3a75ce55d8a183293ffab29e0ae1a4ee3ab19d5c62433/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f762f746f75727a652f626c616b65332d7068702e7376673f7374796c653d666c61742d737175617265)](https://packagist.org/packages/tourze/blake3-php)[![Total Downloads](https://camo.githubusercontent.com/93a60f3f69935f7c540f389d6e46c4bd7f5159f3069e72ec03b777a30b4ac42b/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f64742f746f75727a652f626c616b65332d7068702e7376673f7374796c653d666c61742d737175617265)](https://packagist.org/packages/tourze/blake3-php)[![License](https://camo.githubusercontent.com/ea213b0c40c272985bb922b8a19d86e2d48e5de4aafc2c38d455f9c15e896f8a/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f6c2f746f75727a652f626c616b65332d7068702e7376673f7374796c653d666c61742d737175617265)](https://packagist.org/packages/tourze/blake3-php)[![PHP Version](https://camo.githubusercontent.com/5ab6045c43b28c62ca0189189e660a2dd9b28a5030ccedd62678101de6843ddc/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f7068702d762f746f75727a652f626c616b65332d7068702e7376673f7374796c653d666c61742d737175617265)](https://packagist.org/packages/tourze/blake3-php)[![Build Status](https://camo.githubusercontent.com/9188cedcadf69c714c7a849f20a9fe3ac95d4c5d15f2f915f59b2d1e4a61c2bc/68747470733a2f2f696d672e736869656c64732e696f2f6769746875622f616374696f6e732f776f726b666c6f772f7374617475732f746f75727a652f7068702d6d6f6e6f7265706f2f63692e796d6c)](https://github.com/tourze/php-monorepo/actions)[![Coverage Status](https://camo.githubusercontent.com/6ce0146325478eb7cebae4cc6139b2af2c161735dd0e3c6ff6802f2c5a708179/68747470733a2f2f696d672e736869656c64732e696f2f636f6465636f762f632f6769746875622f746f75727a652f7068702d6d6f6e6f7265706f3f7374796c653d666c61742d737175617265)](https://codecov.io/gh/tourze/php-monorepo)

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
-----------------

[](#table-of-contents)

- [Features](#features)
- [Installation](#installation)
- [Quick Start](#quick-start)
- [Configuration](#configuration)
- [Advanced Usage](#advanced-usage)
- [Performance Considerations](#performance-considerations)
- [API Reference](#api-reference)
- [Security](#security)
- [Testing](#testing)
- [Directory Structure](#directory-structure)
- [Contributing](#contributing)
- [References](#references)
- [License](#license)

Features
--------

[](#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 &amp; PSR-12 Compliant** - Following PHP community standards
- **Comprehensive Test Suite** - Thoroughly tested against official test vectors

Installation
------------

[](#installation)

Install via Composer:

```
composer require tourze/blake3-php
```

### Requirements

[](#requirements)

- PHP 8.1 or higher
- Composer for dependency management

Quick Start
-----------

[](#quick-start)

### Basic Hashing

[](#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)

[](#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

[](#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

[](#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

[](#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
-------------

[](#configuration)

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

### Memory Usage

[](#memory-usage)

For large file processing, enable low memory mode:

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

### Buffer Size Management

[](#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
--------------------------

[](#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](benchmark/benchmark_results.md) for detailed performance data.

API Reference
-------------

[](#api-reference)

### Blake3::newInstance(bool $lowMemoryMode = false)

[](#blake3newinstancebool-lowmemorymode--false)

Creates a standard BLAKE3 hasher instance.

### Blake3::newKeyedInstance(string $key)

[](#blake3newkeyedinstancestring-key)

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

### Blake3::newKeyDerivationInstance(string $context)

[](#blake3newkeyderivationinstancestring-context)

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

### $hasher-&gt;update(string $data): self

[](#hasher-updatestring-data-self)

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

### $hasher-&gt;finalize(int $length = 32): string

[](#hasher-finalizeint-length--32-string)

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

### $hasher-&gt;reset(): self

[](#hasher-reset-self)

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

Advanced Usage
--------------

[](#advanced-usage)

### Incremental Hashing

[](#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

[](#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

[](#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
--------

[](#security)

### Key Management

[](#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

[](#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

[](#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
-------

[](#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
-------------------

[](#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
------------

[](#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
----------

[](#references)

- [BLAKE3 Official Specification](https://github.com/BLAKE3-team/BLAKE3-specs/blob/master/blake3.pdf)
- [BLAKE3 Official Repository](https://github.com/BLAKE3-team/BLAKE3)
- [BLAKE3 Test Vectors](https://github.com/BLAKE3-team/BLAKE3/blob/master/test_vectors/test_vectors.json)

License
-------

[](#license)

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

###  Health Score

32

—

LowBetter than 72% of packages

Maintenance59

Moderate activity, may be stable

Popularity18

Limited adoption so far

Community7

Small or concentrated contributor base

Maturity35

Early-stage or recently created project

 Bus Factor1

Top contributor holds 100% of commits — single point of failure

How is this calculated?**Maintenance (25%)** — Last commit recency, latest release date, and issue-to-star ratio. Uses a 2-year decay window.

**Popularity (30%)** — Total and monthly downloads, GitHub stars, and forks. Logarithmic scaling prevents top-heavy scores.

**Community (15%)** — Contributors, dependents, forks, watchers, and maintainers. Measures real ecosystem engagement.

**Maturity (30%)** — Project age, version count, PHP version support, and release stability.

###  Release Activity

Cadence

Unknown

Total

1

Last Release

359d ago

### Community

Maintainers

![](https://www.gravatar.com/avatar/e354fdb316da535dfa8ba2e9193a473c403b6bc6fb9170778d1dc50e304c6e9d?d=identicon)[tourze](/maintainers/tourze)

---

Top Contributors

[![tourze](https://avatars.githubusercontent.com/u/13899502?v=4)](https://github.com/tourze "tourze (1 commits)")

###  Code Quality

TestsPHPUnit

Static AnalysisPHPStan

Type Coverage Yes

### Embed Badge

![Health badge](/badges/tourze-blake3-php/health.svg)

```
[![Health](https://phpackages.com/badges/tourze-blake3-php/health.svg)](https://phpackages.com/packages/tourze-blake3-php)
```

###  Alternatives

[defuse/php-encryption

Secure PHP Encryption Library

3.9k162.4M214](/packages/defuse-php-encryption)[mews/purifier

Laravel 5/6/7/8/9/10 HtmlPurifier Package

2.0k16.7M113](/packages/mews-purifier)[robrichards/xmlseclibs

A PHP library for XML Security

41478.1M118](/packages/robrichards-xmlseclibs)[bjeavons/zxcvbn-php

Realistic password strength estimation PHP library based on Zxcvbn JS

87117.5M63](/packages/bjeavons-zxcvbn-php)[illuminate/encryption

The Illuminate Encryption package.

9229.7M280](/packages/illuminate-encryption)[paragonie/hidden-string

Encapsulate strings in an object to hide them from stack traces

7410.6M39](/packages/paragonie-hidden-string)

PHPackages © 2026

[Directory](/)[Categories](/categories)[Trending](/trending)[Changelog](/changelog)[Analyze](/analyze)
