簡體   English   中英

如何將sha256對象轉換為整數並將其打包為python中的bytearray?

[英]How to convert a sha256 object to integer and pack it to bytearray in python?

我想先將hash256對象轉換為32字節整數,然后將其打包成bytearray。

>>> import hashlib
>>> hashobj = hashlib.sha256('something')
>>> val_hex = hashobj.hexdigest()
>>> print val_hex
3fc9b689459d738f8c88a3a48aa9e33542016b7a4052e001aaa536fca74813cb
>>> print len(val_hex)
64

十六進制字符串是64字節而不是32字節,這不是我想要的。

>>> val = hashobj.digest()
>>> print val
?ɶ?E?s????????5Bkz@R???6??H?
>>> print len(val)
32

這是一個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'

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

我如何使用struct將它(32字節)打包到bytearray? 我發現python struct文檔中最長的格式是'Q',它只有8字節。

非常感謝你。

bytearray的要點是不適合單個單元格中的整個內容。 這就是為什么單元只有1個字節大的原因。

並且.digest()返回一個字節字符串,所以你可以立即使用它:

>>> import hashlib
>>> hashobj = hashlib.sha256('something')
>>> val = hashobj.digest()
>>> print bytearray(val)
?ɶ�E�s������5Bkz@R���6��H�
>>> print repr(bytearray(val))
bytearray(b'?\xc9\xb6\x89E\x9ds\x8f\x8c\x88\xa3\xa4\x8a\xa9\xe35B\x01kz@R\xe0\x01\xaa\xa56\xfc\xa7H\x13\xcb')

Python 2中獲取SHA-256摘要整數值的最簡單方法是通過hexdigest。 或者,您可以遍歷從二進制摘要構造的bytearray。 兩種方法如下所示。

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

產量

3fc9b689459d738f8c88a3a48aa9e33542016b7a4052e001aaa536fca74813cb
3fc9b689459d738f8c88a3a48aa9e33542016b7a4052e001aaa536fca74813cb
3fc9b689459d738f8c88a3a48aa9e33542016b7a4052e001aaa536fca74813cb
3fc9b689459d738f8c88a3a48aa9e33542016b7a4052e001aaa536fca74813cb

在Python 3中,我們不能將純文本字符串傳遞給hashlib哈希函數,我們必須傳遞一個bytes字符串或一個bytearray ,例如

b'something' 

要么

'something'.encode('utf-8')

要么

bytearray('something', 'utf-8')

我們可以將第二個版本簡化為

'something'.encode()

因為UTF-8是str.encode (和bytes.decode() )的默認編碼。

要執行到int的轉換,可以使用上述任何技術,但我們還有一個附加選項: int.from_bytes方法。 要獲得正確的整數,我們需要告訴它將字節解釋為big-endian數字:

import hashlib

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

產量

3fc9b689459d738f8c88a3a48aa9e33542016b7a4052e001aaa536fca74813cb

我是這樣做的

import hashlib

x = 'input'
hash = int.from_bytes(hashlib.sha256(x.encode('utf-8')).digest(), 'big')
print(my_hash)

# 91106456816457796232999629894661022820411437165637657988648530670402435361824

讓我們檢查哈希的大小

print(len("{0:b}".format(my_hash)))

# 256

完善!

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM