using aes256gcm with provided salt it will encrypt & decrypt data in react js for API payload & response
npm install aes256gcm-encrypt-decrypt-bundlebash
npm install aes256gcm-encrypt-decrypt-bundle
`
or
`bash
yarn add aes256gcm-encrypt-decrypt-bundle
`
Quick Start
$3
The simplest way to use the library is with the default encryption/decryption methods:
`javascript
import { encrypt, decrypt } from 'aes256gcm-encrypt-decrypt-bundle';
// Encrypt data
const data = { username: 'john.doe', email: 'john@example.com' };
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: 'john@example.com' }
`
Detailed API Documentation
$3
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
- Description: Base64 encoded string containing salt, IV, and encrypted data
#### Example with Default Parameters
`javascript
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
`javascript
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);
`
---
$3
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
- Description: The original decrypted data (parsed from JSON)
#### Example with Default Parameters
`javascript
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
`javascript
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
$3
Always use strong passwords for encryption:
`javascript
// Weak passwords
const weakPassword = '123456';
const weakPassword2 = 'password';
// Strong passwords
const strongPassword = 'MyS3cur3P@ssw0rd!2024';
const strongPassword2 = crypto.randomBytes(32).toString('hex');
`
$3
The default iteration count is 1000, but you can increase it for enhanced security:
`javascript
// 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.
$3
`javascript
// 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
$3
`javascript
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 })
});
`
$3
`javascript
// 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
`javascript
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');
`
$3
`javascript
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 (
AES-256-GCM Encryption Demo
type="password"
placeholder="Password"
value={password}
onChange={(e) => setPassword(e.target.value)}
/>
type="text"
placeholder="Data to encrypt"
value={data}
onChange={(e) => setData(e.target.value)}
/>
Encrypted:
{encrypted}
Decrypted:
{decrypted}
);
}
export default SecureForm;
`
Technical Details
$3
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
$3
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
$3
`javascript
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
`javascript
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;
}
}
``