试图将C#函数移植到PHP5

我正在尝试将此函数转换为PHP但不知何故它不会给出相同的结果。

public static string EncodePassword(string pass, string salt) { byte[] bytes = Encoding.Unicode.GetBytes(pass); byte[] src = Convert.FromBase64String(salt); byte[] dst = new byte[src.Length + bytes.Length]; byte[] inArray = null; Buffer.BlockCopy(src, 0, dst, 0, src.Length); Buffer.BlockCopy(bytes, 0, dst, src.Length, bytes.Length); HashAlgorithm algorithm = HashAlgorithm.Create("SHA1"); inArray = algorithm.ComputeHash(dst); return Convert.ToBase64String(inArray); } 

这是我在PHP中的看法

 function CreatePasswordHash($password, $salt) { $salted_password = base64_decode($salt).$password; $result = hash('SHA1',$salted_password,true); return base64_encode($result); } 

当然它不起作用。 那么我在这里做错了什么?

这些是测试的值:

 $salt = 'Xh2pHwDv3VEUQCvz5qOm7w=='; $hashed_value = '0U/kYMz3yCXLsw/r9kocT5zf0cc='; $password = 'Welcome1!'; if ($hashed_value === CreatePasswordHash($password,$salt)) { echo "Good job!"; } 

编辑:基于Martyx和Slacks的建议的工作解决方案

 function CreatePasswordHash($password, $salt) { $upass = mb_convert_encoding($password,'UCS-2LE','auto'); $salted_password = base64_decode($salt).$upass; $result = hash('SHA1',$salted_password,true); return base64_encode($result); } 

一旦我在PHP和C#中使用SHA1,在C#输出字母是大写的,在PHP中它是小写的。

我建议在C#和PHP中使用相同的编码(UTF8和UTF16是不错的选择)。

C#中的选择:

  • Encoding.ASCII.GetBytes
  • Encoding.UTF8.GetBytes

编码PHP:

  • mb_convert_encoding

您需要告诉PHP使用UTF16编码密码字符串,并将salt编码为原始字节。