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

Secure Random Laravel Package

php-standard-library/secure-random

SecureRandom provides cryptographically secure random bytes and strings in PHP for tokens, passwords, nonces, and IDs. Simple API built on secure system sources, suitable for authentication, session, and security-sensitive workflows.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Steps

  1. Installation:

    composer require php-standard-library/secure-random
    

    No additional configuration is required.

  2. First Use Case: Generate a cryptographically secure hexadecimal token (e.g., for CSRF protection or JWT secrets):

    use SecureRandom\SecureRandom;
    
    $token = SecureRandom::hex(32); // 32-byte hex string
    
  3. Where to Look First:

    • API Reference: Focus on these core methods:
      • SecureRandom::hex(int $length) → Hexadecimal string (e.g., SecureRandom::hex(16)).
      • SecureRandom::base64(int $length) → Base64-encoded string (e.g., SecureRandom::base64(24)).
      • SecureRandom::uuid() → RFC 4122 UUID (v4).
      • SecureRandom::int(int $min, int $max) → Cryptographically secure integer.
      • SecureRandom::bytes(int $length) → Raw binary data (for encryption nonces/IVs).
    • Laravel Integration: Bind to the service container (optional but recommended):
      $this->app->singleton(SecureRandom::class, fn() => new \SecureRandom\SecureRandom());
      

Implementation Patterns

Usage Patterns

  1. Token Generation:

    • CSRF Tokens: Replace Str::random(40) with SecureRandom::base64(32).
      $csrfToken = SecureRandom::base64(32);
      
    • JWT Secrets: Use SecureRandom::hex(64) for high-entropy secrets.
      $jwtSecret = SecureRandom::hex(64);
      
  2. Password Reset Tokens:

    • Generate a 60-character alphanumeric token:
      $token = SecureRandom::hex(30); // 60 chars (2 chars per byte)
      
  3. Database IDs:

    • For large integer IDs (e.g., bigint in PostgreSQL):
      $id = SecureRandom::int(1, PHP_INT_MAX);
      
    • For UUIDs (replace Ramsey\Uuid where randomness is critical):
      $uuid = SecureRandom::uuid();
      
  4. Encryption Nonces/IVs:

    • Generate 16-byte IVs for AES:
      $iv = SecureRandom::bytes(16);
      
  5. Laravel Facade (Optional): Create a facade for consistency:

    // app/Providers/AppServiceProvider.php
    use Illuminate\Support\Facades\Facade;
    
    Facade::register('SecureRandom', function () {
        return app(SecureRandom::class);
    });
    

    Usage:

    $token = SecureRandom::hex(32); // Now accessible via facade
    

Workflows

  1. Auth Flow:

    • Generate a secure login token:
      $loginToken = SecureRandom::base64(48);
      
    • Store in session/cookie with SecureRandom::hex(32) as a signature.
  2. CSRF Protection:

    • Replace csrf_token() middleware with a custom guard using SecureRandom::base64(32).
  3. Password Hashing:

    • Use SecureRandom::hex(32) as a pepper for bcrypt (if not using Laravel’s built-in hashing).
  4. Testing:

    • Mock random_bytes() in unit tests:
      $this->partialMock(SecureRandom::class, 'randomBytes')
           ->method('randomBytes')
           ->willReturn('mocked_bytes');
      

Integration Tips

  1. Replace Insecure Primitives:

    • Before: Str::random(32) or random_int(0, PHP_INT_MAX).
    • After: SecureRandom::hex(32) or SecureRandom::int(0, PHP_INT_MAX).
  2. Laravel Service Container:

    • Bind the class for dependency injection:
      $this->app->bind(SecureRandom::class, fn() => new \SecureRandom\SecureRandom());
      
    • Inject into controllers/services:
      public function __construct(private SecureRandom $secureRandom) {}
      
  3. Configuration:

    • No config file is needed, but document usage in config/app.php or a custom secure_random.php:
      'secure_random' => [
          'default_length' => 32, // Default hex length
      ],
      
  4. Performance:

    • Cache non-time-sensitive tokens (e.g., CSRF tokens) to avoid repeated CSPRNG calls.
    • Benchmark critical paths (e.g., auth token generation) to ensure latency SLAs.

Gotchas and Tips

Pitfalls

  1. Entropy Warnings:

    • Issue: random_bytes() may fall back to weaker sources on low-entropy systems (e.g., Docker, CI environments).
    • Fix: Monitor system entropy and log warnings:
      if (random_bytes(16) === false) {
          Log::warning('CSPRNG entropy pool may be depleted');
      }
      
    • Workaround: Use random_int() as a fallback (less secure but better than mt_rand()).
  2. Length Mismatches:

    • Issue: Incorrect lengths for specific use cases (e.g., 16-byte IVs for AES).
    • Fix: Document required lengths in your codebase:
      // AES-128 IV (16 bytes)
      $iv = SecureRandom::bytes(16);
      
  3. Laravel Caching:

    • Issue: Caching SecureRandom instances may not be thread-safe in shared environments.
    • Fix: Use a singleton binding (as shown above) or avoid caching the instance.
  4. UUID Collisions:

    • Issue: While unlikely, SecureRandom::uuid() uses PHP’s random_bytes(), which may not be as vetted as Ramsey\Uuid.
    • Fix: Use Ramsey\Uuid\Uuid::uuid4() for production UUIDs if collision risk is a concern.
  5. Legacy Code:

    • Issue: Existing Str::random() calls may still use insecure PRNGs.
    • Fix: Use static analysis (e.g., PHPStan) to enforce usage:
      // phpstan.neon
      rules:
          SecureRandomUsage:
              type: PHPStan\Rules\CustomRule
              path: vendor/bin/ruleset.php
      

Debugging

  1. Mocking in Tests:

    • Stub random_bytes() to simulate failures:
      $mock = $this->getMockBuilder(SecureRandom::class)
          ->onlyMethods(['randomBytes'])
          ->getMock();
      $mock->method('randomBytes')->willReturn(false);
      
  2. Entropy Checks:

    • On Linux, check entropy pool health:
      cat /proc/sys/kernel/random/entropy_avail
      
    • Values below 1000 may indicate low entropy.
  3. Performance Profiling:

    • Measure SecureRandom::hex(128) latency in production:
      $start = microtime(true);
      $token = SecureRandom::hex(128);
      $latency = microtime(true) - $start;
      

Tips

  1. Default Lengths:

    • Standardize lengths across the codebase:
      • Hex Tokens: 32 bytes (64 chars) for general use.
      • Base64 Tokens: 24 bytes (32 chars) for URLs.
      • UUIDs: Use SecureRandom::uuid() for simplicity.
  2. Laravel Helpers:

    • Extend Illuminate\Support\Str with secure methods:
      Str::macro('secureRandomHex', function (int $length = 32) {
          return SecureRandom::hex($length);
      });
      
      Usage:
      $token = Str::secureRandomHex(32);
      
  3. Documentation:

    • Add PHPDoc comments to enforce usage:
      /**
       * @return string 64-character hex string (32 bytes)
       */
      public function generateCsrfToken(): string {
          return SecureRandom::hex(32);
      }
      
  4. Fallback Strategy:

    • Implement a fallback for random_bytes() failures:
      function secureRandomBytes(int $length): string {
          $bytes = random_bytes($length);
          if ($bytes === false) {
              // Fallback to random_int (less secure but better than nothing)
              $bytes = '';
              for ($i = 0; $i < $length; $i++) {
                  $bytes .= chr(random_int(0, 255));
              }
              Log::warning('Fallback to random_int for secure
      
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