How to hash a string with SHA-256 in JavaScript

2 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 9 hours ago 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 9 hours ago by avibootz
...