• 热门专题

PBKDF2 PHP代码 WPA常见加密算法

作者:  发布日期:2012-07-06 18:38:00
Tag标签:PBKDF2  WPA  加密算法  
  • /*
         * PBKDF2 key derivation function as defined by RSA's PKCS #5: https://www.ietf.org/rfc/rfc2898.txt
         * $algorithm - The hash algorithm to use. Recommended: SHA256
         * $password - The password.
         * $salt - A salt that is unique to the password.
         * $count - Iteration count. Higher = better. Recommended: At least 1024.
         * $key_length - The length of the derived key in BYTES.
         * Returns: A $key_length-byte key derived from the password and salt (in binary).
         *
         * Test vectors can be found here: https://www.www.it165.net/rfc/rfc6070.txt
         */
        function pbkdf2($algorithm, $password, $salt, $count, $key_length)
        {
            $algorithm = strtolower($algorithm);
            if(!in_array($algorithm, hash_algos(), true))
                die('PBKDF2 ERROR: Invalid hash algorithm.');
            if($count < 0 || $key_length < 0)
                die('PBKDF2 ERROR: Invalid parameters.');
            if($key_length > 4294967295)
                die('PBKDF2 ERROR: Derived key too long.');
    
            $hLen = strlen(hash($algorithm, "", true));
            $numBlocks = (int)ceil((double)$key_length / $hLen);
    
            $output = "";
            for($i = 1; $i <= $numBlocks; $i++)
            {
                $output .= pbkdf2_f($password, $salt, $count, $i, $algorithm, $hLen);
            }
    
            return substr($output, 0, $key_length);
        }
    
        /*
         * The pseudorandom function used by PBKDF2.
         * Definition: https://www.ietf.org/rfc/rfc2898.txt
         */
        function pbkdf2_f($password, $salt, $count, $i, $algorithm, $hLen)
        {
            //$i encoded as 4 bytes, big endian.
            $last = $salt . chr(($i >> 24) % 256) . chr(($i >> 16) % 256) . chr(($i >> 8) % 256) . chr($i % 256);
            $xorsum = "";
            for($r = 0; $r < $count; $r++)
            {
                $u = hash_hmac($algorithm, $last, $password, true);
                $last = $u;
                if(empty($xorsum))
                    $xorsum = $u;
                else
                {
                    for($c = 0; $c < $hLen; $c++)
                    {
                        $xorsum[$c] = chr(ord(substr($xorsum, $c, 1)) ^ ord(substr($u, $c, 1)));
                    }
                }
            }
            return $xorsum;
        }

    摘自:lijingquan.net
About IT165 - 广告服务 - 隐私声明 - 版权申明 - 免责条款 - 网站地图 - 网友投稿 - 联系方式
本站内容来自于互联网,仅供用于网络技术学习,学习中请遵循相关法律法规