javascript - 如何将此签名方法从 crypto( Node )转换为 crypto-js(浏览器)?

标签 javascript node.js cryptojs

我有一个旨在在 Node.js 中使用的签名方法,但我想使用 crypto-js 在客户端实现它。它应该可以在最新的 Chrome 版本中运行。

我尝试遵循以下一些答案:Decode a Base64 String using CryptoJS

但我要么收到诸如“错误:格式错误的 UTF-8 数据”之类的错误,要么得到与预期 hmacDigest 不同的结果。

尽管我发现了这个问题,但我不确定如何找到“二进制”摘要的替代方案: How to get digest representation of CryptoJS.HmacSHA256 in JS

该方法应该回答以下问题:

"Message signature using HMAC-SHA512 of (URI path + SHA256(nonce + POST data)) and base64 decoded secret API key"

这是 Nodejs 版本(带加密):

const crypto = require('crypto')

function sign(path, params, secret) {
  const message = querystring.stringify(params)
  const secretBase64 = Buffer.from(secret, 'base64')
  const hash = crypto.createHash('sha256')
  const hmac = crypto.createHmac('sha512', secretBase64)

  const hashDigest = hash.update(params.nonce + message).digest('binary')
  const hmacDigest = hmac.update(path + hashDigest, 'binary').digest('base64')

  return hmacDigest
}

注意:querystring 只是一个辅助模块,也可以在浏览器中运行:https://nodejs.org/api/querystring.html

这是我使用 crypto-js 实现的尝试(wip):

import cryptojs from 'crypto-js')

function sign (path, params, secret) {
  const message = querystring.stringify(params)
  const secretParsed = cryptojs.enc.Base64.parse(secret)
  const secretDecoded = cryptojs.enc.Utf8.stringify(secretParsed) // -> this throws an error as "Error: Malformed UTF-8 data"

  const hash = cryptojs.SHA256(params.nonce + message).toString(cryptojs.enc.hex)
  const hmac = cryptojs.HmacSHA512(path + hash, secretDecoded).toString(cryptojs.enc.hex)
  return hmac
}

最佳答案

试试这个!我想这就是您要找的!

const crypto = require("crypto")

const sign = (path, params, secret) => {
    const message = querystring.stringify(params)
    const secret = Buffer.from(secret, 'base64')
    let sign = params.nonce + message
    let hash = crypto.createHmac('sha256', secret)
                     .update(sign)
                     .digest("base64").toString()

    let encoded = encodeURIComponent(hash)
    return encoded
}

关于javascript - 如何将此签名方法从 crypto( Node )转换为 crypto-js(浏览器)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48812894/

相关文章:

javascript - 为什么我们应该使用knockout utils 而不是普通的JavaScript?

javascript - 注册模态限制

javascript - 为什么不在回调中使用函数?

javascript - RequireJS 搜索 app.app 而不是 app.js(其中 app.js 是 data-main 中指定的入口点)

javascript Triple des 加密值和 java Triple des 加密值不匹配为什么?

javascript - Safari 上的 pageshow 事件

javascript - 使用单选按钮将值从 html 表单传递到 javascript 函数

node.js - express.js - req.body?

javascript - 如何在 javascript 中重新创建 .net 成员资格 hmacsha1 哈希

node.js - 是否可以验证和签署 Node.js "native"中的数据(不使用对 OpenSSL 的外部调用)?