Ana*_*pur 35 php c# cryptography sha1 cryptographic-hash-function
我试图从一个字符串计算一个SHA-1哈希,但是当我使用php的sha1函数计算字符串时,我得到的东西比我在C#中尝试时有所不同.我需要C#来计算与PHP相同的字符串(因为php中的字符串是由我无法修改的第三方计算的).如何让C#生成与PHP相同的哈希?谢谢!!!
String = s934kladfklada@a.com
C#代码(生成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);
}
Run Code Online (Sandbox Code Playgroud)
PHP代码(生成a9410edeaf75222d7b576c1b23ca0a9af0dffa98)
sha1();
Run Code Online (Sandbox Code Playgroud)
小智 8
.NET中的这个方法相当于php中的sha1:
string sha1Hash(string password)
{
return string.Join("", SHA1CryptoServiceProvider.Create().ComputeHash(Encoding.UTF8.GetBytes(password)).Select(x => x.ToString("x2")));
}
Run Code Online (Sandbox Code Playgroud)
我也有这个问题.以下代码将起作用.
string dataString = "string to hash";
SHA1 hash = SHA1CryptoServiceProvider.Create();
byte[] plainTextBytes = Encoding.ASCII.GetBytes(dataString);
byte[] hashBytes = hash.ComputeHash(plainTextBytes);
string localChecksum = BitConverter.ToString(hashBytes)
.Replace("-", "").ToLowerInvariant();
Run Code Online (Sandbox Code Playgroud)