如何从十六进制转换为摘要,反之亦然? [英] How to translate from a hexdigest to a digest and vice-versa?
问题描述
我想将散列存储为二进制(64字节).但是对于任何类型的API(Web服务),我都希望将它们作为字符串传递. hashlib.hexdigest()
将给我一个字符串,而 hashlib.digest()
将给我二进制文件.但是,例如,如果我从磁盘读取二进制版本,该如何将其转换为字符串?而且,如果我从Web服务中读取字符串,该如何将其转换为二进制文件?
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?
推荐答案
您可以从字符串版本开始传递并显示:
You could start with the string version to pass around and display:
>>> 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 back from disk, convert it back to a string:
>>> back_to_string = save_as_binary.decode('utf-8')
>>> print(back_to_string)
5eb63bbbe01eeed093cb22bb8f5acdc3
这篇关于如何从十六进制转换为摘要,反之亦然?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!