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 based on use case.

  2. First Use Case: Generate a SHA-256 hash for a file checksum:

    use PhpStandardLibrary\Hash\HashGenerator;
    use PhpStandardLibrary\Hash\Algorithm;
    
    $generator = new HashGenerator();
    $fileContent = file_get_contents('example.txt');
    $hash = $generator->generate($fileContent, Algorithm::SHA256);
    
  3. Where to Look First:

    • README.md for API overview.
    • src/HashGenerator.php for core functionality.
    • src/Algorithm.php for supported algorithms (e.g., SHA256, MD5, BCRYPT).

Implementation Patterns

Usage Patterns

  1. Hash Generation:

    $generator = new HashGenerator();
    $hash = $generator->generate('sensitive_data', Algorithm::SHA256);
    
  2. Timing-Safe Comparison (Critical for security):

    use PhpStandardLibrary\Hash\HashComparator;
    
    $comparator = new HashComparator();
    $isMatch = $comparator->equals($storedHash, $inputHash);
    
  3. HMAC Generation (For API signatures):

    $hmac = $generator->generateHmac('secret_key', 'data', Algorithm::SHA256);
    
  4. Algorithm Enums: Prefer Algorithm::SHA256 over strings for type safety and IDE autocompletion.

Workflows

  1. File Integrity Checks:

    $fileHash = $generator->generate(file_get_contents($filePath), Algorithm::SHA512);
    cache()->put("file_{$filePath}_hash", $fileHash, now()->addHours(1));
    
  2. API Request Signing:

    $signature = $generator->generateHmac(
        config('app.api_secret'),
        $request->getContent(),
        Algorithm::HMAC_SHA256
    );
    
  3. Password Verification (Use Laravel’s Hash facade instead):

    // Avoid: Use Hash::check() for passwords
    $isMatch = $comparator->equals(
        Hash::make($password),
        $storedPassword
    );
    

Integration Tips

  1. Laravel Service Provider: Bind the generator to the container for dependency injection:

    $this->app->singleton(HashGenerator::class, function () {
        return new HashGenerator();
    });
    

    Usage in controllers:

    public function __construct(private HashGenerator $hash) {}
    
  2. Configuration: Define default algorithms in config/hash.php:

    return [
        'default_algorithm' => Algorithm::SHA256,
        'hmac_key' => env('HMAC_SECRET'),
    ];
    
  3. Testing: Mock HashGenerator in unit tests:

    $mockGenerator = Mockery::mock(HashGenerator::class);
    $mockGenerator->shouldReceive('generate')
        ->once()
        ->with('test', Algorithm::MD5)
        ->andReturn('d41d8cd98f00b204e9800998ecf8427e');
    
  4. Artisan Commands: Use for bulk operations (e.g., regenerating cache keys):

    use Illuminate\Console\Command;
    use PhpStandardLibrary\Hash\HashGenerator;
    
    class RegenerateHashes extends Command
    {
        protected $signature = 'hashes:regenerate';
        public function handle(HashGenerator $hash)
        {
            $data = Model::all();
            foreach ($data as $item) {
                $item->hash = $hash->generate($item->content, Algorithm::SHA256);
                $item->save();
            }
        }
    }
    

Gotchas and Tips

