简体   繁体   English

如何将createHmac从节点转换为C#?

[英]How to convert createHmac from node to C#?

I have this code in node: 我在节点中有以下代码:

const crypto = require('crypto')
 const token = crypto.createHmac('sha1', 'value'+'secretValue').update('value').digest('hex');

I need to convert to C#, but the code default to convert for sha1 in .net doesnt work (actually, the result is different from the node). 我需要转换为C#,但是默认的代码无法在.net中转换为sha1(实际上,结果与节点不同)。

How can I convert to C#? 如何转换为C#?

This is how you would generate a SHA1 Hmac in C#: 这是在C#中生成SHA1 Hmac的方式:

string GenerateHmac(string input, string key)
{
    var inputBytes = Encoding.UTF8.GetBytes(input);
    var keyBytes = Encoding.UTF8.GetBytes(key);

    using (var memoryStream = new MemoryStream(inputBytes))
    {
        using (var hmacSha1 = new HMACSHA1(keyBytes))
        {
            return hmacSha1.ComputeHash(memoryStream).Aggregate("", 
                (aggregator, singleByte) => aggregator + singleByte.ToString("X2"), aggregator => aggregator);
        }
    }
}

// somewhere in your code
var value = "value";
var secretValue = "secretValue";

var hmac = GenerateHmac(value, value + secretValue);
// hmac is "0B3A72A9AF80D0E5F2CEDDCA12EE21E90DD590DE"

Let me know if this isn't what you were looking for and i'll try my best to help you further! 让我知道这是否不是您想要的东西,我会尽力为您提供进一步的帮助!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM