Data Encryption
End-to-end encryption for sensitive data in webMCP applications. Protect user information with industry-standard encryption methods.
Encryption Features
Comprehensive encryption solutions for protecting sensitive data
AES-256 Encryption
Industry-standard AES-256-GCM encryption for maximum security
- AES-256-GCM authenticated encryption
- Automatic nonce generation
- Integrity verification built-in
- FIPS 140-2 compliant implementation
JWE Payload Encryption
JSON Web Encryption for structured data protection
- JWE compact serialization
- Multiple content encryption algorithms
- Key agreement protocols
- Compressed payload support
Field-Level Encryption
Granular encryption of sensitive form fields
- Selective field encryption
- Format-preserving encryption
- Searchable encryption options
- Custom encryption policies
Supported Encryption Methods
Choose the right encryption method for your security requirements
| Method | Key Size | Performance | Security | Use Case |
|---|---|---|---|---|
AES-256-GCM Authenticated encryption with associated data | 256 bits | High | Maximum | General-purpose encryption for sensitive data |
ChaCha20-Poly1305 Modern stream cipher with authentication | 256 bits | Very High | Maximum | Mobile and low-power devices |
JWE (A256GCM) JSON Web Encryption with AES-256-GCM | 256 bits | Medium | Maximum | Structured data and API payloads |
Implementation Examples
Practical examples for implementing encryption in your applications
Basic Field Encryption
Encrypt sensitive form fields automatically
JavaScriptimport { WebMCPProcessor } from '@webmcp/core';
const processor = new WebMCPProcessor({
security: {
encryption: {
method: 'aes-256-gcm',
key: process.env.ENCRYPTION_KEY, // 32-byte key
// Fields to encrypt automatically
sensitiveFields: [
'password',
'ssn',
'creditCard',
'bankAccount',
'email' // Optional: encrypt PII
],
// Custom encryption rules
fieldRules: {
'creditCard': {
algorithm: 'aes-256-gcm',
format: 'preserving', // Keep format for validation
},
'ssn': {
algorithm: 'aes-256-gcm',
searchable: true // Enable encrypted search
}
}
}
}
});
// Process form with automatic encryption
const processForm = async (formData) => {
const encrypted = await processor.encryptSensitiveFields(formData);
console.log('Original:', formData);
console.log('Encrypted:', encrypted);
// Store encrypted data
await database.save(encrypted);
// Decrypt when needed
const decrypted = await processor.decryptSensitiveFields(encrypted);
console.log('Decrypted:', decrypted);
};
// Example usage
processForm({
name: 'John Doe',
email: 'john@example.com',
creditCard: '4111-1111-1111-1111',
ssn: '123-45-6789'
});JWE Encryption
Use JSON Web Encryption for structured data
JavaScriptimport { WebMCPProcessor } from '@webmcp/core';
const processor = new WebMCPProcessor({
security: {
encryption: {
method: 'jwe',
algorithm: 'A256GCM', // Content encryption
keyManagement: 'dir', // Direct key agreement
key: process.env.JWE_KEY,
// JWE-specific options
jwe: {
zip: 'DEF', // Compress before encryption
protected: {
alg: 'dir',
enc: 'A256GCM'
}
}
}
}
});
// Encrypt entire webMCP payload
const encryptPayload = async (webmcpData) => {
const jweToken = await processor.encryptJWE({
elements: webmcpData.elements,
metadata: webmcpData.metadata,
timestamp: Date.now()
});
console.log('JWE Token:', jweToken);
return jweToken;
};
// Decrypt JWE payload
const decryptPayload = async (jweToken) => {
try {
const decrypted = await processor.decryptJWE(jweToken);
console.log('Decrypted payload:', decrypted);
return decrypted;
} catch (error) {
console.error('Decryption failed:', error.message);
throw new Error('Invalid or corrupted encrypted data');
}
};
// Example with error handling
const secureProcessing = async (htmlContent) => {
try {
// Parse and encrypt
const webmcpData = processor.parseWebMCP(htmlContent);
const encrypted = await encryptPayload(webmcpData);
// Store encrypted data
await storage.save('webmcp_data', encrypted);
// Later: retrieve and decrypt
const stored = await storage.get('webmcp_data');
const decrypted = await decryptPayload(stored);
return decrypted;
} catch (error) {
console.error('Secure processing failed:', error);
throw error;
}
};Key Management
Implement secure key rotation and management
JavaScriptimport crypto from 'crypto';
class KeyManager {
constructor(processor) {
this.processor = processor;
this.keys = new Map();
this.currentKeyId = null;
this.rotationInterval = 24 * 60 * 60 * 1000; // 24 hours
}
// Generate new encryption key
generateKey() {
const keyId = crypto.randomUUID();
const key = crypto.randomBytes(32); // 256-bit key
const createdAt = Date.now();
this.keys.set(keyId, {
key: key.toString('base64'),
createdAt,
active: true
});
// Set as current key
if (this.currentKeyId) {
this.keys.get(this.currentKeyId).active = false;
}
this.currentKeyId = keyId;
return keyId;
}
// Get current encryption key
getCurrentKey() {
if (!this.currentKeyId) {
throw new Error('No active encryption key');
}
return this.keys.get(this.currentKeyId);
}
// Get key by ID (for decryption)
getKey(keyId) {
const keyData = this.keys.get(keyId);
if (!keyData) {
throw new Error(`Key not found: ${keyId}`);
}
return keyData;
}
// Encrypt with current key
async encrypt(data) {
const keyData = this.getCurrentKey();
const keyId = this.currentKeyId;
const encrypted = await this.processor.encrypt(data, {
key: keyData.key,
algorithm: 'aes-256-gcm'
});
// Include key ID in encrypted data
return {
keyId,
data: encrypted,
timestamp: Date.now()
};
}
// Decrypt with specified key
async decrypt(encryptedData) {
const { keyId, data } = encryptedData;
const keyData = this.getKey(keyId);
return await this.processor.decrypt(data, {
key: keyData.key,
algorithm: 'aes-256-gcm'
});
}
// Automatic key rotation
setupRotation() {
setInterval(() => {
console.log('Rotating encryption key...');
const newKeyId = this.generateKey();
console.log(`New key generated: ${newKeyId}`);
// Clean up old keys (keep last 3 for decryption)
this.cleanupOldKeys(3);
}, this.rotationInterval);
}
cleanupOldKeys(keepCount) {
const allKeys = Array.from(this.keys.entries())
.sort(([,a], [,b]) => b.createdAt - a.createdAt);
if (allKeys.length > keepCount) {
const toDelete = allKeys.slice(keepCount);
toDelete.forEach(([keyId]) => {
this.keys.delete(keyId);
console.log(`Deleted old key: ${keyId}`);
});
}
}
}
// Usage
const keyManager = new KeyManager(processor);
keyManager.generateKey(); // Initial key
keyManager.setupRotation(); // Auto-rotation
// Encrypt data
const sensitiveData = { ssn: '123-45-6789', creditCard: '4111-1111-1111-1111' };
const encrypted = await keyManager.encrypt(sensitiveData);
// Decrypt data (works with any historical key)
const decrypted = await keyManager.decrypt(encrypted);Python Implementation
Encryption in Python applications
Pythonfrom webmcp_core import WebMCPProcessor, EncryptionConfig
from cryptography.fernet import Fernet
from cryptography.hazmat.primitives import hashes
from cryptography.hazmat.primitives.kdf.pbkdf2 import PBKDF2HMAC
import os
import base64
import json
class WebMCPEncryption:
def __init__(self, password=None):
self.password = password or os.getenv('ENCRYPTION_PASSWORD')
self.salt = os.getenv('ENCRYPTION_SALT', os.urandom(16))
self.key = self._derive_key()
self.fernet = Fernet(self.key)
# Configure processor
self.processor = WebMCPProcessor(
security=EncryptionConfig(
method='aes-256-gcm',
key=self.key,
sensitive_fields=['password', 'ssn', 'credit_card', 'email']
)
)
def _derive_key(self):
"""Derive encryption key from password using PBKDF2"""
kdf = PBKDF2HMAC(
algorithm=hashes.SHA256(),
length=32,
salt=self.salt,
iterations=100000,
)
key = base64.urlsafe_b64encode(kdf.derive(self.password.encode()))
return key
def encrypt_field(self, value):
"""Encrypt a single field value"""
if isinstance(value, str):
value = value.encode()
elif not isinstance(value, bytes):
value = json.dumps(value).encode()
encrypted = self.fernet.encrypt(value)
return base64.urlsafe_b64encode(encrypted).decode()
def decrypt_field(self, encrypted_value):
"""Decrypt a single field value"""
try:
encrypted_bytes = base64.urlsafe_b64decode(encrypted_value.encode())
decrypted = self.fernet.decrypt(encrypted_bytes)
# Try to parse as JSON, fallback to string
try:
return json.loads(decrypted.decode())
except json.JSONDecodeError:
return decrypted.decode()
except Exception as e:
raise ValueError(f"Decryption failed: {e}")
def encrypt_form_data(self, form_data):
"""Encrypt sensitive fields in form data"""
sensitive_fields = ['ssn', 'credit_card', 'password', 'email']
encrypted_data = form_data.copy()
for field in sensitive_fields:
if field in encrypted_data:
encrypted_data[field] = self.encrypt_field(encrypted_data[field])
# Mark as encrypted
encrypted_data[f'{field}_encrypted'] = True
return encrypted_data
def decrypt_form_data(self, encrypted_data):
"""Decrypt sensitive fields in form data"""
decrypted_data = encrypted_data.copy()
# Find encrypted fields
encrypted_fields = [
field.replace('_encrypted', '')
for field in encrypted_data.keys()
if field.endswith('_encrypted') and encrypted_data[field]
]
for field in encrypted_fields:
if field in decrypted_data:
decrypted_data[field] = self.decrypt_field(decrypted_data[field])
# Remove encryption marker
del decrypted_data[f'{field}_encrypted']
return decrypted_data
def process_webmcp_secure(self, html_content):
"""Process webMCP with automatic encryption"""
try:
# Parse webMCP
webmcp_data = self.processor.parse_webmcp(html_content)
# Encrypt sensitive elements
for element in webmcp_data.elements:
if element.element_type == 'input' and element.name in ['password', 'ssn', 'credit_card']:
if hasattr(element, 'value') and element.value:
element.value = self.encrypt_field(element.value)
element.encrypted = True
return webmcp_data
except Exception as e:
raise Exception(f"Secure webMCP processing failed: {e}")
# Usage example
encryption = WebMCPEncryption(password="your-secure-password")
# Encrypt form data
form_data = {
'name': 'John Doe',
'email': 'john@example.com',
'ssn': '123-45-6789',
'credit_card': '4111-1111-1111-1111'
}
encrypted = encryption.encrypt_form_data(form_data)
print("Encrypted:", encrypted)
decrypted = encryption.decrypt_form_data(encrypted)
print("Decrypted:", decrypted)
# Process HTML with encryption
html = '''
<form>
<input name="email" type="email" value="john@example.com" />
<input name="ssn" type="text" value="123-45-6789" />
<input name="password" type="password" />
</form>
'''
secure_data = encryption.process_webmcp_secure(html)
print("Secure webMCP data:", secure_data)Security Considerations
Best practices for secure encryption implementation
Key Management
Secure Key Storage
Store encryption keys in secure key management systems
Key Rotation
Regularly rotate encryption keys to limit exposure
Key Derivation
Use strong key derivation functions for password-based keys
Encryption Implementation
Use Authenticated Encryption
Always use authenticated encryption modes
Secure Random Generation
Use cryptographically secure random number generators
Proper Nonce Handling
Never reuse nonces with the same key
Data Protection
Field-Level Encryption
Encrypt only sensitive fields to maintain functionality
Format Preserving Encryption
Maintain data format for validation when needed
Searchable Encryption
Enable search on encrypted data when required
Performance Optimization
Optimize encryption performance without compromising security
Selective Encryption
Only encrypt truly sensitive fields
Reduces processing overhead by 60-80%
Define clear sensitivity classifications
Encryption Caching
Cache encrypted values for repeated data
Improves performance by 40-60% for repeated values
Use LRU cache with time-based expiration
Batch Operations
Process multiple fields together
Reduces encryption overhead by 30-50%
Group related fields in single encryption calls
Hardware Acceleration
Use AES-NI when available
Improves AES performance by 300-500%
Ensure AES-NI support in production environment
Secure Your Data
Implement comprehensive data encryption to protect sensitive information in your webMCP applications