簡體   English   中英

C# 中的結果 HMACSHA256 與 VB.net 不同

[英]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

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

並寫入 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

我已經嘗試使用 PHP HMACSHA256 (它與 C# 給出相同的結果)

我的 VB.NET 代碼上是否缺少任何配置?

\n轉義序列在 VB.Net 字符串中不起作用。 改用Microsoft.VisualBasic.ControlChars.Lf

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"))

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM