A library for generating random numbers and strings

Related tags

Security RandomLib
Overview

RandomLib

Build Status

A library for generating random numbers and strings of various strengths.

This library is useful in security contexts.

Install

Via Composer

$ composer require ircmaxell/random-lib

Usage

Factory

A factory is used to get generators of varying strength:

$factory = new RandomLib\Factory;
$generator = $factory->getGenerator(new SecurityLib\Strength(SecurityLib\Strength::MEDIUM));

A factory can be configured with additional mixers and sources but can be used out of the box to create both medium and low strength generators.

Convenience methods are provided for creating high, medium, and low strength generators. Example:

$generator = $factory->getMediumStrengthGenerator();

$factory->getLowStrengthGenerator()

Convenience method to get a low strength random number generator.

Low Strength should be used anywhere that random strings are needed in a non-cryptographical setting. They are not strong enough to be used as keys or salts. They are however useful for one-time use tokens.

$factory->getMediumStrengthGenerator()

Convenience method to get a medium strength random number generator.

Medium Strength should be used for most needs of a cryptographic nature. They are strong enough to be used as keys and salts. However, they do take some time and resources to generate, so they should not be over-used

$factory->getHighStrengthGenerator()

Convenience method to get a high strength random number generator.

High Strength keys should ONLY be used for generating extremely strong cryptographic keys. Generating them is very resource intensive and may take several minutes or more depending on the requested size.

There are currently no mixers shipped with this package that are capable of creating a high space generator. This will not work out of the box!

Generator

A generator is used to generate random numbers and strings.

Example:

// Generate a random string that is 32 bytes in length.
$bytes = $generator->generate(32);

// Generate a whole number between 5 and 15.
$randomInt = $generator->generateInt(5, 15);

// Generate a 32 character string that only contains the letters
// 'a', 'b', 'c', 'd', 'e', and 'f'.
$randomString = $generator->generateString(32, 'abcdef');

$generator->generate($size)

Generate a random byte string of the requested size.

$generator->generateInt($min = 0, $max = PHP_INT_MAX)

Generate a random integer with the given range. If range ($max - $min) is zero, $max will be used.

$generator->generateString($length, $characters = '')

Generate a random string of specified length.

This uses the supplied character list for generating the new result string. The list of characters should be specified as a string containing each allowed character.

If no character list is specified, the following list of characters is used:

0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ+/

Examples:

// Give the character list 'abcdef':
print $generator->generateString(32, 'abcdef')."\n";

// One would expect to receive output that only contained those
// characters:
//
// adaeabecfbddcdaeedaedfbbcdccccfe
// adfbfdbfddadbfcbbefebcacbefafffa
// ceeadbcabecbccacdcaabbdccfadbafe
// abadcffabdcacdbcbafcaecabafcdbbf
// dbdbddacdeaceabfaefcbfafebcacdca

License

MIT, see LICENSE.

Community

If you have questions or want to help out, join us in the #php.security channel on irc.freenode.net.

Security Vulnerabilities

If you have found a security issue, please contact the author directly at [email protected].

