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

data-crypt

v1.0.0-rc4

Published

A lightweight and powerful encryption library for Node.js and browser. It allows you to encrypt and decrypt text or files using a password.

Downloads

322

Readme

🔐 DataCrypt

A robust, cross-platform TypeScript/JavaScript library for encrypting and decrypting data and files using AES-GCM with PBKDF2 key derivation. Works seamlessly in both Node.js and browser environments with built-in CLI support.

Table of Contents

Features

  • Secure Encryption: AES-GCM with PBKDF2 key derivation
  • Built-in CLI: Command-line interface for encrypting/decrypting files
  • Cross-Platform: Works in Node.js and modern browsers
  • Zero Dependencies: Uses native Web Crypto API
  • Type Safe: Written in TypeScript with full type definitions
  • Compression Support: Built-in GZIP compression to reduce file size
  • Self-Decrypting HTML: Generate standalone HTML files unlockable in any browser
  • Configurable: Customizable encryption parameters
  • File Support: Encrypt/decrypt binary file data
  • Simple API: Easy-to-use static methods

Installation

npm install data-crypt

or

yarn add data-crypt

Quick Start

// Import DataCrypt
import { DataCrypt } from 'data-crypt';

// Encrypt a string
const encrypted = await DataCrypt.encrypt('Secret message', 'my-password');
console.log('Encrypted:', encrypted);

// Decrypt the data
const decrypted = await DataCrypt.decrypt(encrypted, 'my-password');
console.log('Decrypted:', decrypted); // 'Secret message'

CLI Usage

DataCrypt provides a convenient command-line interface for quick encryption/decryption operations.

CLI Installation

npm install -g data-crypt

Help

dc --help
dc -h

Available Commands

You can use any of these command names:

  • dc (recommended, short and fast)
  • datacrypt (full name)
  • data-crypt (hyphenated)

Basic CLI Text Operations

Encrypt Text

dc encrypt "your secret message" "password"

Decrypt Text

dc decrypt "ENCRYPTED_BASE64_DATA" "password"

CLI File Operations

Encrypt Text

dc encrypt -f input.txt -o encrypted.txt "password"

Decrypt Text

dc decrypt -f encrypted.txt -o decrypted.txt "password"

Advanced CLI Options

| Option | Description | Example | | :------------ | :-------------- | :---------- | | -i, --iterations <number> | PBKDF2 iterations | -i 1000000 | | --hash <algorithm> | Hash algorithm (SHA-256, SHA-384, SHA-512) | --hash SHA-512 | | -l, --length <bits> | Key length in bits (128, 192, 256) | --hash SHA-512 | | -s, --salt-length <bytes> | Salt length in bytes | -s 32 | | -z, --compress | Compress data (GZIP) before encryption | -z | | --html | Generate a self-decrypting HTML file | --html |

Examples with Advanced Options

# Encrypt with custom parameters
dc encrypt "text" -i 1000000 --hash SHA-512 "password"

# Encrypt file with advanced options
dc encrypt -f document.pdf -o secure.pdf -i 500000 --hash SHA-384 "password"

Self-Decrypting HTML Files

Create a standalone .html file that anyone can decrypt in their browser without installing any software.

# Encrypt file into a self-unlocking HTML page
dc encrypt -f secret.pdf -o unlock.html --html "password"

⚠️ Important Note for Chrome/Edge Users:

Modern browsers like Chrome and Edge restrict the Web Crypto API on file:// URLs for security reasons. If you double-click the generated HTML file to open it, decryption might fail.

Solutions:

  1. Open the file in Firefox (it works locally).
  2. Use a local server (e.g., npx serve .).
  3. Upload the file to any website (HTTPS) or localhost.

Compression

Reduce file size by compressing data before encryption (uses GZIP).

# Compress and encrypt a large log file
dc encrypt -f server.log -o server.enc -z "password"

Decompression

When decrypting files that were compressed using the -z flag, decompression is automatic. You do not need to pass a compression flag during decryption. DataCrypt detects the compression headers inside the encrypted data and handles it for you.

