Skip to content

Instantly share code, notes, and snippets.

@ezimuel
Last active December 14, 2015 05:39
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ezimuel/5036694 to your computer and use it in GitHub Desktop.
Save ezimuel/5036694 to your computer and use it in GitHub Desktop.
Proposal for Improvement of ZF2 RND
/**
* Generate random bytes using OpenSSL or Mcrypt and mt_rand() as fallback
*
* @param integer $length
* @param bool $strong true if you need a strong random generator (cryptography)
* @return string
* @throws Exception\RuntimeException
*/
public static function getBytes($length, $strong = false)
{
if ($length <= 0) {
return false;
}
if (extension_loaded('openssl')) {
$rand = openssl_random_pseudo_bytes($length, $secure);
if ($secure === true) {
return $rand;
}
}
if (extension_loaded('mcrypt')) {
// PHP bug #55169
// @see https://bugs.php.net/bug.php?id=55169
if (strtoupper(substr(PHP_OS, 0, 3)) !== 'WIN' ||
version_compare(PHP_VERSION, '5.3.7') >= 0) {
$rand = mcrypt_create_iv($length, MCRYPT_DEV_URANDOM);
if ($rand !== false && strlen($rand) === $length) {
return $rand;
}
}
}
if ($strong) {
throw new Exception\RuntimeException(
'This PHP environment doesn\'t support secure random number generation. ' .
'Please consider to install the OpenSSL and/or Mcrypt extensions'
);
}
if (is_readable('/dev/urandom')) {
$seed = unpack('l', fread(fopen('/dev/urandom', 'r'), 4));
if (isset($seed[1])) {
mt_srand($seed[1]);
}
}
$rand = '';
for ($i = 0; $i < $length; $i++) {
$rand .= chr(mt_rand(0, 255));
}
return $rand;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment