簡體   English   中英

嘗試在 c# 中使用 HMACSHA512 生成簽名

[英]try to generating signature using HMACSHA512 in c#

c# 中使用 HMACSHA512 的簽名不等同於 java 和 JavaScript。跟蹤我的 c# 代碼后,我發現在生成簽名期間未使用密鑰。

using System.Security.Cryptography;

using System.Text;

string privateKey = "OPAYPRV16388855997950.6319778282304234";

string message = "{\r\n  \"country\": \"EG\",\r\n  \"reference\": \"9cf357a79ffc4cb5a57cd0489a1a4bfa\"\r\n}";

byte[] messagebyte = Encoding.Default.GetBytes(message);
byte[] pkey =   Encoding.Default.GetBytes(privateKey);

HMACSHA512 hMACSHA512 = new HMACSHA512(pkey);

//hMACSHA512.Key = pkey; //other way and not give right signature

//hmacsha512.Initialize();

var hmac = hMACSHA512.ComputeHash(messagebyte);
var hmacres = BitConverter.ToString(hmac).Replace("-", "");

Console.WriteLine(hmacres);

// signature c# =FC96AABB47DE439A78CB98943BA3E9F9C25B24264E1431CC4180348F5B48C869F9003E3B67B8E387D25A7189093ACDD90205A103A489856379971EBE07E295E5

// signature in java and JavaScript (the same and the right signature)=
20c8b06951a7907b48db0ccb0b1fb514e8addb2b7c72786cc21316576d57e57560188cac837ffe232a9b24e65e73c6c05e6a5dddff3cc03e26521c92e74e064d 

HMACSHA512 將 \r\n 和空格作為字符處理,當刪除 /r/n 和空格時我得到了正確的簽名

message= message.Replace(System.Environment.NewLine, string.Empty).Replace(" ", "");

byte[] messagebyte = Encoding.Default.GetBytes(消息);

byte[] pkey = Encoding.Default.GetBytes(privateKey);

HMACSHA512 hMACSHA512 = 新的 HMACSHA512(pkey);

var hmac = hMACSHA512.ComputeHash(messagebyte);

var hmacres = BitConverter.ToString(hmac).Replace("-", "");

暫無
暫無

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

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