# Just run the standard decrypt command
dc decrypt -f server.enc -o server.log "password"

Piping Support

You can also pipe data through the CLI:

# Encrypt piped data
echo "secret data" | dc encrypt "password"

# Encrypt file content
cat file.txt | dc encrypt -f "password" > encrypted.txt

API Reference

encrypt(): Encrypts text or binary data.

Syntax

encrypt(
  text: string | Uint8Array,
  password: string,
  opts?: DeriveOptions
): Promise<string>

Parameters

Returns: Base64-encoded encrypted data (salt + iv + ciphertext)

Example

const encrypted = await DataCrypt.encrypt('Hello World', 'password');

decrypt(): Decrypts previously encrypted data.

Syntax

decrypt(
  base64: string,
  password: string,
  opts?: DeriveOptions
): Promise<string | null>

Parameters

  • base64: Base64-encoded encrypted data
  • password: Password used for encryption
  • opts: Optional derivation options (must match encryption options, if used)

Returns: Decrypted string or null if decryption fails.

Example

const decrypted = await DataCrypt.decrypt(encryptedData, 'password');

encryptFile(): Encrypts binary file data.

Syntax

encryptFile(
  fileData: Uint8Array,
  password: string,
  opts?: DeriveOptions
): Promise<string>

Parameters

Returns: Base64-encoded encrypted file data.

Example

const fileData = new TextEncoder().encode('File content');
const encryptedFile = await DataCrypt.encryptFile(fileData, 'password');

decryptFile(): Decrypts previously encrypted file data.

Syntax

decryptFile(
  base64: string,
  password: string,
  opts?: DeriveOptions
): Promise<Uint8Array | null>

Parameters

  • base64: Uint8Array containing file data
  • password: Password used for encryption
  • opts: Optional derivation options (must match encryption options)

Returns: Decrypted Uint8Array or null if decryption fails.

Example

const decryptedFile = await DataCrypt.decryptFile(encryptedFile, 'password');

isEncrypted(): Checks if a string appears to be valid encrypted data.

Syntax

isEncrypted(data: string): boolean

Example

const isValid = DataCrypt.isEncrypted(encryptedData);
console.log('Is encrypted?', isValid); // true or false

generateSelfDecryptingHTML(): Generates a standalone HTML string containing the encrypted data and a decryption script.

Syntax

generateSelfDecryptingHTML(
  encryptedBase64: string, 
  filename: string, 
  opts?: DeriveOptions
): string

Example

const html = DataCrypt.generateSelfDecryptingHTML(encryptedData, 'doc.pdf');

Parameters

  • encryptedBase64: The Base64 string returned by encrypt() or encryptFile().
  • filename: The default filename used when the user downloads the decrypted file (e.g., 'secret.pdf').
  • opts: Optional derivation options (must match encryption options)

[!NOTE] If you used custom options (like specific iterations) to encrypt, you must pass them here so the HTML file uses the correct parameters to derive the key.

Returns: A string containing the full HTML document.

downloadFile(): [Browser Only] Triggers an immediate file download in the browser. Useful for saving generated HTML files or decrypted binary data.

Syntax

downloadFile(
  content: string | Uint8Array,
  filename: string,
  mimeType: string = 'application/octet-stream'
): void

Example

const html = DataCrypt.generateSelfDecryptingHTML(encryptedData, 'doc.pdf');
DataCrypt.downloadFile(html, 'secret.html', 'text/html');

Parameters

  • content: The data to download (string or binary).
  • filename: The name of the file to save (e.g., 'secret.html').
  • mimeType: (Optional) The MIME type (default: 'application/octet-stream').

generateRandomBytes(): Generates cryptographically secure random bytes.

Syntax

generateRandomBytes(length: number): Uint8Array

Example

const randomBytes = DataCrypt.generateRandomBytes(32);

clearCache(): void: Clears the derived key cache.

Syntax

clearCache(): void

Example

DataCrypt.clearCache();

getCacheSize(): Returns the number of cached keys.

