C#中的等效PHP sha1,原始二进制格式,长度为20

时间:2012-08-06 04:43:10

标签: c# php sha1

  

可能重复:
  C# SHA-1 vs. PHP SHA-1…Different Results?

我试图找出C#中PHP sha1(string,true);等效方法的含义。我尝试了很多搜索并尝试编写一些代码,但找不到任何解决方案。任何人都可以告诉我如何以行二进制格式获取长度为20的sha1,如PHP函数:SHA1 in the PHP manual

在PHP中:

sha1($sampletext, true);

在C#中:

string sampletext= "text";
SHA1 hash = SHA1CryptoServiceProvider.Create();
byte[] plainTextBytes = Encoding.ASCII.GetBytes(dataString);
byte[] hashBytes = hash.ComputeHash(plainTextBytes);

两者都返回不同的输出。

由于

1 个答案:

答案 0 :(得分:2)

This IDEOne test似乎产生与在C#中使用UTF-8编码相同的输出:

string sampletext = "text";
System.Security.Cryptography.SHA1 hash = System.Security.Cryptography.SHA1CryptoServiceProvider.Create();
byte[] plainTextBytes = Encoding.UTF8.GetBytes(sampletext);
byte[] hashBytes = hash.ComputeHash(plainTextBytes);

foreach (byte b in hashBytes) {
    Console.Write(string.Format("{0:x2}", b));
}

这将取决于PHP如何处理它,这将是特定于平台的。它甚至可能是某些文档中的ASCII。这与字符编码有关。