Shield Platform Encryption & Compliance
📖 Concept
Salesforce Shield is a set of enterprise security features for highly regulated industries. Understanding Shield, encryption, and compliance requirements (GDPR, HIPAA, PCI-DSS) is essential for architect-level roles.
Salesforce Shield components:
Platform Encryption — Encrypts data at rest
- Encrypts field values in the database
- Supports: text, email, phone, URL, textarea, date, datetime, number, currency
- Data is encrypted with AES-256
- Key management: Salesforce-managed or customer-managed (BYOK)
- Impact: Some features limited (formula fields, SOQL filtering on encrypted fields)
Event Monitoring — Track user activity
- Login events, API calls, report exports, page views
- Transaction Security policies (real-time alerts)
- Event log files (30-day retention, BigQuery/Splunk export)
Field Audit Trail — Extended data retention
- Track field changes for up to 10 years
- Standard audit trail only tracks 20 fields × 18 months
- Critical for regulatory compliance
GDPR (General Data Protection Regulation):
- Right to access: Users can request their data
- Right to erasure: Must delete personal data on request
- Data portability: Export data in machine-readable format
- Consent tracking: Record and manage user consent
- Salesforce features: Individual object, Data Privacy fields, consent management
HIPAA (Health Insurance Portability and Accountability Act):
- Encrypt PHI (Protected Health Information) at rest and in transit
- Audit trail for all PHI access
- Business Associate Agreement (BAA) with Salesforce
- Restrict access using FLS, sharing rules, Shield encryption
Apex Security Best Practices:
- Always use
with sharingby default - Check FLS before DML:
Security.stripInaccessible() - Check CRUD before operations:
isAccessible(),isCreateable() - Never expose sensitive data in debug logs
- Use Shield encryption for PII/PHI fields
💻 Code Example
1// Security & Compliance Patterns23public with sharing class ComplianceService {45 // 1. CRUD/FLS enforcement6 public static List<Account> getAccountsSecure() {7 // Check object-level access8 if (!Schema.SObjectType.Account.isAccessible()) {9 throw new SecurityException('No access to Account object');10 }1112 List<Account> accounts = [13 SELECT Id, Name, Phone, Industry, AnnualRevenue14 FROM Account LIMIT 10015 ];1617 // Strip fields the user can't access (FLS)18 SObjectAccessDecision decision = Security.stripInaccessible(19 AccessType.READABLE, accounts20 );2122 return (List<Account>) decision.getRecords();23 }2425 // 2. Secure DML with FLS26 public static void updateAccountSecure(Account acc) {27 // Check update permission28 if (!Schema.SObjectType.Account.isUpdateable()) {29 throw new SecurityException('No update access to Account');30 }3132 // Strip fields the user can't update33 SObjectAccessDecision decision = Security.stripInaccessible(34 AccessType.UPDATABLE, new List<Account>{acc}35 );3637 update decision.getRecords();38 }3940 // 3. GDPR — Right to Erasure41 public static void handleErasureRequest(String email) {42 // Find all records related to this person43 List<Contact> contacts = [44 SELECT Id, AccountId FROM Contact WHERE Email = :email45 ];46 List<Lead> leads = [47 SELECT Id FROM Lead WHERE Email = :email48 ];4950 // Anonymize or delete based on business requirements51 for (Contact c : contacts) {52 c.FirstName = 'REDACTED';53 c.LastName = 'REDACTED';54 c.Email = null;55 c.Phone = null;56 c.MailingStreet = null;57 }58 update contacts;5960 if (!leads.isEmpty()) {61 delete leads;62 }6364 // Log the erasure for compliance65 insert new Privacy_Request_Log__c(66 Request_Type__c = 'Erasure',67 Subject_Email__c = email,68 Processed_Date__c = Datetime.now(),69 Records_Affected__c = contacts.size() + leads.size()70 );71 }7273 // 4. Data export for portability (GDPR Right to Access)74 public static String exportPersonalData(String email) {75 Contact contact = [76 SELECT FirstName, LastName, Email, Phone,77 MailingAddress, Account.Name78 FROM Contact WHERE Email = :email LIMIT 179 ];8081 Map<String, Object> exportData = new Map<String, Object>{82 'name' => contact.FirstName + ' ' + contact.LastName,83 'email' => contact.Email,84 'phone' => contact.Phone,85 'company' => contact.Account?.Name,86 'exportDate' => Datetime.now().format()87 };8889 return JSON.serializePretty(exportData);90 }9192 // 5. Audit trail logging93 public static void logSensitiveAccess(Id recordId, String action) {94 insert new Audit_Log__c(95 Record_Id__c = recordId,96 Action__c = action,97 User__c = UserInfo.getUserId(),98 Timestamp__c = Datetime.now(),99 IP_Address__c = Auth.SessionManagement.getCurrentSession()?.get('SourceIp')100 );101 }102103 // 6. Encryption-aware code104 public static void handleEncryptedFields() {105 // When Shield Platform Encryption is enabled:106 // - Cannot filter on encrypted fields in SOQL WHERE107 // - Cannot use encrypted fields in ORDER BY108 // - Formula fields referencing encrypted fields are limited109110 // Pattern: Query by non-encrypted field, then filter in Apex111 List<Contact> allContacts = [112 SELECT Id, FirstName, LastName, SSN__c // SSN__c is encrypted113 FROM Contact114 WHERE AccountId = :accountId115 ];116117 // Filter encrypted field in Apex (not SOQL)118 Contact match = null;119 for (Contact c : allContacts) {120 if (c.SSN__c == targetSSN) {121 match = c;122 break;123 }124 }125 }126}
🏋️ Practice Exercise
Security & Compliance Practice:
- Implement CRUD and FLS checks using Security.stripInaccessible() for all object operations
- Build a GDPR erasure service that anonymizes personal data across 5 objects
- Create a data export feature that generates a JSON file of all personal data for a contact
- Design a consent management system using custom objects (Consent__c)
- Implement audit logging for all accesses to sensitive fields (SSN, DOB, medical records)
- Enable Shield Platform Encryption on 3 fields and verify SOQL filtering limitations
- Write test classes that verify FLS enforcement using System.runAs with restricted profiles
- Create an Event Monitoring dashboard using Shield Event Log data
- Design a data retention policy: which data to keep, archive, or delete based on age
- Build a compliance report that shows all users who accessed sensitive records in the last 30 days
⚠️ Common Mistakes
Not enforcing FLS in Apex — Apex runs in system context by default. Without explicit CRUD/FLS checks, all fields are accessible regardless of user permissions
Trying to filter SOQL on encrypted fields — Shield encryption prevents WHERE clause filtering. Query by non-encrypted fields and filter in Apex
Logging PII in debug logs — debug logs may be accessible to admins. Never log SSN, credit cards, passwords, or health data
Hard-deleting GDPR-protected data without audit trail — always log what was deleted, when, and why for compliance audits
Assuming 'with sharing' enforces FLS — 'with sharing' only enforces record-level security (OWD/sharing rules). FLS requires explicit checks with Security.stripInaccessible()
💼 Interview Questions
🎤 Mock Interview
Mock interview is powered by AI for Shield Platform Encryption & Compliance. Login to unlock this feature.