C#相当于PHP中的hash_hmac

Phi*_*ppe 25 c# hmac sha512

使用.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());
Run Code Online (Sandbox Code Playgroud)

但它与PHP hash_hmac()PHP代码不匹配:

$hmac = strtoupper(hash_hmac($pbx_hash, $msg, $binKey));
Run Code Online (Sandbox Code Playgroud)

我尝试用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);
}    
Run Code Online (Sandbox Code Playgroud)

经过多次发布后,我发现如果PHP hash_hmac键是一个字符串,而不是一个字节数组,我会得到相同的结果.似乎问题出在PHP转换函数$ binKey = pack("H*",$ keyTest);

seh*_*ehe 33

问题必须是密钥/消息数据的实际表示.

请参阅以下测试:

PHP

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

输出(通过http://writecodeonline.com/php/直播):

6E9EF29B75FFFC5B7ABAE527D58FDADB2FE42E7219011976917343065F58ED4A
Run Code Online (Sandbox Code Playgroud)

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;
    }    
}
Run Code Online (Sandbox Code Playgroud)

输出(通过http://ideone.com/JdpeL直播):

Result: 6E9EF29B75FFFC5B7ABAE527D58FDADB2FE42E7219011976917343065F58ED4A
Run Code Online (Sandbox Code Playgroud)

因此,检查PHP输入数据的字符集/编码.还要检查实际算法(in $pbx_hash).


Mic*_*rne 14

    private static string HashHmac(string message, string secret)
    {
        Encoding encoding = Encoding.UTF8;
        using (HMACSHA512 hmac = new HMACSHA512(encoding.GetBytes(secret)))
        {
            var msg = encoding.GetBytes(message);
            var hash = hmac.ComputeHash(msg);
            return BitConverter.ToString(hash).ToLower().Replace("-", string.Empty);
        }
    }
Run Code Online (Sandbox Code Playgroud)

  • 许多API都希望使用base64版本的哈希,您可以通过将现有的“ return ...”行替换为return Convert.ToBase64String(hash)来获取此哈希。 (2认同)
  • 您能解释一下为什么需要.Replace(“-”,string.Empty)吗? (2认同)