I am storing an encrypted password using the Settings file in the project. The encryption used is md5, everything up to saving the hash works just fine. When I look in the app.config I can see the correct hash there too. However when retreiving the hash the string has it’s characters escaped which makes a comparison not possible
This is the code I use to generate the hash
System.Security.Cryptography.MD5CryptoServiceProvider x = new System.Security.Cryptography.MD5CryptoServiceProvider();
byte[] data = System.Text.Encoding.ASCII.GetBytes(password);
data = x.ComputeHash(data);
String md5Hash = System.Text.Encoding.ASCII.GetString(data);
For testing I put in the text “Test” which generates “\f?f?T\v???8??Za[“
When retreiving the password from the settings file I get “\\f?f?T\\v???8??Za[“
How to get around this problem?
Firstly, don’t do that. The data returned from
ComputeHashisn’t ASCII-encoded text, so you shouldn’t be callingEncoding.ASCII.GetString(data). PreferConvert.ToBase64String(data)– and also prefer hashing usingEncoding.UTF8.GetBytes(password), as otherwise you’ll lose data for non-ASCII passwords.Secondly, I suspect that the data isn’t really being escaped when you retrieve it – my guess is that you’re looking at it in the Visual Studio debugger, and that’s adding the escaping, rather than it being present in the actual string. Examine the result of
md5Hash.ToCharArray()to see it one character at a time.Thirdly, use a better hash than MD5 for passwords 🙂