我有一个旨在在 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/