我正在尝试在PHP中生成哈希,但没有获得与从代码中的c#获得的输出相同的输出,因此应使用哪种加密算法(或代码中应更改的内容)。我在PHP和c#-
中使用的代码php代码
<?php
$date = gmdate("Y-m-d H:i:s\Z");
$ServiceAPIKey = "abc";
$ServiceAPIPassword = "def";
$serviceId = "1234";
$message = $serviceId.$date;
$signature = $ServiceAPIKey.":".base64_encode(hash_hmac('sha256', $message, $ServiceAPIPassword,true));
echo $signature;
?>
c#代码
using System;
using System.Security.Cryptography;
using System.Text;
public class Program
{
public static void Main()
{
var dateString = DateTime.UtcNow.ToString("u");
var serviceId = "1234";
string ServiceAPIKey = "abc";
string ServiceAPIPassword = "def";
var signature = "";
var signature = CalculateSignature(ServiceAPIKey, ServiceAPIPassword, message);
Console.WriteLine(signature );
}
public static string CalculateSignature(string ServiceAPIKey, string ServiceAPIPassword, string message)
{
string hashString =string.Empty;
using (var hmac = new HMACSHA256(Encoding.UTF8.GetBytes(ServiceAPIPassword)))
{
var hash = hmac.ComputeHash(Encoding.UTF8.GetBytes(message));
hashString = Convert.ToBase64String(hash);
}
hashString = ServiceAPIKey + ":" + hashString;
return hashString;
}
}
我希望这-我从我的php代码获得的abc:DWe/a/aZrapRALbgZLJzx6m1ndaM7RP1hRxCFyBlZo0=
o / p。
我得到的php o / p是abc:14w9U25MPeZ8Wg4lavtrG+IN/UyTe68wEV/Z1fkLLhc=
答案 0 :(得分:1)
您必须在c#和PHP上都使用相同的date
。如果您在$date = gmdate("Y-m-d H:i:s\Z");
中使用此$message = $serviceId.$date;
,则在执行时,这两个H:i:s
会有所不同。仅在两种语言上使用相同的日期,然后尝试在php中使用以下代码
<?php
$date = gmdate("Y-m-d"); // 2019-05-15 use the same in C#
$ServiceAPIKey = "abc";
$ServiceAPIPassword = "def";
$serviceId = "1234";
$message = $serviceId.$date;
//$message = strtolower($message); //Not needed
$signature = hash_hmac("sha256", utf8_encode($message), utf8_encode($ServiceAPIPassword), false);
// Convert hexadecimal string to binary and then to base64
$signature = hex2bin($signature);
$signature = base64_encode($signature);
echo $ServiceAPIKey.":".$signature . "<br>\n";
?>