晚上好,我需要用密钥对数据(字符串)进行签名,函数 HMACSHA256 用户自己输入字符串
当我签署普通字符时,一切正常 - 答案中的哈希是正确的,但如果字符串包含俄语字符,则哈希是错误的。这是 C# 代码:
using System;
using System.IO;
using System.Security.Cryptography;
using System.Text;
public class Program
{
public static void Main()
{
Encoding enc = Encoding.GetEncoding("ASCII");
String key = "20f31fbce8c54800bffa5f5d767f2cf142ebcfb87ac4ab76c0c55ba7f1934481";
String packet;
Console.WriteLine("Input Data: ");
packet = Console.ReadLine();
HMACSHA256 hm = new HMACSHA256(enc.GetBytes(key));
byte[] result = hm.ComputeHash(enc.GetBytes(packet));
String hex = BitConverter.ToString(result);
hex = hex.Replace("-", "");
Console.WriteLine(hex.ToLower());
}
}
有一个 Python 2.7 代码可以正确地用俄语字符对字符串进行签名
import hmac,hashlib
key = '20f31fbce8c54800bffa5f5d767f2cf142ebcfb87ac4ab76c0c55ba7f1934481'
packet= raw_input("Input Data:")
sig = hmac.new(key, packet, digestmod=hashlib.sha256).digest().encode("hex")
print(sig)
例如,输入单词:forum
来自 python 的正确哈希:a6aa8f3d443d7e2592eea7b5c290dbe7d418c8329912b22c2e4e4c0d1ce6a18b
来自 c# 的错误:e5a15bb8434e7f0fb6b6ce5e63730a7d119dc14d223ffb5f48a132416948ecdf 更改了各种编码,不起作用
需要帮助,提前谢谢!
我不知道您尝试过哪些编码,但可以使用 UTF-8:
结果: