Calculate SHA-256 Hash in JavaScript
Overview
This code snippet guides you through the process of calculating a SHA-256 hash in JavaScript. SHA-256, part of the SHA-2 family, is a cryptographic hash function widely recognized for its security and efficiency. It's an essential component in digital signatures, password hashing, and more, making it fundamental for data integrity and security in web applications.
Code
index.js
function calculateSHA256Hash(value) {
return crypto.subtle
.digest("SHA-256", new TextEncoder("utf-8").encode(value))
.then((hashedBuffer) => {
const hexArray = Array.from(new Uint8Array(hashedBuffer)).map((byte) =>
byte.toString(16).padStart(2, "0")
);
return hexArray.join("");
});
}
Example Usage
calculateSHA256Hash(
JSON.stringify({ a: "a", b: [1, 2, 3, 4], foo: { c: "bar" } })
).then((hash) => console.log("Hash:", hash));
// Example output: '04aa106279f5977f59f9067fa9712afc4aedc6f5862a8defc34552d8c7206393'
Code Description
The calculateSHA256Hash
function is a JavaScript utility for computing the SHA-256 hash of a given input. This function uses the Web Crypto API and is suitable for scenarios where cryptographic hashing is required, such as in data integrity checks and secure storage of sensitive information. Here's how it works:
Function Parameter:
value
: The input data to hash. This can be a string or any data structure that can be converted to a string.
Hash Computation:
- The function uses the
crypto.subtle.digest
method to perform SHA-256 hashing. - It first encodes the input value into UTF-8 bytes using
TextEncoder
. - The hashed data, which is an
ArrayBuffer
, is then converted into an array of hexadecimal strings.
Return Value:
- Returns a promise that resolves to a string representing the hexadecimal SHA-256 hash of the input.
Useful Links
- MDN Web Docs - SubtleCrypto.digest()
- MDN Web Docs - DataView.prototype.getUint32()
- Node.js Documentation - crypto.createHash()