回答我自己的问题。下面的代码返回相同的结果CryptoJS.HmacSHA512("myawesomedata", "mysecretkey").toString();
由于 WebCrypto 是异步的,因此到处都有承诺:
// encoder to convert string to Uint8Array
var enc = new TextEncoder("utf-8");
window.crypto.subtle.importKey(
"raw", // raw format of the key - should be Uint8Array
enc.encode("mysecretkey"),
{ // algorithm details
name: "HMAC",
hash: {name: "SHA-512"}
},
false, // export = false
["sign", "verify"] // what this key can do
).then( key => {
window.crypto.subtle.sign(
"HMAC",
key,
enc.encode("myawesomedata")
).then(signature => {
var b = new Uint8Array(signature);
var str = Array.prototype.map.call(b, x => ('00'+x.toString(16)).slice(-2)).join("")
console.log(str);
});
});