hash_tool.php 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  1. <?php
  2. interface i_password_hash_tool {
  3. public function check_password_hash($password, $hash);
  4. public function crypt($password);
  5. }
  6. class md5_hash_tool implements i_password_hash_tool {
  7. public function check_password_hash($password, $hash) {
  8. $passParts = explode('$', $hash);
  9. $salt = $passParts[2];
  10. $hashed = $this->crypt_apr_md5($password, $salt);
  11. return $hashed == $hash;
  12. }
  13. public function crypt($password) {
  14. }
  15. protected function crypt_apr_md5($password, $salt)
  16. {
  17. $len = strlen($password);
  18. $text = $password.'$apr1$'.$salt;
  19. $bin = pack("H32", md5($password.$salt.$password));
  20. for($i = $len; $i > 0; $i -= 16) { $text .= substr($bin, 0, min(16, $i)); }
  21. for($i = $len; $i > 0; $i >>= 1) { $text .= ($i & 1) ? chr(0) : $password{0}; }
  22. $bin = pack("H32", md5($text));
  23. for($i = 0; $i < 1000; $i++) {
  24. $new = ($i & 1) ? $password : $bin;
  25. if ($i % 3) $new .= $salt;
  26. if ($i % 7) $new .= $password;
  27. $new .= ($i & 1) ? $bin : $password;
  28. $bin = pack("H32", md5($new));
  29. }
  30. $tmp = '';
  31. for ($i = 0; $i < 5; $i++) {
  32. $k = $i + 6;
  33. $j = $i + 12;
  34. if ($j == 16) $j = 5;
  35. $tmp = $bin[$i].$bin[$k].$bin[$j].$tmp;
  36. }
  37. $tmp = chr(0).chr(0).$bin[11].$tmp;
  38. $tmp = strtr(strrev(substr(base64_encode($tmp), 2)),
  39. "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",
  40. "./0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz");
  41. return "$"."apr1"."$".$salt."$".$tmp;
  42. }
  43. }
  44. class crypt_hash_tool implements i_password_hash_tool {
  45. public function check_password_hash($password, $hash) {
  46. $salt = substr ( $hash, 0, 2 );
  47. if (crypt ( $password, $salt ) == $hash) {
  48. return true;
  49. } else {
  50. return false;
  51. }
  52. }
  53. public function crypt($password) {
  54. return crypt ( $password, substr ( str_replace ( '+', '.', base64_encode ( pack ( 'N4', mt_rand (), mt_rand (), mt_rand (), mt_rand () ) ) ), 0, 22 ) );
  55. }
  56. }
  57. ?>