Skip to content

Instantly share code, notes, and snippets.

@timoh6
Created April 22, 2014 07:59
Show Gist options
  • Save timoh6/11169328 to your computer and use it in GitHub Desktop.
Save timoh6/11169328 to your computer and use it in GitHub Desktop.
Symfony SecureRandom mockup
<?php
namespace Symfony\Component\Security\Core\Util;
class SecureRandom
{
/**
* Generate a random string of bytes suitable for cryptographic use.
*
* @param int $nbBytes
* @return string
* @throws \RuntimeException
*/
public function nextBytes($nbBytes)
{
$nbBytes = (int) $nbBytes;
if ($nbBytes < 1)
{
throw new \RuntimeException('$nbBytes must be greater than 0');
}
$bytes = '';
$hasBytes = false;
// Try mcrypt_create_iv at first because it works also on the Windows
if (function_exists('mcrypt_create_iv'))
{
$tmp = mcrypt_create_iv($nbBytes, MCRYPT_DEV_URANDOM);
if ($tmp !== false)
{
$bytes = $tmp;
$hasBytes = true;
}
}
// Fall back trying to read straight from /dev/urandom
if ($hasBytes === false && file_exists('/dev/urandom') && is_readable('/dev/urandom') && (false !== ($fh = fopen('/dev/urandom', 'rb'))))
{
if (function_exists('stream_set_read_buffer'))
{
stream_set_read_buffer($fh, 0);
}
$tmp = fread($fh, $nbBytes);
fclose($fh);
if ($tmp !== false)
{
$bytes = $tmp;
}
}
if (strlen($bytes) === $nbBytes)
{
return $bytes;
}
else
{
throw new \RuntimeException('Could not generate random bytes');
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment