Chinaunix首页 | 论坛 | 博客
  • 博客访问: 398057
  • 博文数量: 42
  • 博客积分: 1181
  • 博客等级: 少尉
  • 技术积分: 602
  • 用 户 组: 普通用户
  • 注册时间: 2012-02-28 22:19
文章分类

全部博文(42)

文章存档

2012年(42)

分类: 网络与安全

2012-04-28 14:38:48

最近在研究bcrypt跟PBKDF2, 这是找到的代码.


点击(此处)折叠或打开

  1. /*
  2.      * PBKDF2 key derivation function as defined by RSA's PKCS #5:
  3.      * $algorithm - The hash algorithm to use. Recommended: SHA256
  4.      * $password - The password.
  5.      * $salt - A salt that is unique to the password.
  6.      * $count - Iteration count. Higher = better. Recommended: At least 1024.
  7.      * $key_length - The length of the derived key in BYTES.
  8.      * Returns: A $key_length-byte key derived from the password and salt (in binary).
  9.      *
  10.      * Test vectors can be found here:
  11.      */
  12.     function pbkdf2($algorithm, $password, $salt, $count, $key_length)
  13.     {
  14.         $algorithm = strtolower($algorithm);
  15.         if(!in_array($algorithm, hash_algos(), true))
  16.             die('PBKDF2 ERROR: Invalid hash algorithm.');
  17.         if($count < 0 || $key_length < 0)
  18.             die('PBKDF2 ERROR: Invalid parameters.');
  19.         if($key_length > 4294967295)
  20.             die('PBKDF2 ERROR: Derived key too long.');

  21.         $hLen = strlen(hash($algorithm, "", true));
  22.         $numBlocks = (int)ceil((double)$key_length / $hLen);

  23.         $output = "";
  24.         for($i = 1; $i <= $numBlocks; $i++)
  25.         {
  26.             $output .= pbkdf2_f($password, $salt, $count, $i, $algorithm, $hLen);
  27.         }

  28.         return substr($output, 0, $key_length);
  29.     }

  30.     /*
  31.      * The pseudorandom function used by PBKDF2.
  32.      * Definition:
  33.      */
  34.     function pbkdf2_f($password, $salt, $count, $i, $algorithm, $hLen)
  35.     {
  36.         //$i encoded as 4 bytes, big endian.
  37.         $last = $salt . chr(($i >> 24) % 256) . chr(($i >> 16) % 256) . chr(($i >> 8) % 256) . chr($i % 256);
  38.         $xorsum = "";
  39.         for($r = 0; $r < $count; $r++)
  40.         {
  41.             $u = hash_hmac($algorithm, $last, $password, true);
  42.             $last = $u;
  43.             if(empty($xorsum))
  44.                 $xorsum = $u;
  45.             else
  46.             {
  47.                 for($c = 0; $c < $hLen; $c++)
  48.                 {
  49.                     $xorsum[$c] = chr(ord(substr($xorsum, $c, 1)) ^ ord(substr($u, $c, 1)));
  50.                 }
  51.             }
  52.         }
  53.         return $xorsum;
  54.     }

阅读(4269) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~