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

aes256gcm-encrypt-decrypt-bundle

v1.0.5

Published

using aes256gcm with provided salt it will encrypt & decrypt data in react js for API payload & response

Readme

AES256GCM Encrypt Decrypt Bundle

A secure, lightweight JavaScript library for AES-256-GCM encryption and decryption in React and Node.js applications. This library provides an easy-to-use interface for encrypting and decrypting sensitive data using the industry-standard AES-256-GCM algorithm with PBKDF2 key derivation.

Features

  • AES-256-GCM Encryption: Industry-standard authenticated encryption
  • PBKDF2 Key Derivation: Secure password-based key derivation with SHA-512
  • Automatic IV & Salt Generation: Secure random values for each encryption
  • Flexible API: Use default settings or customize all encryption parameters
  • React & Node.js Compatible: Works seamlessly in both environments
  • Zero Dependencies: Uses native Web Crypto API and Node.js crypto module
  • Base64 Encoding: Easy-to-store and transmit encrypted data

Installation

npm install aes256gcm-encrypt-decrypt-bundle

or

yarn add aes256gcm-encrypt-decrypt-bundle

Quick Start

Basic Usage with Default Method

The simplest way to use the library is with the default encryption/decryption methods:

import { encrypt, decrypt } from 'aes256gcm-encrypt-decrypt-bundle';

// Encrypt data
const data = { username: 'john.doe', email: '[email protected]' };
const password = 'your-strong-password';

const encryptedData = await encrypt(data, password);
console.log('Encrypted:', encryptedData);
// Output: Base64 encoded string

// Decrypt data
const decryptedData = await decrypt(encryptedData, password);
console.log('Decrypted:', decryptedData);
// Output: { username: 'john.doe', email: '[email protected]' }

Detailed API Documentation

encrypt(data, password, [options])

Encrypts data using AES-256-GCM algorithm with customizable parameters.

Parameters

| Parameter | Type | Default | Description | |-----------|------|---------|-------------| | data | any | Required | The data to encrypt (will be JSON stringified) | | password | string | Required | The password used for key derivation | | saltLength | number | 16 | Length of the salt in bytes (used for PBKDF2) | | ivLength | number | 12 | Length of the Initialization Vector in bytes | | tagLength | number | 128 | Authentication tag length in bits (128, 120, 112, 104, 96) | | keyLength | number | 32 | Key length in bytes (32 = 256-bit) | | iteration | number | 1000 | Number of PBKDF2 iterations | | encryptedPosition | number | 28 | Position where encrypted data starts (saltLength + ivLength) |

Returns

  • Type: Promise<string>
  • Description: Base64 encoded string containing salt, IV, and encrypted data

Example with Default Parameters

import { encrypt } from 'aes256gcm-encrypt-decrypt-bundle';

const data = {
  userId: 12345,
  token: 'secret-token-xyz',
  timestamp: Date.now()
};

const password = 'MySecurePassword123!';

try {
  const encrypted = await encrypt(data, password);
  console.log('Encrypted Data:', encrypted);
  // Store or transmit this encrypted string
} catch (error) {
  console.error('Encryption failed:', error);
}

Example with Custom Parameters

import { encrypt } from 'aes256gcm-encrypt-decrypt-bundle';

const data = { sensitiveInfo: 'Top Secret' };
const password = 'MySecurePassword123!';

// Custom parameters for enhanced security
const encrypted = await encrypt(
  data,
  password,
  16,    // saltLength: 16 bytes (default)
  12,    // ivLength: 12 bytes (default)
  128,   // tagLength: 128 bits (default)
  32,    // keyLength: 32 bytes = 256-bit (default)
  10000, // iteration: 10,000 iterations (more secure than default)
  28     // encryptedPosition: saltLength + ivLength
);

console.log('Encrypted with custom params:', encrypted);

decrypt(ciphertextBase64, password, [options])

Decrypts data that was encrypted using the encrypt method.

Parameters

| Parameter | Type | Default | Description | |-----------|------|---------|-------------| | ciphertextBase64 | string | Required | The Base64 encoded encrypted data | | password | string | Required | The password used during encryption | | saltLength | number | 16 | Length of the salt in bytes (must match encryption) | | ivLength | number | 12 | Length of the IV in bytes (must match encryption) | | tagLength | number | 128 | Authentication tag length in bits (must match encryption) | | keyLength | number | 32 | Key length in bytes (must match encryption) | | iteration | number | 1000 | Number of PBKDF2 iterations (must match encryption) | | encryptedPosition | number | 28 | Position where encrypted data starts (must match encryption) |

Returns

  • Type: Promise<any>
  • Description: The original decrypted data (parsed from JSON)

Example with Default Parameters

import { decrypt } from 'aes256gcm-encrypt-decrypt-bundle';

const encryptedData = 'YmFzZTY0LWVuY29kZWQtZW5jcnlwdGVkLWRhdGE='; // From encrypt()
const password = 'MySecurePassword123!';

try {
  const decrypted = await decrypt(encryptedData, password);
  console.log('Decrypted Data:', decrypted);
  // Use the decrypted data
} catch (error) {
  console.error('Decryption failed:', error);
  // Handle wrong password or corrupted data
}

Example with Custom Parameters

import { decrypt } from 'aes256gcm-encrypt-decrypt-bundle';

const encryptedData = 'custom-encrypted-base64-string';
const password = 'MySecurePassword123!';

// Must match the parameters used during encryption
const decrypted = await decrypt(
  encryptedData,
  password,
  16,    // saltLength
  12,    // ivLength
  128,   // tagLength
  32,    // keyLength
  10000, // iteration (must match encryption)
  28     // encryptedPosition
);

console.log('Decrypted Data:', decrypted);

Security Considerations

Password Strength

Always use strong passwords for encryption:

// Weak passwords
const weakPassword = '123456';
const weakPassword2 = 'password';

// Strong passwords
const strongPassword = 'MyS3cur3P@ssw0rd!2024';
const strongPassword2 = crypto.randomBytes(32).toString('hex');

PBKDF2 Iterations

The default iteration count is 1000, but you can increase it for enhanced security:

// Default (faster, less secure)
const encrypted = await encrypt(data, password);

// Enhanced security (slower, more secure)
const encrypted = await encrypt(data, password, 16, 12, 128, 32, 100000);

Recommendation: Use at least 100,000 iterations for sensitive data.

Storing Encrypted Data

// Store in localStorage
const encrypted = await encrypt(userData, password);
localStorage.setItem('userData', encrypted);

// Retrieve and decrypt
const stored = localStorage.getItem('userData');
const decrypted = await decrypt(stored, password);

Use Cases

1. Encrypting API Payloads

import { encrypt, decrypt } from 'aes256gcm-encrypt-decrypt-bundle';

// Before sending to API
const apiPayload = {
  creditCard: '1234-5678-9012-3456',
  cvv: '123',
  expiryDate: '12/25'
};

const encryptedPayload = await encrypt(apiPayload, 'api-secret-key');

// Send to API
fetch('/api/payment', {
  method: 'POST',
  headers: { 'Content-Type': 'application/json' },
  body: JSON.stringify({ data: encryptedPayload })
});

2. Encrypting API Responses

// Receive encrypted response from API
const response = await fetch('/api/sensitive-data');
const { encryptedData } = await response.json();

// Decrypt the response
const decryptedData = await decrypt(encryptedData, 'api-secret-key');
console.log('Decrypted Response:', decryptedData);

3. Secure Local Storage

import { encrypt, decrypt } from 'aes256gcm-encrypt-decrypt-bundle';

// Encrypt before storing
const userSession = {
  token: 'jwt-token-xyz',
  userId: 12345,
  roles: ['admin', 'user']
};

const encrypted = await encrypt(userSession, 'user-password');
localStorage.setItem('session', encrypted);

