您好, 欢迎来到 !    登录 | 注册 | | 设为首页 | 收藏本站

如何创建和使用随机数

如何创建和使用随机数

或者,如果您想编写自己的代码,这很简单。使用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;
}
其他 2022/1/1 18:14:48 有490人围观

撰写回答


你尚未登录,登录后可以

和开发者交流问题的细节

关注并接收问题和回答的更新提醒

参与内容的编辑和改进,让解决方法与时俱进

请先登录

推荐问题


联系我
置顶