php – MySQL散列函数实现

前端之家收集整理的这篇文章主要介绍了php – MySQL散列函数实现前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我知道PHP有md5(),sha1()和hash()函数,但是我想使用 MySQL PASSWORD()函数创建一个哈希.到目前为止,我唯一可以想到的只是查询服务器,但是我想要一个功能(最好是在PHP或Perl中),这样一来就可以完成同样的操作,而不需要查询MysqL.

例如:

MysqL哈希 – > 464bb2cb3cf18b66

MysqL5哈希 – > * 01D01F5CA7CA8BA771E03F4AC55EC73C11EFA229

谢谢!

我本来在这个问题上偶然发现我自己寻找一个 PHP实现的两个MysqL密码哈希函数.我无法找到任何实现,所以我自己从MysqL代码(sql / password.c)修改了自己.以下测试和工作在PHP 5.2:
  1. // The following is free for any use provided credit is given where due.
  2. // This code comes with NO WARRANTY of any kind,including any implied warranty.
  3.  
  4. /**
  5. * MysqL "OLD_PASSWORD()" AKA MysqL323 HASH FUNCTION
  6. * This is the password hashing function used in MysqL prior to version 4.1.1
  7. * By Rev. Dustin Fineout 10/9/2009 9:12:16 AM
  8. **/
  9. function MysqL_old_password_hash($input,$hex = true)
  10. {
  11. $nr = 1345345333; $add = 7; $nr2 = 0x12345671; $tmp = null;
  12. $inlen = strlen($input);
  13. for ($i = 0; $i < $inlen; $i++) {
  14. $byte = substr($input,$i,1);
  15. if ($byte == ' ' || $byte == "\t") continue;
  16. $tmp = ord($byte);
  17. $nr ^= ((($nr & 63) + $add) * $tmp) + (($nr << 8) & 0xFFFFFFFF);
  18. $nr2 += (($nr2 << 8) & 0xFFFFFFFF) ^ $nr;
  19. $add += $tmp;
  20. }
  21. $out_a = $nr & ((1 << 31) - 1);
  22. $out_b = $nr2 & ((1 << 31) - 1);
  23. $output = sprintf("%08x%08x",$out_a,$out_b);
  24. if ($hex) return $output;
  25. return hex_hash_to_bin($output);
  26. } //END function MysqL_old_password_hash
  27.  
  28. /**
  29. * MysqL "PASSWORD()" AKA MysqLSHA1 HASH FUNCTION
  30. * This is the password hashing function used in MysqL since version 4.1.1
  31. * By Rev. Dustin Fineout 10/9/2009 9:36:20 AM
  32. **/
  33. function MysqL_password_hash($input,$hex = true)
  34. {
  35. $sha1_stage1 = sha1($input,true);
  36. $output = sha1($sha1_stage1,!$hex);
  37. return $output;
  38. } //END function MysqL_password_hash
  39.  
  40. /**
  41. * Computes each hexidecimal pair into the corresponding binary octet.
  42. * Similar to MysqL hex2octet function.
  43. **/
  44. function hex_hash_to_bin($hex)
  45. {
  46. $bin = "";
  47. $len = strlen($hex);
  48. for ($i = 0; $i < $len; $i += 2) {
  49. $byte_hex = substr($hex,2);
  50. $byte_dec = hexdec($byte_hex);
  51. $byte_char = chr($byte_dec);
  52. $bin .= $byte_char;
  53. }
  54. return $bin;
  55. } //END function hex_hash_to_bin

希望别人会发现这个有用的:)

猜你在找的PHP相关文章