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 Setup

  1. Install via Composer:

    composer require php-standard-library/hash
    
  2. Basic Usage:

    use PhpStandardLibrary\Hash\HashGenerator;
    
    $generator = new HashGenerator();
    $hash = $generator->generate('my-secret-string');
    // Outputs: e.g., "5e884898da28047151d0e56f8dc6292773603d0d6aabbdd62a11ef721d1542d8"
    
  3. First Use Case:

    • Password Hashing: Securely hash user passwords with a specific algorithm (e.g., bcrypt or argon2i).
      $hash = $generator->generate('user_password', 'argon2i');
      

Implementation Patterns

Core Workflows

  1. Hash Generation:

    • Default Algorithm: Uses sha256 by default for general-purpose hashing.
    • Custom Algorithms: Pass algorithm names (e.g., md5, sha512, bcrypt) to generate().
      $hash = $generator->generate($input, 'bcrypt', ['cost' => 12]);
      
    • Bytes Support: Hash raw binary data (e.g., file contents).
      $hash = $generator->generate(file_get_contents('file.bin'), 'sha1');
      
  2. Secure Comparison:

    • Use HashComparator to mitigate timing attacks when verifying hashes (e.g., passwords).
      use PhpStandardLibrary\Hash\HashComparator;
      
      $comparator = new HashComparator();
      $isMatch = $comparator->compare($storedHash, $input, 'argon2i');
      
  3. Integration with Laravel:

    • Service Provider: Bind the generator/comparator to Laravel’s container.
      // app/Providers/AppServiceProvider.php
      public function register()
      {
          $this->app->singleton(HashGenerator::class);
          $this->app->singleton(HashComparator::class);
      }
      
    • Helper Methods: Create facade or helper for concise syntax.
      // app/Helpers/HashHelper.php
      function hashString($string, $algorithm = 'sha256')
      {
          return app(HashGenerator::class)->generate($string, $algorithm);
      }
      
  4. Configuration:

    • Override defaults via config (e.g., default algorithm, salt length).
      // config/hash.php
      return [
          'default_algorithm' => 'argon2i',
          'argon2_options' => ['memory_cost' => 65536],
      ];
      
    • Load config in HashGenerator constructor or via dependency injection.

Gotchas and Tips

Pitfalls

  1. Algorithm Limitations:

    • Avoid weak algorithms (e.g., md5, sha1) for security-sensitive data (e.g., passwords). Use bcrypt or argon2i instead.
    • Debugging: If hashes don’t match, verify the algorithm and input encoding (e.g., UTF-8 vs. raw bytes).
  2. Timing Attacks:

    • Always use HashComparator for verification, never === or hash_equals() directly. Example of unsafe code:
      // UNSAFE: Timing attack risk
      if (hash('sha256', $input) === $storedHash) { ... }
      
    • Fix: Use HashComparator::compare().
  3. Stateful Algorithms:

    • Algorithms like bcrypt or argon2i require unique salts per input. The library handles this automatically, but ensure you’re not reusing salts manually.
  4. Output Formatting:

    • Hashes are returned as strings by default. For binary-safe operations (e.g., database storage), use hex2bin() or raw binary handling.
      $binaryHash = hex2bin($generator->generate('data'));
      

Tips

  1. Performance:

    • For non-security-critical hashing (e.g., cache keys), use faster algorithms like xxh3 or crc32.
    • Benchmark: Test algorithms with microtime() for your workload:
      $start = microtime(true);
      $generator->generate('large_input', 'sha256');
      echo microtime(true) - $start; // ~0.0001s for 1KB input
      
  2. Extending the Library:

    • Custom Algorithms: Implement PhpStandardLibrary\Hash\Contracts\AlgorithmInterface for new hashing methods.
      class CustomAlgorithm implements AlgorithmInterface {
          public function hash($data): string { ... }
          public function verify($data, $hash): bool { ... }
      }
      
    • Register the algorithm in HashGenerator:
      $generator->addAlgorithm('custom', new CustomAlgorithm());
      
  3. Testing:

    • Mock HashGenerator in unit tests to avoid flaky tests due to hash variability.
      $mockGenerator = Mockery::mock(HashGenerator::class);
      $mockGenerator->shouldReceive('generate')->andReturn('mocked_hash');
      
    • Use deterministic algorithms (e.g., sha256) for test data to ensure reproducibility.
  4. Laravel-Specific:

    • Hashing Request Inputs: Use the library to hash sensitive request data (e.g., API keys) before storage.
      $hashedKey = app(HashGenerator::class)->generate(request('api_key'));
      
    • Migrations: Hash sensitive fields (e.g., remember_token) during migration:
      use Illuminate\Support\Facades\Hash as LaravelHash;
      use PhpStandardLibrary\Hash\HashGenerator;
      
      $hashedToken = app(HashGenerator::class)->generate(str_random(60));
      
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.
davejamesmiller/laravel-breadcrumbs
artisanry/parsedown
christhompsontldr/phpsdk
enqueue/dsn
bunny/bunny
enqueue/test
enqueue/null
enqueue/amqp-tools
milesj/emojibase
bower-asset/punycode
bower-asset/inputmask
bower-asset/jquery
bower-asset/yii2-pjax
laravel/nova
spatie/laravel-mailcoach
spatie/laravel-superseeder
laravel/liferaft
nst/json-test-suite
danielmiessler/sec-lists
jackalope/jackalope-transport