【问题标题】:c# HMACSHA256 encription to HMACSHA256 in phpc# HMACSHA256在php中加密为HMACSHA256
【发布时间】: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吗?

标签: c# php


【解决方案1】:

您必须在 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";
?>

【讨论】:

    猜你喜欢
    • 2011-12-05
    • 1970-01-01
    • 1970-01-01
    • 2020-03-22
    • 2020-03-04
    • 1970-01-01
    • 2016-07-01
    • 1970-01-01
    • 2020-11-01
    相关资源
    最近更新 更多