【发布时间】:2020-02-06 12:50:55
【问题描述】:
我有以下 php 代码,我无法编写与 php 完全相同的 c# 代码。看起来有不同的编码。我需要编写 c# 代码,以 php 代码形式给出结果
我的php代码
echo hexbin('246439589af7f1d84eb638c995687d53');
function hexbin($hexdata) {
$bindata="";
for ($i=0;$i<strlen($hexdata);$i+=2) {
echo hexdec(substr($hexdata,$i,2)) ;
$bindata.=chr(hexdec(substr($hexdata,$i,2)));
}
echo "<br>";
return $bindata;
}
输出
361005788154247241216781825620114910412583
$d9X����N�8ɕh}S
我的 C# 代码
public static void Main()
{
HexToBin("246439589af7f1d84eb638c995687d53");
}
static String HexToBin(string hexdata)
{
String bindata="";
for (int i=0;i<hexdata.Length;i+=2) {
Console.Write(Convert.ToInt64(hexdata.Substring(i,2), 16));
bindata+= Convert.ToChar(Convert.ToInt64(hexdata.Substring(i,2), 16)).ToString();
}
Console.WriteLine();
Console.WriteLine(bindata);
return bindata;
}
输出
361005788154247241216781825620114910412583
$d9X÷ñØN¶8Éh}S
我在下面的代码中计算 hash_mac,给出不同的输出
在php中
hash_hmac('SHA1','123456', hexbin('246439589af7f1d84eb638c995687d53'));
在c#中
static void hash_mac()
{
string message = "123456";
var keyByte = encoding.GetBytes(HexToBin("246439589af7f1d84eb638c995687d53"));
using (var hmacsha1 = new System.Security.Cryptography.HMACSHA1(keyByte))
{
hmacsha1.ComputeHash(encoding.GetBytes(message));
Console.WriteLine("Result: {0}", ByteToString(hmacsha1.Hash));
}
}
【问题讨论】:
-
输出是一样的,只是你的 php 输出与你的 c# 输出有不同的编码(例如,一个使用 ascii,另一个使用 utf8,或类似的东西)。如果您使用的是二进制数据,则不应将其存储在字符串中,而应将其存储在字节[]中。
-
但是在我计算hash_hmac这个函数之后,它给出了不同的结果
-
@Longoon12000 谢谢!!!! 4-5 小时寻找解决方案