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 |
| ignoreConfig | boolean | false | Resolve as if no global config were set: call options and presets only |
Defaults can be set globally on the mutable hashCode.config object (precedence: call options > config > preset). ignoreConfig opts a call out of that global layer — for library code that needs the same output shape regardless of host-app defaults.
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, bits, 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) |
secret |
256 bits (53 chars) with a checksum | session secrets and the tokens derived from them |
code |
12 uppercase chars, grouped, checksummed | human-typed codes (license, redemption, backup) |
A preset states its width in the unit its channel is chosen by. link is 11 characters because a link has to fit somewhere. secret is 256 bits because that is the number a security review asks for, and it clears the field: the Copenhagen Book floors server-side tokens at 112 bits, a 32-byte secret is the common recommendation, and shipped implementations sit near 190. Rounding up to a whole Crockford character emits 260 bits over 52 random characters, with the 53rd holding the check character. Both tiers are unguessable. Reach for token where the id also travels in a URL and gets read back by a person, secret where it is a credential.
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 |
| bits | number | preset’s | Entropy budget, the same width dial as length in another unit. Rounds up to a whole character. The highest precedence layer naming either one decides |
| 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 |
| ignoreConfig | boolean | false | Resolve as if no global config were set: call options and presets only |
Defaults can be set globally on the mutable generateId.config object (precedence: call options > config > preset). ignoreConfig opts a call out of that global layer — for library code whose id shapes must not bend to host-app defaults. isValidId and parseId take it too, so an id minted config-free validates config-free. Width follows the same precedence, so an app-wide length narrows secret like any other preset. Code that mints a credential and must hold its own width passes ignoreConfig: true.
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: 'secret' })); // 53-char, 256-bit session secretconsole.log(generateId({ usage: 'code' })); // 'ABCD-EFGH-JKLM' grouped, checksummedconsole.log(generateId({ length: 17 })); // 17-char idconsole.log(generateId({ usage: 'secret', bits: 512 })); // wider, same shapeconsole.log(generateId({ format: 'uuid' })); // RFC UUIDv7
// global default for a whole appgenerateId.config = { usage: 'page' };
// library code opts out of the global layerconsole.log(generateId({ ignoreConfig: true })); // 26-char ULID, config ignoredisValidId
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