/**
* Demonstrates how to hash a string using SHA-256 in JavaScript.
*
* This example uses Node.js and the built-in crypto module.
*
* Why SHA-256?
* - Widely used and well-tested.
* - Produces a fixed-length hash.
* - Suitable for checksums and data integrity verification.
* - Preferred over writing custom hash functions.
*
* Important:
* - Hashing is not encryption.
* - Hashes are one-way transformations.
* - The original string cannot be recovered from the hash.
* - Different inputs can theoretically produce the same hash
* (a collision), although collisions are considered
* computationally impractical for SHA-256.
*/
const crypto = require("crypto");
/**
* Computes the SHA-256 hash of a string.
*
* @param {string} text - The input string to hash.
* @returns {string} The hash as a hexadecimal string.
*/
function hashString(text) {
if (typeof text !== "string") {
throw new TypeError("Expected a string.");
}
return crypto
.createHash("sha256")
.update(text, "utf8")
.digest("hex");
}
/**
* Application entry point.
*/
function main() {
// Example input string.
const text = "Hello, World!";
// Compute the hash value.
const hashValue = hashString(text);
console.log(`Original string: ${text}`);
console.log(`SHA-256 hash : ${hashValue}`);
console.log();
/*
* Demonstrate hash comparison.
*
* Identical strings should produce
* identical hash values.
*/
const anotherText = "Hello, World!";
const hash1 = hashString(text);
const hash2 = hashString(anotherText);
if (hash1 === hash2) {
console.log("Hashes match.");
/*
* IMPORTANT:
*
* Matching hashes do not mathematically guarantee
* that two inputs are identical because all hash
* functions can theoretically have collisions.
*
* For SHA-256, collisions are extraordinarily
* unlikely, but when exact equality matters,
* compare the original values as well.
*/
if (text === anotherText) {
console.log("Strings are identical.");
}
}
console.log();
console.log("Professional guidance:");
console.log("- Use SHA-256 for checksums and data verification.");
console.log("- Use hashes for cache keys when appropriate.");
console.log("- Do not use hashes as encryption.");
console.log("- For passwords, use a dedicated password");
console.log(" hashing algorithm such as bcrypt, scrypt,");
console.log(" or Argon2.");
}
// Run the application.
main();
/*
run:
Original string: Hello, World!
SHA-256 hash : dffd6021bb2bd5b0af676290809ec3a53191dd81c7f70a4b28688a362182986f
Hashes match.
Strings are identical.
Professional guidance:
- Use SHA-256 for checksums and data verification.
- Use hashes for cache keys when appropriate.
- Do not use hashes as encryption.
- For passwords, use a dedicated password
hashing algorithm such as bcrypt, scrypt,
or Argon2.
*/