A npm module with encryption/decryption data using Native Web Crypto API with support both for node and for browser
npm install common-encryption
base-encryption (published from common-encryption source) provides a modern, cross-platform encryption library that works seamlessly in both Node.js and browser environments. It offers:
bash
npm install common-encryption
`
Requirements:
- Node.js 18 or higher
- Modern browsers (Chrome, Firefox, Safari, Edge - 97%+ compatibility)
ā ļø Breaking Changes in v3.0
$3
- All functions now return Promises (must use async/await or .then())
- Node.js 18+ required (for Web Crypto API support)
- Encrypted data format changed (v2.x data cannot be decrypted)
$3
`javascript
const hash = commonEncryption.oneWayEncrypt('data', true);
const encrypted = commonEncryption.twoWayEncrypt('secret', 'password');
`
$3
`javascript
const hash = await commonEncryption.oneWayEncrypt('data', true);
const encrypted = await commonEncryption.twoWayEncrypt('secret', 'password');
`
$3
- v2.x used AES-CBC with format: [salt][iv][ciphertext]
- v3.0 uses AES-GCM with format: [salt][iv][authTag][ciphertext]
- You cannot decrypt v2.x data with v3.0 due to algorithm change
š Migration Guide: v2.x ā v3.0
$3
`bash
npm install common-encryption@^3.1.1
`
$3
Add async/await to all encryption/decryption calls:
`javascript
// v2.x
function myFunction() {
const encrypted = commonEncryption.twoWayEncrypt(data, password);
return encrypted;
}
// v3.0
async function myFunction() {
const encrypted = await commonEncryption.twoWayEncrypt(data, password);
return encrypted;
}
`
$3
v3.0 cannot decrypt v2.x encrypted data. You must:
1. Decrypt all existing data with v2.x
2. Upgrade to v3.0
3. Re-encrypt data with v3.0
`javascript
// One-time migration script
import v2 from 'common-encryption@2.0.5';
import commonEncryption from 'common-encryption@3.1.1';
async function migrateData(oldEncryptedData, password) {
// Decrypt with v2
const plaintext = v2.twoWayDecrypt(oldEncryptedData, password);
// Re-encrypt with v3
const newEncryptedData = await commonEncryption.twoWayEncrypt(plaintext, password);
return newEncryptedData;
}
`
$3
Ensure Node.js 18+ is installed:
`bash
node --version # Should be v18.0.0 or higher
`
š Migration Guide: v3.0 ā v3.1
$3
Version 3.1 introduces optional performance optimizations. Your existing v3.0 code continues to work without changes.
$3
Version 3.0 used a fixed 600,000 PBKDF2 iterations for all encryptions to meet OWASP 2023 compliance. While secure, this was overkill for many use cases:
- Real-time APIs suffered from ~113ms encryption latency
- Standard application data didn't need password-strength security
- Transport encryption was unnecessarily slow
$3
Version 3.1 adds configurable security levels while maintaining maximum security as the default:
- ā
Default unchanged: 600,000 iterations (OWASP 2023 compliant)
- ā” Optional fast mode: 2,000 iterations (~0.36ms, 297x faster)
- āļø Optional standard mode: 10,000 iterations (~2.14ms, 52x faster)
- š Optional high mode: 100,000 iterations (~19ms, 5.9x faster)
$3
Your existing v3.0 code works identically in v3.1:
`javascript
// v3.0 code - no changes needed
const encrypted = await commonEncryption.twoWayEncrypt(data, passphrase);
const decrypted = await commonEncryption.twoWayDecrypt(encrypted, passphrase);
// Still uses 600,000 iterations (maximum security)
`
$3
To improve performance for non-password use cases, add the options parameter:
Before (v3.0):
`javascript
// Real-time API - slow (113ms)
async function encryptAPIResponse(data) {
return await commonEncryption.twoWayEncrypt(data, apiKey);
}
`
After (v3.1):
`javascript
// Real-time API - fast (0.36ms, 297x faster)
async function encryptAPIResponse(data) {
return await commonEncryption.twoWayEncrypt(
data,
apiKey,
{ securityLevel: 'fast' }
);
}
`
$3
#### Use Case 1: Session Tokens
`javascript
// v3.0 - Slow (113ms)
const token = await commonEncryption.twoWayEncrypt(sessionData, secret);
// v3.1 - Fast (2.14ms, 52x faster)
const token = await commonEncryption.twoWayEncrypt(
sessionData,
secret,
{ securityLevel: 'standard' }
);
`
#### Use Case 2: User Preferences
`javascript
// v3.0 - Slow (113ms)
const encrypted = await commonEncryption.twoWayEncrypt(preferences, userKey);
// v3.1 - Fast (2.14ms, 52x faster)
const encrypted = await commonEncryption.twoWayEncrypt(
preferences,
userKey,
{ securityLevel: 'standard' }
);
`
#### Use Case 3: Passwords (Keep Maximum Security)
`javascript
// v3.0 and v3.1 - Same behavior (113ms, OWASP 2023 compliant)
const encrypted = await commonEncryption.twoWayEncrypt(password, masterKey);
// No changes needed - maximum security by default
`
$3
| Use Case | v3.0 Time | v3.1 Time | Improvement |
|----------|-----------|-----------|-------------|
| Real-time APIs | ~113ms | ~0.36ms | 297x faster |
| Session tokens | ~113ms | ~2.14ms | 52x faster |
| User data | ~113ms | ~19ms | 5.9x faster |
| Passwords | ~113ms | ~113ms | Same (secure) |
$3
All v3.0 encrypted data can be decrypted in v3.1:
- The encrypted data format hasn't changed
- Security levels only affect encryption speed, not the output format
- Mix and match: use different levels for different data
`javascript
// v3.0 encrypted data
const v30Data = "...encrypted with v3.0...";
// v3.1 can decrypt it
const decrypted = await commonEncryption.twoWayDecrypt(v30Data, passphrase);
// Works perfectly - full backward compatibility
`
š What's New in v3.1
$3
- ā” Fast mode: 2,000 iterations for real-time applications
- āļø Standard mode: 10,000 iterations for general data
- š High mode: 100,000 iterations for sensitive data
- š”ļø Maximum mode: 600,000 iterations (default, OWASP 2023)
$3
- š Up to 297x faster encryption with fast mode
- š Configurable trade-offs between speed and security
- š Full backward compatibility with v3.0
- ā
Zero breaking changes - existing code works unchanged
$3
- š Simple API: Just add { securityLevel: 'fast' } option
- šÆ Smart defaults: Maximum security without configuration
- š Benchmark tool: Test performance on your hardware
- š Comprehensive docs: Clear guidance for every use case
š What's New in v3.0
$3
- ā
PBKDF2 iterations increased from 100 to 600,000 (OWASP 2023 compliant)
- ā
AES-GCM authenticated encryption prevents tampering and padding oracle attacks
- ā
Hardware-accelerated crypto via native Web Crypto API
- ā
Cryptographically secure random IV and salt generation
$3
- ā” 10-100x faster encryption/decryption
- š¦ 84% smaller bundle (50KB vs 330KB)
- š Zero crypto dependencies to maintain
$3
- š Web Crypto API - W3C standard, future-proof
- š± Universal compatibility - Browser and Node.js with same code
- š ES6 modules - Modern JavaScript import/export
- ⨠Promise-based API - Modern async patterns
Usage
$3
Node.js (ES Modules):
`javascript
import commonEncryption from 'common-encryption';
`
Node.js (CommonJS):
`javascript
const commonEncryption = require('common-encryption');
`
Browser (ES6 modules):
`javascript
import commonEncryption from './node_modules/common-encryption/dist/index.js';
`
Browser (script tag):
`html
`
$3
#### One-Way Hashing (SHA-256)
`javascript
// Using async function
async function hashData() {
const data = "mySecretData";
const useSHA256 = true;
// Hash the data
const hash = await commonEncryption.oneWayEncrypt(data, useSHA256);
console.log(hash); // SHA-256 hash string
}
// Or using top-level await (in ES modules)
const hash = await commonEncryption.oneWayEncrypt("mySecretData", true);
console.log(hash);
`
#### One-Way Hashing (MD5)
`javascript
async function hashWithMD5() {
const data = "myData";
const useMD5 = false; // false = use MD5
// Hash with MD5 (for checksums/IDs only, NOT for security)
const hash = await commonEncryption.oneWayEncrypt(data, useMD5);
console.log(hash); // MD5 hash string
}
`
#### Hash Comparison
`javascript
async function verifyHash() {
const hash = await commonEncryption.oneWayEncrypt("myPassword", true);
const userInput = "myPassword";
// Compare without exposing the original
const isMatch = await commonEncryption.oneWayCompare(hash, userInput, true);
console.log(isMatch); // true
}
`
#### Two-Way Encryption (String)
`javascript
async function encryptString() {
const passphrase = "mySecurePassphrase";
const sensitiveData = "Sensitive Information";
try {
// Encrypt
const encrypted = await commonEncryption.twoWayEncrypt(sensitiveData, passphrase);
console.log(encrypted); // AES-256-GCM encrypted string
// Decrypt
const decrypted = await commonEncryption.twoWayDecrypt(encrypted, passphrase);
console.log(decrypted); // "Sensitive Information"
} catch (error) {
console.error('Encryption failed:', error);
}
}
`
#### Two-Way Encryption (Object)
`javascript
async function encryptObject() {
const passphrase = "mySecurePassphrase";
const dataObject = {
username: "john_doe",
email: "john@example.com",
preferences: { theme: "dark" }
};
// Automatically stringifies objects
const encrypted = await commonEncryption.twoWayEncrypt(dataObject, passphrase);
console.log(encrypted); // AES-256-GCM encrypted string
// Decrypt returns JSON string
const decrypted = await commonEncryption.twoWayDecrypt(encrypted, passphrase);
const parsedData = JSON.parse(decrypted);
console.log(parsedData); // Original object structure
}
`
#### Error Handling
`javascript
async function encryptWithErrorHandling() {
try {
const encrypted = await commonEncryption.twoWayEncrypt("secret", "password");
const decrypted = await commonEncryption.twoWayDecrypt(encrypted, "password");
console.log('Success:', decrypted);
} catch (error) {
if (error.message.includes('decrypt')) {
console.error('Wrong password or corrupted data');
} else {
console.error('Encryption error:', error);
}
}
}
`
API Documentation
$3
Performs one-way hashing using SHA-256 or MD5.
Parameters:
- data (String|Object): Data to hash. Objects are automatically stringified.
- sha (Boolean, default: true): true for SHA-256, false for MD5
Returns:
- Promise: Hexadecimal hash string
Example:
`javascript
// SHA-256 (recommended)
const sha256Hash = await commonEncryption.oneWayEncrypt("data", true);
// MD5 (for checksums/IDs only, not for security)
const md5Hash = await commonEncryption.oneWayEncrypt("data", false);
// SHA-256 is default
const defaultHash = await commonEncryption.oneWayEncrypt("data");
`
---
$3
Compares a hash with plain data by hashing the plain data and checking equality.
Parameters:
- cypher (String): The hash to compare against
- compare (String|Object): Plain data to hash and compare
- sha (Boolean, default: true): true for SHA-256, false for MD5 (must match the algorithm used to create cypher)
Returns:
- Promise: true if hashes match, false otherwise
Example:
`javascript
const hash = await commonEncryption.oneWayEncrypt("password123", true);
const isValid = await commonEncryption.oneWayCompare(hash, "password123", true);
console.log(isValid); // true
const isInvalid = await commonEncryption.oneWayCompare(hash, "wrongPassword", true);
console.log(isInvalid); // false
`
---
$3
Encrypts data using AES-256-GCM with a passphrase.
Parameters:
- data (String|Object): Data to encrypt. Objects are automatically stringified.
- passphrase (String): Encryption passphrase/password
- options (Object, optional): Encryption configuration
- options.securityLevel (String): Security level - 'fast', 'standard', 'high', or 'maximum' (default)
- options.iterations (Number): Custom PBKDF2 iterations (overrides securityLevel)
Returns:
- Promise: Base64-encoded encrypted string containing salt, IV, authentication tag, and ciphertext
Example:
`javascript
// Default: Maximum security (600,000 iterations)
const encrypted = await commonEncryption.twoWayEncrypt("secret", "my-passphrase");
// Fast mode: For real-time APIs (2,000 iterations)
const fastEncrypted = await commonEncryption.twoWayEncrypt(
"secret",
"my-passphrase",
{ securityLevel: 'fast' }
);
// Standard mode: Balanced (10,000 iterations)
const standardEncrypted = await commonEncryption.twoWayEncrypt(
"secret",
"my-passphrase",
{ securityLevel: 'standard' }
);
// High security: For sensitive data (100,000 iterations)
const highEncrypted = await commonEncryption.twoWayEncrypt(
"secret",
"my-passphrase",
{ securityLevel: 'high' }
);
// Custom iterations
const customEncrypted = await commonEncryption.twoWayEncrypt(
"secret",
"my-passphrase",
{ iterations: 5000 }
);
// With object
const obj = { key: "value" };
const encryptedObj = await commonEncryption.twoWayEncrypt(
obj,
"my-passphrase",
{ securityLevel: 'standard' }
);
`
---
$3
Decrypts AES-256-GCM encrypted data.
Parameters:
- cypher (String): Base64-encoded encrypted string (from twoWayEncrypt())
- passphrase (String): Decryption passphrase (must match encryption passphrase)
- options (Object, optional): Decryption configuration
- options.securityLevel (String): Security level - must match encryption level
- options.iterations (Number): Custom PBKDF2 iterations - must match encryption iterations
Returns:
- Promise: Decrypted data as string. If the original data was an object, you'll need to JSON.parse() the result.
Example:
`javascript
// Default: Maximum security
const encrypted = await commonEncryption.twoWayEncrypt("secret", "my-passphrase");
const decrypted = await commonEncryption.twoWayDecrypt(encrypted, "my-passphrase");
console.log(decrypted); // "secret"
// With security level
const fastEncrypted = await commonEncryption.twoWayEncrypt(
"secret",
"my-passphrase",
{ securityLevel: 'fast' }
);
const fastDecrypted = await commonEncryption.twoWayDecrypt(
fastEncrypted,
"my-passphrase",
{ securityLevel: 'fast' }
);
// With object
const objEncrypted = await commonEncryption.twoWayEncrypt(
{ key: "value" },
"pass",
{ securityLevel: 'standard' }
);
const objDecrypted = await commonEncryption.twoWayDecrypt(
objEncrypted,
"pass",
{ securityLevel: 'standard' }
);
const obj = JSON.parse(objDecrypted); // { key: "value" }
`
Performance & Security Levels
Version 3.1 introduces configurable security levels to balance performance and security based on your use case.
$3
| Level | Iterations | Avg Time | Performance | Best For |
|-------|-----------|----------|-------------|----------|
| fast | 2,000 | ~0.36ms | 297x faster | Real-time APIs, WebSockets, transport encryption |
| standard | 10,000 | ~2.14ms | 52x faster | Standard application data, sessions, tokens |
| high | 100,000 | ~19ms | 5.9x faster | Sensitive user data, financial records, PII |
| maximum | 600,000 | ~113ms | Default | Passwords, OWASP 2023 compliant, regulatory data |
Performance baseline: Measured on modern hardware. Your results may vary.
$3
#### š Fast Mode (securityLevel: 'fast')
2,000 iterations - Optimized for performance-critical applications
Use Cases:
- Real-time API encryption/decryption
- WebSocket message encryption
- High-throughput data processing
- Transport layer encryption
- Temporary session data
Example:
`javascript
// Real-time chat encryption
const encrypted = await commonEncryption.twoWayEncrypt(
chatMessage,
sessionKey,
{ securityLevel: 'fast' }
);
`
#### āļø Standard Mode (securityLevel: 'standard')
10,000 iterations - Balanced performance and security
Use Cases:
- General application data
- User preferences and settings
- Session tokens
- Non-sensitive cached data
- Development and testing
Example:
`javascript
// User preferences encryption
const encrypted = await commonEncryption.twoWayEncrypt(
userPreferences,
userKey,
{ securityLevel: 'standard' }
);
`
#### š High Mode (securityLevel: 'high')
100,000 iterations - Enhanced security for sensitive data
Use Cases:
- Personally Identifiable Information (PII)
- Financial records
- Healthcare data
- API keys and secrets
- Long-term stored credentials
Example:
`javascript
// Financial data encryption
const encrypted = await commonEncryption.twoWayEncrypt(
financialData,
encryptionKey,
{ securityLevel: 'high' }
);
`
#### š”ļø Maximum Mode (securityLevel: 'maximum') - Default
600,000 iterations - OWASP 2023 compliant, maximum security
Use Cases:
- Password storage and verification
- Regulatory compliance (GDPR, HIPAA, PCI-DSS)
- Highly sensitive data
- Long-term archive encryption
- Security-critical applications
Example:
`javascript
// Default - no options needed
const encrypted = await commonEncryption.twoWayEncrypt(
password,
masterKey
);
// Or explicitly
const encrypted = await commonEncryption.twoWayEncrypt(
password,
masterKey,
{ securityLevel: 'maximum' }
);
`
$3
You can run performance benchmarks on your hardware:
`bash
node test/benchmark.js
`
Sample Output:
`
Security Level Performance Comparison
=====================================
Fast mode (2,000 iterations):
Encryption: 0.32ms
Decryption: 0.40ms
Total: 0.72ms
Throughput: 1389 ops/sec
Standard mode (10,000 iterations):
Encryption: 2.01ms
Decryption: 2.27ms
Total: 4.28ms
Throughput: 234 ops/sec
High mode (100,000 iterations):
Encryption: 18.45ms
Decryption: 19.73ms
Total: 38.18ms
Throughput: 26 ops/sec
Maximum mode (600,000 iterations):
Encryption: 110.23ms
Decryption: 115.89ms
Total: 226.12ms
Throughput: 4.4 ops/sec
`
$3
For fine-grained control, you can specify custom iteration counts:
`javascript
// Custom iteration count
const encrypted = await commonEncryption.twoWayEncrypt(
data,
passphrase,
{ iterations: 5000 }
);
// Must match when decrypting
const decrypted = await commonEncryption.twoWayDecrypt(
encrypted,
passphrase,
{ iterations: 5000 }
);
`
Note: The iteration count is not stored in the encrypted data. You must use the same iteration count for decryption.
$3
Version 3.1 is fully backward compatible with v3.0:
- Existing code without options parameter continues to work
- Default behavior unchanged (600,000 iterations)
- No breaking changes to API or data format
`javascript
// v3.0 code - still works in v3.1
const encrypted = await commonEncryption.twoWayEncrypt(data, passphrase);
const decrypted = await commonEncryption.twoWayDecrypt(encrypted, passphrase);
`
Security Considerations
$3
Version 3.0 implements modern cryptographic standards:
1. OWASP 2023 Compliant
- 600,000 PBKDF2-HMAC-SHA256 iterations
- Meets current recommendations for password-based encryption
- Protects against brute-force attacks
2. Authenticated Encryption (AES-GCM)
- Combines encryption and authentication in a single operation
- Prevents tampering and modification of encrypted data
- Eliminates padding oracle attack vulnerabilities
- 128-bit authentication tag ensures data integrity
3. Hardware Acceleration
- Native Web Crypto API uses hardware acceleration when available
- Significantly faster than pure JavaScript implementations
- Consistent security across platforms
4. Cryptographically Secure Randomness
- All IVs and salts generated using cryptographically secure random number generator
- Ensures uniqueness and unpredictability
- No weak or predictable random sources
$3
`javascript
// ā
DO: Use SHA-256 for security-sensitive hashing
const hash = await commonEncryption.oneWayEncrypt(password, true);
// ā
DO: Use strong passphrases for encryption
const strongPassphrase = "correct-horse-battery-staple-with-numbers-123";
const encrypted = await commonEncryption.twoWayEncrypt(data, strongPassphrase);
// ā
DO: Handle errors properly
try {
const decrypted = await commonEncryption.twoWayDecrypt(encrypted, passphrase);
} catch (error) {
console.error('Decryption failed - wrong password or corrupted data');
}
// ā ļø CAUTION: MD5 only for checksums and IDs, never for security
const checksum = await commonEncryption.oneWayEncrypt(data, false);
// ā DON'T: Use MD5 for password hashing
const badHash = await commonEncryption.oneWayEncrypt(password, false); // BAD!
`
$3
ā
Recommended For:
- Web applications needing client-side encryption
- Secure storage of user preferences
- Password-protected configuration files
- Cross-platform encrypted data exchange
- Development and testing environments
- Educational purposes
ā ļø Consider Alternatives For:
- Server-side password storage (use bcrypt or Argon2)
- Large file encryption (use streaming encryption)
- Key management systems (use dedicated KMS solutions)
- Regulatory compliance (may require certified libraries)
Technical Details
$3
- Encryption Algorithm: AES-256-GCM (authenticated encryption)
- Key Derivation: PBKDF2-SHA256 with 600,000 iterations
- Key Size: 256 bits (32 bytes)
- IV Size: 12 bytes (96 bits) - optimal for AES-GCM
- Authentication Tag: 16 bytes (128 bits)
- Salt: 16 bytes (random per encryption)
- Hash Algorithms: SHA-256 (default), MD5 (for IDs only)
$3
`
[16-byte salt][12-byte IV][16-byte auth tag][ciphertext]
`
All encoded as Base64 for text transmission and storage.
$3
- Browser: Uses native window.crypto.subtle Web Crypto API
- Node.js 18+: Uses native crypto.webcrypto module
- No polyfills needed: 97%+ browser support (Chrome, Firefox, Safari, Edge)
- Unified codebase: Same code works in both environments
$3
- 10-100x faster than crypto-js implementation
- Hardware-accelerated encryption (when available)
- Zero dependencies - no external crypto libraries
- Smaller bundle - 84% reduction in package size
$3
| Browser | Version | Support |
|---------|---------|---------|
| Chrome | 37+ | ā
Full |
| Firefox | 34+ | ā
Full |
| Safari | 11+ | ā
Full |
| Edge | 79+ | ā
Full |
| Opera | 24+ | ā
Full |
$3
- Required: Node.js 18.0.0 or higher
- Recommended: Node.js 20+ LTS for best performance
- Web Crypto API available via crypto.webcrypto
Development
$3
- Node.js 18 or higher
- npm 8 or higher
$3
`bash
npm test # All 25 tests should pass
`
$3
- ā
One-way encryption (SHA-256, MD5)
- ā
One-way comparison (SHA-256, MD5)
- ā
Two-way encryption/decryption (strings)
- ā
Two-way encryption/decryption (objects)
- ā
Two-way encryption/decryption (arrays)
- ā
Non-deterministic encryption (random IV per call)
- ā
Wrong password handling
- ā
Corrupted data handling
- ā
Edge cases and error conditions
All tests use native Node.js test runner - no external test frameworks required.
$3
`bash
Install dependencies
npm install
Build production bundle
npm run build
`
The build process:
1. Transpiles and bundles source code with Webpack
2. Generates optimized output in index.js
3. Creates UMD bundle for universal compatibility
$3
`
common-encryption/
āāā src/
ā āāā crypto-utils.js # Web Crypto API wrapper
ā āāā index.js # Main library implementation
āāā test/
ā āāā test.js # Test suite (25 tests)
āāā webpack.config.js # Build configuration
āāā package.json
āāā README.md
`
Changelog
$3
Performance & Security Optimization Release
New Features:
- ā” Configurable security levels: fast, standard, high, maximum
- šÆ 297x faster encryption with fast mode (0.36ms vs 113ms)
- š Performance benchmarks: Built-in benchmark tool (node test/benchmark.js)
- š Full backward compatibility: No breaking changes
Security Levels:
- Fast: 2,000 iterations (~0.36ms) - Real-time APIs
- Standard: 10,000 iterations (~2.14ms) - General data
- High: 100,000 iterations (~19ms) - Sensitive data
- Maximum: 600,000 iterations (~113ms) - Default, OWASP 2023
API Enhancements:
- ā
options.securityLevel parameter for twoWayEncrypt()
- ā
options.iterations parameter for custom control
- ā
Matching parameters for twoWayDecrypt()`