Reputation: 29
I am trying to generating the hash in PHP but not getting the same output as I get from c# in my code so which encryption algorithm(or what should I change in my code) should I use. the code that I am using in PHP and c#-
php code
<?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# code
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;
}
}
I expect this - abc:DWe/a/aZrapRALbgZLJzx6m1ndaM7RP1hRxCFyBlZo0=
o/p that I am getting from mine php code.
php o/p that I am getting is abc:14w9U25MPeZ8Wg4lavtrG+IN/UyTe68wEV/Z1fkLLhc=
Upvotes: 2
Views: 75
Reputation: 892
You have to make same date
on both c# and PHP. if you are using this $date = gmdate("Y-m-d H:i:s\Z");
in $message = $serviceId.$date;
then this H:i:s
will vary on both while executing. Use same date only on both the language then try with following code in 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";
?>
Upvotes: 1