Crypto
The Crypto module provides common cryptographic operations: password hashing, encryption/decryption, token generation, and HMAC signing.
Usage
import { FluxKit } from "@fluxkitdev/core";
const app = new FluxKit({
database: { uri: process.env.MONGODB_URI },
});
const { crypto } = app;
API Reference
Password Hashing
// Hash a password (bcrypt-based)
const hash = await crypto.hashPassword("my-secure-password");
// => "$2b$12$..."
// Verify a password against a hash
const isValid = await crypto.verifyPassword("my-secure-password", hash);
// => true
Token Generation
// Generate a cryptographically secure random token
const token = crypto.randomToken(32);
// => "a1b2c3d4e5f6..." (64 hex characters)
// Generate a UUID v4
const id = crypto.uuid();
// => "550e8400-e29b-41d4-a716-446655440000"
// Generate a short code (e.g., for verification)
const code = crypto.randomCode(6);
// => "482901"
Encryption / Decryption
const secret = "my-encryption-key";
// Encrypt data (AES-256-GCM)
const encrypted = crypto.encrypt("sensitive data", secret);
// => { ciphertext: "...", iv: "...", tag: "..." }
// Decrypt data
const decrypted = crypto.decrypt(encrypted, secret);
// => "sensitive data"
HMAC Signing
// Create an HMAC signature
const signature = crypto.hmac("payload-to-sign", "secret-key");
// => "a1b2c3..."
// Verify an HMAC signature
const valid = crypto.verifyHmac("payload-to-sign", "secret-key", signature);
// => true
Hashing
// SHA-256 hash
const hash = crypto.hash("data", "sha256");
// => "abc123..."
// MD5 hash (for checksums, not security)
const checksum = crypto.hash("data", "md5");
Configuration
| Variable | Default | Description |
|---|---|---|
BCRYPT_ROUNDS | 12 | bcrypt cost factor for password hashing |
ENCRYPTION_KEY | -- | Default encryption key (optional) |