PHP SHA1 的编码方式与 C# 不同


php sha1 encodes differently to c#

我知道这是一个 c# 和 php 编码 sha1 哈希的不同方式的 poroblem,但我无法找到 c# sha1 的 php 版本的示例。

C# 代码:

  private string GetHashedKey(string supplierPrivateKey, DateTime now)
   {
  if (string.IsNullOrEmpty(supplierPrivateKey))
    return "";
  supplierPrivateKey += now.ToString("yyyy/MM/dd HH:mm:ss");
  Encoding enc = Encoding.UTF8;
  byte[] buffer = enc.GetBytes(supplierPrivateKey);
  SHA1CryptoServiceProvider cryptoTransformSha1 =
  new SHA1CryptoServiceProvider();
  string hash = BitConverter.ToString(
  cryptoTransformSha1.ComputeHash(buffer)).Replace("-", "");
  return hash;
   }

.php:

 $hashedSupplierPrivateKey = $supplierPrivateKey.gmdate("Y/m/d H:i:s");

  $hashedSupplierPrivateKey = utf8_encode($hashedSupplierPrivateKey);
  $hashedSupplierPrivateKey = sha1($hashedSupplierPrivateKey,true);
    //Error here
     $hashedSupplierPrivateKey = str_replace("-", "", $hashedSupplierPrivateKey);
     $hashedSupplierPrivateKey = strtoupper($hashedSupplierPrivateKey);
     echo $hashedSupplierPrivateKey;

下面是在 c# 中生成的正确哈希的示例

      530DFA9CD08CF36017B7C781E1A8D0CEC74CB944

我认为你在 c# 中得到原始字节,而在 php sha1() 中默认返回十六进制。您可以将 true 作为第二个参数传递给 php 的 sha1() 以获取原始字节。或者在 c# 中转换为十六进制。