Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- <?php
- function hashPbkdf2($algorithm, $password, $salt, $iterations, $length = 0)
- {
- // Number of blocks needed to create the derived key
- $blocks = ceil($length / strlen(hash($algorithm, null, true)));
- $digest = '';
- $length = strlen(hash($algorithm, '', true));
- if (strlen($password) > $length) {
- $password = hash($algorithm, $password, true);
- }
- for ($i = 1; $i <= $blocks; $i++) {
- $ib = $block = hash_hmac($algorithm, $salt . pack('N', $i), $password, true);
- // Iterations
- for ($j = 1; $j < $iterations; $j++) {
- $ib ^= ($block = hash_hmac($algorithm, $block, $password, true));
- }
- $digest .= $ib;
- }
- return substr($digest, 0, 40);
- }
- function hashPbkdf2Original($algorithm, $password, $salt, $iterations, $length = 0)
- {
- // Number of blocks needed to create the derived key
- $blocks = ceil($length / strlen(hash($algorithm, null, true)));
- $digest = '';
- for ($i = 1; $i <= $blocks; $i++) {
- $ib = $block = hash_hmac($algorithm, $salt . pack('N', $i), $password, true);
- // Iterations
- for ($j = 1; $j < $iterations; $j++) {
- $ib ^= ($block = hash_hmac($algorithm, $block, $password, true));
- }
- $digest .= $ib;
- }
- return substr($digest, 0, 40);
- }
- function bench($p, $s, $i)
- {
- echo 'pw length: ' . strlen($p) . "\n";
- echo 'iterations: ' . $i . "\n";
- $start = microtime(true);
- $h1 = bin2hex(hashPbkdf2('sha256', $p, $s, $i, 32));
- echo 'polyfill: ' . (microtime(true) - $start) . "s\n";
- $start = microtime(true);
- $h2 = hash_pbkdf2('sha256', $p, $s, $i);
- echo 'native: ' . (microtime(true) - $start) . "s\n";
- echo 'h1 === h2: ' . ($h1 === $h2 ? 'true' : 'false') . "\n\n";
- }
- $iter = 1e4;
- bench(str_repeat('*', 1e2), 'somerandombytes', $iter);
- bench(str_repeat('*', 1e3), 'somerandombytes', $iter);
- bench(str_repeat('*', 1e4), 'somerandombytes', $iter);
- bench(str_repeat('*', 1e5), 'somerandombytes', $iter);
Add Comment
Please, Sign In to add comment