How to create hmac in javascript

View Discussion

Improve Article

Save Article

  • Read
  • Discuss
  • View Discussion

    Improve Article

    Save Article

    The crypto.createHmac() method is used to create an Hmac object that uses the stated ‘algorithm’ and ‘key’. Syntax:

    crypto.createHmac( algorithm, key, options )

    Parameters: This method accept three parameters as mentioned above and described below:

    • algorithm: It is dependent on the accessible algorithms which are favored by the version of OpenSSL on the platform. It returns string. The examples are sha256, sha512, etc.
    • key: It is the HMAC key which is used to create the cryptographic HMAC hash. It returns string, Buffer, TypedArray, DataView, or KeyObject. And if it is a KeyObject, then its type must be secret.
    • options: It is optional parameter and used to control stream behavior. It returns an object.

    Return Type: It returns Hmac object. Below examples illustrate the use of crypto.createHmac() method in Node.js: Example 1: 

    javascript

    const crypto = require('crypto');

    const secret = 'GfG';

    const hash = crypto.createHmac('sha256', secret)

                       .update('GeeksforGeeks')

                       .digest('hex');

    console.log(hash);

    Output:

    a08116905e92633e4f30eefd1276206b259305c8783642fc5b7f51c089187939

    Example 2: 

    javascript

    const myfile = process.argv[1];

    const crypto = require('crypto');

    const fs = require('fs');

    const creathmac = crypto.createHmac('sha1', 'CS-Portal!');

    const readfile = fs.createReadStream(myfile);

    readfile.on('readable', () => {

      const data = readfile.read();

      if (data)

        creathmac.update(data);

      else

       {

        console.log("The hmac object returns:",

        `${creathmac.digest('hex')} ${myfile}`);

      }

    });

    console.log("Program done!");

    console.log();

    Output:

    Program done!
    The hmac object returns: 4605d44703c2620fc2574c9a9216bd3267457324 /run_dir/interp.js

    Reference: https://nodejs.org/api/crypto.html#crypto_crypto_createhmac_algorithm_key_options


    [TL;DR] I will easily introduce MAC and HMAC concepts and provide very simple JavaScript sample code that you will be even able to use in your browser console.

    How to create hmac in javascript

    MAC stands for Message Authentication Code, and it also known as tag, and in communications sometimes is substituted by MIC or message integrity code.

    What is a MAC for?

    From a general point of view, a MAC is a piece of information that protects a message by:

    • verifying data integrity, i.e. that the message has not been tampered.
    • verifying its authenticity, confirming that it comes from the stated sender.

    This is specially important when the message has to travel through unsecured channels. Specific use cases will be listed below.

    How does MAC work?

    1. The sender A wants to send a message M to a receiver B.
    2. The sender A and the receiver B sharea key K.
    3. The sender uses a signing algorithm S to calculate a tag T given the shared key K and the message M.
    4. The receiver B uses a verifying algorithm V to verify the authenticity of the message M given the key K and the tag T. That is, the algorithm returns accepted if neither the tag T nor the message M have been tampered with. Otherwise, it returns rejected.

    Requisites for a secure message authentication code

    It must resist an adversary’s attempt to forge tags for arbitrary, selected or all messages, including under conditions of known- or chosen-message. That is, it must resist the forgery of digital signature.

    It should be computationally infeasible to compute a valid tag of the given message without knowledge of the key.

    HMAC

    HMAC (hash-based message authentication code) is a particular type of message authentication code (MAC). As with any MAC, the hash function can be used for both verifying data integrity and authentication of the message.

    The hash function name is used to term the different MAC functions with the pattern HMAC-X, for example HMAC-SHA256 or HMAC-SHA3–512.

    JavaScript example

    Open your browser dev tools to try the following snippets on the console. These snippets should work also with Node.js.

    This function implements the HMAC-SHA256 version:

    async function hmacSha256Hex(secret, message) {
    const enc = new TextEncoder("utf-8");
    const algorithm = { name: "HMAC", hash: "SHA-256" };
    const key = await crypto.subtle.importKey(
    "raw",
    enc.encode(secret),
    algorithm,
    false, ["sign", "verify"]
    );
    const hashBuffer = await crypto.subtle.sign(
    algorithm.name,
    key,
    enc.encode(message)
    );
    const hashArray = Array.from(new Uint8Array(hashBuffer)); const hashHex = hashArray.map(
    b => b.toString(16).padStart(2, '0')
    ).join('');
    return hashHex;
    }

    Using this function is as simple as the following:

    await hmacSha256Hex(
    "key",
    "The quick brown fox jumps over the lazy dog"
    );
    //f7bc83f430538424b13298e6aa6fb143ef4d59a14946175997479dbc2d1a3cd8

    In the previous example, mapping to the MAC explanation, we have that key K has the value “key”, the message M has the value “The quick brown fox jumps over the lazy dog” and the tag T has the value “f7bc83f430538424b13298e6aa6fb143ef4d59a14946175997479dbc2d1a3cd8”.

    Usage scenarios for HMAC

    So by now, you should understand how HMAC works — if not, please tell me in the comments which is the obscure part so I can improve it. You may wonder which are particular scenarios for this technology. Well, here are a few of them that will help you when you face different challenges:

    • Password reset link. You can send an e-mail with a reset link that is only valid for a certain time. With HMAC, you can do this without additional server states.
    • Links in verifying email addresses in order to create or activate accounts.
    • Authenticating data sent by external applications.
    • Authenticating form data that has been sent to the user browser and the posted back.
    • For internet of things (IoT) due to its low computational cost, in particular for Low-Power Wide-Area Networks.
    • HMAC based authentication (for instance, is the main authentication used by Amazon Web Services for request authentication).
    • As a data pseudonymisation technique, for example to comply with GDPR. This is, by the way, recommended by the European Union Agency for Cybersecurity (ENISA).

    How do I create a HMAC?

    Click Settings. Select the Interoperability tab. Click + Create a key for a service account. Select the service account you want the HMAC key to be associated with.

    What is HMAC JavaScript?

    HMAC (hash-based message authentication code) is a particular type of message authentication code (MAC). As with any MAC, the hash function can be used for both verifying data integrity and authentication of the message.

    What is HMAC in node JS?

    Using Clean architecture for Node. The Hmac class is one of the many utility classes that is used for creating the cryptographic HMAC digests. The Hmac.

    How do I use crypto in JavaScript?

    Advanced Encryption in JavaScript Using crypto-js.
    <script>.
    var enbtn = document.getElementById("encrbtn");.
    var rawdata = document.getElementById("rawdata");.
    var password = document.getElementById("password");.
    var display1 = document.getElementById("display1");.
    var endata = document.getElementById("endata");.