从/dev/urandom转换随机值 [英] Convert random values from /dev/urandom
本文介绍了从/dev/urandom转换随机值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
如对mt_rand()
的评论它的安全性很弱,我们应该改用/dev/urandom.我的问题是从urandom中我得到了一个二进制字符串.
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.
如何将该二进制字符串转换为0-9a-zA-Z?
How do I convert this binary string to 0-9a-zA-Z?
看起来像base_convert()
在这里不起作用.
Looks like base_convert()
does not work here.
推荐答案
仅记录完整功能:
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;
}
这篇关于从/dev/urandom转换随机值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文