Arrow keys: ← previous · → next 3 of 37
@nodedk/cipher
0.3.0 stable server

cipher#

Password hashing, random tokens, UUIDs, and content hashes using node:crypto.

Install#

npm i @nodedk/cipher

Usage#

var cipher = require('@nodedk/cipher')

var password = 'example-password'
var stored = cipher.cloak(password)

console.log(cipher.match(password, stored)) // true
console.log(cipher.match('another-password', stored)) // false

var id = cipher.uuid()
var token = cipher.token(32)
var code = cipher.code()
var digest = cipher.hash('hello')

API#

All methods are synchronous. Password derivation blocks the calling thread while it runs.

uuid()#

Returns a UUID v7 string when crypto.randomUUIDv7 is available, falling back to a random UUID v4 string on older Node.js versions.

token(length = 32)#

Returns a random hexadecimal string. length is a positive integer specifying the number of characters, including odd lengths. A falsy length uses 32 characters.

code(length = 6)#

Returns a random numeric string with the specified number of digits. Each digit is generated independently using crypto.randomInt, preserving leading zeros.

cipher.code() // e.g. '004821'
cipher.code(4) // e.g. '0739'
cipher.code(8) // e.g. '90210467'

cloak(password)#

Takes a password string or Buffer. Returns hash:salt, using PBKDF2 with SHA-512, 600,000 iterations, a 64-byte derived key, and a random 16-byte salt. Store the entire returned string.

match(password, storedValue)#

Compares a password string or Buffer with a stored hash:salt string. Returns a boolean. Values without exactly two colon-separated parts or with an incorrect hash length return false.

hash(input, type = 'sha256')#

Returns a hexadecimal content hash. input is a string or Buffer; type is an algorithm supported by the runtime. Use cloak for passwords.

var cipher = require('@nodedk/cipher')

console.log(cipher.hash('hello', 'sha512'))
console.log(cipher.token(16).length) // 16
console.log(cipher.token(3).length) // 3

Created by Vidar Eldøy

Tools for business systems.