【问题标题】:C# HMACSHA256 gives different result than PHP hash_hmacC# HMACSHA256 给出的结果与 PHP hash_hmac 不同
【发布时间】:2020-12-10 22:18:30
【问题描述】:

我在 php 中有以下代码: demo

function generateHash($hashSecret,$postData) {
    ksort($postData);

        $message="";
        $appendAmp=0;
    foreach($postData as $key => $value) {
            if (strlen($value) > 0) {
                if ($appendAmp == 0) {
                    $message .= $key . '=' . $value;
                    $appendAmp = 1;
                } else {
                    $message .= '&' . $key . "=" . $value;
                }
            }
        }

    $secret = pack('H*', $hashSecret);

    return hash_hmac('sha256', $message, $secret);
}

$postData = array(
    "cardNum" =>  "5123456789012346",
    "cardExp" =>  2105,
    "cardCVC" =>  123,
    "holderName" => "John Doe",
    "mobileNumber" => "20100000000000"
);

$secureHash= 'C0DF9A7B3819968807A9D4E48D0E65C6';

$hashSecret = generateHash($secureHash,$postData);

echo $hashSecret;

//输出6975f8f502e5972722a6d8760cc558e7867f36a312a5d336c4ba983dcfb81691 //以及c#中的demo

public static void Main()
{
    Console.Write(CreateToken("cardCVC=123&cardExp=2105&cardNum=5123456789012346&holderName=John Doe&mobileNumber=20100000000000","C0DF9A7B3819968807A9D4E48D0E65C6"));
}

 private static string CreateToken(string message, string secret)
{
  var encoding = new System.Text.UTF8Encoding();
  byte[] keyByte = encoding.GetBytes(secret);
  byte[] messageBytes = encoding.GetBytes(message);
  using (var hmacsha256 = new HMACSHA256(keyByte))
  {
    byte[] hashmessage = hmacsha256.ComputeHash(messageBytes);
    return BitConverter.ToString(hashmessage).Replace("-","");
  }
}

//输出:26FFE2E29513304F96D444CB69210657B4E44E837B7C8E8947C667B344594F18 演示 我需要修改我的 c# 代码以匹配从 php 生成的值

更新:我尝试了在线 sha 生成器,它给出了我的 c# 结果

【问题讨论】:

  • 你对比过你使用的字节数组(表示数据和键)吗?
  • 不,我不懂php

标签: c# php .net security sha


【解决方案1】:

经过多次试验,我发现 PHP pack('H*', $hashSecret) 导致结果不同,所以我添加了以下方法:

public static byte[] Pack(string key)
{
    key = key.Replace("-", "");
    byte[] raw = new byte[key.Length / 2];
    for (int i = 0; i < raw.Length; i++)
    {
        raw[i] = Convert.ToByte(key.Substring(i * 2, 2), 16);
    }
    return raw;
}

【讨论】:

猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多