DEV Community

TateLyman
TateLyman

Posted on

Web Crypto API — Hash Anything in the Browser Without npm Packages

Stop Installing crypto-js

Every browser has a built-in cryptography API. You don't need crypto-js, js-sha256, or any npm package for basic hashing.

The Web Crypto API

async function hash(text, algorithm = 'SHA-256') {
  const encoder = new TextEncoder();
  const data = encoder.encode(text);
  const hashBuffer = await crypto.subtle.digest(algorithm, data);
  const hashArray = Array.from(new Uint8Array(hashBuffer));
  return hashArray.map(b => b.toString(16).padStart(2, '0')).join('');
}

// Usage
await hash('hello world');          // SHA-256
await hash('hello world', 'SHA-1'); // SHA-1
await hash('hello world', 'SHA-384'); // SHA-384
await hash('hello world', 'SHA-512'); // SHA-512
Enter fullscreen mode Exit fullscreen mode

Supported Algorithms

Algorithm Output Length Use Case
SHA-1 40 chars Legacy, git commits
SHA-256 64 chars General purpose
SHA-384 96 chars TLS
SHA-512 128 chars High security

Note: MD5 is NOT supported by Web Crypto API (it's considered broken). If you need MD5 for legacy compatibility, that's the one case where you need a library.

HMAC

async function hmac(key, message) {
  const encoder = new TextEncoder();
  const cryptoKey = await crypto.subtle.importKey(
    'raw', encoder.encode(key),
    { name: 'HMAC', hash: 'SHA-256' },
    false, ['sign']
  );
  const sig = await crypto.subtle.sign('HMAC', cryptoKey, encoder.encode(message));
  return Array.from(new Uint8Array(sig)).map(b => b.toString(16).padStart(2, '0')).join('');
}
Enter fullscreen mode Exit fullscreen mode

Live Demo

I built a hash generator tool using this exact approach:

devtools-site-delta.vercel.app/hash

Part of 22 free browser-based dev tools — all open source.

Top comments (0)