This post will discuss how to generate a SHA-256 hash in JavaScript.

To generate a SHA-256 hash in JavaScript, we need to use a library or a built-in module that provides the hashing functionality. SHA-256 is a cryptographic hash function that produces the fixed-length 256-bit (32-byte) output from any input. A hash function is a one-way function that maps an input to an output in such a way that it is easy to compute the output from the input, but hard to find the input from the output. Hash functions are useful for verifying the integrity and authenticity of data, such as passwords, messages, or files. Here are some of the methods we can use:

1. Using crypto module in Node.js

Node.js is a JavaScript runtime environment that can run JavaScript code outside of a web browser. Node.js has a built-in module called crypto that provides various cryptographic functions, including hashing, encryption, and signing. To use the crypto module, we need to require it in our code and use its createHash() function to create a hash object. Then, we can use the update() function to pass the input data to the hash object, and the digest() function to get the output in hexadecimal format. Here’s an example:

Download Code

2. Using SubtleCrypto API

Another alternative is to use the SubtleCrypto API in the browser. This is a web API that provides low-level cryptographic operations, such as hashing, encryption, and signing. We can use the crypto.subtle.digest() function to compute the hash of an ArrayBuffer or a TypedArray. We can also use the TextEncoder class to convert a string to a Uint8Array. For example:

Download Code

3. Using a third-party library

There are several JavaScript libraries that provide hashing functions, which can be used to create SHA-256 hashes in both Node.js and the browser. For example, js-sha256 is a library that implements the SHA-256 hash function in pure JavaScript. To use the js-sha256 library, we need to install it using npm or yarn, or include it as a script tag in our HTML file. Then, we can use its sha256() function to get the output in hexadecimal format from any input. Here’s an example:

Download Code

 
This is another way to achieve the same result using CryptoJS library:

Download Code

That’s all about generating a SHA-256 hash in JavaScript.