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 🙏

© 2026 – Pkg Stats / Ryan Hefner

@merncloud/secure-crypto-utils

v1.0.2

Published

A secure AES-256-CBC encryption/decryption utility with robust error handling and validation

Downloads

5

Readme

@merncloud/secure-crypto-utils

A secure, TypeScript-first encryption library using AES-256-CBC with robust error handling and validation.

Features

  • 🔒 Secure: Uses AES-256-CBC encryption with random IVs
  • 🛡️ Robust: Comprehensive input validation and error handling
  • 📝 TypeScript: Full TypeScript support with detailed type definitions
  • 🧪 Well-tested: High test coverage with comprehensive test suite
  • 🚀 Easy to use: Simple API with sensible defaults
  • Performance: Optimized for both security and speed

Installation

npm install @merncloud/secure-crypto-utils

Quick Start

import { encrypt, decrypt } from "@merncloud/secure-crypto-utils";

// Set your encryption key (do this once, preferably via environment variable)
process.env.AES_SECRET_KEY = "your-32-character-secret-key-here!!!";

// Encrypt some data
const result = encrypt("Hello, World!");
console.log(result);
// {
//   encryptedData: 'base64-encoded-encrypted-data',
//   iv: 'base64-encoded-initialization-vector'
// }

// Decrypt the data
const decrypted = decrypt(result.encryptedData, result.iv);
console.log(decrypted); // 'Hello, World!'

API Reference

encrypt(text: string, config?: CryptoConfig): EncryptionResult

Encrypts text using AES-256-CBC encryption.

Parameters:

  • text: The string to encrypt (max 10,000 characters by default)
  • config: Optional configuration object

Returns: EncryptionResult

  • encryptedData: Base64 encoded encrypted data
  • iv: Base64 encoded initialization vector

Example:

const result = encrypt("Sensitive data");

// With custom configuration
const result2 = encrypt("Data", {
  maxTextLength: 5000,
  encryptionKey: "custom-32-char-key-here-!!!!!!!!!",
});

decrypt(encryptedData: string, iv: string, config?: CryptoConfig): string

Decrypts data that was encrypted with the encrypt function.

Parameters:

  • encryptedData: Base64 encoded encrypted data
  • iv: Base64 encoded initialization vector
  • config: Optional configuration object

Returns: The decrypted string

Example:

const decrypted = decrypt(result.encryptedData, result.iv);

// With custom key
const decrypted2 = decrypt(data, iv, {
  encryptionKey: "same-custom-key-used-for-encryption!",
});

generateKey(length?: number): string

Generates a cryptographically secure random key.

Parameters:

  • length: Key length in bytes (default: 32 for AES-256)

Returns: Base64 encoded random key

Example:

const key = generateKey(); // 32-byte key
const longerKey = generateKey(64); // 64-byte key

// Use the generated key
process.env.AES_SECRET_KEY = key;

safeCompare(a: string, b: string): boolean

Performs timing-safe string comparison to prevent timing attacks.

Parameters:

  • a: First string to compare
  • b: Second string to compare

Returns: true if strings are equal, false otherwise

Example:

const isValid = safeCompare(userInput, expectedValue);

Configuration

Environment Variables

  • AES_SECRET_KEY: Your encryption key (must be at least 32 characters)

CryptoConfig Interface

interface CryptoConfig {
  maxTextLength?: number; // Maximum text length (default: 10000)
  encryptionKey?: string; // Custom encryption key
  algorithm?: string; // Encryption algorithm (default: 'aes-256-cbc')
}

Error Handling

The library provides specific error types for different failure scenarios:

import {
  encrypt,
  ValidationError,
  DecryptionError,
  CryptoError,
} from "@merncloud/secure-crypto-utils";

try {
  const result = encrypt("data");
  const decrypted = decrypt(result.encryptedData, result.iv);
} catch (error) {
  if (error instanceof ValidationError) {
    console.error("Invalid input:", error.message);
  } else if (error instanceof DecryptionError) {
    console.error("Decryption failed:", error.message);
  } else if (error instanceof CryptoError) {
    console.error("Crypto operation failed:", error.message);
  }
}

Security Best Practices

  1. Key Management: Never hardcode encryption keys. Use environment variables or secure key management services.

  2. Key Rotation: Regularly rotate your encryption keys, especially in production environments.

  3. Input Validation: The library validates inputs, but always validate data at your application level too.

  4. HTTPS: Always use HTTPS when transmitting encrypted data over networks.

  5. Storage: When storing encrypted data, store the IV alongside but never store the encryption key with the data.

Advanced Usage

Working with JSON Data

const userData = { id: 123, email: "[email protected]", role: "admin" };
const jsonString = JSON.stringify(userData);

const encrypted = encrypt(jsonString);
const decrypted = decrypt(encrypted.encryptedData, encrypted.iv);
const parsedData = JSON.parse(decrypted);

Database Integration

// Storing in database
const sensitiveData = "user-sensitive-information";
const encrypted = encrypt(sensitiveData);

await db.users.update(userId, {
  encryptedData: encrypted.encryptedData,
  iv: encrypted.iv,
});

// Retrieving from database
const user = await db.users.findById(userId);
const decryptedData = decrypt(user.encryptedData, user.iv);

Custom Key per Operation

// Generate a unique key for specific data
const dataKey = generateKey();

const encrypted = encrypt("sensitive-data", { encryptionKey: dataKey });
const decrypted = decrypt(encrypted.encryptedData, encrypted.iv, {
  encryptionKey: dataKey,
});

Contributing

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

Testing

# Run tests
npm test

# Run tests in watch mode
npm run test:watch

# Run tests with coverage
npm run test:coverage

License

MIT License - see the LICENSE file for details.

Security

If you discover a security vulnerability, please send an email to [email protected] instead of using the issue tracker.

Changelog

v1.0.0

  • Initial release
  • AES-256-CBC encryption/decryption
  • TypeScript support
  • Comprehensive error handling
  • Full test coverage