So I'm rather new to programming (C#) and especially cryptography in general. I tried learning some by copying a couple of functions using the MD5 hashing algorithm and learning how it works. I then connected to a database and made a log in and reset password feature. However, the problem appeared when i tried making the same password, i realised the hashing value would turn out the same regardless of me adding a randomly generated salt into the hash value.
string MD5(string input)
{
MD5 md5 = new MD5CryptoServiceProvider();
byte[] bytes = md5.ComputeHash(Encoding.Unicode.GetBytes(input));
string result = BitConverter.ToString(bytes).Replace("-", String.Empty);
return result.ToLower();
}
public static byte[] GenerateSalt()
{
RNGCryptoServiceProvider saltGenerator = new RNGCryptoServiceProvider();
byte[] salt = new byte[24];
saltGenerator.GetBytes(salt);
return salt;
}
So this are my functions for generating salt and hashing an input string. This is the code for resetting passwords by filling out two textboxes in WinForms.
private void HashNewPassword(out byte[] salt, out string hashedPassword)
{
string tempHash;
salt = null;
hashedPassword = null;
if (txtPassword1.Text == txtPassword2.Text)
{
tempHash = txtPassword1.Text;
salt = GenerateSalt();
hashedPassword = MD5(MD5(tempHash + salt));
}
else
{
throw new Exception();
}
}
Lastly, the click-even function:
private void btnFinished_Click(object sender, EventArgs e)
{
try
{
string hashedPassword;
byte[] salt;
HashNewPassword(out salt, out hashedPassword);
AddPasswordToDB(salt, hashedPassword);
}
catch (Exception error)
{
MessageBox.Show(error.Message + " : " + error.GetType().ToString());
}
}
As you can see below, the hash value is the same, but the salt differs. Am I adding the salt in a way I should not?
bec78d2acfd2eb4f5d7da2fd231bad1c 0x21B5F48096E31092FCCD20EE22EF9B3C307ADDC1C31B8D84
bec78d2acfd2eb4f5d7da2fd231bad1c 0xC063774EBBD4FAED268811C84D70662F4DDB53BCA52A6720
Is there a logical explanation to this, or is there something wrong with the code? Also, I am not familiar with hashing algorithms, just something I stumbled across and wanted to learn more about. Is there an easier way of doing this? I have read about other algorithms that seems easy enough to use, but as I stated, I am not familiar with this. Security differences between hash algorithms is irrelevant. I did read MD5 was old and not that secure, however it's more than enough for my use.
Thanks in advance.