【问题标题】:Python body.encode( ) Javascript alternativePython body.encode() Javascript 替代
【发布时间】:2020-08-21 01:46:29
【问题描述】:

我正在尝试通过计算 webhook 主体的 Sha256 来验证来自 NodeJS 中 Plaid 的 webhook,并且我正在按照 Python 代码 here 显示代码:

   # Compute the has of the body.
   m = hashlib.sha256()
   m.update(body.encode())
   body_hash = m.hexdigest() 

请问在将 body.encode() 传递给 Sha256 函数之前,Javascript 中的 body.encode() 的替代方法是什么?请注意,我得到的主体是一个包含以下数据的对象:

{ 错误:null,item_id:'4zAGyokJ1XiWP63QNl1RuLZV76o55nudVXzNG',
new_transactions:0,webhook_code:'DEFAULT_UPDATE',webhook_type: “交易”}

但是我正在尝试获取此哈希:

b05ef560b59e8d8e427433c5e0f6a11579b5dfe6534257558b896f858007385a

【问题讨论】:

  • 你应该散列 webhook 的主体字节,而不是你从 JSON 解码的对象。你已经有了一个“对象”,所以你走得太远了。
  • 请问如何获取 webhook 的正文字节?
  • 不看代码很难说。

标签: javascript python node.js sha256 plaid


【解决方案1】:

因此,如果正文是 JSON (NOT JSON STRING),那么您需要将其字符串化并将其放入 .update 函数中,因为 m.body 需要一个字符串。如果你的身体是 STRING,那么就按原样放入。

这是来自加密示例here

const crypto = require('crypto');
const hash = crypto.createHash('sha256');

const stringBody = JSON.stringify(body);
hash.update(stringBody);
console.log(hash.digest('hex'));

编辑:
如果哈希值不同,那么您可能需要更正换行符或空格。你需要使两个身体完全一样。在下面的示例中,我使用 Python 和 NodeJS 使用相同的精确字符串和编码。

import hashlib
body = '{"error":null,"item_id":"4zAGyokJ1XiWP63QNl1RuLZV76o55nudVXzNG","new_transactions":0,"webhook_code":"DEFAULT_UPDATE","webhook_type":"TRANSACTIONS"}'
m = hashlib.sha256()
m.update(body.encode())
body_hash = m.hexdigest()
print(body_hash)

输出:

python3 file.py
26f1120ccaf99a383b7462b233e18994d0c06d4585e3fe9a91a449e97a1c03ba

以及使用 NodeJS:

const crypto = require('crypto');
const hash = crypto.createHash('sha256');
const body = {
  error: null,
  item_id: '4zAGyokJ1XiWP63QNl1RuLZV76o55nudVXzNG',
  new_transactions: 0,
  webhook_code: 'DEFAULT_UPDATE',
  webhook_type: 'TRANSACTIONS'
}

const stringBody = JSON.stringify(body);
hash.update(stringBody);
console.log(hash.digest('hex'));

输出:

node file.js
26f1120ccaf99a383b7462b233e18994d0c06d4585e3fe9a91a449e97a1c03ba

【讨论】:

  • 感谢您的回复,但即使使用 JSON.stringify(body) 我也没有得到相同的哈希
  • 编辑答案以添加比较。
猜你喜欢
  • 2018-01-06
  • 2012-04-08
  • 2012-03-20
  • 2015-01-14
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-03-07
  • 1970-01-01
相关资源
最近更新 更多