将 C# sha256 哈希转换为 PHP 等效项


Convert C# sha256 hashing to PHP equivalent

我需要将一些C#代码转换为等效于PHP的PHP,以便使用SOAP Web API。他们所有的示例都是用 C# 编写的。我想我有等效的 PHP 函数,但我的 SOAP 请求返回"错误请求"或"未经授权 - 无效的 API 密钥" - 而 API 页面上的示例页面使用我的密钥,并且请求 URL 看起来相同没有正在传递的摘要消息。API 和客户端 ID 绝对正确。

下面是 C# 代码:

private string GenerateDigest(long currentTime)
    {
        SHA256Managed hashString = new SHA256Managed();
        StringBuilder hex = new StringBuilder();
        byte[] hashValue = hashString.ComputeHash(Encoding.UTF8.GetBytes(String.Format("{0}{1}", currentTime, txtApiKey.Text)));
        foreach (byte x in hashValue)
        {
            hex.AppendFormat("{0:x2}", x);
        }
        return hex.ToString();
    }

这是我编写的 PHP 函数,用于尝试执行 C# 正在做的事情:

public static function generateDigest($api_key) {
  return hash('sha256', time() . mb_convert_encoding($api_key, 'UTF-8'));
}

我对 C# 不是很流利,所以我认为我出错的地方是它正在做十六进制的地方。追加格式()。我不确定这在 PHP 中应该是什么。最终结果是附加到 URL 以生成 SOAP 请求的哈希,如下所示:

https://payments.homeaway.com/tokens?time=1387385872013&digest=1bd70217d02ecc1398a1c90b2be733ff686b13489d9d5b1229461c8aab6e6844&clientId=[已编辑]

编辑:

下面是在 C# 中传递的当前时间变量。

// Request validation setup
TimeSpan timeSinceEpoch = DateTime.UtcNow - new DateTime(1970, 1, 1);
long currentTime = (long)timeSinceEpoch.TotalMilliseconds;
string digest = GenerateDigest(currentTime);

我在 php 代码中覆盖这个问题时遇到了同样的问题,这是我解决问题的代码:

 function generateDigest($time, $api_key) {
    $hash = hash('sha256', $time . mb_convert_encoding($api_key, 'UTF-8'), true);
    return $this->hexToStr($hash);
}
function hexToStr($string){
    //return bin2hex($string);
    $hex="";
    for ($i=0; $i < strlen($string); $i++)
    {
        if (ord($string[$i])<16)
            $hex .= "0";
        $hex .= dechex(ord($string[$i]));
    }
    return ($hex);
}

如果有人在寻找这个,答案与时间有关。PHP 的 time() 函数以秒为单位返回时间,其中 C# 中的调用返回毫秒。

因此,获得$currentTime的正确方法是

$currentTime = time() * 1000;

这已通过 API 进行了测试。