我有以下代码,它会记录用户输入的密码,然后将其存储在SQL Server数据库中:
Byte[] originalPassword;
Byte[] hashedPassword;
MD5CryptoServiceProvider md5Hasher = new MD5CryptoServiceProvider();
UTF8Encoding encoder = new UTF8Encoding();
originalPassword = encoder.GetBytes(passwordBox.Text);
hashedPassword = md5Hasher.ComputeHash(originalPassword);
command.Parameters.Add(new SqlParameter("Password", hashedPassword));
command.ExecuteNonQuery();
我的问题是我已经在数据库中存储了许多明文密码。我究竟是如何将它们修改为这种新的哈希格式,因为它们显示为“0xA99ED ....”?
答案 0 :(得分:2)
任何哈希函数的输出都是字节的集合,而不是文本的集合。因此,当您输入文本作为测试时,您可能正在输入该字节数组的文本转换。简单地将它在SQL中转换为二进制(16)是不正确的,您需要进行适当的转换,这是您在SQL中无法做到的。这也解释了为什么更改列的数据类型也不起作用。
当散列表示为字符串时,通常通过每个字节的十六进制值或通过字符集编码器。为了在它们之间切换,你需要确定哪一个正在使用并在代码中执行转换,而不是通过在SQL中切换数据类型
答案 1 :(得分:2)
try this out first create a Windows form with 2 buttons and 2 text boxes
1st button label Encrypt
2nd button label Validate
**--- Hashing using the MD5 class ---**
use the following code below
/// <summary>
/// take any string and encrypt it using MD5 then
/// return the encrypted data
/// </summary>
/// <param name="data">input text you will enterd to encrypt it</param>
/// <returns>return the encrypted text as hexadecimal string</returns>
private string GetMD5HashData(string data)
{
//create new instance of md5
MD5 md5 = MD5.Create();
//convert the input text to array of bytes
byte[] hashData = md5.ComputeHash(Encoding.Default.GetBytes(data));
//create new instance of StringBuilder to save hashed data
StringBuilder returnValue = new StringBuilder();
//loop for each byte and add it to StringBuilder
for (int i = 0; i < hashData.Length; i++)
{
returnValue.Append(hashData[i].ToString());
}
// return hexadecimal string
return returnValue.ToString();
}
/// <summary>
/// encrypt input text using MD5 and compare it with
/// the stored encrypted text
/// </summary>
/// <param name="inputData">input text you will enterd to encrypt it</param>
/// <param name="storedHashData">the encrypted text
/// stored on file or database ... etc</param>
/// <returns>true or false depending on input validation</returns>
private bool ValidateMD5HashData(string inputData, string storedHashData)
{
//hash input text and save it string variable
string getHashInputData = GetMD5HashData(inputData);
if (string.Compare(getHashInputData, storedHashData) == 0)
{
return true;
}
else
{
return false;
}
}
答案 2 :(得分:1)
此方法效果很好,使用LINQ从MD5哈希返回一个字符串。这适用于MailChimp API 3.0,而之前返回字节数组的代码没有。
public static string GetMd5HashData(string yourString )
{
return string.Join("", MD5.Create().ComputeHash(Encoding.ASCII.GetBytes(yourString)).Select(s => s.ToString("x2")));
}
在此处找到:http://rion.io/2013/02/23/generating-an-md5-hash-from-a-string-using-linq/
答案 3 :(得分:1)
这是使用LINQ的VB.NET版本(对于那些仍在使用VB.NET的人):
Public Function GenerateMD5(ByVal plainText As String) As String
Return String.Join("", System.Security.Cryptography.MD5.Create().ComputeHash(System.Text.Encoding.ASCII.GetBytes(plainText)).Select(Function(x) x.ToString("x2")))
End Function