简体   繁体   中英

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?

You can try to use crypto-browserify .

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

An HMAC can be determined by most crypto libraries, eg 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>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM