Crypto Utilities API reference for cryptographic utility functions lock API Reference
Categories

Crypto Utilities

The Crypto utilities provide functions for generating unique identifiers and hash codes in JavaScript. These functions are useful for creating unique keys, generating consistent hashes for objects, and other cryptographic purposes.

Functions

hashCode

function hashCode(input, { usage = 'hash', format, seed = 0 } = {})

Deterministic content hash: the same input always produces the same output. Pick a usage by what the hash is for, not by algorithm (it runs cyrb53 for the sync rungs and SHA-256 for secure). The return type follows the usage. For unique ids that are not derived from content, use generateID instead.

Usage presets

usageshapefor
hash53-bit numberin-heap keys (Map keys, memo keys); the default
content64-bit Crockford string (13 chars)short keys that cross a boundary (a URL, a DOM id, storage); use fingerprint for large or growing sets
fingerprint128-bit Crockford string (26 chars)dedup and change detection, where a collision is a bug
secureasync SHA-256 string (52 chars)adversarial resistance; needs a secure context (https or localhost)

Parameters

NameTypeDescription
inputanyThe value to hash. Plain objects are stringified via JSON.stringify; null and undefined become ""
optionsobjectOptional configuration
Options
NameTypeDefaultDescription
usagestring'hash'A usage preset: hash, content, fingerprint, or secure
formatstringpreset’sOutput encoding: 'crockford', 'hex', or 'number'. 'number' is only valid at or below 53 bits
seednumber0Namespacing seed. The same input under two seeds yields independent hashes

Defaults can be set globally on the mutable hashCode.config object (precedence: call options > config > preset).

Returns

A 53-bit number (hash), an encoded string (content / fingerprint), or a Promise<string> (secure). format overrides the encoding.

Example

import { hashCode } from '@semantic-ui/utils';
console.log(hashCode("Hello, world!")); // 53-bit number
console.log(hashCode("Hello, world!", { usage: 'content' })); // 64-bit crockford string
console.log(hashCode("Hello, world!", { usage: 'fingerprint' })); // 128-bit crockford string
console.log(await hashCode("Hello, world!", { usage: 'secure' })); // SHA-256 string
console.log(hashCode("Hello, world!", { usage: 'content', format: 'hex' }));
console.log(hashCode({ a: 1, b: [2, 3] }));
// global default for a whole app
hashCode.config = { usage: 'content' };

generateID

function generateID({ usage = 'db', length, prefix, checksum, upper, format = 'crockford', group } = {})

Generates a unique id. Defaults to a sortable 26-char ULID (usage db). Each usage preset names what the id is for and carries the length, alphabet, and structure that fits that channel. The inverse is isValidID and parseID.

Usage presets

usageshapefor
db26-char sortable ULID (uppercase)persisted records; sorts by creation time, leaks it
page8 chars, always letter-firstDOM/CSS ids and ephemeral in-memory keys
link11 charsURLs and shareable links
token27 chars with a checksum, never timestampedunguessable ids (reset links, capability URLs)
code12 uppercase chars, grouped, checksummedhuman-typed codes (license, redemption, backup)

Options

NameTypeDefaultDescription
usagestring'db'A usage preset: db, page, link, token, or code
lengthnumberpreset’sTotal characters after the prefix. Overrides the preset width
prefixstring''A verbatim prefix (typed-id convention, e.g. usr_). Not counted in length
checksumbooleanpreset’sAppend a trailing check character that catches typos. On by default for token and code
upperbooleanpreset’sEmit uppercase Crockford, overriding the preset case. Validation is case-insensitive either way
formatstring'crockford''uuid' emits an RFC UUIDv7; other Crockford options are then ignored except prefix
groupnumber | falsepreset’sHyphenate the output every n characters for display. 4 for code, off otherwise

Defaults can be set globally on the mutable generateID.config object (precedence: call options > config > preset).

Returns

The generated id string.

Example

import { generateID } from '@semantic-ui/utils';
console.log(generateID()); // '01KV61ZF26Z6BG7T04NVKSPJ7K'
console.log(generateID({ usage: 'page' })); // 'dzadahv3'
console.log(generateID({ usage: 'link' })); // '9zv38gp9ybm'
console.log(generateID({ usage: 'token', prefix: 'sk_' })); // 'sk_…' with a checksum
console.log(generateID({ usage: 'code' })); // 'ABCD-EFGH-JKLM' grouped, checksummed
console.log(generateID({ length: 17 })); // 17-char id
console.log(generateID({ format: 'uuid' })); // RFC UUIDv7
// global default for a whole app
generateID.config = { usage: 'page' };

isValidID

function isValidID(id, options)

Validates an id offline against the same options that would generate it — the cheap rejection before an expensive lookup. Reads loose: folds case, maps I/L to 1 and O to 0, and ignores hyphens, then checks the prefix, length, alphabet, and checksum.

Parameters

NameTypeDescription
idstringThe id to validate
optionsobjectThe same options used to generate it (see generateID)

Returns

true if the id is well-formed for that config, otherwise false.

Example

import { generateID, isValidID } from '@semantic-ui/utils';
const id = generateID({ usage: 'token', prefix: 'sk_' });
console.log(isValidID(id, { usage: 'token', prefix: 'sk_' })); // true
console.log(isValidID('sk_typoatthestart', { usage: 'token', prefix: 'sk_' })); // false

parseID

function parseID(id, options)

Splits a valid id into { prefix, body, checksum }, decoding timestamp for the db preset. Returns null for anything isValidID rejects. There is no in-band signal, so parsing always needs the config that minted the id.

Parameters

NameTypeDescription
idstringThe id to parse
optionsobjectThe same options used to generate it (see generateID)

Returns

{ prefix, body, checksum, timestamp? }, or null if invalid. timestamp (a Date) is present only for the db preset.

Example

import { generateID, parseID } from '@semantic-ui/utils';
const id = generateID({ usage: 'db', prefix: 'doc_' });
const parsed = parseID(id, { usage: 'db', prefix: 'doc_' });
console.log(parsed.prefix); // 'doc_'
console.log(parsed.timestamp); // Date — when the id was minted

getRandomSeed

function getRandomSeed()

Generates a cryptographically secure random seed value.

Returns

A random 32-bit unsigned integer, from crypto.getRandomValues.

Example

import { getRandomSeed } from '@semantic-ui/utils';
console.log(getRandomSeed()); // 2949673445
console.log(getRandomSeed()); // 1234567890
Previous
Colors
Next
Dates