Question

I'm writing a little program based off of a Python code that I have found. There is a few lines I need help with. It is about hasing a value using SHA256 encryption.

The python code is as follows:

first = hashlib.sha256((valueOne + valueTwo).encode()).hexdigest()
second = hashlib.sha256(str(timestamp) + value).encode()).hexdigest()

And when I execute it, my values are as follows:

first: 93046e57a3c183186e9e24ebfda7ca04e7eb4d8119060a8a39b48014d4c5172b
second: bde1c946749f6716fde713d46363d90846a841ad56a4cf7eaccbb33aa1eb1b70

My C# code is:

string first = sha256_hash((secret + auth_token));
string second = sha256_hash((timestamp.ToString() + secret));

And when I execute it, my values are:

first: 9346e57a3c183186e9e24ebfda7ca4e7eb4d81196a8a39b48014d4c5172b   
second: bde1c946749f6716fde713d46363d9846a841ad56a4cf7eaccbb33aa1eb1b70

As you can see, the values are slightly different. The python code returns two values BOTH with the length of 64 characters, where as in C# the values are 60 characters and 63 characters respectively.

My sha256_hash method is from here: Obtain SHA-256 string of a string

Any help would be appreciated, thanks.

Was it helpful?

Solution

Your hex digest method is not producing length-2 hex values for bytes < 16. The byte \x08 is being added to your hex output as just '8' instead of '08', leading to an output that is too short.

Adjust the format to produce 0-padded hex characters:

foreach (Byte b in result)
    Sb.Append(b.ToString("x2"));

See Standard Numeric Format Strings for more information on how to format bytes to hexadecimal strings.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top