Comments
  • Suppress warning on servers with

    Suppress warning on servers with "open_basedir restriction in effect"

    Hi,

    On servers with "open_basedir restrictions", the function file_exists() throws a warning, instead of returning false, as it should do, IMHO. The problem is that users on these servers are also most likely not able to control the settings of the server, and as such, can't prevent these warnings themselves. It's really bad practice to suppress warnings with the @-operator, but as far as i know there's no proper way to circumvent these. For one, is_readable() throws the same warning.

    Full error message:

    Warning: file_exists() [function.file-exists]: open_basedir restriction in
    effect. File(/dev/urandom) is not within the allowed path(s): (/usr/share/php:/f
    oo/:/usr/share/pear:/usr/sbin:/usr/bin:/bin:/tmp:/etc/phpmyadmin:/usr/lib/php4:/
    usr/lib/php5:/opt/ioncube/lib) in /foo/public_html/vendor/ircmaxell/random-
    lib/lib/RandomLib/Source/URandom.php on line 57
    
    Warning: Cannot modify header information - headers already sent by (output
    started at /foo/public_html/vendor/ircmaxell/random-
    lib/lib/RandomLib/Source/URandom.php:57) in
    /foo/public_html/app/src/Bolt/Users.php on line 285 Redirecting to /beheer/.
    
    opened by bobdenotter 8
  • unitialized offset

    unitialized offset

    I am currently running the following code below

    
    $factory = new RandomLib\Factory;
    $generator = $factory->getMediumStrengthGenerator();
    $randomString = $generator->generateString(128);
    
    

    I am getting an unitialized offset error on Line 268 https://github.com/ircmaxell/RandomLib/blob/master/lib/RandomLib/Generator.php#L268

    It's because line Line 266 is returning 113 bytes sometimes 117 bytes or sometimes 123 bytes and a few times it doesn't error at all and the code works fine. https://github.com/ircmaxell/RandomLib/blob/master/lib/RandomLib/Generator.php#L266

    Any ideas on how I can investigate this further or try something that would fix the issue?

    current setup on production is: PHP Version 5.3.10-1ubuntu3.24 Aug 1 2016 20:14:32 SSL Version: OpenSSL/1.0.1 Host: x86_64-pc-linux-gnu Ubuntu 12.04

    I don't get this error on my development box which is on virtual box same php version and ubuntu version 12.04, I have checked all the mbstring settings which are on and UTF-8 and other PHP settings are the same.

    Appreciate any help or advice on this issue, Thanks.

    opened by karimzah 6
  • 7 character base62 collision

    7 character base62 collision

    Hello, I am using this library to generate unique 7 character base62 strings. My code is similar to the following:

    $charset = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
    
    return (new Factory())->getMediumStrengthGenerator()->generateString(7, $charset);
    

    After seeing this issue: https://github.com/ramsey/uuid/issues/80 I was wondering if my system would have collisions as well. I tried a variation of this script and indeed, I had a collision after about 1.2 million generated strings. It is my understanding that there are over 2 trillion possibilities with my system.

    I tried increasing the length to 10 (which would give like 400 quadrillion possibilities) and after 12 million keys there were no collisions.

    I'm trying to understand why 7 isn't good enough.

    Thanks.

    opened by kbond 5
  • improved generateString: added presets for character sets

    improved generateString: added presets for character sets

    Turns the second parameter $characters into a mixed parameter. When passing in an Integer it will be treated as a flag. Relevant flags are available within the Generator class as constants.

    Example:

    $generator->generateString(16, Generator::LOWER_CASE | Generator::DIGITS);
    

    Yields something similar to:

    yofch5qkv2nx0oay
    

    Took inspiration from: http://pwgen-win.sourceforge.net/

    opened by flip111 5
  • missing SecurityLib files

    missing SecurityLib files

    add to lib folder, or tell users that they need that library founded in your https://github.com/ircmaxell/SecurityLib/releases. don't know if the installer install securitylib as well, but for users which like the manual download this can be frustrating.

    opened by madebycambiamentico 4
  • Please tag a new release

    Please tag a new release

    Please tag a new release, because some projects like bolt/bolt started to reference dev-master:

    https://github.com/bolt/bolt/blob/master/composer.json

    opened by h4cc 4
  • Improved string presets

    Improved string presets

    Expanding on the work by @flip111, I have added support for several constant based string combinations.

    Please review and provide feedback.

    Also note that a few minor bugs with string generation were found and fixed in this attempt, so if this is rejected they should be ported as well.

    opened by ircmaxell 4
  • Random INT using default range always returns 0

    Random INT using default range always returns 0

    An extraordinary bug I spotted while reading your source. I decided to double check.

    To reproduce: try generating random int using the default arguments of 0 and PHP_INT_MAX. You will ALWAYS get 0 as result.

    I added this unit test method as a PoC:

        function test_bug() {
            for ($i = 0; $i < 1000; $i++) {
                $res = $this->generator->generateInt(0, PHP_INT_MAX);
                echo "$res ";
            }
            echo "\n\n";
        }
    

    And got output:

    $ vendor/bin/phpunit test
    PHPUnit 3.7.28-24-g92e8faf by Sebastian Bergmann.
    
    Configuration read from /private/tmp/RandomLib/phpunit.xml.dist
    
    .....................................0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0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 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
    
    ..........................  63 / 159 ( 39%)
    ............................................................... 126 / 159 ( 79%)
    .................................
    
    Time: 853 ms, Memory: 7.25Mb
    
    OK (159 tests, 4484 assertions)
    

    The bug comes about due to this line: https://github.com/ircmaxell/RandomLib/blob/master/lib/RandomLib/Generator.php#L113

    In case where range is large enough to require 63 bits to represent it, pow(2, 63) is a float with not enough bits to represent it. This means that pow(2, 63) - 1 is actually an IDENTICAL float (i.e. still 9.2233720368548E+18) and so the int cast turns the mask back into 1 << 63.

    Your range test case with input array(100000, \PHP_INT_MAX) actually does hit this bug but since you only assert the result is in range it passes (it is infact ALWAYS returning 100000).

    Even using 1 << $bits which gives you actual int doesn't help since the result in this case is -9223372036854775808 so the subtraction of 1 gets you back to a float (not enough bits to represent a //lower// number and the int cast gets you right back to the same place.

    I think the simplest correct solution would be to add a special case:

    if ($bits == 63) {
        $mask = 0x7fffffffffffffff;
    } else {
        $mask = (1 << $bits) - 1;
    }
    
    opened by banks 4
  • No mixer for high strength generator

    No mixer for high strength generator

    Currently the library contains only the Hash mixer, which is a medium strength mixer. Because of that, the high strength generator is not working out of the box.

    Since I'm not a security expert, do you have any advice of how to implement one?

    I've seen on this issue that this has already been reported.

    Thanks,

    opened by auburus 2
  • Is there a way to seed the generators?

    Is there a way to seed the generators?

    I am interested in using this library as an option for random test input in Eris, but I was wondering if is possible to seed the generators to get a reproducible test run. This option may depend on the source, as I don't think /dev/urandom is seedable at all while mt_rand() is, albeit by using global state.

    Thank you for any pointers.

    opened by giorgiosironi 2
  • Could not find mixer

    Could not find mixer

    Hi,

    just tried to use the High Strength Generator and received an error with "Could not find mixer". Do you know what causes the issue?

    Regards, Jan

    Update: Just noticed, that there are no High Strength mixer shipped by default.

    opened by janschoenherr 2
  • Insecure randomness

    Insecure randomness

    OS: Windows

    randrange gives security issue. It is less secured to use this function. If it gets integrated with os.urandom, which is a cryprographic PRNG method, it would provide higher security.

    opened by priyaaa705 0
  • Enforcing resulting random string contents

    Enforcing resulting random string contents

    Somewhat typical situation with a password is that it should not be totally random - it should for example contain one number, one lowercase character and one uppercase character. Or it should contain a special character.

    Currently the passwords are generated entirely randomly. So let's say I wanted to create a password that would match following regexes: ~[0-9]~, ~[a-f]~. Then with $generator->generateString(12, 'abcdef0123456789'); you'll get a password aaaabbbbcccc or something like that that wouldn't match the expected format as it's missing the numbers. It's certainly possible to test the generated password and try again unless it passes, but that may well lead to approximately endless loop.

    Do you think it would be possible to extend the generator to add an option to generate random strings that pass typical requirements (contains numbers, uppercase, lowercase, special char)? Or what approach would you suggest in such scenarios?

    I'm worried that userland implementations (like replacing random character with rand(0,9) if number is missing) could mean potential security issues and it's something this library tries to prevent.

    opened by tomasfejfar 6
  • Error class

    Error class

    When i use this library,it get error ( ! ) Fatal error: Class 'SecurityLib\AbstractFactory' not found in C:\wamp64\www\test\RandomLib-master\lib\RandomLib\Factory.php on line 43

    opened by ghost 0
  • Function mcrypt_module_open() is deprecated in PHP 7.1

    Function mcrypt_module_open() is deprecated in PHP 7.1

    ircmaxell/random-lib/lib/RandomLib/AbstractMcryptMixer.php:75

    public function __construct() { **$this->mcrypt = mcrypt_module_open($this->getCipher(), '', MCRYPT_MODE_ECB, '');** $this->blockSize = mcrypt_enc_get_block_size($this->mcrypt); $this->initv = str_repeat(chr(0), mcrypt_enc_get_iv_size($this->mcrypt)); }

    http://php.net/manual/en/function.mcrypt-module-open.php

    opened by jtamm 1
  • Fix XORMixer double XOR issue

    Fix XORMixer double XOR issue

    This pull request fixes an issue where an XOR operation is done in both AbstractMixer and XORMixer, causing the source from the previous iteration to get XORed with itself, setting it to zero. This in turn causes XORMixer to always return the last source verbatim.

    AbstractMixer::mix() contains the following code:

    if ($j % 2 == 1) {
        $stub ^= $this->mixParts1($stub, $newKey);
    } else {
        $stub ^= $this->mixParts2($stub, $newKey);
    }
    

    By inlining XorMixer::mixParts1() and XorMixer::mixParts2(), we get:

    if ($j % 2 == 1) {
        $stub = $stub ^ $stub ^ $newKey;
    } else {
        $stub = $stub ^ $stub ^ $newKey;
    }
    

    which is equivalent to:

    if ($j % 2 == 1) {
        $stub = $newKey;
    } else {
        $stub = $newKey;
    }
    
    opened by aforsblo 0
