C# SHA-1 与 PHP SHA-1...结果不同?
我正在尝试从字符串计算 SHA-1 哈希值,但是当我使用 php 的 sha1 函数计算字符串时,我得到的结果与在 C# 中尝试时不同。 我需要 C# 来计算与 PHP 相同的字符串(因为来自 php 的字符串是由我无法修改的第 3 方计算的)。 如何让 C# 生成与 PHP 相同的哈希值? 谢谢!!!
String = [email protected]
C# 代码(生成 d32954053ee93985f5c3ca2583145668bb7 ade86)
string encode = secretkey + email;
UnicodeEncoding UE = new UnicodeEncoding();
byte[] HashValue, MessageBytes = UE.GetBytes(encode);
SHA1Managed SHhash = new SHA1Managed();
string strHex = "";
HashValue = SHhash.ComputeHash(MessageBytes);
foreach(byte b in HashValue) {
strHex += String.Format("{0:x2}", b);
}
PHP 代码(生成a9410edeaf75222d7b576c1b23ca0a9af0dffa98)
sha1();
I am trying to calculate a SHA-1 Hash from a string, but when I calculate the string using php's sha1 function I get something different than when I try it in C#. I need C# to calculate the same string as PHP (since the string from php is calculated by a 3rd party that I cannot modify). How can I get C# to generate the same hash as PHP? Thanks!!!
String = [email protected]
C# Code (Generates d32954053ee93985f5c3ca2583145668bb7ade86)
string encode = secretkey + email;
UnicodeEncoding UE = new UnicodeEncoding();
byte[] HashValue, MessageBytes = UE.GetBytes(encode);
SHA1Managed SHhash = new SHA1Managed();
string strHex = "";
HashValue = SHhash.ComputeHash(MessageBytes);
foreach(byte b in HashValue) {
strHex += String.Format("{0:x2}", b);
}
PHP Code (Generates a9410edeaf75222d7b576c1b23ca0a9af0dffa98)
sha1();
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
使用 ASCIIEncoding 而不是 UnicodeEncoding。 PHP 使用 ASCII 字符集进行哈希计算。
Use ASCIIEncoding instead of UnicodeEncoding. PHP uses ASCII charset for hash calculations.
.NET中的这个方法相当于php中的sha1:
This method in .NET is equivalent to sha1 in php:
我也有这个问题。 以下代码将起作用。
I had this problem also. The following code will work.
有同样的问题。 这段代码对我有用:
Had the same problem. This code worked for me:
FWIW,我在 Java 中遇到了类似的问题。 事实证明,我必须使用“UTF-8”编码在 Java 中生成与 PHP 5.3.1(在 XAMPP Vista 上运行)中生成的
sha1
函数相同的 SHA1 哈希值。FWIW, I had a similar issue in Java. It turned out that I had to use "UTF-8" encoding to produce the same SHA1 hashes in Java as the
sha1
function produces in PHP 5.3.1 (running on XAMPP Vista).尝试以下方法! 我认为它会很好用:
Try The following! I think it will work great: