Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert random values from /dev/urandom

Tags:

php

random

As mentioned in the comments of mt_rand() 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.

like image 581
PiTheNumber Avatar asked Dec 08 '11 10:12

PiTheNumber


1 Answers

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;
}
like image 185
PiTheNumber Avatar answered Sep 30 '22 10:09

PiTheNumber