PiTheNumber PiTheNumber - 5 months ago 22
PHP Question

Convert random values from /dev/urandom

As mentioned in the comments of

it is weak in security and we should use /dev/urandom instead. My problem is that from urandom I get a binary string.

How do I convert this binary string to 0-9a-zA-Z?

Looks like
base_convert()
does not work here.

Answer

Just for the record the full function:

function randomFromDev($len)
{
    $fp = @fopen('/dev/urandom','rb');
    $result = '';
    if ($fp !== FALSE) {
        $result .= @fread($fp, $len);
        @fclose($fp);
    }
    else
    {
        trigger_error('Can not open /dev/urandom.');
    }
    // convert from binary to string
    $result = base64_encode($result);
    // remove none url chars
    $result = strtr($result, '+/', '-_');
    // Remove = from the end
    $result = str_replace('=', ' ', $result);
    return $result;
}
Comments