![](/img/trans.png)
[英]Need browser equivalent of this specific implementation of crypto.createHmac method
[英]How to replicate Node's Crypto.createHmac( 'sha256', buffer) in the browser?
如何获得Node的Crypto.createHmac( 'sha256', buffer)
和CryptoJS.HmacSHA256(..., secret)
之间的“功能奇偶校验”?
我有一个第三方代码,该代码执行的方法为node1
。 我需要在浏览器中实现相同的结果。 看来,区别在于secret
是在节点侧进行base64解码的。 但是我仍然无法获得相同的输出。
const CryptoJS = require('crypto-js')
const Crypto = require('crypto')
const message = "Message"
const secret = "Eby8vdM02xNOcqFlqUwJPLlmEtlCDXJ1OUzFT50uSRZ6IFsuFq2UVErCz4I6tq/K1SZFPTOtr/KBHBeksoGMGw=="
function node1() {
return Crypto.createHmac("sha256", Buffer.from(secret, 'base64'))
.update(message, "utf8")
.digest("base64");
}
function node2() {
return Crypto.createHmac("sha256", Buffer.from(secret, 'base64').toString('base64'))
.update(message, "utf8")
.digest("base64");
}
function browser() {
const crypted = CryptoJS.HmacSHA256(message, secret)
return CryptoJS.enc.Base64.stringify(crypted)
}
console.log('node1', node1())
console.log('node2', node2())
console.log('browser-like', browser())
// node1 agitai8frSJpJuXwd4HMJC/t2tluUJPMZy8CeYsEHTE=
// node2 fxJQFWs5W3A4otaAlnlV0kh4yfQPb4Y1ChSVZsUAAXA=
// browser-like fxJQFWs5W3A4otaAlnlV0kh4yfQPb4Y1ChSVZsUAAXA=
因此,我可以在节点中重现幼稚的类似浏览器的行为。 这使我atob
在浏览器中使用atob
来重现节点行为的想法。 以下sign
方法是我在浏览器端的最佳猜测。
function sign(message) {
const crypted = CryptoJS.HmacSHA256(message, atob(secret));
return CryptoJS.enc.Base64.stringify(crypted)
}
function signNotDecoded(message) {
const crypted = CryptoJS.HmacSHA256(message, secret);
return CryptoJS.enc.Base64.stringify(crypted)
}
console.log('browser', sign('Message'))
console.log('browser-like', signNotDecoded('Message'))
// browser dnVm5jBgIBNV6pFd4J9BJTjx3BFsm7K32SCcEQX7RHA=
// browser-like fxJQFWs5W3A4otaAlnlV0kh4yfQPb4Y1ChSVZsUAAXA=
因此,在浏览器中运行signDecoded()
和在node中运行browser()
会得到相同的输出。 再次在node中运行node2()
和browser()
都提供相同的输出,但是sign()
与node1()
仍然不同。
基于上述情况,我很确定问题出在我使用atob的问题上,但是我想念的是什么?
更改
atob(secret)
至
CryptoJS.enc.Base64.parse(secret)
因为如果您将原始字符串作为函数的键传递,它将被重新解析为UTF-8。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.