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

@tigthor/encyption-utils

v1.0.0

Published

Simple and secure encryption/decryption utility for TypeScript applications

Downloads

12

Readme

@tigthor/encyption-utils

A simple, secure, and easy-to-use encryption/decryption utility for TypeScript applications. Works seamlessly with both backend APIs and frontend Next.js applications.

Features

  • 🔐 Secure AES Encryption: Uses AES-256-CBC encryption with PBKDF2 key derivation
  • 🚀 Easy to Use: Simple API with both basic and advanced usage patterns
  • 🔧 Configurable: Customizable encryption parameters
  • 🌍 Universal: Works in both Node.js and browser environments
  • 📝 TypeScript: Full TypeScript support with type definitions
  • 🧪 Well Tested: Comprehensive test coverage
  • 📦 Lightweight: Minimal dependencies

Installation

npm install @tigthor/encyption-utils

Quick Start

Basic Usage

import { quickEncrypt, quickDecrypt } from '@tigthor/encyption-utils';

// Encrypt
const encrypted = quickEncrypt('Hello, World!', 'my-secret-password');
console.log(encrypted); // "salt:iv:encryptedData"

// Decrypt
const decrypted = quickDecrypt(encrypted, 'my-secret-password');
console.log(decrypted); // "Hello, World!"

Advanced Usage with EncryptionManager

import { EncryptionManager } from '@tigthor/encyption-utils';

// Create an instance with configuration
const crypto = new EncryptionManager({
  secretKey: 'your-app-secret-key',
  defaultOptions: {
    iterations: 10000,
    keySize: 256,
  },
});

// Encrypt using the configured secret key
const encrypted = crypto.encryptSimple('Sensitive data');
const decrypted = crypto.decryptSimple(encrypted);

// Or encrypt with a specific password
const result = crypto.encrypt('Data to encrypt', 'specific-password');
const original = crypto.decrypt(result, 'specific-password');

Global Instance Pattern

import { initializeEncryption, encrypt, decrypt } from '@tigthor/encyption-utils';

// Initialize once in your app
initializeEncryption({ secretKey: 'your-global-secret' });

// Use anywhere in your app
const encrypted = encrypt('My secret message');
const decrypted = decrypt(encrypted);

Usage Examples

Backend API (Express.js)

import express from 'express';
import { EncryptionManager } from '@tigthor/encyption-utils';

const app = express();
const crypto = new EncryptionManager({ secretKey: process.env.ENCRYPTION_KEY });

app.post('/api/secure-data', (req, res) => {
  const sensitiveData = req.body.data;
  
  // Encrypt before storing in database
  const encrypted = crypto.encryptSimple(JSON.stringify(sensitiveData));
  
  // Store encrypted data...
  res.json({ success: true });
});

app.get('/api/secure-data/:id', (req, res) => {
  // Retrieve encrypted data from database...
  const encryptedData = getFromDatabase(req.params.id);
  
  // Decrypt before sending
  const decrypted = JSON.parse(crypto.decryptSimple(encryptedData));
  
  res.json({ data: decrypted });
});

Frontend Next.js

// utils/crypto.ts
import { createEncryption } from '@tigthor/encyption-utils';

export const crypto = createEncryption({ 
  secretKey: process.env.NEXT_PUBLIC_ENCRYPTION_KEY 
});

// components/SecureForm.tsx
import { useState } from 'react';
import { crypto } from '../utils/crypto';

export default function SecureForm() {
  const [data, setData] = useState('');

  const handleSubmit = async () => {
    // Encrypt data before sending to API
    const encrypted = crypto.encryptSimple(data);
    
    await fetch('/api/secure-endpoint', {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({ encryptedData: encrypted }),
    });
  };

  return (
    <form onSubmit={handleSubmit}>
      <input 
        value={data} 
        onChange={(e) => setData(e.target.value)}
        placeholder="Enter sensitive data"
      />
      <button type="submit">Submit Securely</button>
    </form>
  );
}

Environment Variables

# .env
ENCRYPTION_KEY=your-super-secret-encryption-key-here

# .env.local (Next.js)
NEXT_PUBLIC_ENCRYPTION_KEY=your-frontend-encryption-key

API Reference

EncryptionManager

The main class for encryption operations.

constructor(config?: CryptoConfig)

Methods:

  • encrypt(plaintext: string, password?: string, options?: EncryptionOptions): EncryptionResult
  • decrypt(encryptedData: string | EncryptionResult, password?: string, options?: DecryptionOptions): string
  • encryptSimple(plaintext: string): string
  • decryptSimple(encryptedString: string): string
  • setSecretKey(key: string): void
  • updateConfig(newConfig: Partial<CryptoConfig>): void

Quick Functions

Convenient functions for simple use cases:

quickEncrypt(plaintext: string, password: string): string
quickDecrypt(encryptedString: string, password: string): string

Factory Functions

createEncryption(config?: CryptoConfig): EncryptionManager
initializeEncryption(config: CryptoConfig): EncryptionManager
getEncryption(): EncryptionManager

Utility Functions

generateRandomKey(length?: number): string
generateSalt(length?: number): string
generateIV(length?: number): string
hashString(input: string): string
generateHMAC(message: string, key: string): string
verifyHMAC(message: string, key: string, signature: string): boolean

Configuration Options

interface CryptoConfig {
  secretKey?: string;
  defaultOptions?: EncryptionOptions;
}

interface EncryptionOptions {
  algorithm?: string;    // Default: 'AES'
  keySize?: number;      // Default: 256
  iterations?: number;   // Default: 10000
}

Security Best Practices

  1. Use Environment Variables: Never hardcode encryption keys in your source code
  2. Strong Keys: Use long, random keys (at least 32 characters)
  3. Key Rotation: Regularly rotate your encryption keys
  4. HTTPS: Always use HTTPS when transmitting encrypted data
  5. Backend Validation: Always validate and sanitize data on the backend

Error Handling

The library throws descriptive errors for common issues:

try {
  const encrypted = crypto.encryptSimple('data');
  const decrypted = crypto.decryptSimple(encrypted);
} catch (error) {
  console.error('Encryption error:', error.message);
}

Browser Compatibility

Works in all modern browsers that support:

  • ES2020+
  • Web Crypto API (for secure random number generation)

Node.js Compatibility

  • Node.js 16+
  • Supports both CommonJS and ES Modules

Contributing

  1. Fork the repository
  2. Create a feature branch: git checkout -b feature/new-feature
  3. Make changes and add tests
  4. Run tests: npm test
  5. Commit changes: git commit -am 'Add new feature'
  6. Push to branch: git push origin feature/new-feature
  7. Submit a pull request

License

MIT License - see LICENSE file for details.

Changelog

1.0.0

  • Initial release
  • AES-256-CBC encryption
  • PBKDF2 key derivation
  • TypeScript support
  • Browser and Node.js compatibility