设置文件返回转义字符串 [英] Settings file returns escaped string

查看:73
本文介绍了设置文件返回转义字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用项目中的设置文件存储加密密码.使用的加密是 md5,直到保存散列的所有内容都可以正常工作.当我查看 app.config 时,我也可以在那里看到正确的哈希值.然而,当检索散列时,字符串的字符被转义,这使得无法进行比较

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);

为了测试,我输入了文本Test",它生成\f?f?T\v???8??Za["

For testing I put in the text "Test" which generates "\f?f?T\v???8??Za["

从设置文件中检索密码时,我得到\\f?f?T\\v???8??Za["

When retreiving the password from the settings file I get "\\f?f?T\\v???8??Za["

如何解决这个问题?

推荐答案

首先,不要那样做.从ComputeHash 返回的数据不是 ASCII 编码的文本,因此您不应该调用Encoding.ASCII.GetString(data).首选 Convert.ToBase64String(data) - 也更喜欢使用 Encoding.UTF8.GetBytes(password) 进行散列,否则您将丢失非 ASCII 密码的数据.

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.

其次,我怀疑数据在您检索时并未真正被转义 - 我的猜测是您正在 Visual Studio 调试器中查看它,就是 添加转义,而不是出现在实际字符串中.检查 md5Hash.ToCharArray() 的结果,一次查看一个字符.

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.

第三,使用比 MD5 更好的哈希作为密码:)

Thirdly, use a better hash than MD5 for passwords :)

这篇关于设置文件返回转义字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