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

Generate cryptographically secure random tokens, passwords, nonces, and bytes in PHP. SecureRandom provides simple, reliable APIs built on native CSPRNG sources, suitable for authentication, CSRF protection, and other security-sensitive identifiers.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation

    composer require php-standard-library/secure-random
    

    No additional configuration is required—it relies on PHP’s built-in random_bytes()/random_int().

  2. First Use Case: Generating a Secure Token

    use SecureRandom\SecureRandom;
    
    $token = SecureRandom::hex(32); // Generates a 32-character hex token
    

    Use this for:

    • CSRF tokens
    • Password reset links
    • API keys
  3. Where to Look First

    • API Reference: Focus on SecureRandom::hex(), SecureRandom::base64(), and SecureRandom::int().
    • Documentation: Check description.md for edge cases (e.g., fallback behavior if CSPRNG is unavailable).

Implementation Patterns

Common Workflows

  1. Token Generation for Authentication

    // Generate a 64-character hex token for a JWT secret
    $jwtSecret = SecureRandom::hex(64);
    
    // Generate a base64-encoded token for a URL-safe reset link
    $resetToken = SecureRandom::base64(32);
    
  2. Random IDs for Database Records

    // Generate a 16-byte UUID-like ID (as hex)
    $id = SecureRandom::hex(16);
    
  3. Secure Random Integers for Lotteries/Games

    // Pick a random user ID (1-1000) with uniform distribution
    $randomUserId = SecureRandom::int(1, 1000);
    
  4. Integration with Laravel

    // In a controller or service
    use SecureRandom\SecureRandom;
    
    public function generateCsrfToken()
    {
        return SecureRandom::hex(32);
    }
    

    Replace Laravel’s default Str::random() with this for cryptographic safety.

  5. Batch Generation

    // Generate 10 unique tokens (e.g., for bulk invites)
    $tokens = array_map(fn() => SecureRandom::hex(16), range(1, 10));
    

Best Practices

  • Avoid mt_rand() or rand(): Always use SecureRandom for security-sensitive operations.
  • Prefer hex() over base64() for URLs: Hex is URL-safe by default.
  • Cache tokens judiciously: Tokens like CSRF secrets should be regenerated per request if possible.

Gotchas and Tips

Pitfalls

  1. Fallback Behavior

    • If random_bytes()/random_int() is unavailable (e.g., old PHP versions), the package may degrade to less secure methods. Verify your PHP version supports CSPRNG (PHP 7+).
    • Fix: Add a runtime check:
      if (!function_exists('random_bytes')) {
          throw new RuntimeException('CSPRNG not available. Upgrade PHP.');
      }
      
  2. Token Collisions

    • While unlikely, collisions can occur with short tokens (e.g., SecureRandom::hex(8)). Use at least 16 bytes (32 hex chars) for most use cases.
  3. Base64 URL-Safety

    • SecureRandom::base64() returns standard base64 (with +//). For URLs, manually replace:
      $urlSafeToken = strtr(SecureRandom::base64(32), '+/', '-_');
      
  4. Performance

    • Generating large tokens (e.g., SecureRandom::hex(256)) may be slow. Benchmark for your use case.

Debugging Tips

  • Verify Randomness Use a tool like Dieharder to test entropy if security is critical.
  • Check PHP Configuration Ensure openssl or /dev/urandom is available:
    php -r "echo random_bytes(16);"
    

Extension Points

  1. Custom Token Formats Override the default encodings by extending the class:

    class CustomSecureRandom extends SecureRandom {
        public static function customFormat(int $length): string {
            return bin2hex(random_bytes($length / 2));
        }
    }
    
  2. Integration with Laravel’s Str Facade Replace Str::random() in app/Providers/AppServiceProvider.php:

    use SecureRandom\SecureRandom;
    
    Str::macro('secureRandom', function ($length = 16) {
        return SecureRandom::hex($length);
    });
    
  3. Testing Mock random_bytes() in tests to avoid flakiness:

    $this->partialMock(SecureRandom::class, 'randomBytes')
         ->shouldReceive('randomBytes')
         ->andReturn(hex2bin('a1b2c3...'));
    

Config Quirks

  • No Configuration File: The package is stateless and requires zero config.
  • Thread Safety: Safe for concurrent use (PHP’s CSPRNG is thread-safe).

Pro Tips

  • For Password Reset Links Combine with a timestamp and HMAC for added security:
    $token = SecureRandom::hex(16);
    $resetLink = route('password.reset', [
        'token' => hash_hmac('sha256', $token, config('app.key')),
        'expires' => now()->addHours(1),
    ]);
    
  • Environment-Specific Tokens Use APP_ENV to generate different tokens for local vs. production:
    $token = SecureRandom::hex(32) . '-' . config('app.env');
    
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