hashString
Hashes a string using the specified algorithm (e.g., SHA-1, SHA-256, SHA-512). Returns a hexadecimal string representation.
1/**
2 * Hashes a string using the specified algorithm (e.g., SHA-1, SHA-256, SHA-512).
3 * Returns a hexadecimal string representation.
4 *
5 * @param input - The input string to hash.
6 * @param algorithm - Hashing algorithm (default is 'SHA-256').
7 * @returns A promise resolving to the hex hash string.
8 */
9export async function hashString(
10 input: string,
11 algorithm: AlgorithmIdentifier = 'SHA-256'
12): Promise<string> {
13 const encoder = new TextEncoder();
14 const data = encoder.encode(input);
15 const hashBuffer = await crypto.subtle.digest(algorithm, data);
16 return Array.from(new Uint8Array(hashBuffer))
17 .map(b => b.toString(16).padStart(2, '0'))
18 .join('');
19}
Supports Multiple Algorithms
Accepts any standard
AlgorithmIdentifier
(e.g., 'SHA-1', 'SHA-256', 'SHA-512'), providing flexibility for various cryptographic requirements.Leverages Native Web Crypto API
Utilizes
crypto.subtle.digest
, ensuring secure, performant, and standards-compliant hashing in modern browsers.Output in Hexadecimal Format
Produces hex-encoded output, which is compact, human-readable, and commonly used in hashes for logs, URLs, or database storage.
Promise-Based Asynchronous API
Non-blocking execution allows safe usage in UI-sensitive or concurrent environments.
Cross-Platform Compatibility
Works in modern browsers and secure contexts (like PWAs and browser extensions), suitable for both client-side verification and lightweight hashing tasks.
Tests | Examples
1test('hashString - SHA-256 hash of "hello"', async () => {
2 const hash = await hashString('hello', 'SHA-256');
3 expect(hash).toBe(
4 '2cf24dba5fb0a30e26e83b2ac5b9e29e1b161e5c1fa7425e73043362938b9824'
5 );
6});
7
8test('hashString - SHA-1 hash of "hello"', async () => {
9 const hash = await hashString('hello', 'SHA-1');
10 expect(hash).toBe('aaf4c61ddcc5e8a2dabede0f3b482cd9aea9434d');
11});
12
13test('hashString - SHA-512 hash of "hello"', async () => {
14 const hash = await hashString('hello', 'SHA-512');
15 expect(hash.startsWith('9b71d224')).toBe(true); // just checking prefix
16 expect(hash.length).toBe(128);
17});
18
19test('hashString - empty string returns known hash', async () => {
20 const hash = await hashString('');
21 expect(hash).toBe(
22 'e3b0c44298fc1c149afbf4c8996fb924' +
23 '27ae41e4649b934ca495991b7852b855'
24 );
25});
Common Use Cases
Creating Content Fingerprints
Generate a hash of file contents or user input to detect duplicates or ensure integrity.
Client-Side Password Hashing
Pre-hash passwords before sending them over the network (typically alongside salting and HMAC).
Cache Key Generation
Create consistent, fixed-length keys from complex objects or query strings for client-side caching.
Verifying File Downloads
Compute and compare hash digests to ensure file integrity after a download or upload.
Digital Signatures and HMACs (Preprocessing)
Hash data before signing or MAC generation in secure communication protocols.