微信官方SDK中,源代码如下:
private string CalcHMACSHA256Hash(string plaintext, string salt)
{
string result = "";
var enc = Encoding.Default;
byte[]
baText2BeHashed = enc.GetBytes(plaintext),
baSalt = enc.GetBytes(salt);
System.Security.Cryptography.HMACSHA256 hasher = new HMACSHA256(baSalt);
byte[] baHashedText = hasher.ComputeHash(baText2BeHashed);
result = string.Join("", baHashedText.ToList().Select(b => b.ToString("x2")).ToArray());
return result;
}
但在实际使用中,遇到以下问题:
1. body如果传入中文内容,则签名会报错;
2.服务器端返回的签名,全都是大写。
因此需要调整以下两个内容:
var enc = Encoding.UTF8; //修改Default为UTF8 防止中文乱码
return result.ToUpper();//这里需要将其转为大写,服务器返回的都为大写
这样,生成的签名才与服务端的一致。
完整代码:<