Creating digests e.g. SHA-256

suggest change
// Convert a string to bytes. Skip this when you already have an ArrayBuffer or a Uint8Array.
const input = new TextEncoder().encode('Hello world!');

// Calculate the SHA-256 digest
crypto.subtle.digest('SHA-256', input)
// Wait for completion
.then(function(digest) {
  // digest is an ArrayBuffer. There are multiple ways to proceed.

  // If you want to display the digest as a hexadecimal string, this will work:
  const view = new DataView(digest);
  let hexstr = '';
  for(let i = 0; i < view.byteLength; i++) {
    const b = view.getUint8(i);
    hexstr += '0123456789abcdef'[(b & 0xf0) >> 4];
    hexstr += '0123456789abcdef'[(b & 0x0f)];
  }
  console.log(hexstr);

  // Otherwise, you can simply create an Uint8Array from the buffer:
  const digestAsArray = new Uint8Array(digest);
  console.log(digestAsArray);
})
// Catch errors
.catch(function(err) {
  console.error(err);
});

crypto.subtle is available in browsers and in current Node.js. The SHA-256 digest of "Hello world!" is c0535e4be2b79ffd93291305436bf889314e4a3faec05ecffcbb7df31ad9e51a. The API also provides SHA-1, SHA-384, and SHA-512. Prefer SHA-256 or stronger; SHA-1 is obsolete for new work. TextEncoder always encodes UTF-8.

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents