问题描述
我正在尝试从字符串计算 SHA-1 哈希,但是当我使用 php 的 sha1 函数计算字符串时,我得到的结果与我在 C# 中尝试时不同.我需要 C# 来计算与 PHP 相同的字符串(因为来自 php 的字符串是由我无法修改的第 3 方计算的).如何让 C# 生成与 PHP 相同的哈希?谢谢!!!
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!!!
字符串 = s934kladfklada@a.com
String = s934kladfklada@a.com
C# 代码(生成 d32954053ee93985f5c3ca2583145668bb7ade86)
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 代码(生成 a9410edeaf75222d7b576c1b23ca0a9af0dffa98)
PHP Code (Generates a9410edeaf75222d7b576c1b23ca0a9af0dffa98)
sha1();
推荐答案
使用 ASCIIEncoding 而不是 UnicodeEncoding.PHP 使用 ASCII 字符集进行哈希计算.
Use ASCIIEncoding instead of UnicodeEncoding. PHP uses ASCII charset for hash calculations.
这篇关于C# SHA-1 与 PHP SHA-1 ...不同的结果?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!