PHP Snippet - Generate Random Bytes

Posted at

This code will generate any amount of bytes, in human readable Hex-characters,
using either random_bytes, mcrypt_create_iv or openssl_random_pseudo_bytes (all with added entropy), an additional, in-case of some sort of error or an old or lack of crypto-libraries PHP instance, there is a mt_rand-based on fallback.

<?php
$get_random_bytes = function($length = 64){
  $length = max(1, $length); /* valid input, at-least 1 byte. */

  $result = true === function_exists('random_bytes') ? bin2hex(random_bytes($length)) :
            true === function_exists('mcrypt_create_iv') ? bin2hex(mcrypt_create_iv($length, MCRYPT_DEV_URANDOM)) : /* might give false on error */
            true === function_exists('openssl_random_pseudo_bytes') ? bin2hex(openssl_random_pseudo_bytes($length, true)) : /* might give false on error */
            false /* fallback */
            ;

  /* in case of FALSE (because of function-error or fallback) we will be using "simpler" random */
  $result = false !== $result ? $result : substr(
                                            preg_replace_callback('#@#', function(){
                                              return dechex(mt_rand(0, 16));
                                            }, str_repeat('@', $length * 2)) /*64 bytes are 128 characters*/
                                            ,
                                            (-1 * $length * 2) /*trim - make sure exactly 128 characters (for example, if $length is 64)*/
                                          );
  return $result;
};

var_dump(
  $get_random_bytes()
);
?>