utils-crypto
v1.0.0
Published
A comprehensive utility library with crypto, data manipulation and more - compatible with React and Node.js
Maintainers
Readme
Utils Library
A comprehensive utility library with crypto, data manipulation and more - designed to work seamlessly in both React and Node.js environments.
📚 Documentation
🎯 📖 Live Documentation - Interactive Storybook documentation
Local Development:
npm run storybook # Development server at http://localhost:6006Build & Deploy:
npm run build-storybook # Build static documentation
./deploy-docs.sh --deploy # Deploy to GitHub Pages
./deploy-multiple.sh # Deploy to other platforms🚀 Quick Start
npm install utils-crypto🔐 Basic Encryption
const { encrypt, decrypt } = require('utils-crypto/crypto');
const result = encrypt('secret data');
console.log(result); // { encrypted: "...", iv: "...", key: "..." }
const decrypted = decrypt(result);
console.log(decrypted); // "secret data"🧪 Object Encryption (New!)
const { encryptObject, decryptObject } = require('utils-crypto/crypto');
const user = {
id: 123,
username: 'john',
email: '[email protected]',
profile: { ssn: '123-45-6789' }
};
// Encrypt values only, exclude public fields
const encrypted = encryptObject(user, 'my-key', {}, ['id', 'username']);
console.log(encrypted.encrypted);
// {
// id: 123, // ✅ Not encrypted
// username: 'john', // ✅ Not encrypted
// email: 'a1b2c3d4...', // 🔐 Encrypted
// profile: {
// ssn: 'x9y8z7w6...' // 🔐 Encrypted
// }
// }
const decrypted = decryptObject(encrypted, 'my-key');
console.log(decrypted); // ✅ Original object restored⚛️ React Hook
import { useObjectEncryption } from 'utils-crypto/crypto/react';
function MyComponent() {
const { encryptObjectData, decryptObjectData, isLoading } = useObjectEncryption();
const handleSecure = async () => {
const encrypted = await encryptObjectData(userData, 'my-key', ['publicField']);
// Store encrypted data securely
};
return <button onClick={handleSecure} disabled={isLoading}>🔐 Encrypt</button>;
}Features
- 🔐 Crypto Module - AES Encryption/Decryption, Hash functions, RSA keys, Digital signatures
- 🧪 Object Encryption - Encrypt object values while preserving structure and keys
- 🛠️ Modular Design - Import only what you need
- ⚛️ React Hooks - Ready-to-use React hooks for all utilities
- 🌐 Cross-Platform - Works in browser and Node.js
- 📝 TypeScript - Full TypeScript support with type definitions
- 🚀 Future Modules - Data manipulation, validation, and more coming soon
📖 Documentation & Examples
📋 Quick Reference
- 🚀 Implementation Guide - Step-by-step guide for common use cases
- 📚 Complete Usage Examples - Comprehensive React & Node.js examples
- 📖 Live Interactive Documentation - Storybook with live demos
🏗️ Complete Project Examples
- 🌐 Full-Stack App - Express.js + React with object encryption
- 🔐 Authentication System - JWT + encrypted user profiles
- 📁 Document Management - Enterprise-grade multi-level encryption
- ⚛️ React Components - Ready-to-use React components
- 🛠️ Node.js Examples - Server-side implementations
🎯 Feature Demonstration
- 📊 Storybook Story - Interactive demo with live code
- 🧪 Test Suite - Comprehensive test examples
- 📝 Feature Summary - Technical implementation details
💾 Node.js - Secure Configuration
const { encryptObject, decryptObject } = require('utils-crypto/crypto');
const config = {
app: { name: 'MyApp', version: '1.0' },
database: { host: 'localhost', password: 'secret123' },
api: { key: 'sk_live_abc123' }
};
// Encrypt secrets, keep public info readable
const encrypted = encryptObject(
config,
process.env.MASTER_KEY,
{},
['app.name', 'app.version', 'database.host'] // exclude public
);
// Save encrypted config
fs.writeFileSync('config.secure.json', JSON.stringify(encrypted));
// Later, decrypt for use
const decrypted = decryptObject(encrypted, process.env.MASTER_KEY);⚛️ React - Secure Form Data
import { useObjectEncryption } from 'utils-crypto/crypto/react';
function SecureForm() {
const { encryptObjectData, isLoading } = useObjectEncryption();
const [formData, setFormData] = useState({
name: '', // public
email: '', // sensitive
creditCard: '' // sensitive
});
const handleSubmit = async () => {
// Encrypt sensitive fields only
const encrypted = await encryptObjectData(
formData,
'form-key',
['name'] // exclude name from encryption
);
// Submit encrypted data
await fetch('/api/submit', {
method: 'POST',
body: JSON.stringify(encrypted)
});
};
return (
<form onSubmit={handleSubmit}>
<input value={formData.name} onChange={(e) =>
setFormData(prev => ({...prev, name: e.target.value}))} />
<input type="email" value={formData.email} onChange={(e) =>
setFormData(prev => ({...prev, email: e.target.value}))} />
<input value={formData.creditCard} onChange={(e) =>
setFormData(prev => ({...prev, creditCard: e.target.value}))} />
<button type="submit" disabled={isLoading}>
{isLoading ? '🔄 Encrypting...' : '🔐 Submit Securely'}
</button>
</form>
);
}🛒 Local Storage Encryption
// Custom hook for secure localStorage
function useSecureStorage(key, defaultValue, encryptionKey) {
const { encryptObjectData, decryptObjectData } = useObjectEncryption();
const [data, setData] = useState(defaultValue);
useEffect(() => {
// Load and decrypt from localStorage
const stored = localStorage.getItem(key);
if (stored) {
decryptObjectData(JSON.parse(stored), encryptionKey)
.then(decrypted => decrypted && setData(decrypted));
}
}, []);
const setSecureData = async (newData) => {
const encrypted = await encryptObjectData(newData, encryptionKey);
localStorage.setItem(key, JSON.stringify(encrypted));
setData(newData);
};
return [data, setSecureData];
}
// Usage
function UserProfile() {
const [profile, setProfile] = useSecureStorage('userProfile', {}, 'profile-key');
// profile data is automatically encrypted in localStorage
}Available Modules
🔐 Crypto Module
Complete cryptographic operations including encryption, hashing, and digital signatures.
Usage
Option 1: Import from specific modules (Recommended)
Crypto Module - CommonJS
const { encrypt, decrypt, hash, generatePassword, encryptObject, decryptObject } = require('utils-crypto/crypto');
// Basic Encryption
const data = "Hello, World!";
const result = encrypt(data);
console.log(result); // { encrypted: "...", iv: "...", key: "..." }
// Object Encryption (NEW!)
const userData = {
username: 'john_doe',
password: 'secret123',
profile: {
email: '[email protected]',
age: 30
}
};
// Encrypt only values, preserve keys and structure
const encryptedObj = encryptObject(userData, 'my-key', {}, ['username']); // exclude username
console.log(encryptedObj.encrypted);
// {
// username: 'john_doe', // not encrypted (excluded)
// password: 'a1b2c3d4...', // encrypted
// profile: {
// email: 'e5f6g7h8...', // encrypted
// age: { _encrypted: '03_enc', _type: 'number' } // encrypted number
// }
// }
// Decrypt object back to original
const decryptedObj = decryptObject(encryptedObj, 'my-key');
console.log(decryptedObj); // Original object restoredObject Encryption - Node.js Example
const { encryptObject, decryptObject } = require('utils-crypto/crypto');
// Server-side user data protection
const serverConfig = {
public: {
appName: 'MyApp',
version: '1.0.0'
},
secrets: {
databaseUrl: 'postgresql://user:pass@localhost/db',
jwtSecret: 'super-secret-key',
apiKeys: {
stripe: 'sk_live_abc123',
sendgrid: 'SG.xyz789'
}
}
};
// Encrypt sensitive data, exclude public info
const encryptedConfig = encryptObject(
serverConfig,
process.env.MASTER_KEY,
{},
['public.appName', 'public.version'] // exclude public fields
);
// Store encrypted config safely
require('fs').writeFileSync('config.encrypted.json', JSON.stringify(encryptedConfig));
// Later, decrypt when needed
const decryptedConfig = decryptObject(encryptedConfig, process.env.MASTER_KEY);Object Encryption - React Hook Example
import React, { useState } from 'react';
import { useObjectEncryption } from 'utils-crypto/crypto/react';
function SecureUserProfile() {
const { encryptObjectData, decryptObjectData, isLoading } = useObjectEncryption();
const [userProfile, setUserProfile] = useState({
id: 12345, // public
username: 'john_doe', // public
email: '[email protected]', // sensitive
profile: {
ssn: '123-45-6789', // sensitive
salary: 75000 // sensitive
}
});
const handleSecureProfile = async () => {
// Encrypt sensitive data only
const encrypted = await encryptObjectData(
userProfile,
'user-encryption-key',
['id', 'username'] // exclude public fields
);
if (encrypted) {
// Store encrypted profile to localStorage or send to server
localStorage.setItem('secureProfile', JSON.stringify(encrypted));
console.log('Profile encrypted and stored securely');
}
};
const handleLoadProfile = async () => {
const stored = localStorage.getItem('secureProfile');
if (stored) {
const encryptedProfile = JSON.parse(stored);
const decrypted = await decryptObjectData(encryptedProfile, 'user-encryption-key');
if (decrypted) {
setUserProfile(decrypted);
console.log('Profile decrypted and loaded');
}
}
};
return (
<div>
<h3>Secure User Profile</h3>
<button onClick={handleSecureProfile} disabled={isLoading}>
{isLoading ? 'Encrypting...' : 'Encrypt & Store Profile'}
</button>
<button onClick={handleLoadProfile} disabled={isLoading}>
{isLoading ? 'Decrypting...' : 'Load & Decrypt Profile'}
</button>
<pre>{JSON.stringify(userProfile, null, 2)}</pre>
</div>
);
}Crypto Module - ES Modules
import { encrypt, decrypt, hash, generatePassword } from 'utils-crypto/crypto';
// Same API as CommonJS
const result = encrypt("secret data");
const decrypted = decrypt(result);Crypto React Hooks
import React, { useState } from 'react';
import { useEncryption, usePasswordGenerator } from 'utils-crypto/crypto/react';
function MyComponent() {
const { encryptData, decryptData, isLoading, error } = useEncryption();
const { password, generate, isGenerating } = usePasswordGenerator();
const handleEncrypt = async () => {
const result = await encryptData('secret data');
console.log(result);
};
return (
<div>
<button onClick={handleEncrypt} disabled={isLoading}>
{isLoading ? 'Encrypting...' : 'Encrypt'}
</button>
<button onClick={() => generate(16)}>
Generate Password
</button>
{password && <p>Generated: {password}</p>}
</div>
);
}Option 2: Import from main entry point
// Import entire crypto module
import { crypto } from 'utils-crypto';
const result = crypto.encrypt('data');
// Or import specific functions
import { encrypt, decrypt } from 'utils-crypto';
const result = encrypt('data');API Reference
Core Functions
encrypt(data, key?, config?)
Encrypts data using AES encryption.
data: String to encryptkey: Optional hex key (generates random if not provided)config: Optional configuration object- Returns:
{ encrypted, iv, key? }
decrypt(options, config?)
Decrypts data using AES decryption.
options:{ encrypted, iv, key }config: Optional configuration object- Returns: Decrypted string
hash(data, options?)
Generates hash of data.
data: String to hashoptions:{ algorithm?, encoding? }- Returns: Hash string
generatePassword(length?, includeSymbols?)
Generates secure random password.
length: Password length (default: 16)includeSymbols: Include symbols (default: true)- Returns: Random password string
generateKeyPair() (Node.js only)
Generates RSA key pair.
- Returns: Promise<{ publicKey, privateKey }>
sign(data, privateKey) (Node.js only)
Signs data with private key.
- Returns:
{ signature, data }
verify(options) (Node.js only)
Verifies signature with public key.
options:{ data, signature, publicKey }- Returns: boolean
encryptObject(obj, key, config?, excludeKeys?)
Encrypts values of an object, preserving keys and structure.
obj: Object to encryptkey: Hex key for encryptionconfig: Optional configuration objectexcludeKeys: Array of keys to exclude from encryption- Returns: Encrypted object
decryptObject(encryptedObj, key, config?)
Decrypts an encrypted object back to its original form.
encryptedObj: Encrypted objectkey: Hex key for decryptionconfig: Optional configuration object- Returns: Decrypted object
React Hooks
useEncryption()
Hook for encryption/decryption operations.
Returns: { encryptData, decryptData, isLoading, error, clearError }
useHash()
Hook for hashing operations.
Returns: { hashData, isLoading, error, clearError }
usePasswordGenerator()
Hook for password generation.
Returns: { password, generate, clear, isGenerating }
useEncryptionKeys()
Hook for managing encryption keys.
Returns: { keys, saveKey, getKey, removeKey, clearKeys }
Utility Functions
generateRandomString(length?)
Generates random hex string.
isValidHex(str)
Validates hex string format.
isValidBase64(str)
Validates base64 string format.
stringToBuffer(str, encoding?)
Converts string to Buffer.
bufferToString(buffer, encoding?)
Converts Buffer to string.
Configuration
Default encryption configuration:
{
algorithm: 'aes-256-cbc',
keyLength: 32,
ivLength: 16
}You can override these settings by passing a config object to encrypt/decrypt functions.
Browser Compatibility
The library automatically detects the environment and uses appropriate crypto implementations:
- Node.js: Uses built-in
cryptomodule - Browser: Uses
crypto-browserifyfor compatibility
Development
# Install dependencies
npm install
# Build the library
npm run build
# Run tests
npm test
# Watch mode for development
npm run dev
# Lint code
npm run lintExamples
Node.js Example
const crypto = require('npm-util-crypto');
// Generate key pair
crypto.generateKeyPair().then(({ publicKey, privateKey }) => {
// Sign data
const signature = crypto.sign('important data', privateKey);
// Verify signature
const isValid = crypto.verify({
data: 'important data',
signature: signature.signature,
publicKey
});
console.log('Signature valid:', isValid);
});React Example with Key Management
import React, { useState } from 'react';
import { useEncryption, useEncryptionKeys } from 'npm-util-crypto';
function SecureNotebook() {
const [note, setNote] = useState('');
const [encryptedNote, setEncryptedNote] = useState(null);
const { encryptData, decryptData } = useEncryption();
const { saveKey, getKey } = useEncryptionKeys();
const saveNote = async () => {
const result = await encryptData(note);
if (result) {
setEncryptedNote(result);
saveKey('note-key', result.key);
}
};
const loadNote = async () => {
if (encryptedNote) {
const key = getKey('note-key');
if (key) {
const decrypted = await decryptData({
...encryptedNote,
key
});
setNote(decrypted || '');
}
}
};
return (
<div>
<textarea
value={note}
onChange={(e) => setNote(e.target.value)}
placeholder="Write your secure note..."
/>
<button onClick={saveNote}>Encrypt & Save</button>
<button onClick={loadNote}>Load & Decrypt</button>
</div>
);
}License
MIT
Contributing
Pull requests are welcome. For major changes, please open an issue first to discuss what you would like to change.
Security Note
This library is intended for general use cases. For high-security applications, please consult with security experts and consider additional security measures.
