Guest User

Untitled

a guest
Oct 11th, 2018
83
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.93 KB | None | 0 0
  1. <?php
  2. function hashPbkdf2($algorithm, $password, $salt, $iterations, $length = 0)
  3. {
  4. // Number of blocks needed to create the derived key
  5. $blocks = ceil($length / strlen(hash($algorithm, null, true)));
  6. $digest = '';
  7. $length = strlen(hash($algorithm, '', true));
  8. if (strlen($password) > $length) {
  9. $password = hash($algorithm, $password, true);
  10. }
  11.  
  12. for ($i = 1; $i <= $blocks; $i++) {
  13. $ib = $block = hash_hmac($algorithm, $salt . pack('N', $i), $password, true);
  14. // Iterations
  15. for ($j = 1; $j < $iterations; $j++) {
  16. $ib ^= ($block = hash_hmac($algorithm, $block, $password, true));
  17. }
  18. $digest .= $ib;
  19. }
  20. return substr($digest, 0, 40);
  21. }
  22. function hashPbkdf2Original($algorithm, $password, $salt, $iterations, $length = 0)
  23. {
  24. // Number of blocks needed to create the derived key
  25. $blocks = ceil($length / strlen(hash($algorithm, null, true)));
  26. $digest = '';
  27. for ($i = 1; $i <= $blocks; $i++) {
  28. $ib = $block = hash_hmac($algorithm, $salt . pack('N', $i), $password, true);
  29. // Iterations
  30. for ($j = 1; $j < $iterations; $j++) {
  31. $ib ^= ($block = hash_hmac($algorithm, $block, $password, true));
  32. }
  33. $digest .= $ib;
  34. }
  35. return substr($digest, 0, 40);
  36. }
  37.  
  38. function bench($p, $s, $i)
  39. {
  40. echo 'pw length: ' . strlen($p) . "\n";
  41. echo 'iterations: ' . $i . "\n";
  42.  
  43. $start = microtime(true);
  44. $h1 = bin2hex(hashPbkdf2('sha256', $p, $s, $i, 32));
  45. echo 'polyfill: ' . (microtime(true) - $start) . "s\n";
  46.  
  47. $start = microtime(true);
  48. $h2 = hash_pbkdf2('sha256', $p, $s, $i);
  49. echo 'native: ' . (microtime(true) - $start) . "s\n";
  50.  
  51. echo 'h1 === h2: ' . ($h1 === $h2 ? 'true' : 'false') . "\n\n";
  52. }
  53.  
  54. $iter = 1e4;
  55. bench(str_repeat('*', 1e2), 'somerandombytes', $iter);
  56. bench(str_repeat('*', 1e3), 'somerandombytes', $iter);
  57. bench(str_repeat('*', 1e4), 'somerandombytes', $iter);
  58. bench(str_repeat('*', 1e5), 'somerandombytes', $iter);
Add Comment
Please, Sign In to add comment