如何对 SHA256 十六进制字符串进行 Base64 编码

Qin*_*ing 4 python base64 encode sha256

您好,我需要帮助来获取 Base64 编码列,我得到的是 sha256 哈希列,我想获取 44 个字符,但是当我在 python 中尝试此操作时

[base64.b64encode(x.encode('utf-8')).decode() for x in xxx['yyy']]

它返回 88 个字符,有人可以帮忙吗?基本上我想用Python实现下图所示的步骤,谢谢! 在此输入图像描述

在此输入图像描述

在此输入图像描述

Gri*_*mar 8

第一张图中的步骤包含几个子步骤:

  • 输入了文本,但这只是 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)
Run Code Online (Sandbox Code Playgroud)

第二张图片似乎表明它再次将十六进制表示形式作为文本,并对它进行 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)
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)

这:

  • 使用 UTF-8 将字符“user@example.com”编码为字节
  • 使用 base64 对该字节字符串进行编码
  • 将生成的字节字符串解码为字符串

如果您期望的话,它不会在任何地方应用 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)

...也许这就是您正在寻找的答案。