You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

基于Node.js示例的C# .NET HMAC验证实现故障排查求助

排查C#版HMAC-SHA256验证与Node.js实现不一致的问题

我需要将提供的Node.js HMAC验证逻辑转为C#实现,但测试后生成的哈希值和预期不符,请求帮忙排查问题。

Node.js示例代码

function verifyAuthorizationTokenHTTP(messageBody, expectedAuthToken) {
    const tokenKey= "e1uTy+/blki9cNQPblQMBQ=="; //base64 encoded Guid
    const tokenKeyBinary = Buffer.from(tokenKey, 'base64');

    const hmac = crypto.createHmac('sha256', tokenKeyBinary);
    hmac.update(messageBody);
    const hashInBase64 = hmac.digest('base64');

    return hashInBase64 === expectedAuthToken;
}

我的C#等效代码

public bool VerifyAuthorizationTokenHTTP(string msgBody, string expectedAuthToken)
{
    string tokenKey = "e1uTy+/blki9cNQPblQMBQ==";
    var tokenKeyBinary = Encoding.UTF8.GetBytes(tokenKey);
    
    using HMAC hmac = new HMACSHA256(tokenKeyBinary);
    var hash = hmac.ComputeHash(Encoding.UTF8.GetBytes(msgBody));
    var hashInBase64 = Convert.ToBase64String(hash);
    
    return hashInBase64 == expectedAuthToken;
}

测试数据

string AuthenticationToken = "e1uTyu/blki9cNQPblQMBQ==";
string expectedAuthToken = "ZYP5sZmXqqO9Qj3rAIh/vkOiKwGHcrHubTDPXaQiKZk=";
string messageBody = @"{""siteId"":""NOOlxt3rRruQuEciW6DyCg"",""type"":""HEARTBEAT"",""time"":""2023-11-04T09:08:03.539Z""}";

测试结果

生成的哈希值:maiNj4i24SdSudX1olun6vhww6Q6S7HJYIK6eWOz48k=,与预期的ZYP5sZmXqqO9Qj3rAIh/vkOiKwGHcrHubTDPXaQiKZk=不符。


问题排查与修正

核心错误在于密钥的处理方式:

  • Node.js中,Buffer.from(tokenKey, 'base64')是将base64编码的密钥字符串解码为原始二进制字节;
  • 你的C#代码中,Encoding.UTF8.GetBytes(tokenKey)是直接把base64字符串本身转成UTF-8字节数组,而非解码base64得到原始密钥。

修正后的C#代码:

public bool VerifyAuthorizationTokenHTTP(string msgBody, string expectedAuthToken)
{
    string tokenKey = "e1uTy+/blki9cNQPblQMBQ==";
    // 正确解码base64格式的密钥为二进制数组
    var tokenKeyBinary = Convert.FromBase64String(tokenKey);
    
    using HMACSHA256 hmac = new HMACSHA256(tokenKeyBinary);
    var hash = hmac.ComputeHash(Encoding.UTF8.GetBytes(msgBody));
    var hashInBase64 = Convert.ToBase64String(hash);
    
    return hashInBase64 == expectedAuthToken;
}

另外需要确认:messageBody的编码一致性,Node.js的hmac.update(messageBody)默认使用UTF-8处理字符串,C#中Encoding.UTF8.GetBytes(msgBody)的处理是正确的,这部分无需修改。

内容的提问来源于stack exchange,提问作者ShhTot

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.06 22:05:31