@tigthor/encyption-utils
v1.0.0
Published
Simple and secure encryption/decryption utility for TypeScript applications
Downloads
12
Maintainers
Readme
@tigthor/encyption-utils
A simple, secure, and easy-to-use encryption/decryption utility for TypeScript applications. Works seamlessly with both backend APIs and frontend Next.js applications.
Features
- 🔐 Secure AES Encryption: Uses AES-256-CBC encryption with PBKDF2 key derivation
- 🚀 Easy to Use: Simple API with both basic and advanced usage patterns
- 🔧 Configurable: Customizable encryption parameters
- 🌍 Universal: Works in both Node.js and browser environments
- 📝 TypeScript: Full TypeScript support with type definitions
- 🧪 Well Tested: Comprehensive test coverage
- 📦 Lightweight: Minimal dependencies
Installation
npm install @tigthor/encyption-utilsQuick Start
Basic Usage
import { quickEncrypt, quickDecrypt } from '@tigthor/encyption-utils';
// Encrypt
const encrypted = quickEncrypt('Hello, World!', 'my-secret-password');
console.log(encrypted); // "salt:iv:encryptedData"
// Decrypt
const decrypted = quickDecrypt(encrypted, 'my-secret-password');
console.log(decrypted); // "Hello, World!"Advanced Usage with EncryptionManager
import { EncryptionManager } from '@tigthor/encyption-utils';
// Create an instance with configuration
const crypto = new EncryptionManager({
secretKey: 'your-app-secret-key',
defaultOptions: {
iterations: 10000,
keySize: 256,
},
});
// Encrypt using the configured secret key
const encrypted = crypto.encryptSimple('Sensitive data');
const decrypted = crypto.decryptSimple(encrypted);
// Or encrypt with a specific password
const result = crypto.encrypt('Data to encrypt', 'specific-password');
const original = crypto.decrypt(result, 'specific-password');Global Instance Pattern
import { initializeEncryption, encrypt, decrypt } from '@tigthor/encyption-utils';
// Initialize once in your app
initializeEncryption({ secretKey: 'your-global-secret' });
// Use anywhere in your app
const encrypted = encrypt('My secret message');
const decrypted = decrypt(encrypted);Usage Examples
Backend API (Express.js)
import express from 'express';
import { EncryptionManager } from '@tigthor/encyption-utils';
const app = express();
const crypto = new EncryptionManager({ secretKey: process.env.ENCRYPTION_KEY });
app.post('/api/secure-data', (req, res) => {
const sensitiveData = req.body.data;
// Encrypt before storing in database
const encrypted = crypto.encryptSimple(JSON.stringify(sensitiveData));
// Store encrypted data...
res.json({ success: true });
});
app.get('/api/secure-data/:id', (req, res) => {
// Retrieve encrypted data from database...
const encryptedData = getFromDatabase(req.params.id);
// Decrypt before sending
const decrypted = JSON.parse(crypto.decryptSimple(encryptedData));
res.json({ data: decrypted });
});Frontend Next.js
// utils/crypto.ts
import { createEncryption } from '@tigthor/encyption-utils';
export const crypto = createEncryption({
secretKey: process.env.NEXT_PUBLIC_ENCRYPTION_KEY
});
// components/SecureForm.tsx
import { useState } from 'react';
import { crypto } from '../utils/crypto';
export default function SecureForm() {
const [data, setData] = useState('');
const handleSubmit = async () => {
// Encrypt data before sending to API
const encrypted = crypto.encryptSimple(data);
await fetch('/api/secure-endpoint', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ encryptedData: encrypted }),
});
};
return (
<form onSubmit={handleSubmit}>
<input
value={data}
onChange={(e) => setData(e.target.value)}
placeholder="Enter sensitive data"
/>
<button type="submit">Submit Securely</button>
</form>
);
}Environment Variables
# .env
ENCRYPTION_KEY=your-super-secret-encryption-key-here
# .env.local (Next.js)
NEXT_PUBLIC_ENCRYPTION_KEY=your-frontend-encryption-keyAPI Reference
EncryptionManager
The main class for encryption operations.
constructor(config?: CryptoConfig)Methods:
encrypt(plaintext: string, password?: string, options?: EncryptionOptions): EncryptionResultdecrypt(encryptedData: string | EncryptionResult, password?: string, options?: DecryptionOptions): stringencryptSimple(plaintext: string): stringdecryptSimple(encryptedString: string): stringsetSecretKey(key: string): voidupdateConfig(newConfig: Partial<CryptoConfig>): void
Quick Functions
Convenient functions for simple use cases:
quickEncrypt(plaintext: string, password: string): string
quickDecrypt(encryptedString: string, password: string): stringFactory Functions
createEncryption(config?: CryptoConfig): EncryptionManager
initializeEncryption(config: CryptoConfig): EncryptionManager
getEncryption(): EncryptionManagerUtility Functions
generateRandomKey(length?: number): string
generateSalt(length?: number): string
generateIV(length?: number): string
hashString(input: string): string
generateHMAC(message: string, key: string): string
verifyHMAC(message: string, key: string, signature: string): booleanConfiguration Options
interface CryptoConfig {
secretKey?: string;
defaultOptions?: EncryptionOptions;
}
interface EncryptionOptions {
algorithm?: string; // Default: 'AES'
keySize?: number; // Default: 256
iterations?: number; // Default: 10000
}Security Best Practices
- Use Environment Variables: Never hardcode encryption keys in your source code
- Strong Keys: Use long, random keys (at least 32 characters)
- Key Rotation: Regularly rotate your encryption keys
- HTTPS: Always use HTTPS when transmitting encrypted data
- Backend Validation: Always validate and sanitize data on the backend
Error Handling
The library throws descriptive errors for common issues:
try {
const encrypted = crypto.encryptSimple('data');
const decrypted = crypto.decryptSimple(encrypted);
} catch (error) {
console.error('Encryption error:', error.message);
}Browser Compatibility
Works in all modern browsers that support:
- ES2020+
- Web Crypto API (for secure random number generation)
Node.js Compatibility
- Node.js 16+
- Supports both CommonJS and ES Modules
Contributing
- Fork the repository
- Create a feature branch:
git checkout -b feature/new-feature - Make changes and add tests
- Run tests:
npm test - Commit changes:
git commit -am 'Add new feature' - Push to branch:
git push origin feature/new-feature - Submit a pull request
License
MIT License - see LICENSE file for details.
Changelog
1.0.0
- Initial release
- AES-256-CBC encryption
- PBKDF2 key derivation
- TypeScript support
- Browser and Node.js compatibility
