Welcome to collectivesolver - Programming & Software Q&A with code examples. A website with trusted programming answers. All programs are tested and work.

Contact: aviboots(AT)netvision.net.il

Semrush - keyword research tool

Create your online store today with Shopify

Turn ChatGPT, Claude, Gemini, And CoPilot Into Your Personal Assistant, Business Coach, Content Creator, And More

AFFILIATE MARKETING Your all-in-one performance engine Manage affiliates, creators, and customer referrals in one unified platform—turning every partnership into measurable growth

Secure & Reliable Web Hosting, Free Domain, Free SSL, 1-Click WordPress Install, Expert 24/7 Support

Disclosure: My content contains affiliate links.

43,406 questions

56,397 answers

573 users

How to hash a string with SHA-256 in JavaScript

3 Answers

0 votes
async function sha256(text) {
  // Encode string as UTF‑8
  const encoder = new TextEncoder();
  const data = encoder.encode(text);

  // Compute SHA‑256 hash
  const hashBuffer = await crypto.subtle.digest("SHA-256", data);

  // Convert ArrayBuffer → hex string
  const hashArray = Array.from(new Uint8Array(hashBuffer));
  const hashHex = hashArray.map(b => b.toString(16).padStart(2, "0")).join("");

  return hashHex;
}

(async () => {
  const input = "JavaScript programming language";
  const hash = await sha256(input);
  console.log(hash);
})();



/*
run:

44d639aa872adfd910d7361da49372218ca1048ff41ebd73538b79775e40fc62

*/

 



answered May 1 by avibootz
0 votes
import { createHash } from "crypto";

function sha256(text) {
  return createHash("sha256")
    .update(text, "utf8")
    .digest("hex");
}

const input = "JavaScript programming language";
const hash = sha256(input);
console.log(hash);


/*
run:

44d639aa872adfd910d7361da49372218ca1048ff41ebd73538b79775e40fc62

*/

 



answered May 1 by avibootz
0 votes
/**
 * 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.

*/

 



answered 1 day ago by avibootz
...