Reputation: 2301
I'm attempting to store a user's password in my program, but I don't want to store it in plain text. Therefore, I'm hashing it and storing that instead, and when the user needs to enter his password upon the program start (to protect against unauthorized users), I'm hashing the entered password and comparing the two hashes.
However, the following code is generating the same hash for almost any password entered. Can anyone either tell me how to fix the following code, or direct me to a better hash function?
public static string getSHA1(string userPassword)
{
return BitConverter.ToString(SHA1Managed.Create().ComputeHash(Encoding.Default.GetBytes(userPassword))).Replace("-", "");
}
Thanks for any assistance.
Upvotes: 1
Views: 1957
Reputation: 2141
Use somehting like this
private static string GetSHA1(string text)
{
UnicodeEncoding UE = new UnicodeEncoding();
byte[] hashValue;
byte[] message = UE.GetBytes(text);
SHA1Managed hashString = new SHA1Managed();
string hex = "";
hashValue = hashString.ComputeHash(message);
foreach (byte x in hashValue)
{
hex += String.Format("{0:x2}", x);
}
return hex;
}
Upvotes: 1
Reputation: 10102
I plugged your function into a new project and it seemed to be working OK, so check how the password is being supplied to the function. I'd be wary of using Encoding.Default
instead of an explicit coding, as it says it's system-dependent.
Here's the one I made:
public static string getSHA1(string userPassword)
{
return Convert.ToBase64String(new SHA1Managed().ComputeHash(Encoding.Unicode.GetBytes(userPassword)));
}
Note: as pointed out in the comments, doing password storage/matching this way is bad:
Upvotes: 0