問題描述
如何使用 Crypto Web API (window.crypto
) 在瀏覽器中獲取 HMAC-SHA512(key, data)?
目前我正在使用 CryptoJS 庫,它非常簡單:
CryptoJS.HmacSHA512("myawesomedata", "mysecretkey").toString();
結(jié)果是91c14b8d3bcd48be0488bfb8d96d52db6e5f07e5fc677ced2??c12916dc87580961f422f9543c786eebfb5797bc3febf796b929efac5c83b4ec69228927f21a03a
我想擺脫額外的依賴并開始使用 Crypto Web API.我怎樣才能得到相同的結(jié)果?
回答我自己的問題.下面的代碼返回的結(jié)果與 CryptoJS.HmacSHA512("myawesomedata", "mysecretkey").toString();
因?yàn)?WebCrypto 是異步的,所以到處都有承諾:
//將字符串轉(zhuǎn)換為 Uint8Array 的編碼器var enc = new TextEncoder("utf-8");window.crypto.subtle.importKey("raw",//鍵的原始格式 - 應(yīng)該是 Uint8Arrayenc.encode("mysecretkey"),{//算法細(xì)節(jié)名稱:HMAC",哈希:{名稱:SHA-512"}},false,//導(dǎo)出 = 假["sign", "verify"]//這個(gè)鍵能做什么).then( 鍵 => {window.crypto.subtle.sign("HMAC",鑰匙,enc.encode("myawesomedata")).then(簽名 => {var b = new Uint8Array(簽名);var str = Array.prototype.map.call(b, x => ('00'+x.toString(16)).slice(-2)).join("")控制臺(tái).log(str);});});
How can I get HMAC-SHA512(key, data) in the browser using Crypto Web API (window.crypto
)?
Currently I am using CryptoJS library and it is pretty simple:
CryptoJS.HmacSHA512("myawesomedata", "mysecretkey").toString();
Result is 91c14b8d3bcd48be0488bfb8d96d52db6e5f07e5fc677ced2c12916dc87580961f422f9543c786eebfb5797bc3febf796b929efac5c83b4ec69228927f21a03a
.
I want to get rid of extra dependencies and start using Crypto Web API instead. How can I get the same result with it?
Answering my own question. The code below returns the same result as CryptoJS.HmacSHA512("myawesomedata", "mysecretkey").toString();
There are promises everywhere as WebCrypto is asynchronous:
// 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);
});
});
這篇關(guān)于如何使用 Crypto Web API 獲取 HMAC的文章就介紹到這了,希望我們推薦的答案對(duì)大家有所幫助,也希望大家多多支持html5模板網(wǎng)!