栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

如何创建和使用随机数

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

如何创建和使用随机数

或者,如果您想编写自己的代码,这很简单。使用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;}


转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/400796.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号