如何使用 Crypto Web API 获取 HMAC

2022-01-10 00:00:00 cryptography javascript window.crypto

如何使用 Crypto Web API (window.crypto) 在浏览器中获取 HMAC-SHA512(key, data)?

目前我正在使用 CryptoJS 库,它非常简单:

CryptoJS.HmacSHA512("myawesomedata", "mysecretkey").toString();

结果是91c14b8d3bcd48be0488bfb8d96d52db6e5f07e5fc677ced2​​c12916dc87580961f422f9543c786eebfb5797bc3febf796b929efac5c83b4ec69228927f21a03a

我想摆脱额外的依赖并开始使用 Crypto Web API.我怎样才能得到相同的结果?

解决方案

回答我自己的问题.下面的代码返回的结果与 CryptoJS.HmacSHA512("myawesomedata", "mysecretkey").toString();

相同

因为 WebCrypto 是异步的,所以到处都有承诺:

//将字符串转换为 Uint8Array 的编码器var enc = new TextEncoder("utf-8");window.crypto.subtle.importKey("raw",//键的原始格式 - 应该是 Uint8Arrayenc.encode("mysecretkey"),{//算法细节名称:HMAC",哈希:{名称:SHA-512"}},false,//导出 = 假["sign", "verify"]//这个键能做什么).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("")控制台.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);
    });
});

相关文章