[英]Taking a C# sha512 hash and compare it in php
我查看並找到了代碼來獲取PHP sha512哈希並在C#中匹配它。 我目前正在尋找一種方法來改變在C#中創建的哈希並在PHP中獲得相同的結果。 我們正在慢慢地從asp.net轉移到PHP,需要一種方法來檢查數據庫中的密碼。 這是用於生成哈希的C#代碼。
// Create a hash from a pwd and salt using sha512
public static string CreatePasswordHash(string _password, string _salt)
{
string saltAndPwd = String.Concat(_password, _salt);
SHA512 sha512 = new System.Security.Cryptography.SHA512Managed();
byte[] sha512Bytes = System.Text.Encoding.Default.GetBytes(saltAndPwd);
byte[] cryString = sha512.ComputeHash(sha512Bytes);
string hashedPwd = string.Empty;
for (int i = 0; i < cryString.Length; i++)
{
hashedPwd += cryString[i].ToString("X");
}
return hashedPwd;
}
在PHP中,我試圖讓它匹配,但它似乎只有幾個字節。
function CreatePasswordHash($_password, $_salt)
{
$saltAndPwd = $_password . $_salt;
$hashedPwd = hash('sha512', $saltAndPwd);
return strtoupper($hashedPwd);
}
當使用上面相同的鹽和密碼時,這是我得到的結果。 第一個結果來自C#,第二個結果來自PHP:
60BB73FDA3FF7A444870C6D0DBC7C6966F8D5AD632B0A02762E0283051D7C54A5F4B01571D1A5BC8C689DBC411FEB92158383A56AFC6AE6074696AF36E16
60BB73FDA3FF7A444870C6D0DBC7C609066F8D5AD632B0A02762E0283051D7C54A5F4B001571D1A5BC8C689DBC411FEB092158383A56AFC6AE6074696AF36E16
關於為什么這些不匹配的任何想法? 它是否與字節序字節順序有關?
嘗試
hashedPwd += cryString[i].ToString("X2");
編輯PHP:
function CreatePasswordHash($_password, $_salt)
{
$saltAndPwd = $_password . $_salt;
$hashedPwd = hash('sha512', $saltAndPwd);
$hex_strs = str_split($hashedPwd,2);
foreach($hex_strs as &$hex) {
$hex = preg_replace('/^0/', '', $hex);
}
$hashedPwd = implode('', $hex_strs);
return strtoupper($hashedPwd);
}
C#打印輸出不包括前導零。
更換
hashedPwd += cryString[i].ToString("X");
同
hashedPwd += cryString[i].ToString("X2");
仔細檢查您在C#和PHP中使用相同的字符編碼。 GetBytes返回不同的結果,具體取決於編碼。 System.Text.Encoding.Default取決於操作系統的本地化。
你可以嘗試open_ssl_digest
echo openssl_digest($saltAndPwd, 'sha512');
如果你有PHP> = 5.3
您還可以使用hash_algos函數查看系統中支持哪些算法。
HTH
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.