PHP与C# HMAC raw模式结合字符串输出结果不一致求解
问题原因
存在两处核心错误导致输出不一致:
- 拼接逻辑缺失:PHP代码中构造
$eSignString时末尾拼接了二进制格式的$eServiceKey,你编写的C#代码完全漏掉了这部分内容,是输出不一致的最主要原因。 - 编码不匹配:PHP处理字符串默认使用UTF-8编码,你的C#代码中使用ASCII编码转换输入字符串,若输入参数存在非ASCII字符会出现编码差异,需要统一替换为UTF-8编码。
- 二进制拼接处理错误:直接将二进制的
eServiceKey转换为字符串会出现编码损失,需要直接合并字节数组进行哈希计算,避免额外的编码转换误差。
修正后的C#代码
using System.Security.Cryptography; using System.Text; using System.Linq; static string CreateSignature(string accessKey, string secretKey, string method, string timeStamp, string apiService) { var eSignKey = "api" + secretKey; var eSignKeyBinary = Encoding.UTF8.GetBytes(eSignKey); var eAccessKey = HashHmac(accessKey, eSignKeyBinary); var eMethodKey = HashHmac(method, eAccessKey); var eTimeKey = HashHmac(timeStamp, eMethodKey); var eServiceKey = HashHmac(apiService, eTimeKey); // 补全拼接逻辑:合并前缀字符串字节与二进制eServiceKey string signPrefix = $"{accessKey}|{method}|{timeStamp}|{apiService}|"; byte[] signPrefixBytes = Encoding.UTF8.GetBytes(signPrefix); byte[] fullSignBytes = signPrefixBytes.Concat(eServiceKey).ToArray(); var signature = HashHmacBytes(fullSignBytes, eServiceKey); return signature; } private static byte[] HashHmac(string message, byte[] secret) { // 替换为UTF8编码和PHP逻辑对齐 Encoding encoding = Encoding.UTF8; using (HMACSHA256 hmac = new HMACSHA256(secret)) { var msg = encoding.GetBytes(message); return hmac.ComputeHash(msg); } } // 新增直接处理字节数组的哈希方法,避免二进制转字符串的编码损失 private static string HashHmacBytes(byte[] messageBytes, byte[] secret) { using (HMACSHA256 hmac = new HMACSHA256(secret)) { var hash = hmac.ComputeHash(messageBytes); return BitConverter.ToString(hash).ToLower().Replace("-", string.Empty); } }
内容的提问来源于stack exchange,提问作者lespaul9090
相关产品推荐
相关产品推荐

