Weave Code
Code Weaver
Helps Laravel developers discover, compare, and choose open-source packages. See popularity, security, maintainers, and scores at a glance to make better decisions.
Feedback
Share your thoughts, report bugs, or suggest improvements.
Subject
Message

Keccak Laravel Package

kornrunner/keccak

Pure PHP Keccak (SHA-3) implementation with easy static API. Compute Keccak hashes (224/256/384/512) and SHAKE outputs (XOF) without extensions. Includes test suite and coverage, suitable for Ethereum and other crypto use cases.

View on GitHub
Deep Wiki
Context7

Getting Started

Install via Composer:

composer require kornrunner/keccak

First use case: Generate a SHA-3 hash for a blockchain-related feature (e.g., Ethereum address derivation):

use kornrunner\Keccak;

// Keccak-256 (common for Ethereum)
$hash = Keccak::hash('wallet_data', 256);

Where to look first:


Implementation Patterns

1. Laravel Integration

Facade Wrapper (Recommended)

Extend Laravel’s Hash facade to support Keccak:

// app/Providers/AppServiceProvider.php
use Illuminate\Support\Facades\Hash;
use kornrunner\Keccak;

Hash::extend('keccak', function() {
    return function($value, array $options = []) {
        $rounds = $options['rounds'] ?? 256;
        return Keccak::hash($value, $rounds);
    };
});

Usage:

// In controllers/services
$hash = Hash::driver('keccak')->make('data');

Service Binding

Bind the package to Laravel’s container for dependency injection:

// config/app.php
'aliases' => [
    'Keccak' => kornrunner\Keccak::class,
],

Usage:

use Illuminate\Support\Facades\Keccak;

$hash = Keccak::hash('data', 256);

2. Common Workflows

A. Password Hashing Alternative

Use Keccak for salt derivation or custom hash rounds:

$salt = Keccak::hash(str_random(32), 128); // 128-bit salt
$passwordHash = Hash::make($password, ['rounds' => 12]);

B. Blockchain Features

Generate Ethereum-compatible hashes:

// Keccak-256 for wallet addresses
$addressHash = Keccak::hash($walletData, 256);
$address = '0x' . substr($addressHash, -40);

C. SHAKE for Extendable Output

Use SHAKE for custom-length hashes (e.g., signatures):

$customHash = Keccak::shake('data', 128, 512); // 128-bit output from 512-bit SHAKE

D. Data Integrity Checks

Verify file/database record integrity:

$expectedHash = Keccak::hash($originalData, 256);
$actualHash = Keccak::hash($retrievedData, 256);

if ($expectedHash !== $actualHash) {
    throw new \RuntimeException('Data corruption detected!');
}

3. Performance Optimization

A. Caching

Cache hashes for static data (e.g., config, assets):

$hash = Cache::remember("keccak_{$data}", 3600, function() use ($data) {
    return Keccak::hash($data, 256);
});

B. Batch Processing

Use queues for bulk hashing (e.g., migrating records):

// Dispatch a job
HashBulkJob::dispatch($records);

// Job class
public function handle() {
    foreach ($this->records as $record) {
        $record->hash = Keccak::hash($record->data, 256);
        $record->save();
    }
}

C. Hybrid Approach

Fallback to OpenSSL if available:

function hybridHash($data, $rounds = 256) {
    if (extension_loaded('openssl')) {
        return hash('sha3-' . $rounds, $data);
    }
    return Keccak::hash($data, $rounds);
}

4. Testing

Unit Tests

Test hash outputs against known values:

public function testKeccak256() {
    $hash = Keccak::hash('', 256);
    $this->assertEquals(
        'c5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470',
        $hash
    );
}

Integration Tests

Verify Laravel facade integration:

public function testHashFacade() {
    Hash::extend('keccak', function() { ... });

    $hash = Hash::driver('keccak')->make('test');
    $this->assertEquals(Keccak::hash('test', 256), $hash);
}

Gotchas and Tips

Pitfalls

  1. Performance Overhead

    • Pure PHP Keccak is ~50–100x slower than OpenSSL’s sha3_*.
    • Fix: Benchmark with microtime(true) before production use. Avoid in loops or high-throughput scenarios.
  2. Memory Limits

    • Large inputs (e.g., files >1MB) may hit PHP’s memory_limit.
    • Fix: Stream data in chunks or increase memory_limit in php.ini.
  3. No Constant-Time Comparison

    • The package doesn’t enforce constant-time comparison (risk of timing attacks).
    • Fix: Use hash_equals() for sensitive comparisons:
      if (!hash_equals($expected, $actual)) { ... }
      
  4. Stale Maintenance

    • Last release in 2020; no PHP 8.2+ support guaranteed.
    • Fix: Fork the repo and maintain locally if critical.
  5. SHAKE Misuse

    • SHAKE is a XOF (eXtendable-Output Function), not a fixed hash. Output length must be specified.
    • Fix: Always pass both output length and capacity (e.g., shake($data, 128, 256)).
  6. Non-String Inputs

    • The package may not handle non-string inputs gracefully (e.g., objects, resources).
    • Fix: Normalize inputs:
      $data = is_string($data) ? $data : json_encode($data);
      

Debugging Tips

  1. Verify Outputs

    • Cross-check hashes with NIST SHA-3 test vectors.
    • Example:
      $this->assertEquals(
          'c5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470',
          Keccak::hash('', 256)
      );
      
  2. Memory Issues

    • Enable xdebug.memory_enable=1 in php.ini to track memory usage:
      $start = memory_get_usage();
      $hash = Keccak::hash(file_get_contents('large_file'), 256);
      $end = memory_get_usage();
      $used = $end - $start; // Check if >100MB
      
  3. Performance Profiling

    • Use Laravel Debugbar or XHProf to compare with OpenSSL:
      $time = microtime(true);
      $hash = Keccak::hash(str_repeat('a', 1000), 256);
      $duration = microtime(true) - $time; // Should be >1ms
      
  4. Edge Cases

    • Test with:
      • Empty strings (Keccak::hash('', 256)).
      • Unicode/UTF-8 data (Keccak::hash('🚀', 256)).
      • Binary data (Keccak::hash(file_get_contents('image.png'), 256)).

Configuration Quirks

  1. Laravel Hash Driver

    • If extending the Hash facade, ensure the driver name doesn’t conflict with existing drivers (e.g., bcrypt, argon2).
    • Tip: Use a unique name like keccak_sha3.
  2. PHP Version Compatibility

    • Test on PHP 8.1 (last tested version). PHP 8.2+ may require:
      • Updated type hints (e.g., string return types).
      • Strict mode compatibility.
  3. Autoloading

    • If using a custom facade, ensure the composer.json autoloads the package:
      "autoload": {
          "
      
Weaver

How can I help you explore Laravel packages today?

Conversation history is not saved when not logged in.
Prompt
Add packages to context
No packages found.
terminal42/code-quality-tools
codifyo/ts-generator-bundle
andydefer/laravel-cluster
testo/fiber
mintobit/jobqueue
a4sex/maintenance-bundle
a4sex/entity-date-update
a4sex/client-identifier
a4sex/base-utilites
a4sex/key-value-storage
a4sex/micro-status
chilldev/dependency-injection-extra
datinglibre/datinglibre-app-api
biberltd/corebundle
bricre/symfony-bundle-test
biberltd/logbundle
dominium/http-adapter-bundle
dominium/google-analytics
a4sex/auto-clean-entity
christhompsontldr/laravel-inky