34

.NET と C# を使用して、HMAC SHA512 を使用して整合性文字列を PHP サーバーに提供する必要があります。C# での使用:

Encoding encoding = Encoding.UTF8;
byte[] keyByte = encoding.GetBytes(key);
HMACSHA512 hmacsha512 = new HMACSHA512(keyByte);
byte[] messageBytes = encoding.GetBytes(message);
byte[]  hashmessage = hmacsha512.ComputeHash(messageBytes);
return(ByteToString(hashmessage).toUpper());

しかし、PHP の hash_hmac() PHP コードとは一致しません:

$hmac = strtoupper(hash_hmac($pbx_hash, $msg, $binKey));

C# (utf8、ASCII、Unicode) でエンコーディングを変更しようとしましたが、成功しませんでした。

私はネット上で見つけた多くの解決策を試しましたが、同じ文字列を与えるものはありません:(

PHP コードを変更できず、C# の何が問題なのかわかりません

編集これはByteToString(コメントからコピーされた)です:

static string ByteToString(byte[] buff)
{
    string sbinary = "";
    for (int i = 0; i < buff.Length; i++)
    {
        sbinary += buff[i].ToString("X2"); /* hex format */
    }
    return (sbinary);
}    

多くのテストの後、PHP hash_hmac キーがバイト Array ではなく文字列である場合、同じ結果が得られることがわかりました。問題は PHP の変換関数 $binKey = pack("H*", $keyTest); にあるようです。

4

3 に答える 3

42

問題は、キー/メッセージ データの実際の表現である必要があります。

次のテストを参照してください。

PHP

#!/usr/bin/php
<?php
print strtoupper(hash_hmac("sha256", "message", "key"));
?>

出力 ( http://writecodeonline.com/php/経由でライブ):

6E9EF29B75FFFC5B7ABAE527D58FDADB2FE42E7219011976917343065F58ED4A

C#

using System;
using System.Text;
using System.Security.Cryptography;

public class Program
{
    private const string key = "key";
    private const string message = "message";
    private static readonly Encoding encoding = Encoding.UTF8; 

    static void Main(string[] args)
    {
        var keyByte = encoding.GetBytes(key);
        using (var hmacsha256 = new HMACSHA256(keyByte))
        {
            hmacsha256.ComputeHash(encoding.GetBytes(message));

            Console.WriteLine("Result: {0}", ByteToString(hmacsha256.Hash));
        }
    }
    static string ByteToString(byte[] buff)
    {
        string sbinary = "";
        for (int i = 0; i < buff.Length; i++)
            sbinary += buff[i].ToString("X2"); /* hex format */
        return sbinary;
    }    
}

出力 ( http://ideone.com/JdpeL経由でライブ):

Result: 6E9EF29B75FFFC5B7ABAE527D58FDADB2FE42E7219011976917343065F58ED4A

そのため、PHP 入力データの文字セット/エンコードを確認してください。実際のアルゴリズムも確認してください ( を$pbx_hash参照)。

于 2012-10-09T16:26:39.717 に答える
4

上で述べたように、問題はPHP Pack(キーをバイト配列に変換するために使用されるH *関数。C#Getbytesは同じ結果(utf8、asci、unicode ...)を提供しません。解決策はここにあります:http:/ /www.nuronconsulting.com/c-pack-h.aspxは私にとっては大丈夫でした。C#のHMACがPHPと一致するようになりました。

public static byte[] PackH(string hex)
{
       if ((hex.Length % 2) == 1) hex += '0';
       byte[] bytes = new byte[hex.Length / 2];
       for (int i = 0; i < hex.Length; i += 2)
       {
             bytes[i / 2] = Convert.ToByte(hex.Substring(i, 2), 16);
       }
 return bytes;
}

マヌーはあなたの助けに感謝します。

于 2012-10-10T12:00:42.290 に答える