6

Can someone please help me convert the following two lines of python to C#.

hash = hmac.new(secret, data, digestmod = hashlib.sha1)
key = hash.hexdigest()[:8]

The rest looks like this if you're intersted:

#!/usr/bin/env python

import hmac
import hashlib


secret = 'mySecret'     
data = 'myData'

hash = hmac.new(secret, data, digestmod = hashlib.sha1)
key = hash.hexdigest()[:8]

print key

Thanks

1 Answer 1

7

You could use the HMACSHA1 class to compute the hash:

class Program
{
    static void Main()
    {
        var secret = "secret";
        var data = "data";
        var hmac = new HMACSHA1(Encoding.UTF8.GetBytes(secret));
        var hash = hmac.ComputeHash(Encoding.UTF8.GetBytes(data));
        Console.WriteLine(BitConverter.ToString(hash));
    }
}
Sign up to request clarification or add additional context in comments.

3 Comments

And to print the key, I added: string key = string.Empty; foreach (byte b in hash) { key += b.ToString("X2"); } MessageBox.Show(key);
Or you could BitConverter.ToString(hash).Replace("-", string.Empty).
You can add a using statment to the HMACSHA1 instance like so to dispose of it properly: using var hmac = new HMACSHA1(Encoding.UTF8.GetBytes(secret)); (C# 8 or later. In older versions use using block). This will ensure that the dispose method is called on the HMACSHA1 instance.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.