basic-secure-string
v1.0.0
Published
Universal string encryption/decryption library supporting both Node.js and browser environments using AES-256-CBC
Downloads
95
Maintainers
Readme
basic-secure-string
Universal string encryption/decryption library in both Node.js and browser environments
A lightweight, secure, and easy-to-use encryption library that works seamlessly in both Node.js and browser environments. Perfect for encrypting sensitive data including URLs, protecting strings, equipment identifiers, securing session tokens, and more.
✨ Features
- 🔐 AES-256-CBC Encryption - Industry-standard security
- 🌐 Universal - Works in Node.js and browsers
- 🎯 Easy to Use - Simple, intuitive API
- 🔄 Environment Detection - Automatically uses the best crypto implementation
- 📦 Zero Dependencies (runtime)
- 🧪 Fully Tested - Comprehensive test suite
- 📝 TypeScript Support - Full type definitions included
- 🚀 Lightweight - Minimal footprint
🚀 Quick Start
Installation
npm install basic-secure-stringBasic Usage
import StringEncryption from "basic-secure-string";
// Create an encryptor instance
const encryptor = new StringEncryption(process.env.STRING_ENCRYPTION_KEY!);
// Encrypt a string
const encrypted = await encryptor.encryptStr("sensitive-data");
console.log(encrypted); // "a1b2c3d4e5f6..."
// Decrypt it back
const decrypted = await encryptor.decryptStr(encrypted);
console.log(decrypted); // "sensitive-data"Equipment Encryption
import StringEncryption from "basic-secure-string";
const encryptor = new StringEncryption(process.env.STRING_ENCRYPTION_KEY!);
// Encrypt equipment data
const encrypted = await encryptor.encryptEquipment(10, 228811);
// Use in URL
const url = `https://example.com/equipment/${encrypted}`;
// Decrypt equipment data
const equipment = await encryptor.decryptEquipment(encrypted);
console.log(equipment.companyCode); // "10"
console.log(equipment.equipmentNumber); // "228811"📚 Documentation
- Getting Started Guide - Installation, setup, and basic usage
- API Reference - Complete API documentation with examples
- Security Guide - Security features, best practices, and compliance
🔑 Environment Setup
Important: Never hardcode encryption keys in your code!
1. Create .env file
STRING_ENCRYPTION_KEY=your-very-strong-secret-key-here2. Generate a secure key
# Using OpenSSL (recommended)
openssl rand -base64 48
# Using Node.js
node -e "console.log(require('crypto').randomBytes(48).toString('base64'))"3. Load environment variables
import "dotenv/config";
import StringEncryption from "basic-secure-string";
const encryptor = new StringEncryption(process.env.STRING_ENCRYPTION_KEY!);4. Add .env to .gitignore
echo ".env" >> .gitignore💡 Use Cases
Secure URL Parameters
const userId = "12345";
const encryptedId = await encryptor.encryptStr(userId);
const url = `https://example.com/user?id=${encryptedId}`;API Route Protection
app.get("/api/equipment/:id", async (req, res) => {
try {
const equipment = await encryptor.decryptEquipment(req.params.id);
res.json(equipment);
} catch (error) {
res.status(400).json({ error: "Invalid equipment ID" });
}
});Session Tokens
const sessionData = JSON.stringify({
userId: "user123",
timestamp: Date.now(),
});
const token = await encryptor.encryptStr(sessionData);React/Frontend Applications
const encryptor = new StringEncryption(import.meta.env.VITE_ENCRYPTION_KEY);
useEffect(() => {
const params = new URLSearchParams(window.location.search);
const encryptedId = params.get("id");
if (encryptedId) {
const data = await encryptor.decryptEquipment(encryptedId);
setEquipment(data);
}
}, []);🔒 Security Features
- AES-256-CBC - Military-grade encryption
- Unique IVs - Every encryption uses a random initialization vector
- PBKDF2 Key Derivation (Browser) - 10,000 iterations for enhanced security
- Automatic Padding - PKCS#7 padding for block alignment
- Tamper Detection - Fails gracefully when data is modified
- No Pattern Leakage - Same plaintext produces different ciphertext
🧪 Testing
The library includes comprehensive tests covering:
- ✅ Node.js environment
- ✅ Browser environment
- ✅ Edge cases and boundary conditions
- ✅ Security scenarios
- ✅ Error handling
- ✅ Performance tests
Run Tests
# Run all tests
npm test
# Run with coverage
npm run test:coverage
# Run specific test suites
npm run test:node # Node.js tests only
npm run test:browser # Browser tests only
npm run test:edge-cases # Edge case tests only
# Watch mode
npm run test:watchTest Coverage
The library maintains high test coverage across:
- Constructor validation
- Encryption/decryption operations
- Equipment-specific methods
- Error handling
- Unicode and special characters
- Concurrent operations
- Security scenarios
📋 API Overview
Constructor
new StringEncryption(key: string, salt?: string)Methods
encryptStr(str: string): Promise<string>
Encrypts a string and returns hex-encoded ciphertext.
decryptStr(str: string): Promise<string>
Decrypts a hex-encoded ciphertext back to plaintext.
encryptEquipment(companyCode, equipmentNumber, separator?): Promise<string>
Encrypts equipment identification data.
decryptEquipment(str: string, separator?): Promise<{ companyCode, equipmentNumber }>
Decrypts and parses equipment data.
Static Properties
StringEncryption.EQUIPMENT_SEPARATOR: "#"
Default separator used between company code and equipment number.
🌍 Browser Support
Works in all modern browsers that support the Web Crypto API:
- Chrome 37+
- Firefox 34+
- Safari 11+
- Edge 12+
📦 Node.js Support
- Node.js 18.0.0 or higher
⚙️ How It Works
Browser (Web Crypto API)
- Password → PBKDF2 (10,000 iterations, SHA-256)
- Random IV generation
- AES-256-CBC encryption
- IV + Ciphertext → Hex encoding
Node.js (Native Crypto)
- Password → SHA-256 hash
- Random IV generation (crypto.randomBytes)
- AES-256-CBC encryption
- IV + Ciphertext → Hex encoding
🛡️ Best Practices
✅ DO:
- Use strong, randomly generated keys (48+ characters)
- Store keys in environment variables
- Use different keys for different environments
- Rotate keys periodically
- Handle decryption errors gracefully
❌ DON'T:
- Hardcode encryption keys
- Commit
.envfiles to version control - Use the same key across multiple applications
- Use weak or predictable keys
- Share keys via insecure channels
📄 License
MIT License - see LICENSE file for details
🤝 Contributing
Contributions are welcome! Please feel free to submit a Pull Request.
- Fork the repository
- Create your feature branch (
git checkout -b feature/AmazingFeature) - Commit your changes (
git commit -m 'Add some AmazingFeature') - Push to the branch (
git push origin feature/AmazingFeature) - Open a Pull Request
📞 Support
For issues, questions, or suggestions:
- Open an issue on GitHub
- Check the documentation
- Review the security guide
🙏 Acknowledgments
Built with ❤️ for secure string encryption across all environments.
Secure your strings, protect your data
