Step 4: Advanced Encryption Patterns & Compliance
Once you've mastered the basic pattern of encrypting fields, you can implement more sophisticated, production-grade features for key management, selective decryption, and compliance.
Pattern 1: Key Versioning & Rotation
For security, encryption keys must be rotated periodically. Your encryption logic needs to record which key version was used so that you can still decrypt old data after a key rotation.
- mapping: |
root = this
# Add the key version to the encrypted output
root.payment.card_number_encrypted = "%s:%s".format(
env("KEY_VERSION"),
this.payment.card_number.encrypt_aes("gcm", env("CARD_ENCRYPTION_KEY"))
)
# Add it to the metadata as well for easy searching
root.payment.encryption_metadata.key_version = env("KEY_VERSION")
When decrypting, your application would parse the version from the string (v1:...), fetch the corresponding key from your key vault, and then perform decryption.
Pattern 2: Selective Decryption for Authorized Services
Not all services should be able to decrypt all data. You can build a decryption pipeline that selectively decrypts fields based on the calling service's identity, which can be passed via an HTTP header.
Use Case: A fraud detection service needs to see the email domain and SSN area, but a marketing service should see neither.
- mapping: |
let service_name = meta("http_headers.X-Service-ID")
root = this
# Decrypt email ONLY for the 'fraud-service'
if service_name == "fraud-service" && this.customer.email_encrypted.exists() {
root.customer.email = this.customer.email_encrypted.decrypt_aes(
"gcm", env("PII_ENCRYPTION_KEY")
)
}
# Decrypt SSN ONLY for the 'identity-verification' service
if service_name == "identity-verification" && this.customer.ssn_encrypted.exists() {
root.customer.ssn = this.customer.ssn_encrypted.decrypt_aes(
"gcm", env("PII_ENCRYPTION_KEY")
)
}
Pattern 3: Compliance and Audit Logging
For compliance standards like HIPAA and GDPR, you need detailed audit logs of when data was encrypted and why.
- mapping: |
root = this
# Create an audit log entry
let audit_log = {
"event_id": uuid_v4(),
"action": "ENCRYPT",
"timestamp": now(),
"fields_encrypted": [
"customer.ssn_encrypted",
"customer.email_encrypted"
],
"compliance_standards": ["HIPAA", "GDPR"],
"justification": "Protecting patient/customer PII at rest.",
"pipeline_id": "encrypt-pii-v2",
"node_id": env("NODE_ID")
}
# Send the audit log to a secure endpoint (fire-and-forget)
_ = http_client(
env("AUDIT_ENDPOINT_URL"),
{"verb": "POST", "timeout": "2s"},
audit_log
)
These advanced patterns provide a path toward a production-ready, compliant, and manageable encryption strategy.