我想生成1和0的随机序列,并将其输入Python中的SHA1哈希计算器。
hashlib库(
doc link
)为了生成哈希,在其update()函数中接受类似字节的对象作为输入。
我试过使用random。getrandbits(64)生成随机序列,但当我尝试使用将其转换为字节时。对于\u bytes(),它给出了一个错误,即“utf-8”编解码器无法对其进行解码。
代码:
x = random.getrandbits(64)
print(x)
print(format(x, 'b'))
binary_int = int(format(x, 'b'), 2)
# Getting the byte number
byte_number = (binary_int.bit_length() + 7) // 8
# Getting an array of bytes
binary_array = binary_int.to_bytes(byte_number, "big")
# Converting the array into ASCII text
ascii_text = binary_array.decode()
# Getting the ASCII value
print(ascii_text)
错误:
17659976144931976749
1111010100010100110101101011110010111100100010101111011000101101
---------------------------------------------------------------------------
UnicodeDecodeError Traceback (most recent call last)
/var/folders/9s/msn7k8q55yn6t6br55830hc40000gn/T/ipykernel_33103/157314006.py in <module>
12
13 # Converting the array into ASCII text
---> 14 ascii_text = binary_array.decode()
15
16 # Getting the ASCII value
UnicodeDecodeError: 'utf-8' codec can't decode byte 0xf5 in position 0: invalid start byte
我意识到这个错误意味着生成的随机位序列对于UTF-8/ASCII码无效,但我如何解决这个问题,为SHA1函数创建有效的输入?
我也尝试过上述建议
here
使用“ISO-8859-1”编码:
binary_int = random.getrandbits(64)
# Getting the byte number
byte_number = (binary_int.bit_length() + 7) // 8
# Getting an array of bytes
binary_array = binary_int.to_bytes(byte_number, "big")
# Converting the array into ASCII text
text = binary_array.decode(encoding='ISO-8859-1')
print(text)
print(type(text))
print(len(text))
import sys
print(sys.getsizeof(text.encode('ISO-8859-1')))
print(hash_sha1(text.encode('ISO-8859-1')))
输出:
¦âu¦9}5Ã
<class 'str'>
8
41
bc25cb6cb34c2b7c73bbba610e0388386c2e70b2
但是系统。getsizeof()打印81个字节的文本。编码('ISO-8859-1'),而不是64位。
在上述代码中,我尝试使用64位数据进行测试。但是,最终,我只想确保将大小不变的随机生成的512位数据输入到SHA1生成器中。我希望有办法做到这一点。谢谢
编辑:
多亏了Drakax的回答
最终代码:
import os, hashlib
k = os.urandom(64)
# print random no.
print(k)
# print it in bit format (64 bits)
for byte in k:
print(f'{byte:0>8b}', end='')
print()
# print the sha1 hash
print(hashlib.sha1(k).hexdigest())