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.
Installation:
composer require php-standard-library/secure-random
No additional configuration is required.
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
Where to Look First:
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).$this->app->singleton(SecureRandom::class, fn() => new \SecureRandom\SecureRandom());
Token Generation:
Str::random(40) with SecureRandom::base64(32).
$csrfToken = SecureRandom::base64(32);
SecureRandom::hex(64) for high-entropy secrets.
$jwtSecret = SecureRandom::hex(64);
Password Reset Tokens:
$token = SecureRandom::hex(30); // 60 chars (2 chars per byte)
Database IDs:
bigint in PostgreSQL):
$id = SecureRandom::int(1, PHP_INT_MAX);
Ramsey\Uuid where randomness is critical):
$uuid = SecureRandom::uuid();
Encryption Nonces/IVs:
$iv = SecureRandom::bytes(16);
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
Auth Flow:
$loginToken = SecureRandom::base64(48);
SecureRandom::hex(32) as a signature.CSRF Protection:
csrf_token() middleware with a custom guard using SecureRandom::base64(32).Password Hashing:
SecureRandom::hex(32) as a pepper for bcrypt (if not using Laravel’s built-in hashing).Testing:
random_bytes() in unit tests:
$this->partialMock(SecureRandom::class, 'randomBytes')
->method('randomBytes')
->willReturn('mocked_bytes');
Replace Insecure Primitives:
Str::random(32) or random_int(0, PHP_INT_MAX).SecureRandom::hex(32) or SecureRandom::int(0, PHP_INT_MAX).Laravel Service Container:
$this->app->bind(SecureRandom::class, fn() => new \SecureRandom\SecureRandom());
public function __construct(private SecureRandom $secureRandom) {}
Configuration:
config/app.php or a custom secure_random.php:
'secure_random' => [
'default_length' => 32, // Default hex length
],
Performance:
Entropy Warnings:
random_bytes() may fall back to weaker sources on low-entropy systems (e.g., Docker, CI environments).if (random_bytes(16) === false) {
Log::warning('CSPRNG entropy pool may be depleted');
}
random_int() as a fallback (less secure but better than mt_rand()).Length Mismatches:
// AES-128 IV (16 bytes)
$iv = SecureRandom::bytes(16);
Laravel Caching:
SecureRandom instances may not be thread-safe in shared environments.UUID Collisions:
SecureRandom::uuid() uses PHP’s random_bytes(), which may not be as vetted as Ramsey\Uuid.Ramsey\Uuid\Uuid::uuid4() for production UUIDs if collision risk is a concern.Legacy Code:
Str::random() calls may still use insecure PRNGs.// phpstan.neon
rules:
SecureRandomUsage:
type: PHPStan\Rules\CustomRule
path: vendor/bin/ruleset.php
Mocking in Tests:
random_bytes() to simulate failures:
$mock = $this->getMockBuilder(SecureRandom::class)
->onlyMethods(['randomBytes'])
->getMock();
$mock->method('randomBytes')->willReturn(false);
Entropy Checks:
cat /proc/sys/kernel/random/entropy_avail
1000 may indicate low entropy.Performance Profiling:
SecureRandom::hex(128) latency in production:
$start = microtime(true);
$token = SecureRandom::hex(128);
$latency = microtime(true) - $start;
Default Lengths:
SecureRandom::uuid() for simplicity.Laravel Helpers:
Illuminate\Support\Str with secure methods:
Str::macro('secureRandomHex', function (int $length = 32) {
return SecureRandom::hex($length);
});
Usage:
$token = Str::secureRandomHex(32);
Documentation:
/**
* @return string 64-character hex string (32 bytes)
*/
public function generateCsrfToken(): string {
return SecureRandom::hex(32);
}
Fallback Strategy:
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
How can I help you explore Laravel packages today?