所以,我發現一個問題就像這個接受的答案,所以我跳了下去,並試圖實施必要的更改。由於某種原因,我仍然得到兩個不同的字符串,我不知道我做錯了什麼。我試圖對接受的答案發表評論以尋求幫助,但我缺乏這樣做的聲譽。所以,我想我會再次提出這個問題(這個問題也是2歲)。PHP和C#SHA256散列返回不同的字符串
讓我解釋我在做什麼。
在PHP ...
$intermediatesalt = md5(uniqid(rand(), true));
$salt = substr($intermediatesalt, 0, 8);
$hashpassword = base64_encode(
hash('sha256', $salt . hash('sha256', $password), true)
);
,上面寫着$ hashpassword是從這個問題的答案接受所採取的路線。我沒有寫任何這個PHP,我的朋友做了。我只知道編程來改變代碼,但我無法在php中創建任何東西,更不用說HTML。
哈希創建完成後,哈希和salt都存儲在數據庫中。
我使用的C#方法也來自我在這裏找到的答案。
public static string ComputeHash(string plainText, string salt)
{
// Convert plain text into a byte array.
byte[] plainTextBytes = Encoding.UTF8.GetBytes(plainText);
byte[] saltBytes = Encoding.UTF8.GetBytes(salt);
SHA256Managed hash = new SHA256Managed();
// Compute hash value of salt.
byte[] plainHash = hash.ComputeHash(plainTextBytes);
byte[] concat = new byte[plainHash.Length + saltBytes.Length];
System.Buffer.BlockCopy(saltBytes, 0, concat, 0, saltBytes.Length);
System.Buffer.BlockCopy(plainHash, 0, concat, saltBytes.Length, plainHash.Length);
byte[] tHashBytes = hash.ComputeHash(concat);
// Convert result into a base64-encoded string.
string hashValue = Convert.ToBase64String(tHashBytes);
// Return the result.
return hashValue;
}
但對於一些奇怪的原因,儘管誰問這個問題的人得到了他/她想要的,我仍然得到一個令人失望的結果。
這是加載播放器數據的代碼塊,然後將php生成的哈希密碼與c#生成的哈希密碼進行比較。
// load the player based on the given email
PlayerStructure.Player newPlayer = MySQL.loadPlayer(email);
// compute a hash based on the given password and the retrieved salt
// then, compare it to the hashed password on the database
string hPassword = Program.ComputeHash(password, newPlayer.salt);
if (newPlayer.password != hPassword)
{
sendStatusMsg(index, "Invalid password.");
sendStatusMsg(index, "1: " + hPassword);
sendStatusMsg(index, "2: " + newPlayer.password);
return;
}
MySQL.loadPlayer加載哈希串並從數據庫中鹽字符串,我不得不使用那些sendStatusMessage的方法來打印字符串,因爲這是一個服務器應用程序,最多需要15分鐘,從加載數據數據庫處於調試模式。所以我運行調試exe,而不是使用Console.WriteLine調用。 newPlayer.password是存儲在數據庫中的散列密碼(使用php創建的密碼)。 hPassword是使用我借用的C#方法計算出來的哈希值。
鹽是e0071fa9,明文密碼是'test'。
這是結果,我與sendStatusMsg方法獲得:
Invalid password.
1: 3QQyVEfmBN4kJJHsRQ307TCDYxNMpc4k3r3udBaVz8Y=
2: moHRVv9C0JvpdTk28xGm3uvPPuhatK2rAHXd5he4ZJI=
任何想法,我可能會錯誤地做什麼?正如我以前所說的,我的確在這裏使用了答案(幾乎是逐字地借用代碼),而且我仍然沒有得到我想要的結果。這是我引用的問題:Why isn't my PHP SHA256 hash equivalent to C# SHA256Managed hash
不要創建yourownpassword散列方法。取而代之的是使用一個函數,例如'PBKDF2','Rfc2898DeriveBytes','password_hash','Bcrypt'或類似的函數,CPU時間約爲100ms。關鍵是要讓攻擊者花費大量時間通過強力查找密碼。強制性的:[「Schneier's Law」](https://www.schneier.com/blog/archives/2011/04/schneiers_law.html):任何人,從最無知的業餘愛好者到最好的密碼學家,都可以創建一個算法,他自己不能打破。 – zaph