问题
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?
回答1:
Firstly, don't do that. The data returned from ComputeHash
isn't ASCII-encoded text, so you shouldn't be calling Encoding.ASCII.GetString(data)
. Prefer Convert.ToBase64String(data)
- and also prefer hashing using Encoding.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 :)
来源:https://stackoverflow.com/questions/8756946/settings-file-returns-escaped-string