0

I am hashing a text field with Subtle Crypto and getting an [object ArrayBuffer].

The relevant code is here:

async function asyncCall() {
  var enc = new TextEncoder(); // always utf-8
  var enc2 = new TextDecoder(); // always utf-8
  var digest3 = enc.encode(localStorage.getItem("Item 1"));
  const digest2 = await crypto.subtle.digest("SHA-256", (digest3));

  localStorage.setItem("Item Hashed", (digest2));
  field2.value = localStorage.getItem("Item Hashed");
};

When I hash any text ("Item 1" is localStorage text that is defined with a text field) with this, I get [object ArrayBuffer] as the result. Why am I not getting something that looks like a SHA256 hash?

metamonkey
  • 427
  • 7
  • 33
  • 1
    Convert it into a string as shown in [MDN: Converting a digest to a hex stringSection](https://developer.mozilla.org/en-US/docs/Web/API/SubtleCrypto/digest#Converting_a_digest_to_a_hex_string). – wOxxOm Oct 04 '19 at 08:28
  • That worked!! Thank you @wOxxOm – metamonkey Oct 04 '19 at 23:44

1 Answers1

0

Convert ArrayBuffer to a Hex string:

  const hashArray = Array.from(new Uint8Array(digest2));                     // convert buffer to byte array
  const hashHex = hashArray.map(b => b.toString(16).padStart(2, '0')).join(''); // convert bytes to hex string

https://developer.mozilla.org/en-US/docs/Web/API/SubtleCrypto/digest#converting_a_digest_to_a_hex_string

D_Pavel
  • 29
  • 5