Skip to main content
 首页 » 编程设计

c#之尝试将 C# 函数移植到 PHP5

2024年02月24日28over140

我正在尝试将此函数转换为 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# 中的选择:

  • 编码.ASCII.GetBytes
  • 编码.UTF8.GetBytes
  • ...

PHP 编码: