PHP Classes

PHP Random Bytes: Generate cryptographically strong random bytes

Recommend this page to a friend!
  Info   View files Example   View files View files (5)   DownloadInstall with Composer Download .zip   Reputation   Support forum   Blog    
Ratings Unique User Downloads Download Rankings
Not enough user ratingsTotal: 175 All time: 8,774 This week: 571Up
Version License PHP version Categories
random-bytes 0.14GNU General Publi...5.4PHP 5, Cryptography, Security
Description 

Author

This class can generate cryptographically strong random bytes.

It can generate a string of bytes with random values using a given method.

Currently it can use either methods using mcrypt, OpenSSL, or /dev/urandom on Linux. The default is to use mcrypt.

Innovation Award
PHP Programming Innovation award nominee
May 2015
Number 5


Prize: One downloadable e-book of choice by O'Reilly
Many cryptography algorithms use random numbers to make it harder to break the security measures based on those algorithms.

There are many pseudo-random number generators that can be used to generate cryptographically strong data values.

This class can generate random streams of bytes that are more secure to use in cryptography applications by either using /dev/random on Linux, OpenSSL or mcrypt libraries.

Manuel Lemos
Picture of Martin Latter
  Performance   Level  
Name: Martin Latter <contact>
Classes: 8 packages by
Country: United Kingdom
Age: ???
All time rank: 130660 in United Kingdom
Week rank: 411 Up12 in United Kingdom Up
Innovation award
Innovation award
Nominee: 5x

Example

<?php

/**
    * Example web server usage of RandomBytes class.
    * Martin Latter, 13/04/2015
*/

##################################################
declare(strict_types=1);
mb_internal_encoding('UTF-8');
mb_http_output('UTF-8');
header('Content-Type: text/html; charset=utf-8');
##################################################

##################################################
require('classes/randombytes.class.php');
use
Tinram\RandomBytes\RandomBytes;
##################################################


$aRandGenMethods = ['openssl', 'urandom', 'random_bytes'];

$bSubmitted = (isset($_POST['submit_check'])) ? true : false;


function
generateTable(array $aData): void
{
    echo
'
        <table>
            <tr><td class="tfirst">raw</td><td>'
. $aData['raw'] . '</td></tr>
            <tr><td>raw, hex</td><td>'
. $aData['hex']. '</td></tr>
            <tr><td>SHA256</td><td>'
. $aData['sha'] . '</td></tr>
            <tr><td>SHA256 <small>(bytes)</small></td><td>'
. $aData['shabytes'] . '</td></tr>
            <tr><td>Whirlpool</td><td>'
. $aData['whirlpool'] . '</td></tr>
        </table>
    '
;
}

?><!DOCTYPE html>

<html lang="en">

    <head>

        <meta charset="utf-8">

        <title>Random Bytes</title>

        <meta name="author" content="Martin Latter">

        <style>

            html * {margin:0; padding:0;}
            body {font:0.83em verdana,arial,helvetica,sans-serif; background:#fff; color:#000; margin:4em 0 0 4em;}

            h1 {margin:0 0 20px 0; font-size:1.1em;}

            div#frbcont {width:376px; margin:0 0 60px 0;}
            form#frb label {margin:0 5px 0 0;}
            form#frb input, form#frb select {border-radius:5px; background:#f2f9f9; padding:2px; border:1px solid #c8e4ff; background:linear-gradient(to top, #ebf8ff, #ffffff 80%);}
            form#frb select {margin:0 12px 0 0;}
            form#frb select#chars {width:50px;}
            form#frb select#genmethod {width:120px;}
            form#frb input[type='submit'] {width:80px; height:24px; color:#333; background:#f7ffff; border:0; font-weight:bold; text-align:center; margin-top:10px; padding-bottom:3px; height:25px; background:linear-gradient(to bottom, #f7ffff, #c8e4ff 100%);}
            form#frb input[type='submit']:hover {background:#39f; color:#fff; cursor:pointer;}

            table {border-collapse:collapse;}
            td {padding:4px; border:1px solid #bbb;}
            td.tfirst {width:130px;}

        </style>

    </head>

    <body>

        <h1>Random Bytes</h1>

        <div id="frbcont">

            <form id="frb" method="post" action="<?php echo htmlspecialchars(strip_tags($_SERVER['PHP_SELF']), ENT_QUOTES, 'UTF-8'); ?>">

                <div>

                    <label for="chars" title="number of characters">chars</label>
                    <select id="chars" name="chars">
                    <?php

                        $iChars
= ($bSubmitted) ? (int) $_POST['chars'] : 0;
                       
$sSelected = '';
                       
$sOut = '';

                        for (
$i = 16; $i < 72; $i += 8)
                        {
                           
$sSelected = ($i !== $iChars) ? '' : ' selected';
                           
$sOut .= '<option value="' . $i . '"' . $sSelected . '>' . $i . '</option>';
                        }

                        echo
$sOut;
                   
?>

                    </select>

                    <label for="genmethod" title="random bytes generation method">method</label>
                    <select id="genmethod" name="genmethod">
                    <?php

                        $sOut
= '';

                        foreach (
$aRandGenMethods as $sMethod)
                        {
                           
$sSelected = ($bSubmitted && $_POST['genmethod'] === $sMethod) ? ' selected' : '';
                           
$sOut .= '<option value="' . $sMethod . '"' . $sSelected . '>' . $sMethod . '</option>';
                        }

                        echo
$sOut;
                   
?>

                    </select>

                    <input type="submit" value="generate">

                </div>

                <input type="hidden" name="submit_check">

            </form>

        </div>

        <?php

           
if ($bSubmitted)
            {
               
$iChars = (int) $_POST['chars'];
               
$aData = RandomBytes::generate($iChars, htmlentities(strip_tags($_POST['genmethod'])));
               
generateTable($aData);
            }

       
?>

    </body>

</html>


Details

Random Bytes

Generate cryptographically-strong random bytes.

Purpose

Create random bytes &ndash; as cryptographically-strong as possible &ndash; from available sources of entropy, and display in different output formats.

Crypto Sources

  • Linux/Unix: OpenSSL, `random_bytes()`, /dev/urandom
  • Windows: OpenSSL, `random_bytes()`

Random Bytes Definitions:

  • openssl
  • random_bytes
  • urandom

Usage

Prototype

    array RandomBytes::generate(int $length, string $source);

Example

    require('randombytes.class.php');
    use Tinram\RandomBytes\RandomBytes;
    $aData = RandomBytes::generate(32, 'openssl');
    var_dump($aData);

Details

The random bytes generated are only as good as the underlying entropy generator of the OS.

Linux's /dev/urandom entropy source is a non-blocking generator 'suitable for most cryptographic purposes'. (/dev/random, being blocking, isn't suitable for this script.)

OpenBSD and FreeBSD have non-blocking /dev/random implementations.

The random_bytes() function was added to PHP version 7.0

License

Random Bytes is released under the GPL v.3.


  Files folder image Files  
File Role Description
Files folder imageclasses (1 file)
Accessible without login Plain text file LICENSE Lic. License text
Accessible without login Plain text file randombytes_example.php Example Example script
Accessible without login Plain text file randombytes_example2.php Aux. Auxiliary script
Accessible without login Plain text file README.md Data Documentation

  Files folder image Files  /  classes  
File Role Description
  Plain text file randombytes.class.php Class Class source

 Version Control Unique User Downloads Download Rankings  
 100%
Total:175
This week:0
All time:8,774
This week:571Up