Skip to content

hash

Terminal window
bun add @stopcock/hash
import { sha256, crc32, toHex, hmac } from '@stopcock/hash'
toHex(sha256('hello')) // "2cf24dba..."
crc32('hello') // 907060870
toHex(hmac(sha256, 'key', 'msg'))
import { sha256, toHex } from '@stopcock/hash'
const cacheKey = (body: string) => toHex(sha256(body)).slice(0, 16)
const key = cacheKey(JSON.stringify(requestBody))
// "a3f2b7c9e1d04f8a" → use as Redis/cache key
import { sha256, hmac, timeSafeEqual, fromHex } from '@stopcock/hash'
const verify = (payload: string, signature: string, secret: string) =>
timeSafeEqual(hmac(sha256, secret, payload), fromHex(signature))
// Verify a webhook from a third party
const valid = verify(rawBody, req.headers['x-signature'], WEBHOOK_SECRET)
import { xxhash32 } from '@stopcock/hash'
const seen = new Set<number>()
const deduped = items.filter(item => {
const hash = xxhash32(JSON.stringify(item))
if (seen.has(hash)) return false
seen.add(hash)
return true
})
sha256(input: string | Uint8Array): Uint8Array
md5(input: string | Uint8Array): Uint8Array
xxhash32(input: string | Uint8Array, seed?: number): number
crc32(input: string | Uint8Array): number

sha256 and md5 return Uint8Array. Use toHex or toBase64 to format. xxhash32 and crc32 return numbers directly.

toHex(data: Uint8Array): string
toBase64(data: Uint8Array): string
fromHex(hex: string): Uint8Array
hmac(hashFn: (data: Uint8Array) => Uint8Array, key: string | Uint8Array, message: string | Uint8Array): Uint8Array
timeSafeEqual(a: Uint8Array, b: Uint8Array): boolean