Semooze
Semooze

Reputation: 143

Is there any ways to convert hash data from digest version to hexdigest version

I want to get a value in string format from library I currently use.

Right now the library return a value in bytes type but I want to get it in string types. So I use bytes.decode() to convert it but it gave an errors because it cannot decode some characters.

I digged into how the library work. Turned out it use this method to provide a hash and return the value back

hashlib.sha256(data).digest()

an example of value is

b'\xce\xe00-Y\x84M2\xbd\xca\x91\\\x82\x03\xddD\xb3?\xbb~\xdc\

then I decode it and got an error.

So is there any way to turn it back to string type or I have to create my own version of hash data and use hexdigest() instead.

**Edited

give a real example of an error

b'\xce\xe00-Y\x84M2\xbd\xca\x91\\\x82\x03\xddD\xb3?\xbb~\xdc\x19\x05\x1e\xa3z\xbe\xdf(\xec\xd4r'

return this error

*** UnicodeDecodeError: 'utf-8' codec can't decode byte 0xce in position 0: invalid continuation byte

Upvotes: 1

Views: 1002

Answers (2)

If the value is returning digest as you have mentioned above,

hashlib.sha256(data).digest()

Then to get the hexdigest of this, you can use the following code,

hex_digest = digest.encode('hex').decode()

example :

digest = b'\xce\xe00-Y\x84M2\xbd\xca\x91\\\x82\x03\xddD\xb3?\xbb~\xdc'
hex_digest = digest.encode('hex').decode()
print(hex_digest)

u'cee0302d59844d32bdca915c8203dd44b33fbb7edc'

Upvotes: 2

Michal Charemza
Michal Charemza

Reputation: 27012

You should be able to use binacii.hexlify:

import binascii
binary_string = b'\xce\xe00-Y\x84M2\xbd\xca\x91\\\x82\x03\xddD\xb3?\xbb~\xdc'
hex_string = binascii.hexlify(binary_string)
print(hex_string)

outputs:

b'cee0302d59844d32bdca915c8203dd44b33fbb7edc'

Upvotes: 2

Related Questions