@merncloud/secure-crypto-utils
v1.0.2
Published
A secure AES-256-CBC encryption/decryption utility with robust error handling and validation
Downloads
5
Maintainers
Readme
@merncloud/secure-crypto-utils
A secure, TypeScript-first encryption library using AES-256-CBC with robust error handling and validation.
Features
- 🔒 Secure: Uses AES-256-CBC encryption with random IVs
- 🛡️ Robust: Comprehensive input validation and error handling
- 📝 TypeScript: Full TypeScript support with detailed type definitions
- 🧪 Well-tested: High test coverage with comprehensive test suite
- 🚀 Easy to use: Simple API with sensible defaults
- ⚡ Performance: Optimized for both security and speed
Installation
npm install @merncloud/secure-crypto-utilsQuick Start
import { encrypt, decrypt } from "@merncloud/secure-crypto-utils";
// Set your encryption key (do this once, preferably via environment variable)
process.env.AES_SECRET_KEY = "your-32-character-secret-key-here!!!";
// Encrypt some data
const result = encrypt("Hello, World!");
console.log(result);
// {
// encryptedData: 'base64-encoded-encrypted-data',
// iv: 'base64-encoded-initialization-vector'
// }
// Decrypt the data
const decrypted = decrypt(result.encryptedData, result.iv);
console.log(decrypted); // 'Hello, World!'API Reference
encrypt(text: string, config?: CryptoConfig): EncryptionResult
Encrypts text using AES-256-CBC encryption.
Parameters:
text: The string to encrypt (max 10,000 characters by default)config: Optional configuration object
Returns: EncryptionResult
encryptedData: Base64 encoded encrypted dataiv: Base64 encoded initialization vector
Example:
const result = encrypt("Sensitive data");
// With custom configuration
const result2 = encrypt("Data", {
maxTextLength: 5000,
encryptionKey: "custom-32-char-key-here-!!!!!!!!!",
});decrypt(encryptedData: string, iv: string, config?: CryptoConfig): string
Decrypts data that was encrypted with the encrypt function.
Parameters:
encryptedData: Base64 encoded encrypted dataiv: Base64 encoded initialization vectorconfig: Optional configuration object
Returns: The decrypted string
Example:
const decrypted = decrypt(result.encryptedData, result.iv);
// With custom key
const decrypted2 = decrypt(data, iv, {
encryptionKey: "same-custom-key-used-for-encryption!",
});generateKey(length?: number): string
Generates a cryptographically secure random key.
Parameters:
length: Key length in bytes (default: 32 for AES-256)
Returns: Base64 encoded random key
Example:
const key = generateKey(); // 32-byte key
const longerKey = generateKey(64); // 64-byte key
// Use the generated key
process.env.AES_SECRET_KEY = key;safeCompare(a: string, b: string): boolean
Performs timing-safe string comparison to prevent timing attacks.
Parameters:
a: First string to compareb: Second string to compare
Returns: true if strings are equal, false otherwise
Example:
const isValid = safeCompare(userInput, expectedValue);Configuration
Environment Variables
AES_SECRET_KEY: Your encryption key (must be at least 32 characters)
CryptoConfig Interface
interface CryptoConfig {
maxTextLength?: number; // Maximum text length (default: 10000)
encryptionKey?: string; // Custom encryption key
algorithm?: string; // Encryption algorithm (default: 'aes-256-cbc')
}Error Handling
The library provides specific error types for different failure scenarios:
import {
encrypt,
ValidationError,
DecryptionError,
CryptoError,
} from "@merncloud/secure-crypto-utils";
try {
const result = encrypt("data");
const decrypted = decrypt(result.encryptedData, result.iv);
} catch (error) {
if (error instanceof ValidationError) {
console.error("Invalid input:", error.message);
} else if (error instanceof DecryptionError) {
console.error("Decryption failed:", error.message);
} else if (error instanceof CryptoError) {
console.error("Crypto operation failed:", error.message);
}
}Security Best Practices
Key Management: Never hardcode encryption keys. Use environment variables or secure key management services.
Key Rotation: Regularly rotate your encryption keys, especially in production environments.
Input Validation: The library validates inputs, but always validate data at your application level too.
HTTPS: Always use HTTPS when transmitting encrypted data over networks.
Storage: When storing encrypted data, store the IV alongside but never store the encryption key with the data.
Advanced Usage
Working with JSON Data
const userData = { id: 123, email: "[email protected]", role: "admin" };
const jsonString = JSON.stringify(userData);
const encrypted = encrypt(jsonString);
const decrypted = decrypt(encrypted.encryptedData, encrypted.iv);
const parsedData = JSON.parse(decrypted);Database Integration
// Storing in database
const sensitiveData = "user-sensitive-information";
const encrypted = encrypt(sensitiveData);
await db.users.update(userId, {
encryptedData: encrypted.encryptedData,
iv: encrypted.iv,
});
// Retrieving from database
const user = await db.users.findById(userId);
const decryptedData = decrypt(user.encryptedData, user.iv);Custom Key per Operation
// Generate a unique key for specific data
const dataKey = generateKey();
const encrypted = encrypt("sensitive-data", { encryptionKey: dataKey });
const decrypted = decrypt(encrypted.encryptedData, encrypted.iv, {
encryptionKey: dataKey,
});Contributing
- Fork the repository
- Create your feature branch (
git checkout -b feature/amazing-feature) - Run tests (
npm test) - Commit your changes (
git commit -m 'Add amazing feature') - Push to the branch (
git push origin feature/amazing-feature) - Open a Pull Request
Testing
# Run tests
npm test
# Run tests in watch mode
npm run test:watch
# Run tests with coverage
npm run test:coverageLicense
MIT License - see the LICENSE file for details.
Security
If you discover a security vulnerability, please send an email to [email protected] instead of using the issue tracker.
Changelog
v1.0.0
- Initial release
- AES-256-CBC encryption/decryption
- TypeScript support
- Comprehensive error handling
- Full test coverage
