How to transfer from hexagonal to digest and vice versa?

I want to store hashes as binary (64 bytes). But for any type of API (web service), I would like to pass them as strings. hashlib.hexdigest() will give me a string, and hashlib.digest() will give me a 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 a line from a web service, how would I convert it to binary?

+4
source share
3 answers

You can start with the string version to get around and display it:

 >>> import hashlib >>> string_version = hashlib.md5(b'hello world').hexdigest() 

Convert it to binary to write it to disk:

 >>> save_as_binary = string_version.encode('utf-8') >>> print(save_as_binary) b'5eb63bbbe01eeed093cb22bb8f5acdc3' 

When reading it from disk, convert it back to line:

 >>> back_to_string = save_as_binary.decode('utf-8') >>> print(back_to_string) 5eb63bbbe01eeed093cb22bb8f5acdc3 
+4
source

You might want to learn the binascii module, in particular hexlify and unhexlify .

+4
source

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

+3
source

All Articles