Advertisement
benjaminvr

util-ref

May 10th, 2024
566
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. // https://developer.mozilla.org/en-US/docs/Web/API/SubtleCrypto/digest#converting_a_digest_to_a_hex_string
  2.  
  3. /*
  4.     Open a new browser tab or window and paste the following in your developer console (CTRL + SHIFT + I)
  5.    
  6.     (You may need to type "allow pasting", as indicated by your browser)
  7. */
  8.  
  9. const text =
  10.   "An obscure body in the S-K System, your majesty. The inhabitants refer to it as the planet Earth.";
  11.  
  12. async function digestMessage(message) {
  13.   const msgUint8 = new TextEncoder().encode(message); // encode as (utf-8) Uint8Array
  14.   const hashBuffer = await crypto.subtle.digest("SHA-256", msgUint8); // hash the message
  15.   const hashArray = Array.from(new Uint8Array(hashBuffer)); // convert buffer to byte array
  16.   const hashHex = hashArray
  17.     .map((b) => b.toString(16).padStart(2, "0"))
  18.     .join(""); // convert bytes to hex string
  19.   return hashHex;
  20. }
  21.  
  22. /*
  23.     Get the sha256 hash for any string, in this case the string assigned to the text variable
  24. */
  25.  
  26. const result = await digestMessage(text);
  27.  
  28. /*
  29.     The result is "6efd383745a964768989b9df420811abc6e5873f874fc22a76fe9258e020c2e1"
  30.    
  31.     Repeat this with any other string
  32. */
  33.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement