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

Hash Laravel Package

php-standard-library/hash

Hash utilities for PHP: cryptographic and non-cryptographic hashing via an Algorithm enum, HMAC helpers, and timing-safe string comparison. Lightweight package from PHP Standard Library for consistent, secure hashing across projects.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Steps

  1. Installation:

    composer require php-standard-library/hash
    

    Add to composer.json under require or require-dev depending on use case.

  2. First Usage:

    use PhpStandardLibrary\Hash\HashGenerator;
    
    $generator = new HashGenerator();
    $hash = $generator->generate('my-data');
    // Returns: string (e.g., "5e884898da28047151d0e56f8dc6292773603d0d6aabbdd62a11ef721d1542d8")
    
  3. First Laravel Integration:

    • Service Provider:
      // app/Providers/HashServiceProvider.php
      namespace App\Providers;
      use Illuminate\Support\ServiceProvider;
      use PhpStandardLibrary\Hash\HashGenerator;
      
      class HashServiceProvider extends ServiceProvider
      {
          public function register()
          {
              $this->app->singleton('hash.generator', function () {
                  return new HashGenerator();
              });
          }
      }
      
    • Register in config/app.php:
      'providers' => [
          // ...
          App\Providers\HashServiceProvider::class,
      ],
      
  4. Basic Laravel Usage:

    $hash = app('hash.generator')->generate('user_input');
    

Implementation Patterns

Common Laravel Use Cases

1. Password Hashing (Non-Laravel Auth)

  • Use this package for non-password hashing (e.g., API tokens, checksums). For passwords, stick with Laravel’s built-in Hash facade.
// For non-password data (e.g., API tokens)
$token = app('hash.generator')->generate('user_id:timestamp', 'sha256');

2. File Integrity Checks

public function verifyFileIntegrity(string $filePath, string $expectedHash)
{
    $fileBytes = file_get_contents($filePath);
    $actualHash = app('hash.generator')->generate($fileBytes, 'sha512');
    return $actualHash === $expectedHash;
}

3. Timing-Safe Hash Comparison

  • Use HashComparator for sensitive comparisons (e.g., API keys, tokens).
use PhpStandardLibrary\Hash\HashComparator;

$comparator = new HashComparator();
$isValid = $comparator->compare(
    $userInput,
    $storedHash,
    'sha256'
);

4. HMAC Generation for API Requests

use PhpStandardLibrary\Hash\HmacGenerator;

$hmac = new HmacGenerator('my-secret-key');
$signature = $hmac->generate('request_data');

5. Configuration-Driven Hashing

  • Store algorithm preferences in config/hash.php:
return [
    'default_algorithm' => 'sha256',
    'algorithms' => [
        'file_checksum' => 'sha512',
        'api_signature' => 'hmac-sha256',
    ],
];
  • Use in code:
$algorithm = config('hash.algorithms.file_checksum');
$hash = app('hash.generator')->generate($data, $algorithm);

6. Middleware for Request Signatures

  • Validate HMAC signatures in incoming requests:
public function handle(Request $request, Closure $next)
{
    $hmac = new HmacGenerator(config('app.hmac_secret'));
    $expectedSignature = $hmac->generate($request->getContent());
    if (!$expectedSignature === $request->header('X-Signature')) {
        abort(403, 'Invalid signature');
    }
    return $next($request);
}

7. Artisan Commands for Bulk Hashing

use Illuminate\Console\Command;
use PhpStandardLibrary\Hash\HashGenerator;

class BulkHashCommand extends Command
{
    protected $signature = 'hash:bulk {--file=}';
    protected $description = 'Generate hashes for bulk data';

    public function handle(HashGenerator $generator)
    {
        $data = $this->option('file') ? file($this->option('file')) : [];
        foreach ($data as $item) {
            $hash = $generator->generate(trim($item));
            $this->line($hash);
        }
    }
}

8. Event Listeners for Audit Logs

  • Hash sensitive data before logging:
public function handle(LogEvent $event)
{
    $logger = new HashGenerator();
    $hashedData = $logger->generate($event->data['sensitive_field']);
    $event->data['sensitive_field'] = $hashedData;
}

