On This Page
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
| usage | shape | for |
|---|---|---|
hash |
53-bit number | in-heap keys (Map keys, memo keys); the default |
content |
64-bit Crockford string (13 chars) | short keys that cross a boundary (a URL, a DOM id, storage); use fingerprint for large or growing sets |
fingerprint |
128-bit Crockford string (26 chars) | dedup and change detection, where a collision is a bug |
secure |
async SHA-256 string (52 chars) | adversarial resistance; needs a secure context (https or localhost) |
Parameters
| Name | Type | Description |
|---|---|---|
| input | any | The value to hash. Plain objects are stringified via JSON.stringify; null and undefined become “” |
| options | object | Optional configuration |
Options
| Name | Type | Default | Description |
|---|---|---|---|
| usage | string | 'hash' |
A usage preset: hash, content, fingerprint, or secure |
| format | string | preset’s | Output encoding: 'crockford', 'hex', or 'number'. 'number' is only valid at or below 53 bits |
| seed | number | 0 | Namespacing 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 numberconsole.log(hashCode("Hello, world!", { usage: 'content' })); // 64-bit crockford stringconsole.log(hashCode("Hello, world!", { usage: 'fingerprint' })); // 128-bit crockford stringconsole.log(await hashCode("Hello, world!", { usage: 'secure' })); // SHA-256 stringconsole.log(hashCode("Hello, world!", { usage: 'content', format: 'hex' }));console.log(hashCode({ a: 1, b: [2, 3] }));
// global default for a whole apphashCode.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
| usage | shape | for |
|---|---|---|
db |
26-char sortable ULID (uppercase) | persisted records; sorts by creation time, leaks it |
page |
8 chars, always letter-first | DOM/CSS ids and ephemeral in-memory keys |
link |
11 chars | URLs and shareable links |
token |
27 chars with a checksum, never timestamped | unguessable ids (reset links, capability URLs) |
code |
12 uppercase chars, grouped, checksummed | human-typed codes (license, redemption, backup) |
Options
| Name | Type | Default | Description |
|---|---|---|---|
| usage | string | 'db' |
A usage preset: db, page, link, token, or code |
| length | number | preset’s | Total characters after the prefix. Overrides the preset width |
| prefix | string | '' |
A verbatim prefix (typed-id convention, e.g. usr_). Not counted in length |
| checksum | boolean | preset’s | Append a trailing check character that catches typos. On by default for token and code |
| upper | boolean | preset’s | Emit uppercase Crockford, overriding the preset case. Validation is case-insensitive either way |
| format | string | 'crockford' |
'uuid' emits an RFC UUIDv7; other Crockford options are then ignored except prefix |
| group | number | false | preset’s | Hyphenate 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 checksumconsole.log(generateID({ usage: 'code' })); // 'ABCD-EFGH-JKLM' grouped, checksummedconsole.log(generateID({ length: 17 })); // 17-char idconsole.log(generateID({ format: 'uuid' })); // RFC UUIDv7
// global default for a whole appgenerateID.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
| Name | Type | Description |
|---|---|---|
| id | string | The id to validate |
| options | object | The 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_' })); // trueconsole.log(isValidID('sk_typoatthestart', { usage: 'token', prefix: 'sk_' })); // falseparseID
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
| Name | Type | Description |
|---|---|---|
| id | string | The id to parse |
| options | object | The 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 mintedgetRandomSeed
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()); // 2949673445console.log(getRandomSeed()); // 1234567890