Pitfalls

  1. Algorithm Confusion:

    • Gotcha: Using Algorithm::MD5 or Algorithm::SHA1 for security-sensitive data (e.g., tokens, passwords).
    • Fix: Reserve cryptographic algorithms (SHA256, BCRYPT) for sensitive data. Use non-cryptographic ones (e.g., CRC32) only for non-security purposes like checksums.
  2. Timing Attacks:

    • Gotcha: Forgetting to use HashComparator for sensitive comparisons (e.g., API keys, session tokens).
    • Fix: Always use HashComparator::equals() instead of === or ==:
      // UNSAFE
      if ($storedHash === $inputHash) { ... }
      
      // SAFE
      if ($comparator->equals($storedHash, $inputHash)) { ... }
      
  3. HMAC Misuse:

    • Gotcha: Using HMAC without a secret key or reusing keys across requests.
    • Fix: Store HMAC secrets in .env and regenerate them periodically:
      $hmac = $generator->generateHmac(
          env('API_HMAC_SECRET'),
          $request->getContent(),
          Algorithm::HMAC_SHA256
      );
      
  4. Input Handling:

    • Gotcha: Passing non-string inputs (e.g., objects, arrays) directly to generate().
    • Fix: Convert inputs to strings first:
      $hash = $generator->generate(json_encode($arrayData), Algorithm::SHA256);
      
  5. Laravel Facade Overlap:

    • Gotcha: Mixing this package with Laravel’s Hash facade for passwords.
    • Fix: Enforce a rule: Use php-standard-library/hash only for non-password data. Passwords must use Laravel’s Hash facade.

Debugging

  1. Hash Mismatches:

    • Debug Tip: Log the raw input and algorithm to identify encoding issues:
      $rawInput = json_encode($data, JSON_UNESCAPED_UNICODE);
      $hash = $generator->generate($rawInput, Algorithm::SHA256);
      
  2. Performance Bottlenecks:

    • Debug Tip: Profile hash generation in bulk operations (e.g., file checksums):
      $start = microtime(true);
      foreach ($files as $file) {
          $generator->generate(file_get_contents($file), Algorithm::SHA512);
      }
      $time = microtime(true) - $start;
      
  3. Algorithm Support:

    • Debug Tip: Check supported algorithms in Algorithm.php. If missing, consider:
      • Using native hash() functions as a fallback.
      • Extending the package (see Extension Points below).

Config Quirks

  1. Algorithm Enums:

    • Quirk: Enums are case-sensitive. Use Algorithm::SHA256, not Algorithm::sha256.
    • Tip: Use IDE autocompletion to avoid typos.
  2. HMAC Defaults:

    • Quirk: The package doesn’t auto-generate HMAC keys. Always pass a secret explicitly:
      // UNSAFE (no secret provided)
      $generator->generateHmac('data');
      
      // SAFE
      $generator->generateHmac(env('HMAC_SECRET'), 'data', Algorithm::HMAC_SHA256);
      
  3. Resource Inputs:

    • Quirk: File streams (resource) may not work as expected. Read content first:
      $fileContent = file_get_contents($filePath);
      $hash = $generator->generate($fileContent, Algorithm::SHA256);
      

Extension Points

  1. Custom Algorithms:

    • Extend Algorithm enum to add support for missing algorithms (e.g., BLAKE3):
      namespace App\Extensions;
      
      use PhpStandardLibrary\Hash\Algorithm;
      
      class CustomAlgorithm extends Algorithm
      {
          public const BLAKE3 = 'blake3';
      }
      
  2. Custom Comparators:

    • Implement a decorator for HashComparator to add logging or additional checks:
      class LoggingHashComparator implements ComparatorInterface
      {
          public function equals(string $hash1, string $hash2): bool
          {
              \Log::debug("Comparing hashes: {$hash1} vs {$hash2}");
              return $comparator->equals($hash1, $hash2);
          }
      }
      
  3. Laravel Facade Wrapper:

    • Create a facade to unify access with Laravel’s Hash:
      // app/Facades/StandardHash.php
      namespace App\Facades;
      
      use Illuminate\Support\Facades\Facade;
      
      class StandardHash extends Facade
      {
          protected static function getFacadeAccessor()
          {
              return 'hash.standard';
          }
      }
      
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.
codraw/entity-migrator
codraw/doctrine-extra
codraw/aws-tool-kit
codraw/validator
codraw/workflow
codraw/open-api
codraw/cron-job
codraw/process
codraw/log
nexmo/api-specification
capell-app/block-library
axium/identity
cetria/laravel-dummy-models
cetria/reflection-helper
agropredict/sso-auth-bundle
evolvestudio/spam-protection
datacore/hub-sdk
develia/commons
cuci/prototurk-sdk
cuci/prototurk-sdk-symfony