【发布时间】:2019-05-15 05:57:38
【问题描述】:
我正在尝试在 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;
}
}
我希望这个 - abc:DWe/a/aZrapRALbgZLJzx6m1ndaM7RP1hRxCFyBlZo0= o/p 是我从我的 php 代码中得到的。
我得到的 php o/p 是abc:14w9U25MPeZ8Wg4lavtrG+IN/UyTe68wEV/Z1fkLLhc=
【问题讨论】:
-
PHP 是否甚至使用 UTF8 作为其编码?你试过
Encoding.Unicode吗?