npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2025 – Pkg Stats / Ryan Hefner

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

Readme

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