Settings file returns escaped string

隐身守侯 提交于 2019-12-12 04:01:31

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!