brewedbits.dev

Personal blog with guides and news on selfhosting, Linux and AI, from the Netherlands

nextDash nextdash --aboutYour bookmarks. Your terminal. checks your links knows your Docker host one container, no cloudLive demo →nextdash.cc ↗

Tip: the Web Crypto API makes a SHA-256 hash right in the browser

Web
~/tips/tip-web-crypto-sha256-digest

async function sha256(text) {

Fingerprint text or a file in the page without adding a library.

Need to know whether a file changed, or show its checksum before someone uploads it? The browser can hash it by itself, so I leave the extra package out.

async function sha256(text) {
  const data = new TextEncoder().encode(text);
  const buf = await crypto.subtle.digest('SHA-256', data);
  return [...new Uint8Array(buf)]
    .map(b => b.toString(16).padStart(2, '0'))
    .join('');
}

console.log(await sha256('hello'));

That prints 2cf24dba5fb0a30e26e83b2ac5b9e29e1b161e5c1fa7425e73043362938b9824, the same string common checksum tools give for those five letters. For a file from an input, replace the encoder line with await file.arrayBuffer().

crypto.subtle only exists in a secure context, meaning HTTPS or localhost. On a plain HTTP address it is undefined, which is confusing the first time. The method also wants all the data at once, so a very large file has to fit in memory.

Please do not use this to store passwords. A bare SHA-256 is far too fast for that; password hashing belongs on the server with a function made for it.

Further reading: MDN: SubtleCrypto digest()

More Web tips url = URL.createObjectURL(file); function setFilter(name, value) { and open <span translate="no">Home Assistant</span> in your browser. …the page behind the drawer… inputmode="numeric" autocomplete="one-time-code"> All Web tips (6) All topics

Link