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.
- π 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
npm install basic-secure-stringimport 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"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"- Getting Started Guide - Installation, setup, and basic usage
- API Reference - Complete API documentation with examples
- Security Guide - Security features, best practices, and compliance
Important: Never hardcode encryption keys in your code!
STRING_ENCRYPTION_KEY=your-very-strong-secret-key-here# Using OpenSSL (recommended)
openssl rand -base64 48
# Using Node.js
node -e "console.log(require('crypto').randomBytes(48).toString('base64'))"import "dotenv/config";
import StringEncryption from "basic-secure-string";
const encryptor = new StringEncryption(process.env.STRING_ENCRYPTION_KEY!);echo ".env" >> .gitignoreconst userId = "12345";
const encryptedId = await encryptor.encryptStr(userId);
const url = `https://example.com/user?id=${encryptedId}`;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" });
}
});const sessionData = JSON.stringify({
userId: "user123",
timestamp: Date.now(),
});
const token = await encryptor.encryptStr(sessionData);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);
}
}, []);- 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
The library includes comprehensive tests covering:
- β Node.js environment
- β Browser environment
- β Edge cases and boundary conditions
- β Security scenarios
- β Error handling
- β Performance 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:watchThe library maintains high test coverage across:
- Constructor validation
- Encryption/decryption operations
- Equipment-specific methods
- Error handling
- Unicode and special characters
- Concurrent operations
- Security scenarios
new StringEncryption(key: string, salt?: string)Encrypts a string and returns hex-encoded ciphertext.
Decrypts a hex-encoded ciphertext back to plaintext.
Encrypts equipment identification data.
Decrypts and parses equipment data.
Default separator used between company code and equipment number.
Works in all modern browsers that support the Web Crypto API:
- Chrome 37+
- Firefox 34+
- Safari 11+
- Edge 12+
- Node.js 18.0.0 or higher
- Password β PBKDF2 (10,000 iterations, SHA-256)
- Random IV generation
- AES-256-CBC encryption
- IV + Ciphertext β Hex encoding
- Password β SHA-256 hash
- Random IV generation (crypto.randomBytes)
- AES-256-CBC encryption
- IV + Ciphertext β Hex encoding
β 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
MIT License - see LICENSE file for details
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
For issues, questions, or suggestions:
- Open an issue on GitHub
- Check the documentation
- Review the security guide
Built with β€οΈ for secure string encryption across all environments.
Secure your strings, protect your data