Node & python 不 return 相同的 hash256

Node & python don't return the same hash256

我的 NodeJS 和 Python 脚本没有 return 相同的哈希值,什么会导致这个问题?

Node.js

const { createHmac } = require("crypto");
var message = 'v1:1583197109:'
var key = 'Asjei8578FHasdjF85Hfjkasi875AsjdiAas_CwueKL='
const digest = Buffer.from(key, "base64");
const hash = createHmac("sha256", digest)
  .update(message)
  .digest("hex");

console.log(hash)
> 7655b4f816dc7725fb4507a20f2b97823979ea00b121c84b76924fea167dcaf7

Python3

message = 'v1:1583197109:'
key = 'Asjei8578FHasdjF85Hfjkasi875AsjdiAas_CwueKL=' + '=' #add a "=" to avoid incorrect padding
digest = base64.b64decode(key.encode('utf-8'))
hash_ = hmac.new(digest, message.encode('utf-8'), hashlib.sha256)
hash_result = hash_.hexdigest()
print(hash_result)
> c762b612d7c56d3f9c95052181969b42c604c2d41b7ce5fc7f5a06457e312d5b

我想这可能是额外的 = 来避免不正确的填充,但我的 key 以单个 结尾=

Node.js Buffer.from(..., 'base64') 可以使用 "urlsafe" base64 (https://nodejs.org/api/buffer.html#buffer_buffers_and_character_encodings) 中的输入,并且 _ 不是 [= 的有效 Base64 字符28=],而它是针对节点的。

将对应于 "urlsafe" 版本的 Base64 的 altchars 添加到 python 代码会产生相等的哈希值。

const { createHmac } = require("crypto");
var message = 'v1:1583197109:'
var key = 'Asjei8578FHasdjF85Hfjkasi875AsjdiAas_CwueKL='

const digest = Buffer.from(key, "base64");
const hash = createHmac("sha256", digest)
  .update(message)
  .digest("hex");

console.log(hash) // 7655b4f816dc7725fb4507a20f2b97823979ea00b121c84b76924fea167dcaf7
message = 'v1:1583197109:'
key = 'Asjei8578FHasdjF85Hfjkasi875AsjdiAas_CwueKL=' + '=' #add a "=" to avoid incorrect padding
digest = base64.b64decode(key.encode('utf-8'), altchars='-_')
hash_ = hmac.new(digest, message.encode('utf-8'), hashlib.sha256)
hash_result = hash_.hexdigest()
print(hash_result) # 7655b4f816dc7725fb4507a20f2b97823979ea00b121c84b76924fea167dcaf7

此外,python 的 b64decodevalidate kwarg,它会检查输入字符串和 "fail loud" 而不是忽略不正确的字符