我正在尝试使用登录名和密码凭据创建一个身份验证服务器,并使用this tutorial为我提供了以下PasswordHash
类。当我将Verify
方法与字符串一起使用但我不希望通过UDP发送未加密的密码时出于安全原因,但是当我通过向字节数组输入它直接测试哈希值时它返回false(如图所示)在课堂下面。)
public sealed class PasswordHash
{
const int SaltSize = 16, HashSize = 20, HashIter = 10000;
readonly byte[] _salt, _hash;
private PasswordHash() { }
public PasswordHash(string password)
{
new RNGCryptoServiceProvider().GetBytes(_salt = new byte[SaltSize]);
_hash = new Rfc2898DeriveBytes(password, _salt, HashIter).GetBytes(HashSize);
}
public PasswordHash(byte[] hashBytes)
{
Array.Copy(hashBytes, 0, _salt = new byte[SaltSize], 0, SaltSize);
Array.Copy(hashBytes, SaltSize, _hash = new byte[HashSize], 0, HashSize);
}
public PasswordHash(byte[] salt, byte[] hash)
{
Array.Copy(salt, 0, _salt = new byte[SaltSize], 0, SaltSize);
Array.Copy(hash, 0, _hash = new byte[HashSize], 0, HashSize);
}
public byte[] ToArray()
{
byte[] hashBytes = new byte[SaltSize + HashSize];
Array.Copy(_salt, 0, hashBytes, 0, SaltSize);
Array.Copy(_hash, 0, hashBytes, SaltSize, HashSize);
return hashBytes;
}
public byte[] Salt { get { return (byte[])_salt.Clone(); } }
public byte[] Hash { get { return (byte[])_hash.Clone(); } }
public bool Verify(string password)
{
byte[] test = new Rfc2898DeriveBytes(password, _salt, HashIter).GetBytes(HashSize);
for (int i = 0; i < HashSize; i++)
if (test[i] != _hash[i])
return false;
return true;
}
public bool Verify(byte[] passwordHash)
{
for (int i = 0; i < HashSize; i++)
if (passwordHash[i] != _hash[i])
return false;
return true;
}
}
我使用以下方法测试了它:
bool test = new PasswordHash("test123").Verify("test123"); //TRUE
bool test2 = new PasswordHash("test123").Verify(newPasswordHash("test123").ToArray()); //FALSE
正如Nissim指出的那样,它们不匹配,因为每次调用时都会随机生成盐new PasswordHash().
无论如何都要绕过添加到字节[]中的盐?
答案 0 :(得分:3)
每次调用PasswordHash的构造函数时,它都会创建一个新的salt,因此在以下示例中:
byte[] pass1 = new HashPassword("abc").ToArray();
byte[] pass2 = new HashPassword("abc").ToArray();
pass1与pass2不同