Python 中字节的奇怪表示
Strange representation of Bytes in Python
我有一个散列字符串的简单程序。
from Crypto.Hash import SHA512
PAYLOAD = "Hello world"
def sha(message):
h = SHA512.new()
h.update(message.encode('ascii'))
return h.digest()
if __name__ == '__main__':
print(sha(PAYLOAD))
print(type(sha(PAYLOAD)))
这是输出,
b'\xb7\xf7\x83\xba\xed\x82\x97\xf0\xdb\x91tb\x18O\xf4\xf0\x8ei\xc2\xd5\xe5\xf7\x9a\x94&\x00\xf9r_X\xce\x1f)\xc1\x819\xbf\x80\xb0l\x0f\xff+\xdd4s\x84R\xec\xf4\x0cH\x8c"\xa7\xe3\xd8\x0c\xdfo\x9c\x1c\rG'
我不明白这是一个字节数组吗?
digest()
is documented to return a bytes
object, and a bytes
object is exactly what you're getting: https://docs.python.org/3/library/stdtypes.html#bytes-objects
bytearray
类似于 bytes
但又不完全相同(它基本上是 bytes
的可变版本)。
如果你需要一个整数列表,你可以简单地调用 list()
>>> list(b'\xb7\xf7\x83\xba\xed\x82\x97\xf0\xdb\x91tb\x18O\xf4\xf0\x8ei\xc2\xd5\xe5\xf7\x9a\x94&\x00\xf9r_X\xce\x1f)\xc1\x819\xbf\x80\xb0l\x0f\xff+\xdd4s\x84R\xec\xf4\x0cH\x8c"\xa7\xe3\xd8\x0c\xdfo\x9c\x1c\rG')
[183, 247, 131, 186, 237, 130, 151, 240, 219, 145, 116, 98, 24, 79, 244, 240, 142, 105, 194, 213, 229, 247, 154, 148, 38, 0, 249, 114, 95, 88, 206, 31, 41, 193, 129, 57, 191, 128, 176, 108, 15, 255, 43, 221, 52, 115, 132, 82, 236, 244, 12, 72, 140, 34, 167, 227, 216, 12, 223, 111, 156, 28, 13, 71]
如果您需要 SHA 摘要的十六进制表示,hexdigest()
。
我有一个散列字符串的简单程序。
from Crypto.Hash import SHA512
PAYLOAD = "Hello world"
def sha(message):
h = SHA512.new()
h.update(message.encode('ascii'))
return h.digest()
if __name__ == '__main__':
print(sha(PAYLOAD))
print(type(sha(PAYLOAD)))
这是输出,
b'\xb7\xf7\x83\xba\xed\x82\x97\xf0\xdb\x91tb\x18O\xf4\xf0\x8ei\xc2\xd5\xe5\xf7\x9a\x94&\x00\xf9r_X\xce\x1f)\xc1\x819\xbf\x80\xb0l\x0f\xff+\xdd4s\x84R\xec\xf4\x0cH\x8c"\xa7\xe3\xd8\x0c\xdfo\x9c\x1c\rG'
我不明白这是一个字节数组吗?
digest()
is documented to return a bytes
object, and a bytes
object is exactly what you're getting: https://docs.python.org/3/library/stdtypes.html#bytes-objects
bytearray
类似于 bytes
但又不完全相同(它基本上是 bytes
的可变版本)。
如果你需要一个整数列表,你可以简单地调用 list()
>>> list(b'\xb7\xf7\x83\xba\xed\x82\x97\xf0\xdb\x91tb\x18O\xf4\xf0\x8ei\xc2\xd5\xe5\xf7\x9a\x94&\x00\xf9r_X\xce\x1f)\xc1\x819\xbf\x80\xb0l\x0f\xff+\xdd4s\x84R\xec\xf4\x0cH\x8c"\xa7\xe3\xd8\x0c\xdfo\x9c\x1c\rG')
[183, 247, 131, 186, 237, 130, 151, 240, 219, 145, 116, 98, 24, 79, 244, 240, 142, 105, 194, 213, 229, 247, 154, 148, 38, 0, 249, 114, 95, 88, 206, 31, 41, 193, 129, 57, 191, 128, 176, 108, 15, 255, 43, 221, 52, 115, 132, 82, 236, 244, 12, 72, 140, 34, 167, 227, 216, 12, 223, 111, 156, 28, 13, 71]
如果您需要 SHA 摘要的十六进制表示,hexdigest()
。