Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What's a C# equivalent of hexdigest in Python 3.2?

I'm currently working on a project to convert a Python 3.2 program to C#.

In the python program there's a line of code which returns a string object of double length, containing only hexadecimal digits.

The bit of code in the Python program is:

if sha1.hexdigest().upper() == hash_string:
    #do whatever

I've been trying and failing to find an equivalent in C# of hexdigest from the hashlib in python.

In C# I've already got the SHA1 hash in a byte array but all the methods I've tried to carry out an equivalent of hexdigest have failed to provide a match to the hash_string - which is what the hexdigest of sha1 should match.

I'm not sure whether the problem is the method I'm using to emulate hexdigest or the method I use to generate the sha1 hash in the first place - so it'd be brilliant if anyone had a hexdigest method which they know works as that'd allow me to eliminate at least one possible cause of the problem.

The method I'm using at the moment in place of hexdigest is:

string hexaHash = "";
foreach (byte b in sha1result)
{
    hexaHash += String.Format("{0:x2}", b);
}
string result = hexaHash;

EDIT: facepalm okay, I just worked out what my problem was. When generating the sha1 hash in the python it was doing it from a lower case hex string. In my C# it was an upper case hex string. So I'd guess that the hexdigest equivalent I'm using is fine as it is. Sorry for wasting people's time.

like image 250
GeorgePotter Avatar asked Feb 02 '23 06:02

GeorgePotter


2 Answers

var hmac = BitConverter.ToString(hashBytes).Replace("-", "").ToLower();
like image 139
Doug Avatar answered Feb 04 '23 20:02

Doug


Use the HMACSHA1 class to convert it.

like image 28
Jonas Avatar answered Feb 04 '23 19:02

Jonas