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