4

I want to compute the SHA256 based HMAC for some key and a message in front-end using JavaScript. It's easily done in Python like so:

import hmac
h = hmac.new(b'key', b'message', 'sha256')
print(h.hexdigest())

I searched and found something in NodeJS but can't do the same thing in front-end (I mean in browser of the user), which I guess I need to bundle the required library and do the stuff but could not figure out how.

Masked Man
  • 2,176
  • 2
  • 22
  • 41
  • Many of those libraries are usable in-browser as well. If your question is about bundling, post a new separate question for that. A quick tip... check out Browserify. It does the bundling in the most painless way. Webpack and a collection of modules for it is an alternative, but I've found Webpack to be the biggest pain. Spent years messing with it and decided to abandon as it's such a hassle to work with, and it breaks regularly. – Brad Oct 17 '19 at 20:47
  • @Brad, I can edit the question if necessary, but will be glad if you post your answer. – Masked Man Oct 17 '19 at 20:50
  • [https://www.npmjs.com/package/js-sha256](https://www.npmjs.com/package/js-sha256). – tao Oct 17 '19 at 20:51
  • @AndreiGheorghiu my question is about using this kind of stuff in browser, could you post an answer? – Masked Man Oct 17 '19 at 20:53

1 Answers1

7

npm i js-sha256 [link]

will install it on the domain of your choice, in node_modules/ and you can link it from there.

console.log(sha256.hmac('key', 'message'));
<script src="https://cdnjs.cloudflare.com/ajax/libs/js-sha256/0.9.0/sha256.min.js"></script>
tao
  • 82,996
  • 16
  • 114
  • 150
  • I guess I can download the library and serve it through my own site instead of `cdnjs.cloudflare.com`, right? – Masked Man Oct 17 '19 at 20:56
  • Yes, it's publicly available. You should install it with `npm` (`npm i js-sha256`), so you can upgrade it whenever a new version is released. `npm` installs it in your `node_packages` and you can link it from there. You have complete control over version. – tao Oct 17 '19 at 20:57
  • 1
    Thanks for the answer, *happy coding :)* – Masked Man Oct 17 '19 at 20:58