Skip to content

uddin-a/basic-secure-string

Folders and files

NameName
Last commit message
Last commit date

Latest commit

Β 

History

2 Commits
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 

Repository files navigation

basic-secure-string

Universal string encryption/decryption library in both Node.js and browser environments

License: MIT Node Version

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-string

Basic 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

πŸ”‘ Environment Setup

Important: Never hardcode encryption keys in your code!

1. Create .env file

STRING_ENCRYPTION_KEY=your-very-strong-secret-key-here

2. 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:watch

Test 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)

  1. Password β†’ PBKDF2 (10,000 iterations, SHA-256)
  2. Random IV generation
  3. AES-256-CBC encryption
  4. IV + Ciphertext β†’ Hex encoding

Node.js (Native Crypto)

  1. Password β†’ SHA-256 hash
  2. Random IV generation (crypto.randomBytes)
  3. AES-256-CBC encryption
  4. 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 .env files 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.

  1. Fork the repository
  2. Create your feature branch (git checkout -b feature/AmazingFeature)
  3. Commit your changes (git commit -m 'Add some AmazingFeature')
  4. Push to the branch (git push origin feature/AmazingFeature)
  5. Open a Pull Request

πŸ“ž Support

For issues, questions, or suggestions:

πŸ™ Acknowledgments

Built with ❀️ for secure string encryption across all environments.


Secure your strings, protect your data

About

No description, website, or topics provided.

Resources

License

Security policy

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published