【发布时间】:2013-06-16 19:39:36
【问题描述】:
我在PHP 中编写了一个函数来为我的应用生成一个随机密码(仅0-9a-zA-Z)。生成的密码必须是加密安全的,并且尽可能随机。 IE。密码很敏感。
我做的大招是每次都洗牌$possible 字符,所以即使mt_rand() 不是真正随机的,它也不应该是可预测的。
我的功能中有任何建议的更改或安全问题吗?使用openssl_random_pseudo_bytes() 而不是mt_rand() 真的会让算法更强大、更安全吗?
public function generate_random($length = 15) {
$random = "";
$possible = "1234567890abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
$possible = str_shuffle($possible);
$maxlength = strlen($possible);
if ($length > $maxlength) {
$length = $maxlength;
}
$i = 0;
while ($i < $length) {
$random .= substr($possible, mt_rand(0, $maxlength-1), 1);
$i++;
}
return $random;
}
谢谢。
【问题讨论】:
-
'只有 0-9a-zA-Z' - 为什么?
-
只是规范的一部分。可以添加特殊字符,但让我们忽略这方面。
-
使用这种方法,你仍然会有某些字母彼此相邻吗?
-
codereview.stackexchange.com 可能是解决此类问题的更好网站。
-
str_shuffle在内部使用rand。
标签: php security random passwords cryptography