2

So, I have this piece of code that's written in Node.js

crypto.createHmac('sha256', secret).update(orderedParams).digest('hex')

I wish to bring this piece of code in the browser but that doesn't work since the 'crypto' library is not supported on the browser. Can somebody just help me re-create the same method in the browser?

Topaco
  • 40,594
  • 4
  • 35
  • 62
Anonymous
  • 1,658
  • 2
  • 14
  • 19

2 Answers2

4

An HMAC can be determined by most crypto libraries, e.g. CryptoJS or WebCrypto API.

The following example uses CryptoJS:

var secret = 'my secret';
var orderedParams = 'the ordered params';

// Short
var hmac3 = CryptoJS.HmacSHA256(orderedParams, secret).toString();
console.log(hmac3.replace(/(.{48})/g,'$1\n'));

// Progressive
var hmac2 = CryptoJS.algo.HMAC.create(CryptoJS.algo.SHA256, secret).update(orderedParams).finalize().toString();
console.log(hmac2.replace(/(.{48})/g,'$1\n'));
<script src="https://cdnjs.cloudflare.com/ajax/libs/crypto-js/4.0.0/crypto-js.min.js"></script>
Topaco
  • 40,594
  • 4
  • 35
  • 62
  • Any way I can import "crypto-js" through NPM? I'm using webpack. – Anonymous May 20 '21 at 08:11
  • @Anonymous - _CryptoJS_ runs in the browser or as NodeJS. For installation details see e.g. [here](https://www.npmjs.com/package/crypto-js). Regarding _webpack_ I can't help you, I' m sorry. – Topaco May 20 '21 at 08:28
1

You can try to use crypto-browserify.

It's a reimplementation of crypto, made it so that it can run on the Browser.

mdeamp
  • 128
  • 3
  • 1
    Can't get it to work for some reason. Getting `Can't resolve 'stream' in node_modules/cipher-base`. – Anonymous May 19 '21 at 19:36
  • @Anonymous Does this resolve your issue? https://github.com/crypto-browserify/cipher-base/issues/10 – mdeamp May 19 '21 at 20:39