Rana Faiz Ahmad
Rana Faiz Ahmad

Reputation: 1698

Need browser equivalent of this specific implementation of crypto.createHmac method

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?

Upvotes: 2

Views: 4033

Answers (2)

Topaco
Topaco

Reputation: 49415

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>

Upvotes: 3

mdeamp
mdeamp

Reputation: 128

You can try to use crypto-browserify.

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

Upvotes: 1

Related Questions