.NET 和 MySQL 中 SHA1 的差异
我有一些不同的代码,但简单来说,我使用 SHA1 将一些密码插入 MySQL 数据库,并将 SHA1 哈希值计算到 .NET 中,但它们不匹配。我认为这是我在 .NET 中的编码代码的问题。
SQL 代码:
INSERT INTO user_credentials (Password) VALUES (SHA1('password'));
密码哈希为 5baa61e4c9b93f3f0682250b6cf8331b7ee68fd8
.NET 代码:
public static string GetPasswordHash(string password)
{
// problem here with encoding?
byte[] byteArray = Encoding.ASCII.GetBytes(password);
SHA1 sha = new SHA1CryptoServiceProvider();
byte[] hashedPasswordBytes = sha.ComputeHash(byteArray);
return Encoding.ASCII.GetString(hashedPasswordBytes);
}
密码哈希为 [?a??????%l?3~???
感谢您的帮助!
I have a couple different bits of code but the short story is I insert some passwords into a MySQL database using SHA1 and also compute SHA1 hashes into .NET and they are not matching. I think this is a problem with my encoding code in .NET.
SQL Code:
INSERT INTO user_credentials (Password) VALUES (SHA1('password'));
password hashes to 5baa61e4c9b93f3f0682250b6cf8331b7ee68fd8
.NET Code:
public static string GetPasswordHash(string password)
{
// problem here with encoding?
byte[] byteArray = Encoding.ASCII.GetBytes(password);
SHA1 sha = new SHA1CryptoServiceProvider();
byte[] hashedPasswordBytes = sha.ComputeHash(byteArray);
return Encoding.ASCII.GetString(hashedPasswordBytes);
}
password hashes to [?a??????%l?3~???
Thanks for any help!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
在 MySQL 示例中,您编码为 十六进制 字符串,在 .NET 示例中,您编码为ASCII。两个编码不一样。
如果在 .NET 版本中转换为十六进制,您将得到正确的结果:
结果:
In the MySQL example you are encoding to a hexadecimal string, in the .NET example you are encoding in ASCII. The two encodings are not the same.
If you convert to hexadecimal in the .NET version you get the correct result:
Result:
您需要将
[?a??????%l?3~???
放入 HEX 表示形式中。您打印的内容可能是二进制形式(因此有多个?
字符)。尝试这样做:
并查看
hexstring
和 MySQL 哈希是否匹配。You need to put
[?a??????%l?3~???
in HEX representation. What you are printing is probably in binary form (hence the multiple?
chars).Try doing this:
And see if
hexstring
and MySQL hash match.以下内容将为您提供与 MySQL 生成的内容完全匹配的内容:
The following will give you an exact match to what MySQL produces:
SHA1 哈希值应该相等,但表示形式却不相等。 MySql 输出一个十六进制字符串,因此您需要在 .NET 中执行相同的操作:
The SHA1 hashes should be equal, but the representation is not. MySql outputs a hex-string, so you will need to do the same in .NET:
您的 MySQL 表/数据库是如何编码的?尝试将两者都设置为UTF-8(因此使用Encoding.UTF8.GetBytes)
How is your MySQL table/database encoded? Try setting both to UTF-8 (therefore using Encoding.UTF8.GetBytes)