sha256
Generates a SHA-256 hash of the input string.
1/**
2 * Generates a SHA-256 hash of the input string.
3 *
4 * @param input - The input string to hash.
5 * @returns A Promise that resolves to the hex-encoded SHA-256 hash.
6 */
7export async function sha256(input: string): Promise<string> {
8 const encoder = new TextEncoder();
9 const data = encoder.encode(input);
10 const hashBuffer = await crypto.subtle.digest('SHA-256', data);
11 const hashArray = Array.from(new Uint8Array(hashBuffer));
12 return hashArray.map(b => b.toString(16).padStart(2, '0')).join('');
13}
Strong Cryptographic Hashing
Utilizes the SHA-256 algorithm, which is part of the SHA-2 family and widely trusted for data integrity and digital signatures.
Browser-Native Web Crypto API
Leverages
crypto.subtle.digest
, ensuring modern, secure, and performant hashing without third-party libraries.Hex-Encoded Output
Converts the binary digest to a lowercase hexadecimal string, making it human-readable and easy to store or transmit.
Asynchronous Execution
Uses
Promise
-based design to avoid blocking the main thread, suitable for performance-critical applications.Cross-Platform Compatibility
Runs in all modern browsers and environments that support the Web Crypto API, including many desktop and mobile contexts.
Tests | Examples
1import { sha256 } from './sha256';
2
3test('sha256 - hashes known value', async () => {
4 const hash = await sha256('hello');
5 expect(hash).toBe('2cf24dba5fb0a30e26e83b2ac5b9e29e1b161e5c1fa7425e73043362938b9824');
6});
7
8test('sha256 - produces different hashes for different inputs', async () => {
9 const hash1 = await sha256('apple');
10 const hash2 = await sha256('banana');
11 expect(hash1).not.toBe(hash2);
12});
13
14test('sha256 - empty string hash', async () => {
15 const hash = await sha256('');
16 expect(hash).toBe('e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855');
17});
Common Use Cases
Password Hashing for Storage or Comparison
Transform plaintext credentials into fixed-length hashes before verification or local storage (with salt in real-world scenarios).
Data Integrity Checks
Generate hashes to verify whether files, payloads, or responses have been tampered with.
Digital Signatures or Tokens
Use hashes as part of token signing or for deterministic value generation in client-authenticated flows.
Cache Keys and ETag Generation
Create unique, reproducible keys based on content for caching systems or HTTP ETag headers.
Fingerprinting or De-duplication
Detect duplicate content or uniquely identify resources based on their hashed value.