首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >将节点JS转换为C#

将节点JS转换为C#
EN

Stack Overflow用户
提问于 2022-05-18 13:44:02
回答 1查看 80关注 0票数 0

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

代码语言:javascript
运行
复制
 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#代码

代码语言:javascript
运行
复制
    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与my convert有关?

EN

回答 1

Stack Overflow用户

发布于 2022-05-25 14:12:31

因此,我需要深入研究node.js代码为HMAC哈希所做的具体工作。我发现,一旦我理解了json.stringify()正在做什么,这就变得很容易实现。

代码语言:javascript
运行
复制
    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()等价的内容

代码语言:javascript
运行
复制
     //Stringify
     strBody = strBody.Replace(" ", "");
     strBody = strBody.Replace(Environment.NewLine, "");
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/72290364

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档