Generate a SHA-256 hash in JavaScript
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:
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 |
// Require the crypto module const crypto = require('crypto'); // Create a function that takes an input and returns its SHA-256 hash function sha256(input) { // Create a hash object const hash = crypto.createHash('sha256'); // Pass the input data to the hash object hash.update(input); // Get the output in hexadecimal format return hash.digest('hex'); } // Test the function with some inputs // 64ec88ca00b268e5ba1a35678a1b5316d212f4f366b2477232534a8aeca37f3c console.log(sha256('Hello world')); // c0535e4be2b79ffd93291305436bf889314e4a3faec05ecffcbb7df31ad9e51a console.log(sha256('Hello world!')); |
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:
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 |
// Generate SHA-256 hash async function generateSHA256Hash(data) { // Encode the data as UTF-8 const encoder = new TextEncoder(); const dataBuffer = encoder.encode(data); // Compute the hash const hashBuffer = await window.crypto.subtle.digest('SHA-256', dataBuffer); // Convert the hash to a hexadecimal string const hashArray = Array.from(new Uint8Array(hashBuffer)); const hashHex = hashArray.map(byte => byte.toString(16).padStart(2, '0')).join(''); console.log(hashHex); } // Test the function with some inputs // 64ec88ca00b268e5ba1a35678a1b5316d212f4f366b2477232534a8aeca37f3c generateSHA256Hash('Hello world'); // c0535e4be2b79ffd93291305436bf889314e4a3faec05ecffcbb7df31ad9e51a generateSHA256Hash('Hello world!'); |
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:
|
1 2 3 4 5 6 7 8 9 10 11 |
// Import the sha256 function from the library const sha256 = require('js-sha256').sha256; // Or use it as a global variable if included as a script tag // Test the function with some inputs // 64ec88ca00b268e5ba1a35678a1b5316d212f4f366b2477232534a8aeca37f3c console.log(sha256('Hello world')); // c0535e4be2b79ffd93291305436bf889314e4a3faec05ecffcbb7df31ad9e51a console.log(sha256('Hello world!')); |
This is another way to achieve the same result using CryptoJS library:
|
1 2 3 4 5 6 7 8 9 10 11 |
// Import CryptoJS const CryptoJS = require('crypto-js'); // Compute the SHA-256 hash of a string const hash = CryptoJS.SHA256('Hello world'); // Get the hexadecimal hash value const hashHex = hash.toString(CryptoJS.enc.Hex); // 64ec88ca00b268e5ba1a35678a1b5316d212f4f366b2477232534a8aeca37f3c console.log(hashHex); |
That’s all about generating a SHA-256 hash in JavaScript.
Thanks for reading.
To share your code in the comments, please use our online compiler that supports C, C++, Java, Python, JavaScript, C#, PHP, and many more popular programming languages.
Like us? Refer us to your friends and support our growth. Happy coding :)