我试图在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=
发布于 2019-05-15 18:10:54
你必须在c#和PHP上创建相同的date。如果您在$message = $serviceId.$date;中使用此$date = gmdate("Y-m-d H:i:s\Z");,则在执行时,此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";
?>https://stackoverflow.com/questions/56142566
复制相似问题