c# - 将 Node JS HMAC 转换为 C#

我一直在尝试将 HMAC 中间件代码片段转换为 C#。 Node JS 代码非常简单。

const hash = crypto
.createHmac('sha256', 'SHA-Key')
.update(JSON.stringify(req.body))
.digest('hex');

if (hash === req.header('X-HMAC-Sha-256')) {
    next();
} else {
    res.send(401, 'Not authorized.');
}

我的 C# 代码

public string CalculateSHA256Hash(byte[] key, string requestContent, string senderHash)
    {   
        string hexHash = "";
        // Initialize the keyed hash object.
        using (HMACSHA256 hmac = new HMACSHA256(key))
        {
            byte[] requestByteArray = Encoding.UTF8.GetBytes(requestContent);

            // Create a FileStream for the source file.
            using (MemoryStream inStream = new MemoryStream(requestByteArray))
            {
                // Read in the storedHash.
                inStream.Read(requestByteArray, 0, requestByteArray.Length);
                // Compute the hash of the remaining contents of the file.
                // The stream is properly positioned at the beginning of the content,
                // immediately after the stored hash value.
                byte[] computedHash = hmac.ComputeHash(inStream);
                hexHash = Convert.ToHexString(computedHash);
            }
        }

        return hexHash;
     }

当我运行代码时,我永远不会得到与发送者 HMAC 哈希相同的结果。这与 node.js 中的 Digest Hex 与我的转换 toHexString 有关吗?

回答1

所以我需要深入研究 node.js 代码为这个 HMAC 哈希完成了什么。我发现一旦我了解了 json.stringify() 的作用,实现起来就变得微不足道了。

public string CalculateSHA256Hash(byte[] key, string requestContent)
    {
        string hexHash = "";
        try
        {
            // Initialize the keyed hash object.
            using (HMACSHA256 hmac = new HMACSHA256(key))
            {
                byte[] requestByteArray = Encoding.UTF8.GetBytes(requestContent);

                // Create a FileStream for the source request body.
                using (MemoryStream inStream = new MemoryStream(requestByteArray))
                {
                    byte[] computedHash = hmac.ComputeHash(inStream);
                    hexHash = Convert.ToHexString(computedHash).ToLower();
                }
            }
        }
        catch (Exception e)
        {
            throw;
        }
        return hexHash;
    }

我使用以下内容获得了 json.stringify() 的等价物

//Stringify
     strBody = strBody.Replace(" ", "");
     strBody = strBody.Replace(Environment.NewLine, "");

相似文章

c - 无法删除C中双向链表的重复数据

我在从双向链表中删除重复数据时遇到问题。所以这个列表的data元素是一个数字数组。我想用这个delete_duplicates代码删除重复数据的节点。我使用以下print_list函数来打印列表。该函...

随机推荐

最新文章