如何使用Crypto Web API获取HMAC [英] How to get HMAC with Crypto Web API

查看:182
本文介绍了如何使用Crypto Web API获取HMAC的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

How can I get HMAC-SHA512(key, data) in the browser using Crypto Web API (window.crypto)?

当前我正在使用CryptoJS库,这很简单:

Currently I am using CryptoJS library and it is pretty simple:

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

结果是91c14b8d3bcd48be0488bfb8d96d52db6e5f07e5fc677ced2c12916dc87580961f422f9543c786eebfb5797bc3febf796b929efac5c83b4ec69228927f21a03a.

我想摆脱额外的依赖关系,而是开始使用Crypto Web API.如何获得相同的结果?

I want to get rid of extra dependencies and start using Crypto Web API instead. How can I get the same result with it?

推荐答案

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

Answering my own question. The code below returns the same result as CryptoJS.HmacSHA512("myawesomedata", "mysecretkey").toString();

无处不在,因为WebCrypto是异步的:

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);
    });
});

这篇关于如何使用Crypto Web API获取HMAC的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