How to hash a string with SHA-256 in TypeScript

1 Answer

0 votes
async function sha256(text: string): Promise<string> {
  const encoder: TextEncoder = new TextEncoder();
  const data: Uint8Array<ArrayBuffer> = encoder.encode(text);

  const hashBuffer: ArrayBuffer = await crypto.subtle.digest("SHA-256", data);
  const hashArray: number[] = Array.from(new Uint8Array(hashBuffer));

  return hashArray
    .map(b => b.toString(16).padStart(2, "0"))
    .join("");
}

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



/*
run:

04afc63bd1ff14200880ddd522dffb3fb985275bb088ecd1cebd83ac13ff8351

*/

 



answered 9 hours ago by avibootz
...