Python: 如何使用hashlib.md5算法创建一个16个字符长的摘要?
Python: How to create a 16 character long digest using hashlib.md5 algorithm?
Php's md5 function 采用可选的第二个参数,如果为真,returns 长度为 16 的较小散列而不是正常的 32 字符长散列。
我们如何使用 python 的 hashlib.md5
来做同样的事情。
"an optional second argument which, if true, returns a smaller hash of length 16 instead of the normal 32 character long hash."
这不是真的:第二个参数$raw_output
specifies whether the output should be hexadecimal (hex) encoded or in a raw binary字符串。哈希长度不变,但编码字符串的长度不变。
import hashlib
digest = hashlib.md5("asdf").digest() # 16 byte binary
hexdigest = hashlib.md5("asdf").hexdigest() # 32 character hexadecimal
第一个应该只在您的代码中使用,而不应呈现给用户,因为它将包含不可打印的字符。这就是为什么如果您想向用户显示哈希,您应该始终使用 hexdigest
函数。
给那些试图在 Python 3 中获取哈希值的人的注意事项:
因为 Unicode-objects 必须在使用 hashlib
散列之前进行编码,并且因为 Python 3 中的字符串默认是 Unicode(与 Python 2 不同),所以您需要使用 .encode
方法对字符串进行编码。使用上面的示例,并假设 utf-8 编码:
import hashlib
digest = hashlib.md5("asdf".encode("utf-8")).digest() # 16 byte binary
hexdigest = hashlib.md5("asdf".encode("utf-8")).hexdigest() # 32 character hexadecimal
Php's md5 function 采用可选的第二个参数,如果为真,returns 长度为 16 的较小散列而不是正常的 32 字符长散列。
我们如何使用 python 的 hashlib.md5
来做同样的事情。
"an optional second argument which, if true, returns a smaller hash of length 16 instead of the normal 32 character long hash."
这不是真的:第二个参数$raw_output
specifies whether the output should be hexadecimal (hex) encoded or in a raw binary字符串。哈希长度不变,但编码字符串的长度不变。
import hashlib
digest = hashlib.md5("asdf").digest() # 16 byte binary
hexdigest = hashlib.md5("asdf").hexdigest() # 32 character hexadecimal
第一个应该只在您的代码中使用,而不应呈现给用户,因为它将包含不可打印的字符。这就是为什么如果您想向用户显示哈希,您应该始终使用 hexdigest
函数。
给那些试图在 Python 3 中获取哈希值的人的注意事项:
因为 Unicode-objects 必须在使用 hashlib
散列之前进行编码,并且因为 Python 3 中的字符串默认是 Unicode(与 Python 2 不同),所以您需要使用 .encode
方法对字符串进行编码。使用上面的示例,并假设 utf-8 编码:
import hashlib
digest = hashlib.md5("asdf".encode("utf-8")).digest() # 16 byte binary
hexdigest = hashlib.md5("asdf".encode("utf-8")).hexdigest() # 32 character hexadecimal