如何在python中将sha256对象转换为整数并将其打包为bytearray?

Luk*_*uke 7 python type-conversion python-2.x

我想先把一个hash256对象转换成一个32字节的整数,然后再打包成一个bytearray。

>>> import hashlib
>>> hashobj = hashlib.sha256('something')
>>> val_hex = hashobj.hexdigest()
>>> print val_hex
3fc9b689459d738f8c88a3a48aa9e33542016b7a4052e001aaa536fca74813cb
>>> print len(val_hex)
64
Run Code Online (Sandbox Code Playgroud)

十六进制字符串是 64 字节而不是 32 字节,这不是我想要的。

>>> val = hashobj.digest()
>>> print val
???E?s????????5Bkz@R???6??H?
>>> print len(val)
32
Run Code Online (Sandbox Code Playgroud)

这是一个 32 字节的字符串,我想将其转换为 32 字节的整数。

当我尝试时,它给了我一条错误消息:

>>> val_int = int(val, 10)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: invalid literal for int() with base 10: '?\xc9\xb6\x89E\x9ds\x8f\x8c\x88\xa3\xa4\x8a\xa9\xe35B\x01kz@R\xe0\x01\xaa\xa56\xfc\xa7H\x13\xcb'
Run Code Online (Sandbox Code Playgroud)

我该怎么做才能得到我的 int_val?

以及如何使用 struct 将其(32 字节)打包为字节数组?我发现python结构文档中最长的格式是'Q',它只有8个字节。

非常感谢。

PM *_*ing 7

Python 2 中获取 SHA-256 摘要的整数值的最简单方法是通过 hexdigest。或者,您可以循环遍历从二进制摘要构造的字节数组。下面对这两种方法进行了说明。

import hashlib

hashobj = hashlib.sha256('something')
val_hex = hashobj.hexdigest()
print val_hex

# Build bytearray from binary digest
val_bytes = bytearray(hashobj.digest())
print ''.join(['%02x' % byte for byte in val_bytes])

# Get integer value of digest from the hexdigest
val_int = int(val_hex, 16)
print '%064x' % val_int

# Get integer value of digest from the bytearray
n = 0
for byte in val_bytes:
    n = n<<8 | byte
print '%064x' % n
Run Code Online (Sandbox Code Playgroud)

输出

3fc9b689459d738f8c88a3a48aa9e33542016b7a4052e001aaa536fca74813cb
3fc9b689459d738f8c88a3a48aa9e33542016b7a4052e001aaa536fca74813cb
3fc9b689459d738f8c88a3a48aa9e33542016b7a4052e001aaa536fca74813cb
3fc9b689459d738f8c88a3a48aa9e33542016b7a4052e001aaa536fca74813cb
Run Code Online (Sandbox Code Playgroud)

在Python 3中,我们不能将纯文本字符串传递给hashlib哈希函数,我们必须传递bytes字符串或a bytearray,例如

b'something' 
Run Code Online (Sandbox Code Playgroud)

或者

'something'.encode('utf-8')
Run Code Online (Sandbox Code Playgroud)

或者

bytearray('something', 'utf-8')
Run Code Online (Sandbox Code Playgroud)

我们可以将第二个版本简化为

'something'.encode()
Run Code Online (Sandbox Code Playgroud)

str.encode因为 UTF-8 是( 和)的默认编码bytes.decode()

要执行到 的转换int,可以使用上述任何技术,但我们还有一个附加选项:方法int.from_bytes。为了获得正确的整数,我们需要告诉它将字节解释为大端数字:

import hashlib

hashobj = hashlib.sha256(b'something')
val = int.from_bytes(hashobj.digest(), 'big')
print('%064x' % val)
Run Code Online (Sandbox Code Playgroud)

输出

3fc9b689459d738f8c88a3a48aa9e33542016b7a4052e001aaa536fca74813cb
Run Code Online (Sandbox Code Playgroud)