简体   繁体   中英

How to SHA-256 hash text in a chrome extension with SubtleCrypto

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?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM