• Stars
    star
    8,170
  • Rank 4,545 (Top 0.09 %)
  • Language
    PHP
  • License
    MIT License
  • Created over 9 years ago
  • Updated 3 months ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

PHP 5.x support for random_bytes() and random_int()

random_compat

Build Status Scrutinizer Latest Stable Version Latest Unstable Version License Downloads

PHP 5.x polyfill for random_bytes() and random_int() created and maintained by Paragon Initiative Enterprises.

Although this library should function in earlier versions of PHP, we will only consider issues relevant to supported PHP versions. If you are using an unsupported version of PHP, please upgrade as soon as possible.

Important

Although this library has been examined by some security experts in the PHP community, there will always be a chance that we overlooked something. Please ask your favorite trusted hackers to hammer it for implementation errors and bugs before even thinking about deploying it in production.

Do not use the master branch, use a stable release.

For the background of this library, please refer to our blog post on Generating Random Integers and Strings in PHP.

Usability Notice

If PHP cannot safely generate random data, this library will throw an Exception. It will never fall back to insecure random data. If this keeps happening, upgrade to a newer version of PHP immediately.

Installing

With Composer:

# For libraries and frameworks that support PHP 5 but may be used by
# other software that only supports PHP 7:
composer require paragonie/random_compat:\>=2

# For software that explicitly needs PHP 5 support:
composer require paragonie/random_compat:\<9.99

Signed PHP Archive:

As of version 1.2.0, we also ship an ECDSA-signed PHP Archive with each stable release on Github.

  1. Download the .phar, .phar.pubkey, and .phar.pubkey.asc files.
  2. (Recommended but not required) Verify the PGP signature of .phar.pubkey (contained within the .asc file) using the PGP public key for Paragon Initiative Enterprises.
  3. Extract both .phar and .phar.pubkey files to the same directory.
  4. require_once "/path/to/random_compat.phar";
  5. When a new version is released, you only need to replace the .phar file; the .pubkey will not change (unless our signing key is ever compromised).

Manual Installation:

  1. Download a stable release.
  2. Extract the files into your project.
  3. require_once "/path/to/random_compat/lib/random.php";

The entrypoint should be lib/random.php directly, not any of the other files in /lib.

Usage

This library exposes the CSPRNG functions added in PHP 7 for use in PHP 5 projects. Their behavior should be identical.

Generate a string of random bytes

try {
    $string = random_bytes(32);
} catch (TypeError $e) {
    // Well, it's an integer, so this IS unexpected.
    die("An unexpected error has occurred"); 
} catch (Error $e) {
    // This is also unexpected because 32 is a reasonable integer.
    die("An unexpected error has occurred");
} catch (Exception $e) {
    // If you get this message, the CSPRNG failed hard.
    die("Could not generate a random string. Is our OS secure?");
}

var_dump(bin2hex($string));
// string(64) "5787c41ae124b3b9363b7825104f8bc8cf27c4c3036573e5f0d4a91ad2eeac6f"

Generate a random integer between two given integers (inclusive)

try {
    $int = random_int(0, 255);
} catch (TypeError $e) {
    // Well, it's an integer, so this IS unexpected.
    die("An unexpected error has occurred"); 
} catch (Error $e) {
    // This is also unexpected because 0 and 255 are both reasonable integers.
    die("An unexpected error has occurred");
} catch (Exception $e) {
    // If you get this message, the CSPRNG failed hard.
    die("Could not generate a random int. Is our OS secure?");
}

var_dump($int);
// int(47)

Exception handling

When handling exceptions and errors you must account for differences between PHP 5 and PHP7.

The differences:

  • Catching Error works, so long as it is caught before Exception.
  • Catching Exception has different behavior, without previously catching Error.
  • There is no portable way to catch all errors/exceptions.

Our recommendation

Always catch Error before Exception.

Example

try {
    return random_int(1, $userInput);
} catch (TypeError $e) {
    // This is okay, so long as `Error` is caught before `Exception`.
    throw new Exception('Please enter a number!');
} catch (Error $e) {
    // This is required, if you do not need to do anything just rethrow.
    throw $e;
} catch (Exception $e) {
    // This is optional and maybe omitted if you do not want to handle errors
    // during generation.
    throw new InternalServerErrorException(
        'Oops, our server is bust and cannot generate any random data.',
        500,
        $e
    );
}

Troubleshooting

Exception: "Could not gather sufficient random data"

If an Exception is thrown, then your operating system is not secure.

  1. If you're on Windows, make sure you enable mcrypt.
  2. If you're on any other OS, make sure /dev/urandom is readable.
    • FreeBSD jails need to expose /dev/urandom from the host OS
    • If you use open_basedir, make sure /dev/urandom is allowed

This library does not (and will not accept any patches to) fall back to an insecure random number generator.

Version Conflict with [Other PHP Project]

If you're using a project that has a line like this in its composer.json

"require" {
    ...
    "paragonie/random_compat": "~1.1",
    ...
}

...and then you try to add random_compat 2 (or another library that explicitly requires random_compat 2, such as this secure PHP encryption library), you will get a version conflict.

The solution is to get the project to update its requirement string to allow version 2 and above to be used instead of hard-locking users to version 1.

"require" {
    ...
-    "paragonie/random_compat": "~1.1",
+    "paragonie/random_compat": ">=1",
    ...
}

Version 9.99.99

Note: There is a special version called 9.99.99 which makes this library do nothing, but is only installable on PHP 7.

If you're writing software (e.g. a library) that supports PHP 5, but may be used by software that doesn't, you'll want to allow 9.99.99 to be installed. The above diff is what you want.

Conversely, if you're writing software that (in and of itself) supports PHP 5, you do not want 9.99.99 to be installed, so you'll want to make this change instead:

"require" {
    ...
-    "paragonie/random_compat": "~1.1",
+    "paragonie/random_compat": ">=1 <9.99",
    ...
}

To avoid installing "empty" version 9.99.99 you can add replace section in your root composer.json:

"replace": {
    "paragonie/random_compat": "9.99.99"
},

Manifest Read Length Error

If you're using the PHP Archive (Phar) approach rather than Composer, and you are getting an error message to the effect of "manifest read length was {int1} should be {int2}", the Phar extension may not be enabled.

See this comment for specific guidance on how to fix this issue.

Contributors

This project would not be anywhere near as excellent as it is today if it weren't for the contributions of the following individuals:

Support Contracts

If your company uses this library in their products or services, you may be interested in purchasing a support contract from Paragon Initiative Enterprises.

More Repositories

1

awesome-appsec

A curated list of resources for learning about application security
PHP
6,305
star
2

paseto

Platform-Agnostic Security Tokens
PHP
3,248
star
3

halite

High-level cryptography interface powered by libsodium
PHP
1,124
star
4

sodium_compat

Pure PHP polyfill for ext/sodium
PHP
894
star
5

constant_time_encoding

Constant-Time Character Encoding in PHP Projects
PHP
816
star
6

easydb

Easy-to-use PDO wrapper for PHP projects.
PHP
736
star
7

csp-builder

Build Content-Security-Policy headers from a JSON file (or build them programmatically)
PHP
543
star
8

chronicle

Public append-only ledger microservice built with Slim Framework
PHP
469
star
9

ciphersweet

Fast, searchable field-level encryption for PHP projects
PHP
436
star
10

airship

Secure Content Management for the Modern Web - "The sky is only the beginning"
PHP
418
star
11

sapient

Secure API Toolkit
PHP
314
star
12

anti-csrf

Full-Featured Anti-CSRF Library
PHP
297
star
13

certainty

Automated cacert.pem management for PHP projects
PHP
262
star
14

EasyRSA

Simple and Secure Wrapper for phpseclib
PHP
198
star
15

password_lock

Wraps Bcrypt-SHA2 in Authenticated Encryption
PHP
190
star
16

sodium-plus

Developer-friendly libsodium interface
JavaScript
171
star
17

multi_factor

Vendor-Agnostic Two-Factor Authentication
PHP
142
star
18

gpg-mailer

GnuPG-encrypted emails made easy
PHP
96
star
19

pecl-libsodium-doc

Free Online Documentation for the Libsodium PHP Extension
88
star
20

typed-arrays

