php 如何生成noncestr,如何创建和使用nonce

它实际上很容易......有一些库可以帮到你:

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;

}

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值