secure-json-encoder
v1.0.0
Published
Secure JSON encoding/decoding with private key encryption for Node.js and browser
Maintainers
Readme
Secure JSON Encoder
A secure NPM package for encoding and decoding JSON data with AES-256-GCM encryption using a private key. Perfect for securing data transmission between your Node.js server and React application.
Features
- 🔐 AES-256-GCM Encryption - Military-grade encryption
- 🔑 Private Key Authentication - Same key required for encode/decode
- 🌐 Universal Support - Works in Node.js and browsers (React, Vue, etc.)
- 🚀 Easy to Use - Simple API with async/await support
- 📦 Zero Dependencies - Uses native crypto APIs
- ✅ Type Safe - Full error handling
Installation
npm install secure-json-encoderQuick Start
Node.js Server Example
const SecureJSONEncoder = require('secure-json-encoder');
// Initialize with your private key
const PRIVATE_KEY = 'your-secret-private-key-here';
const encoder = new SecureJSONEncoder(PRIVATE_KEY);
// Encode data
const userData = { id: 123, name: 'John Doe' };
const encoded = encoder.encode(userData);
// Decode data
const decoded = encoder.decode(encoded);
console.log(decoded); // { id: 123, name: 'John Doe' }React Application Example
import SecureJSONEncoder from 'secure-json-encoder';
// Use the SAME private key as your Node.js server
const PRIVATE_KEY = 'your-secret-private-key-here';
const encoder = new SecureJSONEncoder(PRIVATE_KEY);
// Fetch encrypted data from API and decode
async function fetchUserData() {
const response = await fetch('https://api.example.com/user');
const result = await response.json();
// Decode the encrypted data
const userData = await encoder.decode(result.data);
console.log(userData);
}
// Encode data before sending to API
async function sendData() {
const data = { message: 'Hello Server!' };
const encoded = await encoder.encode(data);
await fetch('https://api.example.com/message', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ data: encoded })
});
}Use Cases
1. Server sends encrypted data → React decodes it
Node.js Server:
const SecureJSONEncoder = require('secure-json-encoder');
const encoder = new SecureJSONEncoder('my-secret-key-2024');
app.get('/api/user', (req, res) => {
const userData = { id: 1, email: '[email protected]' };
const encoded = encoder.encode(userData);
res.json({ data: encoded });
});React App:
import SecureJSONEncoder from 'secure-json-encoder';
const encoder = new SecureJSONEncoder('my-secret-key-2024');
const response = await fetch('/api/user');
const { data } = await response.json();
const userData = await encoder.decode(data);2. React sends encrypted data → Server decodes it
React App:
const formData = { username: 'john', password: 'secret' };
const encoded = await encoder.encode(formData);
await fetch('/api/login', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ data: encoded })
});Node.js Server:
app.post('/api/login', (req, res) => {
const decoded = encoder.decode(req.body.data);
console.log(decoded); // { username: 'john', password: 'secret' }
// Process login...
});API Reference
Constructor
new SecureJSONEncoder(privateKey)- privateKey (string, required): Your secret key (32+ characters recommended)
Methods
encode(data) → string (Node.js) / Promise<string> (Browser)
Encrypts and encodes JSON data.
Parameters:
data(Object): JSON-serializable data
Returns:
- Node.js: Encrypted string (synchronous)
- Browser: Promise resolving to encrypted string (async)
Example:
// Node.js
const encoded = encoder.encode({ message: 'Hello' });
// Browser/React
const encoded = await encoder.encode({ message: 'Hello' });decode(encodedData) → Object (Node.js) / Promise<Object> (Browser)
Decrypts and decodes encrypted string back to JSON.
Parameters:
encodedData(string): Encrypted string from encode()
Returns:
- Node.js: Decrypted object (synchronous)
- Browser: Promise resolving to decrypted object (async)
Example:
// Node.js
const decoded = encoder.decode(encodedString);
// Browser/React
const decoded = await encoder.decode(encodedString);Security Notes
Important Security Practices
Keep Your Private Key Secret
- Never commit your private key to Git
- Use environment variables:
process.env.PRIVATE_KEY - Different keys for development/production
Private Key Requirements
- Minimum 16 characters (32+ recommended)
- Use random, complex strings
- Same key required on both server and client
Transport Security
- Always use HTTPS in production
- Encryption adds security but doesn't replace HTTPS
Environment Variables
Node.js (.env file):
PRIVATE_KEY=your-super-secret-key-here-min-32-charsrequire('dotenv').config();
const encoder = new SecureJSONEncoder(process.env.PRIVATE_KEY);React (.env file):
REACT_APP_PRIVATE_KEY=your-super-secret-key-here-min-32-charsconst encoder = new SecureJSONEncoder(process.env.REACT_APP_PRIVATE_KEY);Complete Example
See the examples/ folder for complete implementations:
server.js- Express server with encode/decode endpointsnodejs-usage.js- Basic Node.js usagereact-usage.jsx- React component examplereact-api-helper.js- React API helper functions
Running the Example Server
npm install
npm startServer runs on http://localhost:3000
Test endpoints:
# Get encrypted data
curl http://localhost:3000/api/data
# Encode data
curl -X POST http://localhost:3000/api/encode \
-H "Content-Type: application/json" \
-d '{"name":"John","email":"[email protected]"}'
# Decode data
curl -X POST http://localhost:3000/api/decode \
-H "Content-Type: application/json" \
-d '{"encoded":"YOUR_ENCODED_STRING_HERE"}'How It Works
Encoding Process:
- JSON data → Stringify → AES-256-GCM encryption → Base64 encoding
Decoding Process:
- Base64 string → Decryption → JSON parsing → Original data
Encryption Details:
- Algorithm: AES-256-GCM (Authenticated encryption)
- Key derivation: SHA-256 hash of private key (Node.js) / PBKDF2 (Browser)
- Random IV for each encryption
- Authentication tag for integrity verification
Browser Compatibility
- ✅ Chrome 37+
- ✅ Firefox 34+
- ✅ Safari 11+
- ✅ Edge 12+
- ✅ All modern browsers with Web Crypto API support
Error Handling
try {
const encoded = encoder.encode(data);
const decoded = encoder.decode(encoded);
} catch (error) {
console.error('Encryption error:', error.message);
// Handle: Invalid key, corrupted data, wrong key, etc.
}Common errors:
Private key is required- No key provided to constructorEncoding failed- Invalid data formatDecoding failed- Wrong key or corrupted encrypted data
License
ISC
Contributing
Issues and pull requests are welcome!
Support
For issues and questions, please open a GitHub issue.
