hmac-js

A simple implementation of HMAC hash generation and validation.

Usage no npm install needed!

<script type="module">
  import hmacJs from 'https://cdn.skypack.dev/hmac-js';
</script>

README

hmac-js

A simple implementation of HMAC token generation and validation.

npm install hmac-js

or

yarn add hmac-js

Getting Started

This package needs some args:

  • algorithm (string): can be sha256 or sha512;
  • secret (string): your app secret key;
  • payload (string): any data that you want;
  • timestamp (integer): a valid timestamp;

In verifyHash method you can add an extra param, the ttl (hash life time). By default it is 30 seconds.

const Hmac = require('hmac-js');

const timestamp = new Date().getTime();

const hash = Hmac.generateHash({
  algorithm: "sha512",
  secret: "mysecret",
  payload: "mypayload",
  timestamp,
});

const isValidHash = Hmac.verifyHash(hash, {
  algorithm: "sha512",
  secret: "mysecret",
  payload: "mypayload",
  timestamp,
});

if (isValidHash) {
  console.log("This is a valid hash");
} else {
  console.log("This is an invalid hash");
}

That's all folks!

Simple as everything should be.