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.
Installation
composer require php-standard-library/secure-random
No additional configuration is required—it relies on PHP’s built-in random_bytes()/random_int().
First Use Case: Generating a Secure Token
use SecureRandom\SecureRandom;
$token = SecureRandom::hex(32); // Generates a 32-character hex token
Use this for:
Where to Look First
SecureRandom::hex(), SecureRandom::base64(), and SecureRandom::int().description.md for edge cases (e.g., fallback behavior if CSPRNG is unavailable).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);
Random IDs for Database Records
// Generate a 16-byte UUID-like ID (as hex)
$id = SecureRandom::hex(16);
Secure Random Integers for Lotteries/Games
// Pick a random user ID (1-1000) with uniform distribution
$randomUserId = SecureRandom::int(1, 1000);
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.
Batch Generation
// Generate 10 unique tokens (e.g., for bulk invites)
$tokens = array_map(fn() => SecureRandom::hex(16), range(1, 10));
mt_rand() or rand(): Always use SecureRandom for security-sensitive operations.hex() over base64() for URLs: Hex is URL-safe by default.Fallback Behavior
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+).if (!function_exists('random_bytes')) {
throw new RuntimeException('CSPRNG not available. Upgrade PHP.');
}
Token Collisions
SecureRandom::hex(8)). Use at least 16 bytes (32 hex chars) for most use cases.Base64 URL-Safety
SecureRandom::base64() returns standard base64 (with +//). For URLs, manually replace:
$urlSafeToken = strtr(SecureRandom::base64(32), '+/', '-_');
Performance
SecureRandom::hex(256)) may be slow. Benchmark for your use case.openssl or /dev/urandom is available:
php -r "echo random_bytes(16);"
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));
}
}
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);
});
Testing
Mock random_bytes() in tests to avoid flakiness:
$this->partialMock(SecureRandom::class, 'randomBytes')
->shouldReceive('randomBytes')
->andReturn(hex2bin('a1b2c3...'));
$token = SecureRandom::hex(16);
$resetLink = route('password.reset', [
'token' => hash_hmac('sha256', $token, config('app.key')),
'expires' => now()->addHours(1),
]);
APP_ENV to generate different tokens for local vs. production:
$token = SecureRandom::hex(32) . '-' . config('app.env');
How can I help you explore Laravel packages today?