valorin / random
Random is a simple helper package designed to make it easy to generate a range of different cryptographically secure random values.
Fund package maintenance!
valorin
Installs: 37 865
Dependents: 2
Suggesters: 0
Security: 0
Stars: 200
Watchers: 4
Forks: 11
Open Issues: 2
Requires
- php: ^7.1 || ^8.0
- arokettu/random-polyfill: ^1.0
Requires (Dev)
- illuminate/support: ^5.0 || ^10.0 || ^11.0
- phpunit/phpunit: ^7.0 || ^9.6 || ^10.5
README
Random
by Valorin
Random generates cryptographically secure random values in a range of different formats through a simple helper package for PHP.
Random was created because I was constantly encountering weak and insecure random value generations within apps during my Laravel and PHP Security Audits and I wanted a secure solution to point my clients to without needing them to implement secure algorithms themselves. The idea was then expanded out a bit to support all the common random value types I've encountered.
Random is completely framework agnostic, the only production dependency is the excellent php-random-polyfill, which does nothing on PHP 8.2+ where the functions are included in core. It supports Laravel's Collections, but doesn't pull in any Laravel code.
You can find more about Random in the Securing Laravel In Depth article.
Installation
You can install the package via composer:
composer require valorin/random
There is no need to install any service providers, Random should just work out of the box.
Random is supported on PHP 7.1 and later.
Usage
Random is designed to be as simple as possible to use. It's a static class, so you can just call the methods directly.
Import the class into your namespace:
use Valorin\Random\Random;
Random Integers
Generate a random integer between $min
, and $max
(inclusive):
$number = Random::number(int $min, int $max): int;
Note, this is only really useful if you're using a specific
Randomizer Engine (such as when using seeds).
For most use cases, I'd suggest sticking with random_int()
for simplicity.
Random One-Time Password (Numeric fixed-length OTPs)
Generate a random numeric one-time password (OTP) of $length
digits:
$otp = Random::otp(int $length): string;
This is useful for generating OTPs for SMS or email verification codes. These are commonly done using
rand(100000, 999999)
, which is both insecure and also loses 10% of the possible codes in the 0-99999
range.
This provides a secure alternative which includes the full 000000-999999
range (with variable length).
Random String
Generate a random string of $length
characters which includes characters from the enabled character types.
By default, it will randomly select characters and not guarantee any specific character types are present.
If you require one of each character to be included, you can set $requireAll = true
.
// Primary method $string = Random::string( int $length = 32, bool $lower = true, bool $upper = true, bool $numbers = true, bool $symbols = true, bool $requireAll = false ): string;
The following are wrappers for common use cases:
// Random letters only $letters = Random::letters(int $length = 32): string; // Random alphanumeric (letters and numbers) token string $token = Random::token(int $length = 32): string; // Random letters, numbers, and symbols (i.e. a random password). $password = Random::password(int $length = 16, bool $requireAll = false): string; // Random alphanumeric token string with chunks separated by dashes, making it easy to read and type. $password = Random::dashed(int $length = 25, string $delimiter = '-', int $chunkLength = 5, bool $mixedCase = true): string;
To limit the characters available in any of the types (i.e. lower, upper, numbers, or symbols), you can create a custom Generator instance with your customer character set:
// Override just symbols $generator = Random::useSymbols(['!', '@', '#', '$', '%', '^', '&', '*', '(', ')'])->string(); // Override everything $generator = Random::useLower(range('a', 'f')) ->useUpper(range('G', 'L')) ->useNumbers(range(2, 6)) ->useSymbols(['!', '@', '#', '$', '%', '^', '&', '*', '(', ')']); $string = $generator->string( $length = 32, $lower = true, $upper = true, $numbers = true, $symbols = true, $requireAll = true );
Note, you can chain the use*()
methods in any order, and they will persist within that Generator only.
Shuffle Array, String, or Collection
Securely shuffle an array, string, or Laravel Collection, optionally preserving the keys.
$shuffled = Random::shuffle( array|string|\Illuminate\Support\Collection $values, bool $preserveKeys = false ): array|string|\Illuminate\Support\Collection;
Pick $count
Items or Characters
Securely pick $count
items (or characters) from an array, string, or Laravel Collection.
$picks = Random::pick( array|string|\Illuminate\Support\Collection $values, int $count ): array|string|\Illuminate\Support\Collection;
Passing $count > 1
will return the picks in the same type as $values
, so either an array, a Collection,
or a string of characters.
When passing $count = 1
, the output will be a single array/collection item or character chosen from the input.
You can also use the alias pickOne()
to pick a single item from $values
:
$pick = Random::pickOne( array|string|\Illuminate\Support\Collection $values ): array|string|\Illuminate\Support\Collection;
Using a specific \Random\Engine
By default Random
will use the secure default \Random\Engine
defined by PHP.
To use a different Engine, pass it to the use()
method and call the above methods on the returned
Generator
class.
$generator = Random::use(\Random\Engine $engine): \Valorin\Random\Generator;
The primary use case for use()
is when you need to specify a specific random seed, in order to control the output.
Only the returned \Valorin\Random\Generator
object will use the provided Engine (and seed), allowing you to
create and use the Generator independently of other uses of Random
within your app.
$generator = Random::use(new \Random\Engine\Mt19937(3791)); $number = $generator->number(1, 1000); $password = $generator->password();
You can use use()
alongside the character set helpers (useLower()
, useUpper()
, useNumbers()
, useSymbols()
),
although you will need to call use()
first to define the Engine before customising the character set on the
Generator
object.
TODO
[ ] Use pickArrayKeys()
inside shuffle()
for better picking
[ ] pick()
should always return array/collection, while pickOne()
returns a single value
[ ] Use $collection->slice(0, 0)->push(...$items);
to replace collection items
Support My Work! ❤️
You can support my work over on GitHub Sponsors or by becoming a paid subscriber to Securing Laravel, the essential security resource for Laravel and PHP developers!
Contributing
Contributions are very welcome! There isn't a formal guide, but throw in an Issue or PR, and we'll go from there.
Security Vulnerabilities
Please report any security vulnerabilities via the GitHub project or by contacting Stephen Rees-Carter directly.
License
Random is open-source software licensed under the MIT license.