Skip to content

Instantly share code, notes, and snippets.

@ezimuel
Created May 30, 2012 20:25
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/2838705 to your computer and use it in GitHub Desktop.
Save ezimuel/2838705 to your computer and use it in GitHub Desktop.
Zend\Math\Math::randBytes fix
public static function randBytes($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')) {
$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'
);
}
$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