第一张图片中的步骤由几个子步骤组成:
- 输入了一个文本,但这只是 UTF-8 编码的字符表示
- sha256 散列应用于该字节字符串
- 生成的摘要字节序列以其十六进制表示形式呈现
所以:
from hashlib import sha256
s = 'user@example.com'
h = sha256()
h.update(s.encode('utf-8')) # specifying encoding, optional as this is the default
hex_string = h.digest().hex()
print(hex_string)
第二张图片似乎表明它再次将十六进制表示作为文本,并且 base64 对其进行编码 - 但实际上它采用十六进制字符串表示的字节字符串并对其进行编码。
所以,从十六进制字符串开始:
- 将十六进制解码为字节(重构摘要字节)
- 使用 base64 将字节编码为 ascii 字节字符串
- 将生成的字节字符串解码为用于打印的字符
from base64 import b64encode
digest_again = bytes.fromhex(hex_string)
b64bytes = b64encode(digest_again)
# no real need to specify 'ascii', the relevant code points overlap with UTF-8:
result = b64bytes.decode('ascii')
print(result)
放在一起:
from hashlib import sha256
from base64 import b64encode
s = 'user@example.com'
h = sha256()
h.update(s.encode())
print(h.digest().hex())
b64bytes = b64encode(h.digest())
print(b64bytes.decode())
输出:
b4c9a289323b21a01c3e940f150eb9b8c542587f1abfd8f0e1cc1ffc5e475514
tMmiiTI7IaAcPpQPFQ65uMVCWH8av9jw4cwf/F5HVRQ=
为什么您的代码不起作用:
base64.b64encode('user@example.com'.encode('utf-8')).decode() # superfluous utf-8
这个:
- 使用 UTF-8 将字符“user@example.com”编码为字节
- 使用 base64 对该字节字符串进行编码
- 将生成的字节串解码为字符串
它不会在任何地方应用 SHA256 哈希,也不会创建十六进制表示,如果您期望的话。最终结果不匹配,因为它是原始文本 UTF-8 编码的 base64 编码的文本表示,而不是其 SHA256 哈希的摘要。
或者我误解了,你已经有了十六进制编码,但是你把它作为一个字符串:
x = 'b4c9a289323b21a01c3e940f150eb9b8c542587f1abfd8f0e1cc1ffc5e475514'
base64.b64encode(x.encode()).decode()
这确实会产生 88 个字符的 base64 编码,因为您不是在对字节进行编码,而是在对十六进制表示进行编码。那应该是这样的:
x = 'b4c9a289323b21a01c3e940f150eb9b8c542587f1abfd8f0e1cc1ffc5e475514'
base64.b64encode(bytes.fromhex(x)).decode()
...也许这就是您正在寻找的答案。