Reputation: 617
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).
How can I convert to C#?
Upvotes: 0
Views: 258
Reputation: 7454
This is how you would generate a SHA1 Hmac in C#:
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!
Upvotes: 2