MD5密码检查总是返回false?
问题描述:
我有以下的代码要检查用户输入的密码的MD5加密密码:MD5密码检查总是返回false?
UserDAO userDAO = new UserDAO();
// encrypt the input password
MD5 md5 = new MD5CryptoServiceProvider();
UTF8Encoding encoder = new UTF8Encoding();
Byte[] encryptedPassword;
encryptedPassword = md5.ComputeHash(encoder.GetBytes(TxtBoxPassword.Text));
// get information for this username and begin checking authentication
DataTable data = userDAO.GetUserInformation(TxtBoxUsername.Text);
if (data.Rows.Count == 0)
{
LblError.Text = "Wrong username!";
return;
}
Byte[] password = (Byte[])data.Rows[0]["Password"];
if (!Convert.ToBase64String(password).Equals(Convert.ToBase64String(encryptedPassword)))
{
LblError.Text = "Wrong password!";
return;
}
是我,而当我发表我的网站我的电脑(管理/ 123456正确验证)上运行该代码就好了问题到服务器,检查总是返回“错误的密码”?是什么赋予了?
答
不知道你为什么不工作,但是当我在下面编写SHA512实现时,我有一些散列问题。它不像你通常看到它显示给人类那样输出。出于这个原因,你的数据类型在数据库中应该是二进制的。另外这里是我使用的实现(使用改变的盐),使用SHA512。使用ByteArrayToHexString将其置于人类可识别的格式。然后你可以在数据库中使用varchar。
/// <summary>
/// Takes a string as input, SHA512 hashes it, and returns the hexadecimal representation of the hash as a string.
/// </summary>
/// <param name="toHash">string to be hashed</param>
/// <returns>hexadecimal representation of the hash as a string</returns>
private string GetHash(string toHash)
{
/* As of this writing, both the –Cng and –CryptoServiceProvider implementation classes are FIPS-certified,
* but –Managed classes are not. http://msdn.microsoft.com/en-us/magazine/ee321570.aspx
*/
// Salt the string
toHash = "%my" + toHash.Insert(Convert.ToInt16(toHash.Length/2), "!secret") + ".sauce#";
SHA512CryptoServiceProvider hasher = new SHA512CryptoServiceProvider();
byte[] hashBytes = hasher.ComputeHash(Encoding.Unicode.GetBytes(toHash));
hasher.Clear();
return ByteArrayToHexString(hashBytes);
}
/// <summary>
/// Takes a byte[] and converts it to its string hexadecimal representation
/// </summary>
/// <param name="ba">Array of bytes[] to convert</param>
/// <returns>string, hexadecimal representation of input byte[]</returns>
private string ByteArrayToHexString(byte[] ba)
{
StringBuilder hex = new StringBuilder(ba.Length * 2);
foreach (byte b in ba)
hex.AppendFormat("{0:x2}", b);
return hex.ToString();
}
答
字节[]是在数据库中消失?你可以记录哈希进入数据库并记录它,当你在这里获取它,看看它们是否相等?
另外,请注意,MD5被认为是弱的,而且你没有腌制密码。如果发生数据泄露,这很容易导致账户被入侵。考虑使用SHA1和随机盐。
答
UTF8密码在被散列并保存到UserDAO之前是否被UTF8密码保存?