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?

1
  • 2
    Are there any examples using the standard browser crypto api without any libraries? Commented Mar 29, 2023 at 2:48

2 Answers 2

3

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>

Sign up to request clarification or add additional context in comments.

2 Comments

Any way I can import "crypto-js" through NPM? I'm using webpack.
@Anonymous - CryptoJS runs in the browser or as NodeJS. For installation details see e.g. here. Regarding webpack I can't help you, I' m sorry.
1

You can try to use crypto-browserify.

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

2 Comments

Can't get it to work for some reason. Getting Can't resolve 'stream' in node_modules/cipher-base.
@Anonymous Does this resolve your issue? github.com/crypto-browserify/cipher-base/issues/10

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.