Skip to content

Instantly share code, notes, and snippets.

@chrisveness
Last active July 20, 2023 04:45
Show Gist options
  • Save chrisveness/e5a07769d06ed02a2587df16742d3fdd to your computer and use it in GitHub Desktop.
Save chrisveness/e5a07769d06ed02a2587df16742d3fdd to your computer and use it in GitHub Desktop.
Uses the SubtleCrypto interface of the Web Cryptography API to hash a message using SHA-256.
/**
* Returns SHA-256 hash from supplied message.
*
* @param {String} message.
* @returns {String} hash as hex string.
*
* @example
* sha256('abc').then(hash => console.log(hash));
* const hash = await sha256('abc');
*/
async function sha256(message) {
const msgUint8 = new TextEncoder().encode(message); // encode as (utf-8) Uint8Array
const hashBuffer = await crypto.subtle.digest('SHA-256', msgUint8); // hash the message
const hashArray = Array.from(new Uint8Array(hashBuffer)); // convert buffer to byte array
const hashHex = hashArray.map(b => b.toString(16).padStart(2, '0')).join(''); // convert bytes to hex string
return hashHex;
}
@chrisveness
Copy link
Author

Note that access to the WebCrypto API is restricted to secure origins (e.g. https).

@ziacsoft
Copy link

How to use this algorithm as the signature in (Razorpay )payment gateway integration?

@chrisveness
Copy link
Author

I'm not familiar with Razorpay, but checking it quickly, I suspect what you require may be for payment verification? If so, I think you would probably need crypto.subtle.sign for an HMAC signature using SHA-256, but I've not had occasion to use that, so I can't really help.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment