我有下面的代碼以哈希/存儲/檢索的密碼數據,但我的第一個單元測試,它失敗。散列和GetString/GetBytes會發出
我相信它的編碼引起的問題,因爲當GetBytes被調用時,它返回byte[38]
,byte[36]
當它應該是20我認爲。
我必須轉換爲字符串,因爲我將其存儲在數據庫中。
任何想法?謝謝
[Fact]
public void EncryptDecryptPasswordShouldMatch()
{
string password = "password";
string passwordKey = string.Empty;
string passwordSalt = string.Empty;
Helpers.CreatePasswordHash(password, out passwordSalt, out passwordKey);
Assert.True(Helpers.PasswordsMatch(passwordSalt, passwordKey, password));
}
public static bool PasswordsMatch(string passwordSalt, string passwordKey, string password)
{
byte[] salt = Encoding.UTF8.GetBytes(passwordSalt);
byte[] key = Encoding.UTF8.GetBytes(passwordKey);
using (var deriveBytes = new Rfc2898DeriveBytes(password, salt))
{
byte[] newKey = deriveBytes.GetBytes(20); // derive a 20-byte key
if (!newKey.SequenceEqual(key))
return false;
}
return true;
}
public static void CreatePasswordHash(string password, out string passwordSalt, out string passwordKey)
{
// specify that we want to randomly generate a 20-byte salt
using (var deriveBytes = new Rfc2898DeriveBytes(password, 20))
{
byte[] salt = deriveBytes.Salt;
byte[] key = deriveBytes.GetBytes(20); // derive a 20-byte key
passwordSalt = Encoding.UTF8.GetString(salt);
passwordKey = Encoding.UTF8.GetString(key);
}
}
使用的Base64編碼字符串二進制值,它可以處理任意字節序列。 UTF-8用於在unicode文本和字節之間進行轉換,而不是每個有效的字節序列對於UTF-8都有效。 – CodesInChaos 2013-05-02 15:51:27
謝謝你做到了 – Jon 2013-05-02 15:54:57