它实际上很容易......有一些库可以帮到你:
PHP Nonce库
OpenID Nonce库
或者如果你想自己编写,那很简单。使用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;
}
它实际上很容易......有一些库可以帮到你:
PHP Nonce库
OpenID Nonce库
或者如果你想自己编写,那很简单。使用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;
}