gpt4 book ai didi

php - PHP 中的安全随机数生成

转载 作者:IT王子 更新时间:2023-10-29 01:04:54 26 4
gpt4 key购买 nike

用例:“我忘记了密码”按钮。我们无法找到用户的原始密码,因为它是以散列形式存储的,所以唯一要做的就是生成一个新的随 secret 码并将其通过电子邮件发送给他。这需要密码学不可预测的随机数,mt_rand 对此不够好,而且通常我们不能假设托管服务将提供对操作系统的访问以安装密码学随机数模块等。所以我正在寻找一种方法在 PHP 本身中生成安全的随机数。

到目前为止,我提出的解决方案包括存储初始种子,然后针对每次调用,

result = seed
seed = sha512(seed . mt_rand())

这是基于 sha512 哈希函数的安全性(mt_rand 调用只是为了让获得数据库副本的对手的日子更难过)。

我是否遗漏了什么,或者是否有更好的解决方案?

最佳答案

我强烈建议将 unix 系统上的/dev/urandom 或 windows 平台上的 crypto-api 作为密码的熵源。

我不能足够强调实现哈希不是神奇的熵增加设备的重要性。以这种方式滥用它们并不比在散列之前使用种子和 rand() 数据更安全,我相信你知道这不是一个好主意。种子抵消了(确定性 mt_rand()),因此即使包含它也没有任何意义。

人们认为他们很聪明很聪明,他们的劳动成果是脆弱的系统和设备,它们将他们系统的安全性和其他系统的安全性(通过糟糕的建议)置于不必要的危险之中。

两个错误不等于一个正确。一个系统的强大取决于它最薄弱的部分。这不是一个许可或借口,可以接受让它变得更加不安全。


这里是一些 PHP 代码,用于从 this comment at php.net by Mark Seecof 获取安全的随机 128 位字符串。 :

"If you need some pseudorandom bits for security or cryptographic purposes (e.g.g., random IV for block cipher, random salt for password hash) mt_rand() is a poor source. On most Unix/Linux and/or MS-Windows platforms you can get a better grade of pseudorandom bits from the OS or system library, like this:

<?php
// get 128 pseudorandom bits in a string of 16 bytes

$pr_bits = '';

// Unix/Linux platform?
$fp = @fopen('/dev/urandom','rb');
if ($fp !== FALSE) {
$pr_bits .= @fread($fp,16);
@fclose($fp);
}

// MS-Windows platform?
if (@class_exists('COM')) {
// http://msdn.microsoft.com/en-us/library/aa388176(VS.85).aspx
try {
$CAPI_Util = new COM('CAPICOM.Utilities.1');
$pr_bits .= $CAPI_Util->GetRandom(16,0);

// if we ask for binary data PHP munges it, so we
// request base64 return value. We squeeze out the
// redundancy and useless ==CRLF by hashing...
if ($pr_bits) { $pr_bits = md5($pr_bits,TRUE); }
} catch (Exception $ex) {
// echo 'Exception: ' . $ex->getMessage();
}
}

if (strlen($pr_bits) < 16) {
// do something to warn system owner that
// pseudorandom generator is missing
}
?>

NB: it is generally safe to leave both the attempt to read /dev/urandom and the attempt to access CAPICOM in your code, though each will fail silently on the other's platform. Leave them both there so your code will be more portable."

关于php - PHP 中的安全随机数生成,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1182584/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com