C#相当于PHP hash_hmac [英] C# equivalent to hash_hmac in PHP
问题描述
使用.NET和C#我需要提供使用HMAC SHA512到PHP服务器完整性字符串。
使用C#中:
using .NET and C# i need to provide an integrity string using HMAC SHA512 to a PHP server . Using in 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 code:
But it doesn't match with PHP hash_hmac() PHP code :
$hmac = strtoupper(hash_hmac($pbx_hash, $msg, $binKey));
我试图改变在C#(UTF8,ASCII,统一code)编码没有成功。
I try to change encoding in C# (utf8, ASCII,Unicode) Without success.
我试着在网上发现了许多解决方案,但没有给出相同的字符串:(
I've tried many solution found on the net but nothing give the same string :(
我无法改变的PHP code,并没有看到什么在C#中是错误的。
I can't change the PHP code, and doesn't see what's wrong in C#
修改这是 ByteToString
(从评论复制):
Edit This is ByteToString
(copied from the comment):
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键是一个字符串,而不是字节数组。看来,问题出在PHP转换功能$ binKey =包(H *,$ keyTest);
After many tets, in found that i get the same results if PHP hash_hmac key is a string, not a byte Array . Seems that the problem is with the PHP convert function $binKey = pack("H*", $keyTest);
推荐答案
这个问题必须是键/消息数据的实际重presentation。
The problem must be the actual representation of the key/message data.
请参阅以下测试:
#!/usr/bin/php
<?php
print strtoupper(hash_hmac("sha256", "message", "key"));
?>
输出(通过活 HTTP://write$c$conline.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
)。
这篇关于C#相当于PHP hash_hmac的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!