Skip to main content

Import

What it does

CryptoUtils exposes static methods for common cryptographic and encoding operations: secure token generation, UUID v4, Base64 encoding/decoding (standard and URL-safe), hashing (simple and SubtleCrypto-based), HMAC, AES-256-GCM encryption/decryption, and constant-time string comparison.
simpleHash is a fast 32-bit hash intended for non-security use cases (hash maps, fingerprinting). For security-sensitive hashing use hash() or hmac().
v3 breaking change: hash() and hmac() now throw if no secure crypto backend (crypto.subtle in browsers, or Node.js crypto) is available. The previous silent fallback to weak algorithms has been removed.

Methods

generateToken(length?)

Generates a cryptographically random hex token.

generateUUID()

Returns a random UUID v4 string.

base64Encode(str)

Encodes a string to standard Base64.

base64Decode(str)

Decodes a standard Base64 string.

base64UrlEncode(str)

Encodes a string to URL-safe Base64 (replaces +/ with -_, strips =).

base64UrlDecode(str)

Decodes a URL-safe Base64 string.

simpleHash(str)

Returns a fast, non-cryptographic 32-bit hash string. Suitable for cache keys or bucketing.

hash(str, algorithm?)

Computes a cryptographic hash using the SubtleCrypto API.
v3: Throws if no secure crypto backend is available. Ensure crypto.subtle (browser) or Node.js crypto is present before calling.

hmac(message, secret, algorithm?)

Computes an HMAC digest.
v3: Throws if no secure crypto backend is available instead of returning an empty string.

verifyHash(str, hash, algorithm?)

Hashes str and compares it to hash. Returns true if they match.

encrypt(str, key)

Encrypts a string using AES-256-GCM. The returned string includes the IV and auth tag, so it is self-contained.

decrypt(encrypted, key)

Decrypts a string previously encrypted with encrypt.

randomBytes(length)

Returns a Uint8Array of cryptographically random bytes.

constantTimeCompare(a, b)

Compares two strings in constant time to prevent timing attacks. Returns true if they are equal.

Examples

Webhook signature verification

Token-based authentication

Encrypt sensitive data at rest

Use constantTimeCompare whenever you compare tokens, signatures, or hashes to prevent timing side-channel attacks.
Async methods (hash, hmac, encrypt, decrypt, verifyHash) use the Web Crypto API (SubtleCrypto) and require a secure context (HTTPS) in browsers.