小编典典

如何创建和使用随机数

php

我正在运行一个网站,并且有一个计分系统,可为您提供玩游戏次数的积分。

它使用散列来证明http请求评分的完整性,因此用户无法更改任何内容,但是正如我担心的那样,有人发现他们不需要更改它,他们只需要获得高分并复制http请求,标头和所有。

以前,我被禁止防御此攻击,因为它被认为不太可能。但是,既然已经发生,我可以。http请求源自Flash游戏,然后由php验证,然后php将其输入数据库。

我很确定随机数会解决该问题,但是我不确定如何实现它们。建立随机数系统的常见且安全的方法是什么?


阅读 368

收藏
2020-05-26

共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;
}
2020-05-26