第一张图中的步骤包含几个子步骤:
所以:
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)
Run Code Online (Sandbox Code Playgroud)
第二张图片似乎表明它再次将十六进制表示形式作为文本,并对它进行 Base64 编码 - 但实际上它采用十六进制字符串表示的字节字符串并对其进行编码。
因此,从十六进制字符串开始:
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)
Run Code Online (Sandbox Code Playgroud)
放在一起:
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())
Run Code Online (Sandbox Code Playgroud)
输出:
b4c9a289323b21a01c3e940f150eb9b8c542587f1abfd8f0e1cc1ffc5e475514
tMmiiTI7IaAcPpQPFQ65uMVCWH8av9jw4cwf/F5HVRQ=
Run Code Online (Sandbox Code Playgroud)
为什么你的代码不起作用:
base64.b64encode('user@example.com'.encode('utf-8')).decode() # superfluous utf-8
Run Code Online (Sandbox Code Playgroud)
这:
如果您期望的话,它不会在任何地方应用 SHA256 哈希,也不会创建十六进制表示形式。最终结果不匹配,因为它是原始文本 UTF-8 编码的 base64 编码的文本表示形式,而不是其 SHA256 哈希的摘要。
或者也许我误解了,您已经有了十六进制编码,但您将其作为字符串放入:
x = 'b4c9a289323b21a01c3e940f150eb9b8c542587f1abfd8f0e1cc1ffc5e475514'
base64.b64encode(x.encode()).decode()
Run Code Online (Sandbox Code Playgroud)
这确实会产生 88 个字符的 base64 编码,因为您不是对字节进行编码,而是对十六进制表示进行编码。那必须是这样的:
x = 'b4c9a289323b21a01c3e940f150eb9b8c542587f1abfd8f0e1cc1ffc5e475514'
base64.b64encode(bytes.fromhex(x)).decode()
Run Code Online (Sandbox Code Playgroud)
...也许这就是您正在寻找的答案。