Owner
Anthony Ferrara
Anthony Ferrara
Fetches random integers from random.org instead of using PHP's PRNG implementation

TrulyRandom Composer-compatible library to interact with random.org's API in order to generate truly random lists of integers, sequences of integers,

Erik Wurzer 46 Nov 25, 2022
ChestRandomBP: This plugin generates chests in random places within a specific world. Where you can customize what each one of them contains, the time and the world of spawning.

ChestRandomBP ChestRandomBP: This plugin generates chests, it works PocketMine-MP and random places within a specific world. Where you can customize w

null 5 Sep 19, 2021
Api random address

RandomAddress what actually it does? Its scrap Address from Fakeaddress and gives output in json format for api use. This address are working many pla

Nitin1818 6 Dec 28, 2022
Security CSRF (cross-site request forgery) component provides a class CsrfTokenManager for generating and validating CSRF tokens.

Security Component - CSRF The Security CSRF (cross-site request forgery) component provides a class CsrfTokenManager for generating and validating CSR

Symfony 1.5k Jan 3, 2023
Obfuscate your data by generating reversible, non-sequential, URL-safe identifiers.

Laravel Hashid Laravel Hashid provides a unified API across various drivers such as Base62, Base64, Hashids and Optimus, with support for multiple con

Elf Sundae 390 Nov 16, 2022
A cryptography API wrapping the Sodium library, providing a simple object interface for symmetrical and asymmetrical encryption, decryption, digital signing and message authentication.

