简体   繁体   中英

Result HMACSHA256 in C# different with VB.net

I'm translating code from C# to vb.net using HMACSHA256 but the result is different when using C# and vb.net

the code in vb.net

Imports System
Imports System.Security.Cryptography
Imports System.Text
                
Public Module Module1
    Public Sub Main()
        Console.WriteLine(hmacSHA256("Client-Id:MCH-1634273860130\nRequest-Id:425944\nRequest-Timestamp:2022-09-06T09:23:00Z\nRequest-Target:/checkout/v1/payment\nDigest:9ZhZatgEJvY4c87mSwbknmfWL9+3eS18YV6xnivYIV4=","KHUvvn4fm3zXRIip0UWY"))
    End Sub

    Function hmacSHA256(ByVal data As String, ByVal key As String) As String
        Using hmac As HMACSHA256 = New HMACSHA256(Encoding.ASCII.GetBytes(key))
        Dim a2 As Byte() = hmac.ComputeHash(Encoding.ASCII.GetBytes(data))
        Dim a3 As String = Convert.ToBase64String(a2).ToString().Replace("+", "-").Replace("/", "_").Replace("=", "")
        Return a3
    End Using
End Function
    
End Module

https://dotnetfiddle.net/e95rZl

and Writing in C#

using System;
using System.Text;
using System.Security.Cryptography;
                    
public class Program
{
    public static void Main()
    {
        Console.WriteLine(hmacSHA256("Client-Id:MCH-1634273860130\nRequest-Id:425944\nRequest-Timestamp:2022-09-06T09:23:00Z\nRequest-Target:/checkout/v1/payment\nDigest:9ZhZatgEJvY4c87mSwbknmfWL9+3eS18YV6xnivYIV4=","KHUvvn4fm3zXRIip0UWY"));
    }
    
    private static string hmacSHA256(String data, String key)
    {
        using (HMACSHA256 hmac = new HMACSHA256(Encoding.ASCII.GetBytes(key))) {
            byte[] a2 = hmac.ComputeHash(Encoding.ASCII.GetBytes(data));
            string a3 = Convert.ToBase64String(a2).ToString().Replace("+", "-").Replace("/", "_").Replace("=", "");
            return a3;
        }
    }
}

https://dotnetfiddle.net/JblmZD

I already trying using PHP HMACSHA256 (it's giving same result with C#)

is there any missing configuration on my VB.NET code?

The \n escape sequence does not work in VB.Net strings. Use Microsoft.VisualBasic.ControlChars.Lf instead:

Console.WriteLine(hmacSHA256("Client-Id:MCH-1634273860130" & ControlChars.Lf & "Request-Id:425944" & ControlChars.Lf & "Request-Timestamp:2022-09-06T09:23:00Z" & ControlChars.Lf & "Request-Target:/checkout/v1/payment" & ControlChars.Lf & "Digest:9ZhZatgEJvY4c87mSwbknmfWL9+3eS18YV6xnivYIV4=","KHUvvn4fm3zXRIip0UWY"))

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