Syntax

getCacheSize(): number

Example

console.log('Cached keys: ', DataCrypt.getCacheSize());

Compression & Decompression

DataCrypt includes built-in GZIP compression to reduce the size of your encrypted data. This is especially useful for large text files, logs, or JSON data.

1. Compressing Data

When you enable compression, the data is first compressed using GZIP and then encrypted. This results in significantly smaller output files for compressible data.

CLI Usage

Use the -z or --compress flag during encryption:

# Encrypt and compress a large log file
dc encrypt -f app.log -o app.log.enc -z "password"

API Usage

Pass { compress: true } in the options object:

const bigData = JSON.stringify(largeObject);
const encrypted = await DataCrypt.encrypt(bigData, 'password', { compress: true });

1. Decompressing Data

Decompression is automatic. You do not need to specify any special flags or options when decrypting. DataCrypt automatically detects the GZIP compression headers inside the encrypted payload and decompresses the data transparently.

CLI Usage

# Just run the standard command; DataCrypt handles the rest
dc decrypt -f app.log.enc -o restored.log "password"

API Usage

// No options needed; automatic detection
const decrypted = await DataCrypt.decrypt(encrypted, 'password');

Custom Options

Customize the key derivation process:

| Option | Type | Default | Description | | :------------ | :-------------- | :---------- | :-------------------------------------------------------- | | iterations | number | 600000 | Number of PBKDF2 iterations (more = stronger but slower) | | hash | HashAlgorithm | 'SHA-256' | Hash algorithm for PBKDF2 | | length | KeyLength | 256 | Key length in bits (128 / 192 / 256) | | saltLength | number | 16 | Salt length in bytes (default: 16) | | compress | boolean | false | Enable GZIP compression before encryption |

Interface

interface DeriveOptions {
  iterations?: number;
  hash?: HashAlgorithm;
  length?: KeyLength;
  saltLength?: number;
  compress?: boolean;
}

Usage

Browser Usage

With Bundlers (Webpack, Vite, etc.)

import { DataCrypt } from 'data-crypt';
// NOw use as normal Javascript

Direct Script Tag

You can use the same API in a browser environment.

<script type="module">
  import { DataCrypt } from 'https://cdn.skypack.dev/data-crypt';

  const text = 'Hello from Browser!';
  const password = 'browser-key';

  const encrypted = await DataCrypt.encrypt(text, password);
  const decrypted = await DataCrypt.decrypt(encrypted, password);

  console.log({ encrypted, decrypted });
</script>

Node.js Usage

CommonJS

const { DataCrypt } = require('data-crypt');

async function main() {
  const encrypted = await DataCrypt.encrypt('Node.js data', 'password');
  const decrypted = await DataCrypt.decrypt(encrypted, 'password');
  console.log(decrypted);
}

main().catch(console.error);

ES Modules

import { DataCrypt } from 'data-crypt';
// Use as shown in browser examples

Security Considerations

Best Practices

  1. Use Strong Passwords: The security depends on password strength.
  2. Increase Iterations: Use higher PBKDF2 iterations for sensitive data.
  3. Unique Salts: Each encryption uses a random salt (automatically handled).
  4. Secure Storage: Store encrypted data securely, separate from keys.

Default Security Parameters

  • PBKDF2 Iterations: 600,000 (OWASP recommended minimum)
  • Hash Algorithm: SHA-256
  • Key Length: 256-bit
  • Encryption: AES-GCM with 12-byte IV
  • Salt Length: 16 bytes

Performance

The library is optimized for performance with:

  • Key Caching: Derived keys are cached for same parameters
  • Native Crypto: Uses platform's native Web Crypto API
  • Efficient Encoding: Minimal data copying and encoding

For large files, consider streaming encryption in chunks (not currently supported).

Limitations

  • Password Strength: Security depends entirely on password strength
  • No Key Management: This library doesn't handle key storage/management
  • Memory: Large files are loaded entirely into memory

Contributing

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

License

MIT © 2025 [M B Parvez]