// Decrypt when needed
const storedSession = localStorage.getItem('session');
const session = await decrypt(storedSession, 'user-password');

4. React Component Example

import React, { useState } from 'react';
import { encrypt, decrypt } from 'aes256gcm-encrypt-decrypt-bundle';

function SecureForm() {
  const [password, setPassword] = useState('');
  const [data, setData] = useState('');
  const [encrypted, setEncrypted] = useState('');
  const [decrypted, setDecrypted] = useState('');

  const handleEncrypt = async () => {
    try {
      const result = await encrypt(
        { message: data },
        password
      );
      setEncrypted(result);
    } catch (error) {
      console.error('Encryption failed:', error);
    }
  };

  const handleDecrypt = async () => {
    try {
      const result = await decrypt(encrypted, password);
      setDecrypted(result.message);
    } catch (error) {
      console.error('Decryption failed:', error);
    }
  };

  return (
    <div>
      <h2>AES-256-GCM Encryption Demo</h2>
      <input
        type="password"
        placeholder="Password"
        value={password}
        onChange={(e) => setPassword(e.target.value)}
      />
      <input
        type="text"
        placeholder="Data to encrypt"
        value={data}
        onChange={(e) => setData(e.target.value)}
      />
      <button onClick={handleEncrypt}>Encrypt</button>
      <button onClick={handleDecrypt}>Decrypt</button>
      
      <div>
        <h3>Encrypted:</h3>
        <p>{encrypted}</p>
        <h3>Decrypted:</h3>
        <p>{decrypted}</p>
      </div>
    </div>
  );
}

export default SecureForm;

Technical Details

Encryption Process

  1. Salt Generation: Random 16-byte salt is generated
  2. IV Generation: Random 12-byte Initialization Vector is generated
  3. Key Derivation: PBKDF2 with SHA-512 derives a 256-bit key from password and salt
  4. Encryption: AES-256-GCM encrypts the JSON-stringified data
  5. Concatenation: Salt + IV + Encrypted Data are combined
  6. Encoding: The result is Base64 encoded for easy storage/transmission

Decryption Process

  1. Decoding: Base64 string is decoded to bytes
  2. Extraction: Salt, IV, and encrypted data are extracted
  3. Key Derivation: Same PBKDF2 process recreates the key
  4. Decryption: AES-256-GCM decrypts the data with authentication
  5. Parsing: JSON.parse restores the original data structure

Default Constants

ALGORITHM = 'AES-GCM'
SALT_LENGTH = 16 bytes
IV_LENGTH = 12 bytes
TAG_LENGTH = 128 bits
KEY_LENGTH = 32 bytes (256-bit)
ITERATION = 1000
ENCRYPTED_POSITION = 28 (SALT_LENGTH + IV_LENGTH)

Error Handling

import { encrypt, decrypt } from 'aes256gcm-encrypt-decrypt-bundle';

async function secureOperation() {
  try {
    const encrypted = await encrypt(data, password);
    const decrypted = await decrypt(encrypted, password);
    return decrypted;
  } catch (error) {
    if (error.name === 'OperationError') {
      console.error('Decryption failed - wrong password or corrupted data');
    } else {
      console.error('Encryption/Decryption error:', error.message);
    }
    throw error;
  }
}

Requirements

  • React: ^16.8.0 || ^17.0.0 || ^18.0.0 || ^19.0.0
  • React-DOM: ^16.8.0 || ^17.0.0 || ^18.0.0 || ^19.0.0
  • Browser: Modern browsers with Web Crypto API support
  • Node.js: Version with crypto.subtle support (v15+)

Contributing

Contributions are welcome! Please feel free to submit a Pull Request.

License

ISC

Author

Prasannjit Prabhat

Issues

If you encounter any issues, please report them at: GitHub Issues

Additional Resources

Repository

https://github.com/prasannjit87/ReactjsAES256GCM-encrypt-decrypt


Note: Always keep your passwords secure and never commit them to version control. Consider using environment variables for production applications.