Skip to main content

Step 4: Advanced Encryption Patterns

These variants illustrate key-version, selective-decryption, and audit-metadata ideas. They are not executed by a current machine gate.

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.

Add Key Versioning
- 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.

Selective Decryption Pipeline
- mapping: |
let service_name = meta("http_headers.X-Service-ID")
root = this

# Select email decryption for the authored 'fraud-service' identity
if service_name == "fraud-service" && this.customer.email_encrypted.exists() {
root.customer.email = this.customer.email_encrypted.decrypt_aes(
"gcm", env("PII_ENCRYPTION_KEY")
)
}

# Select SSN decryption for the authored 'identity-verification' identity
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: Transformation audit metadata

This example records when and why a configured transformation was selected. A real audit design needs an independently protected event destination, access model, retention policy, and failure handling.

HIPAA/GDPR Audit Logging
- 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 metadata to a separately managed audit endpoint
_ = http_client(
env("AUDIT_ENDPOINT_URL"),
{"verb": "POST", "timeout": "2s"},
audit_log
)

These advanced patterns provide a path toward a more complete and manageable encryption strategy.