libcryptts
v1.0.1
Published
TypeScript crypto library for encrypting, decrypting, and hashing text, files, or binary data. Works in Node.js 24+ and browser environments.
Maintainers
Readme
libcryptts
A TypeScript crypto library for encrypting, decrypting, and hashing text, files, or binary data Modern WebCrypto APIs Strong Typing Node.js Enterprise-Grade Security
What's New in v1.0.1
Complete Rewrite & Major Features Added:
- Full Encryption/Decryption - Text, buffers, and files
- Multiple Output Formats - Plaintext (combined) & Binary (separated)
- Simplified API - Clean, modular architecture
- Enhanced Security - AES-256-GCM with proper authentication
- Zero Dependencies - Pure Node.js crypto implementation
- TypeScript Strict - Full type safety with exact optional properties
Features
- ** AES-256-GCM Encryption** - Military-grade authenticated encryption
- ** Secure Key Generation** - Cryptographically strong random generation
- ** TypeScript First** - Full type safety and IntelliSense support
- ** Modern Crypto** - Built on Node.js crypto APIs
- ** Zero Dependencies** - Lightweight and secure
- ** Enterprise Ready** - Production-grade error handling and security
- ** File Support** - Encrypt/decrypt files with ease
- ** Multiple Formats** - Plaintext (combined) and Binary output options
Installation
npm install libcrypttsRequirements: Node.js 24.0.0 or higher
Quick Start
Generate Cryptographic Keys
import LibCryptTS from 'libcryptts';
// Initialize with custom security iterations (optional)
const crypto = new LibCryptTS(200000);
// Generate keys - automatically saves to file
const result = await crypto.keygen({
keyName: 'myapp',
outputPath: './secrets/myapp.keys',
});
console.log(' Access Token:', result.keys.accessToken);
console.log(' Saved to:', result.filePath);Encrypt & Decrypt Text
// Encrypt text
const originalText = 'Hello, World! This is a secret message.';
const encryptResult = await crypto.encryptText(originalText, result.keys, {
outputType: 'plaintext', // or 'binary'
});
console.log(' Encrypted:', encryptResult.encryptedData.substring(0, 50) + '...');
// Decrypt text
const decryptResult = await crypto.decryptCombined(encryptResult.encryptedData, result.keys);
console.log(' Decrypted:', decryptResult.decryptedData);
console.log(' Match:', originalText === decryptResult.decryptedData);Encrypt & Decrypt Files
// Encrypt file
const fileEncryptResult = await crypto.encryptToFile(
'Sensitive file content',
result.keys,
'./encrypted-file.txt'
);
// Decrypt file
const fileDecryptResult = await crypto.decryptFile(
'./encrypted-file.txt',
fileEncryptResult.iv,
result.keys
);Advanced Usage
Binary Format Encryption
// Binary format (separate components)
const binaryEncrypt = await crypto.encryptText(originalText, result.keys, {
outputType: 'binary',
});
// Decrypt binary format
const binaryDecrypt = await crypto.decryptText(
binaryEncrypt.encryptedData,
binaryEncrypt.iv,
result.keys,
true, // isBinaryFormat
binaryEncrypt.authTag
);Working with Buffers
// Encrypt buffer data
const bufferData = Buffer.from('Binary data', 'utf8');
const bufferEncrypt = await crypto.encryptBuffer(bufferData, result.keys);
// Decrypt to buffer
const decryptedBuffer = await crypto.decryptBuffer(
bufferEncrypt.encryptedData,
bufferEncrypt.iv,
result.keys
);Key Management
// Load existing keys
const loadedKeys = crypto.loadKeys('./secrets/myapp.keys');
// Validate key integrity
const isValid = await crypto.validateMasterKey(loadedKeys.masterKey);
console.log('Master key integrity:', isValid ? ' Valid' : ' Compromised');
// Generate individual components
import { generateSalt, generateIv, genAccessToken } from 'libcryptts';
const masterKey = generateMasterKey();
const salt = generateSalt();
const iv = generateIv();
const accessToken = genAccessToken(masterKey, salt, iv);API Reference
LibCryptTS Class
Constructor
new LibCryptTS(iterations?: number)iterations: Optional scrypt iterations (default: 100,000)
Key Management Methods
keygen(options?: KeyGenOptions): Promise<KeyGenResult>- Generate cryptographic keysvalidateMasterKey(masterKey: string): Promise<boolean>- Validate master key integrityloadKeys(filePath: string): KeysConfig- Load keys from file
Encryption Methods
encryptText(text: string, keysConfig: KeysConfig, options?: EncryptOptions): Promise<EncryptResult>encryptBuffer(buffer: Buffer, keysConfig: KeysConfig, options?: EncryptOptions): Promise<EncryptResult>encryptFile(filePath: string, keysConfig: KeysConfig, options?: EncryptOptions): Promise<FileEncryptResult>encryptToFile(data: string | Buffer, keysConfig: KeysConfig, outputPath: string, options?: EncryptOptions): Promise<FileEncryptResult>encryptCombined(data: string | Buffer, keysConfig: KeysConfig): Promise<EncryptResult>- Easy combined format
Decryption Methods
decryptText(encryptedData: string, iv: string, keysConfig: KeysConfig, isBinaryFormat?: boolean, authTag?: string): Promise<DecryptResult>decryptBuffer(encryptedData: string, iv: string, keysConfig: KeysConfig, isBinaryFormat?: boolean, authTag?: string): Promise<Buffer>decryptFile(encryptedFilePath: string, iv: string, keysConfig: KeysConfig, isBinaryFormat?: boolean, authTag?: string): Promise<FileDecryptResult>decryptToFile(encryptedData: string, iv: string, keysConfig: KeysConfig, outputPath: string, isBinaryFormat?: boolean, authTag?: string): Promise<FileDecryptResult>decryptCombined(combinedData: string, keysConfig: KeysConfig): Promise<DecryptResult>- Easy combined format
Static Properties
LibCryptTS.version- Library versionLibCryptTS.algorithms- Supported algorithmsLibCryptTS.keyFormats- Available key formats
Security Features
Cryptographic Standards
- AES-256-GCM - Authenticated encryption with associated data
- Scrypt KDF - Key derivation with configurable iterations
- 12-byte IV - Proper initialization vector size for GCM
- 256-bit Keys - Military-grade key length
- 16-byte Auth Tag - Strong authentication
Security Protections
- Timing Attack Protection - Constant-time comparisons
- Secure File Permissions - 0o600 (owner read/write only)
- Input Validation - Comprehensive parameter validation
- Memory Safety - Proper buffer handling and cleanup
- Authentication Tags - Ensures data integrity
Output Formats
Plaintext Format (Combined)
// Base64 string containing: IV (12) + AuthTag (16) + EncryptedData
// Easy to store and transmit
const result = await crypto.encryptText(data, keys, { outputType: 'plaintext' });
// Use decryptCombined for easy decryptionBinary Format (Separated)
// Separate components for advanced use cases
const result = await crypto.encryptText(data, keys, { outputType: 'binary' });
// encryptedData (hex), iv (base64), authTag (hex)Project Structure
libcryptts/
src/
index.ts # Main exports and library entry
types/
types.ts # Type definitions
lib/
config.ts # Configuration and utilities
keygen.ts # Key generation
enc.ts # Encryption core
dc.ts # Decryption core
error.ts # Error handling
dist/ # Compiled JavaScript
test/ # Test suitesTesting
Complete Feature Test
# Create test file
mkdir -p test
cat > test/test-complete.js << 'EOF'
import LibCryptTS from '../dist/index.js';
const run = async () => {
try {
console.log(' Testing Complete LibCryptTS Features\n');
const crypto = new LibCryptTS(150000);
// Generate keys
console.log('1. Generating keys...');
const keyResult = await crypto.keygen({
keyName: 'test-app',
outputPath: './test-secrets/test'
});
// Test encryption/decryption
console.log('\n2. Testing encryption/decryption...');
const originalText = 'Hello, World! This is a secret message.';
const encryptResult = await crypto.encryptText(originalText, keyResult.keys);
const decryptResult = await crypto.decryptCombined(
encryptResult.encryptedData,
keyResult.keys
);
console.log(' All tests completed successfully!');
} catch (error) {
console.error(' Error:', error.message);
}
};
run();
EOF
# Run test
node test/test-complete.jsUsage Examples
Basic Text Encryption
import LibCryptTS from 'libcryptts';
const crypto = new LibCryptTS();
const keys = await crypto.keygen({ keyName: 'app' });
// Encrypt
const encrypted = await crypto.encryptText('Secret message', keys.keys);
// Decrypt
const decrypted = await crypto.decryptCombined(encrypted.encryptedData, keys.keys);
console.log(decrypted.decryptedData); // 'Secret message'File Encryption
// Encrypt file content
await crypto.encryptToFile('Sensitive data', keys.keys, './encrypted-data.txt');
// Decrypt file
const result = await crypto.decryptFile('./encrypted-data.txt', encrypted.iv, keys.keys);Binary Format for Advanced Use
// Binary format gives you separate components
const binaryResult = await crypto.encryptText(data, keys.keys, {
outputType: 'binary',
});
// Components are separate
console.log('IV:', binaryResult.iv);
console.log('Auth Tag:', binaryResult.authTag);
console.log('Encrypted:', binaryResult.encryptedData);Advanced Configuration
Custom Iterations
// Development (faster)
const devCrypto = new LibCryptTS(100000);
// Production (more secure)
const prodCrypto = new LibCryptTS(300000);Error Handling
import { CryptoError, errorHandler } from 'libcryptts';
try {
const result = await crypto.encryptText(text, keys);
} catch (error) {
if (error instanceof CryptoError) {
console.error('Cryptographic error:', error.code);
console.error('Context:', error.context);
} else {
console.error('Unexpected error:', error);
}
}Performance
| Operation | Time (ms) | Memory (MB) | Security | | --------------------- | --------- | ----------- | --------- | | Key Generation (100k) | ~120ms | ~128MB | Good | | Key Generation (300k) | ~360ms | ~128MB | Excellent | | Text Encryption | <5ms | <1MB | Maximum | | File Encryption (1MB) | ~10ms | ~2MB | Maximum |
Migration from v1.0.0
Breaking Changes:
- Removed deprecated
CryptoCoreclass - Simplified folder structure
- New encryption/decryption API
- Enhanced type safety with exact optional properties
Upgrade Path:
// OLD (v1.0.0)
import { CryptoCore } from 'libcryptts/lib/core/crypto-core';
// NEW (v1.0.1)
import LibCryptTS from 'libcryptts';
const crypto = new LibCryptTS();Troubleshooting
Common Issues
File Not Found
// Ensure the directory exists
await crypto.keygen({
outputPath: './existing-directory/keys',
});Invalid Key File
// Regenerate if corrupted
await crypto.keygen({ keyName: 'recovery' });Decryption Failed
// Ensure you're using the correct format
// For combined format:
await crypto.decryptCombined(encryptedData, keys);
// For binary format:
await crypto.decryptText(encryptedData, iv, keys, true, authTag);Contributing
We welcome contributions! Please see our contributing guidelines:
- Fork the repository
- Create a feature branch:
git checkout -b feature/amazing-feature - Commit your changes:
git commit -m 'Add amazing feature' - Push to the branch:
git push origin feature/amazing-feature - Open a Pull Request
Development Setup
git clone https://github.com/nxf-oss/libcryptts.git
cd libcryptts
npm install
npm run build
npm testLicense
MIT License - see LICENSE file for details.
Acknowledgments
Built with modern TypeScript and Node.js crypto APIs.
Special thanks to the Node.js Crypto team and TypeScript community for their excellent work.
** Star us on GitHub if you find this project helpful!**
"Security is not a product, but a process." - Bruce Schneier
