如何创建和使用随机数

如何创建和使用随机数,第1张

如何创建和使用随机数

或者,如果您想编写自己的代码,这很简单。使用WikiPedia页面作为起点,使用伪代码:

在服务器端,您需要两个客户端可调用函数

getNonce() {    $id = Identify Request //(either by username, session, or something)    $nonce = hash('sha512', makeRandomString());    storeNonce($id, $nonce);    return $nonce to client;}verifyNonce($data, $cnonce, $hash) {    $id = Identify Request    $nonce = getNonce($id);  // Fetch the nonce from the last request    removeNonce($id, $nonce); //Remove the nonce from being used again!    $testHash = hash('sha512',$nonce . $cnonce . $data);    return $testHash == $hash;}

在客户端:

sendData($data) {    $nonce = getNonceFromServer();    $cnonce = hash('sha512', makeRandomString());    $hash = hash('sha512', $nonce . $cnonce . $data);    $args = array('data' => $data, 'cnonce' => $cnonce, 'hash' => $hash);    sendDataToClient($args);}

该函数

makeRandomString
实际上只需要返回一个随机数或字符串。随机性越好,安全性就越好。。还要注意,由于它是直接输入到哈希函数中的,因此实现细节在请求之间无关紧要。客户端的版本和服务器的版本不需要匹配。实际上,唯一需要匹配100%的位是用于
hash('sha512',$nonce . $cnonce . $data);
… 的哈希函数。这是一个相当安全的
makeRandomString
函数的示例…

function makeRandomString($bits = 256) {    $bytes = ceil($bits / 8);    $return = '';    for ($i = 0; $i < $bytes; $i++) {        $return .= chr(mt_rand(0, 255));    }    return $return;}


欢迎分享,转载请注明来源:内存溢出

原文地址:https://54852.com/zaji/5009481.html

(0)
打赏 微信扫一扫微信扫一扫 支付宝扫一扫支付宝扫一扫
上一篇 2022-11-14
下一篇2022-11-14

发表评论

登录后才能评论

评论列表(0条)

    保存