Installation:
composer require ircmaxell/random-lib ircmaxell/security-lib
security-lib is a required dependency for strength definitions.First Use Case:
Replace insecure randomness (e.g., Str::random() or uniqid()) in a Laravel controller:
use RandomLib\Factory;
$factory = new Factory();
$generator = $factory->getMediumStrengthGenerator();
// Generate a secure token (e.g., for password reset)
$token = $generator->generateString(32);
Where to Look First:
RandomLib\Factory for creating generators.generate(), generateInt(), generateString() for specific needs.SecurityLib\Strength (e.g., MEDIUM, LOW) for risk-appropriate randomness.Strength-Based Workflows:
$lowGenerator = $factory->getLowStrengthGenerator();
$nonce = $lowGenerator->generateString(16);
$mediumGenerator = $factory->getMediumStrengthGenerator();
$token = $mediumGenerator->generateString(64);
// Requires custom mixer setup (see "Gotchas")
$highGenerator = $factory->getGenerator(new Strength(Strength::HIGH));
Laravel Integration:
// app/Providers/AppServiceProvider.php
public function register()
{
$this->app->singleton('random-lib.factory', function () {
return new Factory();
});
}
// app/Facades/RandomLib.php
public static function secureToken($length = 32)
{
return app('random-lib.factory')
->getMediumStrengthGenerator()
->generateString($length);
}
Usage:
$token = RandomLib::secureToken();
Dynamic Strength Selection:
$strength = config('random-lib.default_strength', Strength::MEDIUM);
$generator = $factory->getGenerator(new Strength($strength));
Bulk Generation:
$generator = $factory->getLowStrengthGenerator();
$tokens = collect(range(1, 100))->map(fn() => $generator->generateString(16));
Replace Laravel’s Str::random():
Str::random() in a macro for security-sensitive contexts:
Str::macro('secureRandom', function ($length = 16) {
return app('random-lib.factory')
->getMediumStrengthGenerator()
->generateString($length);
});
Database UUIDs:
generate() for UUIDs (if not using Laravel’s Str::uuid()):
$uuid = bin2hex($generator->generate(16)); // 32-character UUID
Testing:
$mockGenerator = Mockery::mock(RandomLib\Generator::class);
$mockGenerator->shouldReceive('generateString')->andReturn('test-token');
$this->app->instance('random-lib.factory', $factory);
Custom Character Sets:
$urlSafeChars = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-_';
$token = $generator->generateString(32, $urlSafeChars);
High Strength Limitations:
HmacGenerator or SHA256 mixers from security-lib).
medium for most cryptographic needs.Thread Safety:
PHP Version Constraints:
security-lib). Laravel 10+ (PHP 8.1+) may introduce deprecation risks for legacy code.
create_function() deprecations in security-lib).Entropy Source Dependencies:
/dev/urandom) may be unavailable in serverless or containerized environments.
random_int() or openssl_random_pseudo_bytes() in such cases:
try {
return $generator->generateString(32);
} catch (\Exception $e) {
return bin2hex(random_bytes(16));
}
Strength Misconfiguration:
low strength for sensitive data (e.g., salts, tokens) can lead to security vulnerabilities.
medium as the default in config:
// config/random-lib.php
'default_strength' => \SecurityLib\Strength::MEDIUM,
Generator Failures:
generate() throws exceptions, check:
/dev/urandom or equivalent is available.RuntimeException if resources are insufficient.try {
$bytes = $generator->generate(32);
} catch (\Exception $e) {
\Log::error('RandomLib failure: ' . $e->getMessage(), [
'entropy_source' => $generator->getEntropySource(),
]);
}
Non-Uniform Outputs:
generateString() includes all desired characters.Performance Bottlenecks:
low strength for non-critical paths or optimize mixer configurations.Laravel-Specific Optimizations:
$generator = $factory->getLowStrengthGenerator();
foreach ($users as $user) {
$user->api_token = $generator->generateString(40);
}
$strength = app()->environment('local') ? Strength::LOW : Strength::MEDIUM;
Extension Points:
$factory->addMixer(new \SecurityLib\Mixer\CustomMixer(
fn() => $_SERVER['REMOTE_ADDR'] ?? ''
));
use Illuminate\Validation\Rule;
Rule::define('secure_random', function ($attribute, $value, $parameters) {
$generator = app('random-lib.factory')->getMediumStrengthGenerator();
return strlen($value) === 32 && preg_match('/^[a-zA-Z0-9+/]+={0,2}$/', $value);
});
Security Audits:
public function validateToken($token)
{
$generator = app('random-lib.factory')->getMediumStrengthGenerator();
$expectedLength = 32;
return strlen($token)
How can I help you explore Laravel packages today?