Generating a Signature Value in python

Viewed 587

So the documentation i am looking at says to generate a Signature Value with C#, however I am wanting to do the whole thing in Python here is the information they have given me, however the expected result is Signature: wpGKFbhcBl+8JLVXGP0QqBooK6dtLBv9bYtI15NXL1U= for SHA256, I am returning b'YzI5MThhMTViODVjMDY1ZmJjMjRiNTU3MThmZDEwYTgxYTI4MmJhNzZkMmMxYmZkNmQ4YjQ4ZDc5MzU3MmY1NQ=='

Can someone point me into the right direction?

var bytesToHash = Encoding.UTF8.GetBytes(TimeStamp.GetUnixTime() + transactionId + apiKey);
string signature = Convert.ToBase64String(GetHashAlgorithm(Algorithm).ComputeHash(bytesToHash));

My code:

import hashlib
import base64
epochTime = 1547498533216
transactionId = "07643622"
APIKey = "13f1fd1b-ab2d-4c1f-8e2c-ca61878f2a44"
hash256 = bytes(str(epochTime) + transactionId + APIKey,'utf-8')
print(hash256)
signature = base64.b64encode(bytes(hashlib.sha256(hash256).hexdigest(),'utf-8'))
print(signature)
2 Answers

hexdigest() contains only hexadecimal digits. You need to return the digest of the strings passed

import hashlib
import base64

epochTime = 1547498533216
transactionId = "07643622"
APIKey = "13f1fd1b-ab2d-4c1f-8e2c-ca61878f2a44"

signature = base64.b64encode(hashlib.sha256(
    (str(epochTime) + transactionId + APIKey).encode()
).digest())

print( signature.decode() )
# wpGKFbhcBl+8JLVXGP0QqBooK6dtLBv9bYtI15NXL1U=

Your only problem is that you encoded the hexdigest (a string form that displays each byte as two characters in the 0-9a-f range, which would be used as an alternative to base64 for making a human readable hash, not in combination with it), not the digest (the raw bytes of the SHA256 hash). Change:

signature = base64.b64encode(bytes(hashlib.sha256(hash256).hexdigest(),'utf-8'))

to:

signature = base64.b64encode(hashlib.sha256(hash256).digest())

and the output is as you expect: b'wpGKFbhcBl+8JLVXGP0QqBooK6dtLBv9bYtI15NXL1U='

Related