Userland typed array implementation
PHP
74
star
21

ciphersweet-js

Searchable Encryption for Node.js projects
JavaScript
65
star
22

hidden-string

The HiddenString class extracted from Halite.
PHP
64
star
23

corner

Exceptions and Errors made more user-friendly
PHP
62
star
24

paseto-io

Paseto Website
Twig
58
star
25

iaso

Powerful JSON Toolkit, includes a JSON parser immune to Hash-DoS attacks
PHP
51
star
26

easy-ecc

High-Level Usability Wrapper for PHPECC
PHP
44
star
27

hpkp-builder

Build HTTP Public-Key-Pinning headers from a JSON file (or build them programmatically)
PHP
41
star
28

seedspring

Seeded, Deterministic PRNG (based on AES-CTR instead of LCG)
PHP
39
star
29

passwdqc

Password/passphrase strength checking and enforcement (PHP port)
PHP
39
star
30

pharaoh

Utility to quickly and effectively diff two PHP Archives
PHP
36
star
31

libgossamer

Public Key Infrastructure without Certificate Authorities, for WordPress and Packagist
PHP
33
star
32

ionizer

Input Filter System for PHP Software
PHP
32
star
33

easydb-cache

EasyDB with Prepared Statement Caching
PHP
30
star
34

argon2-refiner

Generate Parameter Recommendations for Argon2id in PHP 7.3+
PHP
25
star
35

bsidesorl-2017

Supplementary Material for Building Defensible Solutions to Weird Problems
PHP
23
star
36

blakechain

Hash chains built with BLAKE2b
PHP
22
star
37

quill

Library for quickly and easily writing data to a Chronicle instance
PHP
21
star
38

stern

Stern lets you built type-safe PHP projects, even if your project's users aren't writing type-safe code
PHP
21
star
39

herd

Hash-Ensured Replicated Database
PHP
16
star
40

eloquent-ciphersweet

Bridge library between Eloquent ORM and CipherSweet
PHP
14
star
41

discretion

On-demand and reusable contact forms that only send GnuPG-encrypted messages to your inbox.
PHP
13
star
42

xchacha20-js

JavaScript implementation of ChaCha20, HChaCha20, and XChaCha20
JavaScript
12
star
43

pco_prototype

PCO - PHP Crypto Objects
PHP
12
star
44

paserk-php

PHP Implementation of PASERK
PHP
12
star
45

slim-sapient

Slim Framework Adapter for Sapient
PHP
10
star
46

airship-docs

Documentation for CMS Airship
Nginx
10
star
47

php-jwt-guard

Security Defense for Firebase's PHP-JWT Library
PHP
9
star
48

zend-diactoros-sapient

Zend Diactoros Adapter for Sapient
PHP
8
star
49

phone-to-pick

Whitelist Your Incoming Phone Calls (for Android)
Java
7
star
50

gossamer-server

Standalone Gossamer server
PHP
5
star
51

poly1305-js

JavaScript implementation of the Poly1305 one-time authenticator
JavaScript
5
star
52

paseto-browser.js

PASETO in the Web Browser
JavaScript
4
star
53

airship-barge

Build Gadgets for Airship projects (Command Line Interface)
PHP
3
star
54

monolog-quill

A Monolog Handler for writing to a Chronicle instance
PHP
3
star
55

sodium-jvm

Pure-Java implementation of the Sodium cryptography library.
3
star
56

blogpost-translations

Translations of Paragon Initiative Enterprise blog posts
2
star
57

ward-docs

Online Documentation for Ward (Web Application Realtime Defender)
2
star
58

php71_crypto

Pluggable Cryptography Interface for PHP 7.1
2
star
59

ristretto-php

Implements a type-safe API for working with the Ristretto Group in PHP projects.
PHP
2
star
60

node-halite

High-level cryptography interface powered by node-sodium
1
star
61

pie-hosted.com

Source code for the pie-hosted.com website
PHP
1
star
62

halite-legacy

Legacy versions of Halite to facilitate migrations from older ciphersuites to the latest supported version
PHP
1
star
63

certainty-js

Certainty-js: Automated CACert.pem Management for Node.js Software
JavaScript
1
star