Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to translate from a hexdigest to a digest and vice-versa?

I want to store hashes as binary (64 bytes). But for any type of API (web service) I would want to pass them around as strings. hashlib.hexdigest() will give me a string, and hashlib.digest() will give me the binary. But if, for example, I read in the binary version from disk, how would I convert it to a string? And if I read in the string from a web service, how would I convert it to binary?

like image 400
esac Avatar asked Oct 21 '11 23:10

esac


People also ask

What does Hexdigest () do in Python?

hexdigest() : Returns the encoded data in hexadecimal format.

What is the hex digest of a hash?

From the documentation for hash. hexdigest() : the digest is returned as a string object of double length, containing only hexadecimal digits. This may be used to exchange the value safely in email or other non-binary environments.


2 Answers

You might want to look into binascii module, specifically hexlify and unhexlify functions.

like image 143
lormus Avatar answered Oct 18 '22 22:10

lormus


In 2.x you can use str.decode('hex') and str.encode('hex') to convert between raw bytes and a hex string. In 3.x you need to use the binascii module.

like image 24
Ignacio Vazquez-Abrams Avatar answered Oct 18 '22 21:10

Ignacio Vazquez-Abrams