Encryption at Rest, In Transit, and Key Management for Java Services
Fast recall
Quick revision
Core answer
Cipher with AES-GCM, never ECB; SecureRandom; never roll your own); use libraries like Tink (Google) or Bouncy Castle for higher-level safety; use Spring Security's BCryptPasswordEncoder / Argon2PasswordEncoder for passwords (these are hashing, not encryption — different problem). For TLS: rely on JDK defaults (Java 17+ has sane choices); enforce TLS 1.2 minimum, prefer 1.3; never disable certificate validation; pin certificates only when you can rotate them. Envelope encryption is the standard pattern at scale: data encrypted with a DEK (data encryption key); DEK encrypted with a KEK (key encryption key) in KMS; only the encrypted DEK is stored alongside data. Common mistakes: using ECB mode, hardcoded keys in code/config, custom crypto algorithms, storing keys with data they encrypt, using MD5/SHA1 for passwords, ignoring key rotation, sending PII in URLs (logged everywhere), and confusing 'encoding' (Base64) with 'encryption'. Compliance frameworks (PCI-DSS, HIPAA, GDPR, SOC2) all mandate specific encryption controls — know what your domain requires.ECB mode; hardcoded keys; custom crypto; confusing hashing with encryption; ignoring rotation
Discuss envelope encryption, KMS integration, Tink library, mTLS, compliance mappings, BYOK/HYOK
Interview-ready guide
Interview answer
Encryption is three layered concerns: in transit, at rest, and key management.
In transit
- TLS 1.2+ everywhere, mTLS internally, HTTPS-only ingress
At rest
- Database TDE, encrypted volumes, S3 SSE-KMS
- Application-level field encryption for most sensitive PII/PCI
Key management
- KMS (AWS KMS / GCP KMS / Azure Key Vault / HashiCorp Vault) — never hardcoded keys
- Envelope encryption for performance
- Key rotation as policy
Java specifics
- Standard JCE primitives: Cipher with AES-GCM, never ECB; SecureRandom; never roll own
- Libraries: Tink (Google) or Bouncy Castle for higher-level safety
- Spring Security BCryptPasswordEncoder/Argon2PasswordEncoder for passwords (hashing, not encryption — different problem)
TLS
- JDK defaults (Java 17+ has sane choices)
- Enforce TLS 1.2 minimum, prefer 1.3
- Never disable certificate validation
- Pin certs only when you can rotate them
Envelope encryption (standard pattern at scale)
- Data encrypted with DEK (data encryption key)
- DEK encrypted with KEK (key encryption key) in KMS
- Only encrypted DEK stored alongside data
Common mistakes
- ECB mode
- Hardcoded keys in code/config
- Custom crypto algorithms
- Storing keys with data they encrypt
- MD5/SHA1 for passwords
- Ignoring rotation
- Sending PII in URLs (logged everywhere)
- Confusing encoding (Base64) with encryption
Compliance
- PCI-DSS, HIPAA, GDPR, SOC2 mandate specific controls
- Know what your domain requires
Three layers detail
1. In transit — protect data moving between systems
- TLS for HTTP/gRPC/database connections
- mTLS for service-to-service inside trust boundary (zero-trust)
- VPN / private links for cross-region
2. At rest — protect data on disk
- Disk-level (LUKS, AWS EBS, GCP PD) — default-on with KMS keys
- Database TDE (Postgres pgcrypto/pg_tde, MySQL InnoDB, Oracle TDE)
- Object storage (S3 SSE-S3/SSE-KMS/SSE-C, GCS CMEK)
- Application-level field for most sensitive (SSN, card, health)
3. Key management — protect keys themselves
- KMS (AWS KMS, GCP KMS, Azure Key Vault, Vault, on-prem HSM)
- Envelope pattern
- Rotation + audit logs
- Access via IAM
Fourth often confused: hashing
- One-way for passwords and integrity
- Not encryption; can't decrypt a hash
- BCrypt/Argon2 for passwords; SHA-256 for integrity (HMAC for keyed)
Why all three layers matter — defense in depth
- TLS protects wire but not disk
- Disk protects against stolen drives but not against attacker with DB access
- Field-level protects against database compromise
- Each layer mitigates different threats
Java specifics
TLS server side
- Spring Boot: server.ssl.enabled=true with keystore; behind LB/ingress in K8s usually does TLS termination
- Enforce TLS 1.2+: server.ssl.enabled-protocols=TLSv1.2,TLSv1.3
- HSTS: Strict-Transport-Security: max-age=31536000; includeSubDomains
- Redirect HTTP→HTTPS at LB/Ingress
- Cert: cert-manager + Let's Encrypt; or AWS ACM
TLS client
- JDK defaults; never disable cert validation in prod
- Self-signed dev: custom truststore, not TrustAllCerts
- HttpClient default validates; mTLS via SSLContext with keystore + truststore
AES-GCM field level
- 96-bit IV (12 bytes) random per encryption
- Cipher.getInstance('AES/GCM/NoPadding')
- GCMParameterSpec(128, iv)
- updateAAD for context binding (user ID)
- Store iv || ciphertext together
- Rules: AES-GCM never ECB (deterministic, leaks); never AES-CBC without HMAC; unique IV per encryption; never reuse with same key; auth tag prevents tampering
KMS integration (AWS example)
- KmsClient.generateDataKey → plaintext DEK + encrypted DEK
- Encrypt payload with DEK; store ciphertext + encryptedDek
- Decrypt: kms.decrypt(encryptedDek) → plaintext DEK; decrypt ciphertext
Higher-level libraries
- Google Tink: opinionated, safe defaults, key set management, envelope automatic
- AWS Encryption SDK / KMS Java SDK: envelope, framing, KMS integration
- Bouncy Castle: lower-level; many algorithms; only when JCE lacks
- Don't write own framework; Tink-style eliminates IV reuse, mode confusion, key handling mistakes
Key management
Hierarchy + envelope
- Root keys (KEKs) in KMS/HSM; never leave boundary
- DEKs short-lived; per object/record; encrypted with KEK
- KMS handles only small key ops (fast); apps handle bulk with cheap symmetric crypto
Rotation
- Automatic KMS rotation (AWS yearly): keeps prior versions; old decrypts; new uses new
- App-driven: re-encrypt on next access; or background reencryption
- DEK rotation: re-generate per write (envelope does this)
- TLS cert rotation: cert-manager auto-renews; short-lived certs (24h-90d)
Access control
- IAM policies on KMS keys: only specific roles can Decrypt
- Separate keys for domains (PII vs config vs audit)
- KMS audit (CloudTrail): every encrypt/decrypt with caller
- Vault: policies + dynamic tokens with TTL
Crypto-shredding
- Per-user KEK
- 'Forget' user (GDPR erasure): delete KEK
- All data cryptographically inaccessible even if backups exist
Compliance
- PCI-DSS: card numbers AES-256 min; key mgmt documented; quarterly rotation
- HIPAA: PHI encrypted at rest + transit; access controls + audit
- GDPR: encryption recommended safeguard; mandatory at scale; supports right-to-erasure via crypto-shredding
- SOC2: encryption controls audited; rotation policy required
- FIPS 140-2/3: validated crypto modules for federal/regulated; AWS KMS HSM tier + CloudHSM are FIPS-validated
BYOK/HYOK
- Customer provides own key material into KMS (BYOK)
- Customer holds key entirely; cloud only sees encrypted (HYOK; less common)
- Regulated industries / multi-tenant SaaS
Common pitfalls
- 1Hardcoded keys in source/properties/Docker images; always vault/KMS
- 2Same key forever; no rotation; if compromised, all data
- 3AES-ECB: deterministic; identical plaintexts identical ciphertext; leaks structure
- 4IV reuse with AES-CTR/GCM: catastrophic; leaks plaintext
- 5MD5/SHA1 for passwords: fast = brute-forceable; use BCrypt/Argon2
- 6'Encryption' that's Base64: encoding ≠ encryption
- 7PII in URLs: logs, analytics, browser history, referer headers — leaks everywhere
- 8TLS with self-signed in prod: unclear trust boundary
- 9Disabling cert validation 'just for testing' that ships to prod
- 10Custom crypto: 'XOR'd it twice' = broken
- 11Keys next to data: defeats purpose
- 12Unencrypted backups: prod encrypted but backups in S3 unencrypted
- 13Encrypted logs forgotten: PII flows to log storage
- 14No KMS audit: can't tell if key misused
Performance
- Symmetric AES-GCM on modern CPUs (AES-NI): essentially free for typical web (>1 GB/s per core)
- TLS handshake has cost; reuse connections, HTTP/2/3, session resumption
- KMS calls: ~5-20 ms per; envelope + DEK caching reduces dramatically
- Field-level: queryable only via deterministic (lose security) or searchable encryption (complex); use sparingly
What encryption protects against
- Stolen disks/backups
- Network sniffing
- Some database compromise (if attacker doesn't get keys too)
- Insider raw storage access
- Multi-tenant data leaks via storage misconfig
What encryption does NOT protect against
- App-level vulns (SQLi, IDOR, broken authz) — attacker gets plaintext through normal API
- Compromised app servers (have keys)
- Memory dumps from running processes
- Key compromise itself
- Bad code that logs decrypted data
- Side-channel attacks on the application
Necessary but not sufficient. Combine with authn/authz, secure coding, audit logs, runtime monitoring.
When to use field-level
- Truly sensitive: card data, SSN, health records, gov IDs
- When DB compromise in threat model scope
- When 'admin sees clear data' unacceptable
- NOT for data queried frequently (lose index/sort)
Operational maturity ladder
- 1TLS everywhere external
- 2Disk encryption on (default cloud)
- 3Database TDE / encrypted volumes
- 4Secrets in vault
- 5mTLS for internal services
- 6KMS-managed keys with rotation
- 7Envelope encryption for stored objects
- 8Field-level for top-sensitive
- 9Crypto-shredding for GDPR
- 10HSM/FIPS-validated for regulated
- Most should be 5-6; high-compliance push 8-10
Senior engineer moves
- Standard libraries (Tink, AWS Encryption SDK); don't roll crypto
- Centralize: small EncryptionService interface, one implementation, everyone uses
- Automatic rotation: scheduled re-encryption; rotate KMS yearly
- Audit KMS access: alerts on unusual
- Document design: which data, which key, which rotation, which compliance
- Threat-model: what data, who's attacker, what encryption stops
- Coordinate with security/compliance before designing
Strategic take
- Encryption is plumbing; get it boring and right
- Cloud-native KMS + envelope for almost all use cases
- Field-level only when threat model demands
- Key management discipline matters more than algorithm choice
- Compliance is the floor; threat model is the ceiling
Encryption at Rest, In Transit, and Key Management for Java Services
Direct Answer
Encryption is three layered concerns: in transit (TLS 1.2+ everywhere, mTLS internally, HTTPS-only ingress), at rest (database TDE, encrypted volumes, S3 SSE-KMS, application-level field encryption for the most sensitive PII/PCI data), and key management (KMS like AWS KMS / GCP KMS / Azure Key Vault / HashiCorp Vault — never hardcoded keys; envelope encryption for performance; key rotation as policy). For Java specifically: use standard JCE primitives (Cipher with AES-GCM, never ECB; SecureRandom; never roll your own); use libraries like Tink (Google) or Bouncy Castle for higher-level safety; use Spring Security's BCryptPasswordEncoder / Argon2PasswordEncoder for passwords (these are hashing, not encryption — different problem). For TLS: rely on JDK defaults (Java 17+ has sane choices); enforce TLS 1.2 minimum, prefer 1.3; never disable certificate validation; pin certificates only when you can rotate them. Envelope encryption is the standard pattern at scale: data encrypted with a DEK (data encryption key); DEK encrypted with a KEK (key encryption key) in KMS; only the encrypted DEK is stored alongside data. Common mistakes: using ECB mode, hardcoded keys in code/config, custom crypto algorithms, storing keys with data they encrypt, using MD5/SHA1 for passwords, ignoring key rotation, sending PII in URLs (logged everywhere), and confusing 'encoding' (Base64) with 'encryption'. Compliance frameworks (PCI-DSS, HIPAA, GDPR, SOC2) all mandate specific encryption controls — know what your domain requires.
Common Mistakes & Pitfalls
ECB mode; hardcoded keys; custom crypto; confusing hashing with encryption; ignoring rotation
Check your understanding
Answer these without looking back at the article.
- Walk through implementing field-level encryption for SSNs in a Spring Data JPA entity.
- Why is AES-GCM preferred over AES-CBC for application-level encryption?
- Explain envelope encryption with KMS and why it scales.
- How does crypto-shredding satisfy GDPR right-to-erasure?
Related interview prep categories
1Looking for a structured roadmap?
Every module on this page is also part of the full Java backend interview track.