@rtorcato/js-common / crypto
crypto
Functions
hashString()
hashString(
str,algorithm?):Promise<string>
Defined in: crypto/index.ts:30
Hashes a string using the specified algorithm.
Web Crypto supports SHA-1/256/384/512 only — there is no md5. An unsupported algorithm rejects.
Example
await hashString('hello')
// '2cf24dba5fb0a30e26e83b2ac5b9e29e1b161e5c1fa7425e73043362938b9824'
await hashString('hello', 'sha1') // 'aaf4c61ddcc5e8a2dabede0f3b482cd9aea9434d'
Parameters
str
string
The string to hash.
algorithm?
"sha1" | "sha256" | "sha384" | "sha512"
The hash algorithm (default: 'sha256').
Returns
Promise<string>
The hex-encoded hash.
randomHex()
randomHex(
length?):string
Defined in: crypto/index.ts:51
Generates a cryptographically secure random hex string of the specified length (in bytes).
Example
randomHex(4) // '9f3c1ab7' (8 hex chars)
randomHex() // 32 hex chars (16 bytes)
randomHex(32) // 64 hex chars — a password-reset token
Parameters
length?
number = 16
The number of bytes (not hex chars).
Returns
string
A random hex string.
hmacHash()
hmacHash(
str,secret,algorithm?):Promise<string>
Defined in: crypto/index.ts:70
Creates an HMAC hash of a string using a secret and algorithm.
Example
await hmacHash('payload', 's3cret')
// 'd1d0f5b6...' (64 hex chars, stable for the same input + secret)
await hmacHash('payload', 's3cret', 'sha1') // 40 hex chars
Parameters
str
string
The string to hash.
secret
string
The secret key.
algorithm?
"sha1" | "sha256" | "sha384" | "sha512"
The hash algorithm (default: 'sha256').
Returns
Promise<string>
The hex-encoded HMAC.
base64Encode()
base64Encode(
str):string
Defined in: crypto/index.ts:91
Encodes a string (as UTF-8) to base64.
Parameters
str
string
The string to encode.
Returns
string
The base64-encoded string.
base64Decode()
base64Decode(
b64):string
Defined in: crypto/index.ts:101
Decodes a base64 string to a UTF-8 string.
Parameters
b64
string
The base64 string to decode (standard alphabet; padding optional).
Returns
string
The decoded string.
Throws
When b64 is not valid base64 (including the URL-safe -/_ alphabet).