Hash Generator — TypeScript source
Compute SHA-1, SHA-256, SHA-384 and SHA-512 hashes of any text at once, using the browser's native SubtleCrypto. Copy each digest. 100% client-side.
This is the TypeScript implementation — the same logic the interactive tool runs, in a shareable, citable form.
// Pure surface of the hash tool (slug: hash). The digest core is SubtleCrypto
// — platform-bound and async — so digestHex accepts an injectable
// implementation; everything else (algorithm set, hex encoding, UTF-8 byte
// length) is pure. The vectors in hash.test.ts are the standard SHA test
// vectors: they double as the lock-step contract for a future Go CLI twin.
export const HASH_ALGORITHMS = ['SHA-1', 'SHA-256', 'SHA-384', 'SHA-512'] as const;
export type HashAlgorithm = (typeof HASH_ALGORITHMS)[number];
/** Digest implementation contract (ArrayBuffer, as crypto.subtle.digest). */
export type DigestImpl = (alg: HashAlgorithm, data: Uint8Array) => Promise<ArrayBuffer>;
const subtleDigest: DigestImpl = (alg, data) =>
crypto.subtle.digest(alg, data as unknown as BufferSource);
/** Lowercase hex of a digest buffer — two digits per byte. */
export function toHex(buf: ArrayBuffer | Uint8Array): string {
const bytes = buf instanceof Uint8Array ? buf : new Uint8Array(buf);
return [...bytes].map((b) => b.toString(16).padStart(2, '0')).join('');
}
/** UTF-8 byte length of a string (what the digest actually hashes). */
export function byteLength(s: string): number {
return new TextEncoder().encode(s).length;
}
/** Hex digest of text under alg. Inject `digestImpl` to test without
* SubtleCrypto; the default uses the platform implementation. */
export async function digestHex(
alg: HashAlgorithm,
text: string,
digestImpl: DigestImpl = subtleDigest,
): Promise<string> {
return toHex(await digestImpl(alg, new TextEncoder().encode(text)));
}
Also available in 13 other languages
Every CosmoDev tool ships its pure logic in TypeScript (web) and Go (CLI), with authored implementations in a dozen-plus languages — the same contract, ported. Compare all languages side by side →