PHP Encryption A cryptography API wrapping the Sodium library, providing a simple object interface for symmetrical and asymmetrical encryption, decryp

null 19 Dec 31, 2022
Fast, general Elliptic Curve Cryptography library. Supports curves used in Bitcoin, Ethereum and other cryptocurrencies (secp256k1, ed25519, ..)

Fast Elliptic Curve Cryptography in PHP Information This library is a PHP port of elliptic, a great JavaScript ECC library. Supported curve types: Sho

Simplito 178 Dec 28, 2022
A multitool library offering access to recommended security related libraries, standardised implementations of security defences, and secure implementations of commonly performed tasks.

SecurityMultiTool A multitool library offering access to recommended security related libraries, standardised implementations of security defences, an

Pádraic Brady 131 Oct 30, 2022
TCrypto is a simple and flexible PHP 5.3+ in-memory key-value storage library

About TCrypto is a simple and flexible PHP 5.3+ in-memory key-value storage library. By default, a cookie will be used as a storage backend. TCrypto h

timoh 57 Dec 2, 2022
JSON Object Signing and Encryption library for PHP.

NAMSHI | JOSE Deprecation notice Hi there, as much as we'd like to be able to work on all of the OSS in the world, we don't actively use this library

Namshi 1.7k Dec 22, 2022
PHP Secure Communications Library

phpseclib - PHP Secure Communications Library Supporting phpseclib Become a backer or sponsor on Patreon One-time donation via PayPal or crypto-curren

null 4.9k Jan 7, 2023
A modern, portable, easy to use crypto library.

Sodium is a new, easy-to-use software library for encryption, decryption, signatures, password hashing and more. It is a portable, cross-compilable, i

Frank Denis 10.7k Jan 1, 2023
PHPGGC is a library of PHP unserialize() payloads along with a tool to generate them, from command line or programmatically.

PHPGGC: PHP Generic Gadget Chains PHPGGC is a library of unserialize() payloads along with a tool to generate them, from command line or programmatica

Ambionics Security 2.5k Jan 4, 2023
A petite library of encryption functions for PHP

?? dcrypt A petite library of essential encryption functions for PHP 7.1+. For legacy PHP version support, look here. If you need a dcrypt inspired en

null 96 Oct 6, 2022
Sodium Compat is a pure PHP polyfill for the Sodium cryptography library (libsodium)

Sodium Compat is a pure PHP polyfill for the Sodium cryptography library (libsodium), a core extension in PHP 7.2.0+ and otherwise available in PECL.

Paragon Initiative Enterprises 817 Dec 26, 2022
A PHP library for counting short DNA sequences for use in Bioinformatics

Helix A PHP library for counting short DNA sequences for use in Bioinformatics. Helix consists of tools for data extraction as well as an ultra-low me

Andrew DalPino 2 Jan 25, 2022
php-chmod is a PHP library for easily changing permissions recursively.

PHP chmod php-chmod is a PHP library for easily changing the permissions recursively. Versions & Dependencies Version PHP Documentation ^1.1 ^7.4 curr

Mathias Reker ⚡️ 5 Oct 7, 2022
Automatic Encrypt and Decrypt your database data. Tested and used on Laravel 8

Laravel Encrypt Database Automatic Encrypt and Decrypt your database data. Tested and used on Laravel 8. I'm yet building the tests. Important Note th

Wellington Barbosa 2 Dec 15, 2021
Laravel Security was created by, and is maintained by Graham Campbell, and is a voku/anti-xss wrapper for Laravel, using graham-campbell/security-core

Laravel Security Laravel Security was created by, and is maintained by Graham Campbell, and is a voku/anti-xss wrapper for Laravel, using graham-campb

Graham Campbell 170 Nov 20, 2022