Home > Backend Development > PHP Tutorial > PHP hash_equals polyfill

PHP hash_equals polyfill

WBOY
Release: 2016-06-06 20:38:46
Original
1097 people have browsed it

在 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>
Copy after login
Copy after login

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


從 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 </code>
Copy after login
Copy after login

貌似和上面的 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>
Copy after login
Copy after login

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


從 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 </code>
Copy after login
Copy after login

貌似和上面的 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>
Copy after login

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

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template