• 欢迎访问搞代码网站,推荐使用最新版火狐浏览器和Chrome浏览器访问本网站!
  • 如果您觉得本站非常有看点,那么赶紧使用Ctrl+D 收藏搞代码吧

PHP hash_equals polyfill

php 搞代码 3年前 (2022-01-25) 17次浏览 已收录 0个评论
文章目录[隐藏]

在 php.net 看到一個版本,然而卻有很多 downvotes,不知爲何。

<code>if(!function_exists('hash_equals')) {  function hash_equals($str1, $str2) {    if(strlen($str1) != strlen($str2)) {      return false;    } else {      $res = $str1 ^ $str2;      $ret = 0;      for($i = strlen($res) - 1; $i >= 0; $i--) $ret |= ord($res[$i]);      return !$ret;    }  }}</code>

如果這個函數真的不好,請說明原因,最好還能給出替代解決方案,謝謝。


從 stackoverflow 看到其實現如下:

<code>PHP_FUNCTION(hash_equals){    /* ... */    if (Z_STRLEN_P(known_zval) != Z_STRLEN_P(user_zval)) {        RETURN_FALSE;    }    /* ... */    /* This is security sensitive code. Do not optimize this for speed. */    for (j = 0; j < Z_STRLEN_P(known_zval); j++) {        result |= known_str[j] ^ user_str[j];    }    RET<strong>*本文来源gaodai#ma#com搞@代~码^网+</strong><strong>搞代gaodaima码</strong>URN_BOOL(0 == result);}</code>

貌似和上面的 polyfill 沒什麼區別啊

回复内容:

在 php.net 看到一個版本,然而卻有很多 downvotes,不知爲何。

<code>if(!function_exists('hash_equals')) {  function hash_equals($str1, $str2) {    if(strlen($str1) != strlen($str2)) {      return false;    } else {      $res = $str1 ^ $str2;      $ret = 0;      for($i = strlen($res) - 1; $i >= 0; $i--) $ret |= ord($res[$i]);      return !$ret;    }  }}</code>

如果這個函數真的不好,請說明原因,最好還能給出替代解決方案,謝謝。


從 stackoverflow 看到其實現如下:

<code>PHP_FUNCTION(hash_equals){    /* ... */    if (Z_STRLEN_P(known_zval) != Z_STRLEN_P(user_zval)) {        RETURN_FALSE;    }    /* ... */    /* This is security sensitive code. Do not optimize this for speed. */    for (j = 0; j < Z_STRLEN_P(known_zval); j++) {        result |= known_str[j] ^ user_str[j];    }    RETURN_BOOL(0 == result);}</code>

貌似和上面的 polyfill 沒什麼區別啊

因为类型不严格,导致如果攻击者能够通过某种方式控制入参的类型,可以攻击

<code>php</code><code>function bug_hash_equals($str1, $str2) {    if(strlen($str1) != strlen($str2)) {      return false;    } else {      $res = $str1 ^ $str2;      $ret = 0;      for($i = strlen($res) - 1; $i >= 0; $i--) $ret |= ord($res[$i]);      return !$ret;    }}var_dump(bug_hash_equals('aaabbb', 0.0001));//true</code>

http://sandbox.onlinephpfunctions.com/code/e7c978d047486534441403a88680cefb85b1a48c


搞代码网(gaodaima.com)提供的所有资源部分来自互联网,如果有侵犯您的版权或其他权益,请说明详细缘由并提供版权或权益证明然后发送到邮箱[email protected],我们会在看到邮件的第一时间内为您处理,或直接联系QQ:872152909。本网站采用BY-NC-SA协议进行授权
转载请注明原文链接:PHP hash_equals polyfill

喜欢 (0)
[搞代码]
分享 (0)
发表我的评论
取消评论

表情 贴图 加粗 删除线 居中 斜体 签到

Hi,您需要填写昵称和邮箱!

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址