Integration Tips

Laravel Facade Wrapper

Create a facade for cleaner syntax:

// app/Facades/Hash.php
namespace App\Facades;

use Illuminate\Support\Facades\Facade;

class Hash extends Facade
{
    protected static function getFacadeAccessor()
    {
        return 'hash.generator';
    }
}

Usage:

$hash = Hash::generate('data');

Algorithm Validation

Validate algorithms against a whitelist in a trait:

trait ValidatedHashing
{
    protected function validateAlgorithm(string $algorithm): void
    {
        $allowed = ['sha256', 'sha512', 'bcrypt', 'hmac-sha256'];
        if (!in_array($algorithm, $allowed)) {
            throw new \InvalidArgumentException("Algorithm {$algorithm} not allowed.");
        }
    }
}

Caching Hashes

Cache generated hashes to avoid recomputation:

public function getCachedHash(string $key, string $data)
{
    return cache()->remember("hash:{$key}", now()->addHours(1), function () use ($data) {
        return app('hash.generator')->generate($data);
    });
}

Testing Strategies

  • Unit Tests: Mock HashGenerator to test hash-dependent logic.
    $mockGenerator = Mockery::mock(HashGenerator::class);
    $mockGenerator->shouldReceive('generate')->andReturn('mocked-hash');
    $this->app->instance('hash.generator', $mockGenerator);
    
  • Integration Tests: Verify real hash generation in feature tests.
    public function test_hash_generation()
    {
        $hash = Hash::generate('test');
        $this->assertEquals(64, strlen($hash)); // SHA-256 length
    }
    

Migration from Native hash()

Replace:

// Old
$hash = hash('sha256', $data);

// New
$hash = Hash::generate($data, 'sha256');

Gotchas and Tips

Pitfalls

  1. Algorithm Confusion with Laravel’s Hash Facade:

    • Issue: Mixing this package with Laravel’s Hash facade (for passwords) can lead to confusion.
    • Fix: Document a clear boundary:
      • Use php-standard-library/hash for non-password data (e.g., tokens, checksums).
      • Use Laravel’s Hash facade for passwords only.
  2. Timing Attacks in Custom Comparisons:

    • Issue: Using === or == for hash comparisons can expose timing attacks.
    • Fix: Always use HashComparator for sensitive comparisons:
      $comparator = new HashComparator();
      $isValid = $comparator->compare($input, $storedHash);
      
  3. Algorithm-Specific Options:

    • Issue: Some algorithms (e.g., bcrypt, argon2) require additional options (e.g., cost, memory).
    • Fix: Pass options as the third argument:
      $hash = $generator->generate('data', 'bcrypt', ['cost' => 12]);
      
  4. Binary Data Handling:

    • Issue: Passing non-string data (e.g., file resources) may cause errors.
    • Fix: Convert to string or bytes explicitly:
      $fileBytes = file_get_contents($path);
      $hash = $generator->generate($fileBytes);
      
  5. HMAC Key Management:

    • Issue: Hardcoding HMAC keys in code.
    • Fix: Store keys in .env:
      HMAC_SECRET=your_secure_key_here
      
      $hmac = new HmacGenerator(config('app.hmac_secret'));
      
  6. Deprecation of Weak Algorithms:

    • Issue: The package may drop support for weak algorithms (e.g., md5, sha1) in future updates.
    • Fix: Pin the package version in composer.json if relying on specific algorithms.
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.
hexters/coinpayment
rjcodes/rjcms
act-training/laravel-permissions-manager
alimarchal/laravel-chart-of-accounts
babenkoivan/elastic-scout-driver
mkwebdesign/filament-watchdog-v5
renatomarinho/laravel-page-speed
zedmagdy/filament-business-hours
renatovdemoura/blade-elements-ui
devgeek/beacon-admin
benjamin-rqt/data-watcher-bundle
atriumphp/atrium
sandermuller/package-boost-laravel
sandermuller/boost-skills
redaxo/core
yusufgenc/filament-api-forge
l3aro/rating-star-for-filament
leek/filament-subtenant-scope
anil/file-picker
broqit/fields-ai