javascriptcryptographywindow.crypto

How to get HMAC with Crypto Web API


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?


Solution

  • 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 => x.toString(16).padStart(2, '0')).join("")
            console.log(str);
        });
    });