Search by

riimu/kit-securerandom

Library for leveraging available secure random generators

v1.3.12017-09-09 15:23 UTC

Requires

  • php: >=5.6.0

Requires (Dev)

Suggests

  • ext-mcrypt: To use the Mcrypt secure random byte generator
  • ext-openssl: To use the OpenSSL secure random byte generator

Provides

None

Conflicts

None

Replaces

None

MIT 707917beea9538b7a9b1853e5c5d8bb53b781995

generatorrandomsecure

This package is auto-updated.

Last update: 2025-03-19 21:33:19 UTC


README

SecureRandom is a PHP library for generating secure random numbers and usingthem for common randomization operations such as shuffling arrays or generatingstring sequences like passwords. Prior to version 7.0, PHP did not have built insecure random functions, but it was still possible to use different sources ofrandomness for generating secure random values. Thus, this library has two mainpurposes:

  • To provide a common interface for different sources of secure randomnessacross different platforms and PHP versions
  • To make it easier to properly use the sources of randomness to generaterandom values and to perform common random array operations.

This library does not provide any additional secure random byte generators. Itsimply uses the byte generators that are available to PHP via extensions orinternally. The four generators that are commonly available to PHP are:

  • CSPRNG functions provided by PHP 7.0
  • reading from the random device/dev/(u)random
  • calling themcrypt_create_iv() function
  • calling theopenssl_random_pseudo_bytes() function

The security of the randomness generated by this library is entirely dependanton the underlying random byte generator. The library does not do any additionaltransformations on the bytes other than the normalization needed to generateeven distributions of random numbers.

The API documentation is available at:http://kit.riimu.net/api/securerandom/

TravisScrutinizerScrutinizer CoveragePackagist

Requirements

  • The minimum supported PHP version is 5.6
  • The library depends on the following PHP Extensions
    • OpenSSL (To use OpenSSQL generator)
    • Mcrypt (To use Mcrypt generator)
  • The/dev/urandom must be readable in order to use the Random reader generator

Installation

Installation with Composer

The easiest way to install this library is to use Composer to handle yourdependencies. In order to install this library via Composer, simply followthese two steps:

  1. Acquire thecomposer.phar by running the ComposerCommand-line installationin your project root.

  2. Once you have run the installation script, you should have thecomposer.pharfile in you project root and you can run the following command:

    php composer.phar require "riimu/kit-securerandom:^1.3"

After installing this library via Composer, you can load the library byincluding thevendor/autoload.php file that was generated by Composer duringthe installation.

Adding the library as a dependency

If you are already familiar with how to use Composer, you may alternatively addthe library as a dependency by adding the followingcomposer.json file to yourproject and running thecomposer install command:

{"require": {"riimu/kit-securerandom":"^1.3"    }}

Manual installation

If you do not wish to use Composer to load the library, you may also downloadthe library manually by downloading thelatest releaseand extracting thesrc folder to your project. You may then include theprovidedsrc/autoload.php file to load the library classes.

Usage

Usage of the library is very simple. Simply create an instance of theSecureRandom and call any of the methods to generate random values. Forexample:

<?phprequire'vendor/autoload.php';$rng =new \Riimu\Kit\SecureRandom\SecureRandom();var_dump(base64_encode($rng->getBytes(32)));// Returns a random byte stringvar_dump($rng->getInteger(100,1000));// Returns a random integer between 100 and 1000var_dump($rng->getFloat());// Returns a random float between 0 and 1var_dump($rng->getRandom());// Returns a random float between 0 and 1 (not including 1)var_dump($rng->getArray(range(0,100),5));// Returns 5 randomly selected elements from the arrayvar_dump($rng->choose(range(0,100)));// Returns one randomly chosen value from the arrayvar_dump($rng->shuffle(range(0,9)));// Returns the array in random ordervar_dump($rng->getSequence('01',32));// Returns a random sequence of 0s and 1s with length of 32var_dump($rng->getSequence(['a','b','c'],5));// Returns an array with 5 elements randomly chosen from 'a', 'b', and 'c'var_dump($rng->getUuid());// Returns a random version UUID, e.g. '00056a74-036b-47c5-ab35-6f34a41a70ae'

Random methods

The following methods are available inSecureRandom to retrieve randomness:

  • getBytes($count) returns a string of random bytes with length equal to$count.

  • getInteger($min, $max) returns an random integer between the two givenpositive integers (inclusive).

  • getFloat() returns a random float value between 0 and 1 (inclusive).

  • getRandom() returns a random float value between 0 and 1 that has 52 bitsof precision and so that the returned value is always less than 1. Incomparison togetFloat(), the value distribution is more uniform and notdependent onPHP_INT_MAX.

  • getArray(array $array, $count) returns a number of random elements fromthe given array. The elements are in random order, but the keys arepreserved.

  • choose(array $array) returns a random value chosen from the array.

  • shuffle(array $array) returns the array in random order. The keys arepreserved.

  • getSequence($choices, $length) returns a random sequence of values orcharacters. The choices can be provided as a string or an array. The type ofthe return value depends on the type of choices.

  • getUuid() returns a random version 4Universally unique identifier.UUIDs are unique identifiers that can be generated randomly, independentlyand have very small likelihood of collision. And example of UUID could be00056a74-036b-47c5-ab35-6f34a41a70ae.

Notes about /dev/random

The generators provided by this library use/dev/urandom as the randomnesssource by default. Reading from/dev/random provides no additional securityto typical PHP web applications and its blocking nature would make it veryunsuitable for such purposes.

There are only few legitimate cases where you should read from/dev/randominstead. This is mostly if you are concerned that/dev/urandom has not yetbeen seeded properly. However, this is typically not the case with webapplications, since this tends to be issue only on system startup.

If you know that you absolutely need to read from/dev/random it's possibleto set theRandomReader andMcrypt to use it as the randomness sourceinstead by setting the constructor parameter to false and providing thegenerator toSecureRandom in the constructor. For example:

<?phprequire'vendor/autoload.php';$generator =new \Riimu\Kit\SecureRandom\Generator\RandomReader(false);$rng =new \Riimu\Kit\SecureRandom\SecureRandom($generator);

Available random generators

WhenSecureRandom is created, it will attempt to use one of the availablesecure random generators, depending on which one is supported by the currentplatform. Following random sources are available and they will be tried in thefollowing order:

  • Generator\Internal uses the internal functions available in PHP 7.0
  • Generator\RandomReader simply reads bytes from the random device/dev/urandom
  • Generator\Mcrypt usesmcrypt_create_iv() to generate random bytes usingMCRYPT_DEV_URANDOM as the source.
  • Generator\OpenSSL usesopenssl_random_pseudo_bytes() to generate randombytes.

There has been some debate on whether the algorithm used by OpenSSL is actuallycryptographically strong or not. However, due to lack of concrete evidenceagainst it and due to implications of it's strength in the PHP manual, thislibrary will use OpenSSL as the last fallback by default to achieve bettercompatibility across different platforms.

If you wish to explicitly define the byte generator, you may provide it as theconstructor parameter for theSecureRandom. For example:

<?phprequire'vendor/autoload.php';$rng =new \Riimu\Kit\SecureRandom\SecureRandom(new \Riimu\Kit\SecureRandom\Generator\Mcrypt());

Credits

This library is Copyright (c) 2014-2017 Riikka Kalliomäki.

See LICENSE for license and copying information.