简体   繁体   中英

C# vs PHP - They return different HMACSHA256

This is my PHP code:

<?php
    $sig_string = "GET&https%3A%2F%2Fapi.pinterest.com%2Fv3%2Fusers%2Farchimede%2Fboards%2F&client_id=987654&timestamp=1391761866";
    $secret = "123456";
    $sig = hash_hmac("sha256", $sig_string, $secret);
    echo $sig;
?>

which returns (correctly) a7918aec50919915f3cefed8622ddbe35448c8f71a54ad115828f07a05930f4c

Now, I want to translate this function inside C#. Code:

signature_base_string = "GET&https%3A%2F%2Fapi.pinterest.com%2Fv3%2Fusers%2Farchimede%2Fboards%2F&client_id=987654&timestamp=1391761866";
signing_key = "123456";
var encoding = new System.Text.ASCIIEncoding();
byte[] keyByte = encoding.GetBytes(signing_key);
byte[] messageBytes = encoding.GetBytes(signature_base_string);
using (var hmacsha256 = new HMACSHA256(keyByte))
{
    byte[] hashmessage = hmacsha256.ComputeHash(messageBytes);
    Response.Write(Convert.ToBase64String(hashmessage));
}

but it retuns p5GK7FCRmRXzzv7YYi3b41RIyPcaVK0RWCjwegWTD0w=

Why two different results? Whats wrong in the C# code?

PHP encodes the result in hexadecimal and c# encodes that in base64. But the are same.

Change this line:

Response.Write(Convert.ToBase64String(hashmessage));

To this:

Response.Write(BitConverter.ToString(hashmessage).Replace("-", "").ToLower());

to have the result in hexadecimal encoding.

They are the same:

The result from .NET C# is p5GK7FCRmRXzzv7YYi3b41RIyPcaVK0RWCjwegWTD0w= . This is a base64 string.

You can convert it to hexadecimal using this tool for example. And you'll get the same as PHP after converting:

A7918AEC50919915F3CEFED8622DDBE35448C8F71A54AD115828F07A05930F4C

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM