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:
// The following is free for any use provided credit is given where due.
// This code comes with NO WARRANTY of any kind,including any implied warranty.

/**
 * MysqL "OLD_PASSWORD()" AKA MysqL323 HASH FUNCTION
 * This is the password hashing function used in MysqL prior to version 4.1.1
 * By Rev. Dustin Fineout 10/9/2009 9:12:16 AM
**/
function MysqL_old_password_hash($input,$hex = true)
{
  $nr = 1345345333; $add = 7; $nr2 = 0x12345671; $tmp = null;
  $inlen = strlen($input);
  for ($i = 0; $i < $inlen; $i++) {
    $byte = substr($input,$i,1);
    if ($byte == ' ' || $byte == "\t") continue;
    $tmp = ord($byte);
    $nr ^= ((($nr & 63) + $add) * $tmp) + (($nr << 8) & 0xFFFFFFFF);
    $nr2 += (($nr2 << 8) & 0xFFFFFFFF) ^ $nr;
    $add += $tmp;
  }
  $out_a = $nr & ((1 << 31) - 1);
  $out_b = $nr2 & ((1 << 31) - 1);
  $output = sprintf("%08x%08x",$out_a,$out_b);
  if ($hex) return $output;
  return hex_hash_to_bin($output);
} //END function MysqL_old_password_hash

/**
 * MysqL "PASSWORD()" AKA MysqLSHA1 HASH FUNCTION
 * This is the password hashing function used in MysqL since version 4.1.1
 * By Rev. Dustin Fineout 10/9/2009 9:36:20 AM
**/
function MysqL_password_hash($input,$hex = true)
{
  $sha1_stage1 = sha1($input,true);
  $output = sha1($sha1_stage1,!$hex);
  return $output;
} //END function MysqL_password_hash

/**
 * Computes each hexidecimal pair into the corresponding binary octet.
 * Similar to MysqL hex2octet function.
**/
function hex_hash_to_bin($hex)
{
  $bin = "";
  $len = strlen($hex);
  for ($i = 0; $i < $len; $i += 2) {
    $byte_hex = substr($hex,2);
    $byte_dec = hexdec($byte_hex);
    $byte_char = chr($byte_dec);
    $bin .= $byte_char;
  }
  return $bin;
} //END function hex_hash_to_bin

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

原文链接:https://www.f2er.com/php/140017.html

猜你在找的PHP相关文章