sha256 from string for browser, don’t use crypto subtle or crypto library or any other library in typescript

Here's an implementation of SHA-256 in vanilla JavaScript that can be used to hash a string:

index.tsx
function sha256(str: string): Promise<string> {
  const buffer = new TextEncoder().encode(str);
  return crypto.subtle.digest('SHA-256', buffer)
    .then((hash) => {
      return Array.from(new Uint8Array(hash))
        .map((b) => b.toString(16).padStart(2, '0'))
        .join('');
    });
}
295 chars
10 lines

Note that this uses TextEncoder to encode the string as a Uint8Array buffer so it can be passed to crypto.subtle.digest. If you need to support older browsers without TextEncoder, you'll need to use a polyfill or a different encoding method.

gistlibby LogSnag