System Design Part 8 Security

Encryption in Transit and at Rest, and Secrets Management: What Encryption Protects Depends on Who Can Get the Key

Bill.Lin 19 min read

System Design series Part 8-4 | Previous: After BOLA Gets Past the BFF: Identity Propagation Between Microservices | Next: Abuse Prevention | Series map

Read first: Part 8-3 After BOLA Gets Past the BFF: Identity Propagation Between Microservices.

Scenario and problem

The talk platform stores this data:

Data Sensitivity Consequences of a leak
Talk titles, times, speaker names Public None
Members’ email, phone, and sign-up records Personal data Notify the regulator and the people affected, fines, damaged trust
Speakers’ bank accounts and tax records Highly sensitive Used for fraud; if tampered with, payouts go into someone else’s account
Database passwords, payment API keys, the IdP client secret, signing keys Secrets The attacker gets the system’s own privileges

A security assessment asks: “Do you encrypt?” Most teams answer: “Yes, we turned on HTTPS and database disk encryption.” But the questions that come next are what matter:

  • An attacker uses SQL injection to dump the whole speaker_bank_account table. Do they see plaintext or ciphertext?
  • A database backup was copied to the test environment. Who can read it?
  • A former employee’s laptop holds a copy of application-prod.yml. What is in it?
Three questions after "we encrypt"1 / 4
Three questions after "we encrypt"AttackerApplicationDatabaseEx-employeeTest envDB backupApplicationDatabaseHTTPS is onDisk encryption onAttackerApplicationDatabaseSQL injectiondump accountsGets plaintextDatabaseDB backupTest envbackupcopy to testWho can read it?Ex-employeeApplicationconfig passwordapplication-prod.yml
  1. Do you encrypt?Most teams answer: yes, we turned on HTTPS and database disk encryption.
  2. SQL injectionAn attacker uses SQL injection to dump the whole speaker bank account table. Disk encryption only guards against a disk or a snapshot being taken. While the database runs, it decrypts transparently, so queries see plaintext.
  3. A backup reaches testA database backup was copied to the test environment. Permissions there are usually much looser. Who can read it?
  4. The ex-employee's configA former employee's laptop holds a copy of application-prod.yml. Does it contain the database password or the payment API key?

The simplest approach and its limits

  • HTTPS up to the load balancer: traffic between the browser and the load balancer is encrypted, but between the load balancer and the application, and between the application and the database and Redis, it is still plaintext (the Load Balancing post)
  • Database disk encryption: it only protects against “the storage media or a snapshot being taken”. The database decrypts transparently while it runs, so any account that can log in to the database, any SQL injection, and any mysqldump sees plaintext
  • Passwords in application.yml or environment variables: once the config file is in Git, it stays in the history forever; environment variables show up in crash dumps, child processes, debug endpoints, and CI logs

Core mechanism

What each layer of encryption stops

How far encryption protects your data depends on who can get the key to decrypt it.

Encryption layer Who holds the key Stops Does not stop
Encryption in transit (TLS) Both ends of the connection Eavesdropping and tampering on the network Either end being compromised
Storage-layer encryption (disks, RDS at-rest encryption, TDE) The storage system or the database Disks, snapshots, or backup files being copied (as long as whoever copies them cannot get the key) Anyone who can query the database: DBAs, a stolen application account, SQL injection
Application-layer field encryption The application (through KMS) The whole database being dumped, DBAs, backups The application itself being compromised (it can decrypt)

Storage-layer encryption costs almost nothing, so turn it on everywhere; but it is not the answer to “the data stays safe when the database leaks”. Only the few fields with the highest sensitivity are worth the cost of application-layer encryption.

Encryption in transit

  • Encrypt every hop: browser to load balancer, load balancer to service, service to service (mTLS), service to the database, Redis, and Kafka; every hop uses TLS
  • Verify the other side’s identity: if the database connection only turns on encryption and does not verify the server certificate, a man in the middle can still intercept it. MySQL Connector/J needs sslMode=VERIFY_IDENTITY, not REQUIRED
  • Allow only TLS 1.2 and above, and use HSTS to prevent downgrades to HTTP
  • Automate certificates: the validity period of publicly trusted certificates is being cut in stages, down to only 47 days by 2029, so renewing by hand is no longer workable (web certificate trust)

Envelope encryption: the key never leaves KMS

The hardest part of application-layer encryption is not the algorithm but where the key lives. Put the AES key in a config file and it is likely to leak together with the data, which makes the encryption pointless.

Envelope encryption splits keys into two layers:

flowchart LR
    subgraph KMS["KMS or HSM"]
        KEK[Master key KEK<br/>never leaves KMS]
    end
    App[Application] -->|1 request a data key| KMS
    KMS -->|2 plaintext DEK and encrypted DEK| App
    App -->|3 encrypt data with the plaintext DEK<br/>then clear it from memory| App
    App -->|4 store ciphertext and encrypted DEK| DB[(Database)]
  • The master key (KEK) is stored in KMS or an HSM and never leaves it in plaintext. The application can only ask KMS to use it to encrypt or decrypt small amounts of data
  • The data key (DEK) is generated by KMS, and the application uses it to encrypt data. The encrypted DEK is stored together with the ciphertext, and the plaintext DEK is cleared from memory once it has been used
  • To decrypt, the application sends the encrypted DEK to KMS to unwrap it, then uses it to decrypt the data

What this buys you:

  • If the whole database is dumped, the attacker has only ciphertext and encrypted DEKs, and cannot decrypt anything without KMS permissions
  • Every decryption goes through KMS, so there is an audit log of who decrypted what, and when, and permissions are controlled by IAM
  • Rotating the master key only requires re-encrypting the DEKs (which are small), not all the data

The cost is a KMS call on every decryption, which adds a few milliseconds of latency, and KMS has a quota on requests per second. Speakers’ bank accounts are read only for the monthly payout: 5,000 speakers means 5,000 decryptions, which is no problem at all. But if the field you encrypt is read on every request, you need to cache the DEK briefly in memory, or switch to one DEK per tenant, trading security against cost.

Use AEAD, and bind the ciphertext to its location

For the algorithm, use authenticated encryption (AEAD), such as AES-256-GCM: it guarantees both confidentiality and integrity, so if the ciphertext is modified, decryption fails.

GCM has two things to watch:

  • Never repeat a nonce: if the same key is used twice with the same nonce, an attacker can work out relationships between the plaintexts and even forge ciphertext. With random 96-bit nonces, NIST SP 800-38D limits a single key to at most 2³² encryptions. A rough estimate: one key encrypting 1,000 records a second reaches 2³² ≈ 4.3 billion in about 50 days. So high-frequency encryption needs to replace the DEK regularly, or use a different DEK for each record or each tenant
  • Bind the location: AEAD can carry additional authenticated data (AAD), which is not encrypted but is verified. Without this binding, an attacker who can write to the database can copy the ciphertext of their own bank account into speaker B’s row, and the next payout sends B’s money to the attacker, with decryption working perfectly. Put the table name, the column, and the speaker ID into the AAD (the KMS equivalent is the encryption context), and ciphertext moved to another row fails to decrypt

Querying after encryption

Encrypted columns cannot use LIKE, range queries, or ordinary indexes. When you need an equality lookup such as “has this tax ID already been registered”, you can store a separate blind index: compute HMAC-SHA256 with a different key, store it in its own column, and put a unique index on it.

A blind index leaks “whether two records have the same value”, as well as the distribution of values (for example, many people use the same bank). So build one only for columns that really need to be queried, and keep the HMAC key separate from the encryption key.

Do not encrypt data you never need to read back

Data Need the original value back? Approach
User passwords No, only compare A slow password hash (the Authentication post)
API keys you issue to customers No, only compare A high-entropy random value; store only its SHA-256 and show it only once, at creation
Speakers’ bank accounts Yes, needed for payouts Application-layer encryption
Credit card numbers You should not handle them Use the payment provider’s payment page and tokens; card numbers never enter your system

The safest data is data you do not store. Leaving card numbers to the payment provider can greatly shrink your PCI DSS scope.

Key rotation and crypto-shredding

  • Master key rotation: KMS can rotate the master key automatically and keep old versions for decryption, with no changes to the application. But this does not re-encrypt existing data. If the goal is “once an old key leaks, old data still cannot be decrypted”, you have to re-encrypt separately
  • Ciphertext records the key version: the ciphertext format carries the key’s identifier, so old and new keys can coexist and rotation can happen gradually
  • Crypto-shredding: delete a tenant’s DEK, and all data encrypted with it (including backups, replicas, and old versions in an LSM-Tree that have not been compacted yet) turns into unreadable ciphertext at once (the B-Tree vs LSM-Tree post)
  • Losing the key means losing the data: KMS key deletion has a waiting period (7 to 30 days on AWS KMS), during which you can cancel it. Before deleting a key, make sure no data still depends on it

Secrets management

Secrets are the credentials that give a system its privileges: database passwords, third-party API keys, OAuth client secrets, signing keys, TLS private keys.

Where they must not go:

  • Git, including private repos. Even after deletion, they stay in the history and in every clone
  • Container images. Every layer of an image can be unpacked
  • Environment variables. They show up in crash dumps, child processes, debug endpoints, and CI logs
  • Logs and error messages

Where they should go, and how:

  • A secrets management service: AWS Secrets Manager, HashiCorp Vault, or Kubernetes Secrets with etcd at-rest encryption. By default a Kubernetes Secret is only base64-encoded and stored unencrypted in etcd; you have to turn on encryption separately and use RBAC to limit who can read it
  • Mount them as files, not environment variables; the application reads only the few it needs
  • Short-lived dynamic credentials: systems like Vault can generate a database account with an expiry for each application instance, and revoke it automatically when it expires. A leaked credential is valid only for a short time
  • The best secret is no secret: in the cloud, use workload identity (for example EKS Pod Identity) to get short-lived cloud permissions instead of long-lived access keys; when the database supports IAM authentication, use it instead of a fixed password; between services, use mTLS (8-3)

Rotation:

  • Rotation has to work without downtime: keep two valid sets of credentials at the same time (the new one takes effect, then the old one is revoked), or give the database two accounts that take turns
  • A connection pool uses the password only when it opens a new connection; connections that are already open are unaffected. HikariCP can update the password at runtime through HikariConfigMXBean (HikariCP tuning)

After a leak: rotate first, then clean up. Removing it from Git history only limits how far it spreads; that secret must be treated as leaked. Add secret scanning to CI to block it at push time.

Comparing options

Option Fits Cost
Only encryption in transit and storage-layer encryption Most data, including ordinary personal data When a database account leaks, the data is plaintext
Application-layer field encryption (envelope encryption) A few highly sensitive, rarely queried fields No querying or sorting in the database; KMS latency and quotas; more complex code
The database’s column encryption feature When you want the database to handle encryption The keys are usually managed by the database too, so DBAs and database accounts can still decrypt
Tokenization (a third party stores the data) Credit card numbers and other data that dedicated services handle Depends on a third party; looking up the original value means calling an external service

The talk platform’s choices:

  • All data: encryption in transit on every hop; storage-layer encryption on the database, Redis, Kafka, and object storage, using KMS keys whose permissions you manage yourself
  • Speakers’ bank accounts and tax records: application-layer envelope encryption, with the AAD bound to the speaker ID; tax records also get a blind index to check for duplicate registrations
  • Members’ email and phone: no application-layer encryption. Login, notifications, and customer support lookups all need them, so encryption would cost too much; protect them with access control, log masking, and auditing instead
  • Credit cards: never handled; use the payment provider’s payment page
  • Secrets: stored in the secrets management service and mounted as files; cloud permissions come from workload identity; database passwords rotate automatically every 30 days

In Java

1. Envelope encryption: speakers’ bank accounts

java
public record EncryptedValue(byte[] wrappedKey, byte[] nonce, byte[] ciphertext) {
}

@Component
public class BankAccountCipher {

    private static final int NONCE_BYTES = 12;
    private static final int TAG_BITS = 128;

    private final KmsClient kms;
    private final String keyId;
    private final SecureRandom random = new SecureRandom();

    public BankAccountCipher(KmsClient kms, @Value("${lectures.crypto.bank-account-key-id}") String keyId) {
        this.kms = kms;
        this.keyId = keyId;
    }

    public EncryptedValue encrypt(long speakerId, String accountNumber) {
        GenerateDataKeyResponse dataKey = kms.generateDataKey(GenerateDataKeyRequest.builder()
                .keyId(keyId)
                .keySpec(DataKeySpec.AES_256)
                .encryptionContext(context(speakerId))          // binding on the KMS side, also written to the CloudTrail audit log
                .build());
        byte[] key = dataKey.plaintext().asByteArray();
        try {
            byte[] nonce = new byte[NONCE_BYTES];
            random.nextBytes(nonce);
            Cipher cipher = Cipher.getInstance("AES/GCM/NoPadding");
            cipher.init(Cipher.ENCRYPT_MODE, new SecretKeySpec(key, "AES"), new GCMParameterSpec(TAG_BITS, nonce));
            cipher.updateAAD(aad(speakerId));                   // binding on the application side: ciphertext moved to another speaker fails to decrypt
            byte[] ciphertext = cipher.doFinal(accountNumber.getBytes(StandardCharsets.UTF_8));
            return new EncryptedValue(dataKey.ciphertextBlob().asByteArray(), nonce, ciphertext);
        } catch (GeneralSecurityException e) {
            throw new IllegalStateException("Encryption failed", e);
        } finally {
            Arrays.fill(key, (byte) 0);
        }
    }

    public String decrypt(long speakerId, EncryptedValue value) {
        byte[] key = kms.decrypt(DecryptRequest.builder()
                        .keyId(keyId)
                        .ciphertextBlob(SdkBytes.fromByteArray(value.wrappedKey()))
                        .encryptionContext(context(speakerId))
                        .build())
                .plaintext().asByteArray();
        try {
            Cipher cipher = Cipher.getInstance("AES/GCM/NoPadding");
            cipher.init(Cipher.DECRYPT_MODE, new SecretKeySpec(key, "AES"), new GCMParameterSpec(TAG_BITS, value.nonce()));
            cipher.updateAAD(aad(speakerId));
            return new String(cipher.doFinal(value.ciphertext()), StandardCharsets.UTF_8);
        } catch (AEADBadTagException e) {
            throw new TamperedDataException("Bank account ciphertext for speaker " + speakerId + " failed verification");   // alert: possibly tampered with or moved
        } catch (GeneralSecurityException e) {
            throw new IllegalStateException("Decryption failed", e);
        } finally {
            Arrays.fill(key, (byte) 0);
        }
    }

    private static Map<String, String> context(long speakerId) {
        return Map.of("table", "speaker_bank_account", "speakerId", Long.toString(speakerId));
    }

    private static byte[] aad(long speakerId) {
        return ("speaker_bank_account:account_number:" + speakerId).getBytes(StandardCharsets.UTF_8);
    }
}
  • One DEK per record: one KMS call for each write and each read, which suits fields that are rarely read, and never hits GCM’s encryption limit
  • A verification failure (AEADBadTagException) is not an ordinary error. It means the ciphertext was modified or moved, and it should trigger an alert
  • The application’s IAM permissions allow only GenerateDataKey and Decrypt on this KMS key; only the payout service has the Decrypt permission, while the speaker panel can only write and can only see the masked last four digits
  • A Java String cannot be wiped from memory, so you cannot fully control how long the plaintext stays in memory; what gets cleared here is the key

2. Blind index: checking for duplicate tax IDs

java
@Component
public class TaxIdBlindIndex {

    private final SecretKeySpec hmacKey;

    // the key is stored as Base64 in the secrets management service, separate from the KMS key used for encryption
    public TaxIdBlindIndex(@Value("${lectures.crypto.tax-id-index-key}") String base64Key) {
        this.hmacKey = new SecretKeySpec(Base64.getDecoder().decode(base64Key), "HmacSHA256");
    }

    public byte[] of(String taxId) {
        try {
            Mac mac = Mac.getInstance("HmacSHA256");
            mac.init(hmacKey);
            return mac.doFinal(taxId.strip().getBytes(StandardCharsets.UTF_8));   // normalize first, or the same value produces different results
        } catch (GeneralSecurityException e) {
            throw new IllegalStateException(e);
        }
    }
}
sql
ALTER TABLE speaker_tax_profile
    ADD COLUMN tax_id_index BINARY(32) NOT NULL,
    ADD UNIQUE KEY uk_tax_id_index (tax_id_index);

3. Secrets: mounted as files, never shown on any endpoint

yaml
spring:
  config:
    import: "optional:configtree:/etc/secrets/"      # /etc/secrets/db/password becomes db.password
  datasource:
    url: jdbc:mysql://lectures-db.internal:3306/lectures?sslMode=VERIFY_IDENTITY
    username: ${db.username}
    password: ${db.password}
  data:
    redis:
      ssl:
        enabled: true

management:
  endpoint:
    env:
      show-values: never                            # masked by default; set explicitly so nobody changes it to always
  • /etc/secrets/ is mounted by the secrets management service’s Kubernetes integration (for example the Secrets Store CSI Driver) or by a Kubernetes Secret, so the application does not need to know where the secrets are stored
  • Do not expose the heapdump and env endpoints publicly: a heap dump contains every secret and every piece of personal data in memory (the Observability post)

The code above was written from the official documentation for Spring Boot 4.1, the AWS SDK for Java 2.x, and the Java standard library (JCA); it has not been compiled or run.

Pitfalls and gotchas

  • Keys stored with the data: the AES key sits in the same application’s config file, or in the same database, so it leaks along with the data
  • Inventing your own encryption format: ECB mode, combining encryption and HMAC yourself, reusing nonces. Use AEAD and a mature library
  • Assuming “at-rest encryption is on” keeps the data safe when the database leaks: see the table above
  • Assuming master key rotation re-encrypts the data: it only changes encryption from then on; old data is still decrypted with the old version
  • Finding out after encrypting that you need to query it: before encrypting a field, check every query and report that reads it
  • Treating a Kubernetes Secret as encryption: base64 is only an encoding; RBAC permission to read a Secret is permission to read the plaintext
  • Secrets in CI logs: a build script echoes an environment variable, or a failing test prints the whole configuration
  • Rotation causing downtime: with only one set of credentials, the moment it is replaced, every instance that has not yet received the new password cannot open a connection
  • Deleting a key that is still in use: all data that depends on it can never be decrypted again

Attack scenarios

Attack How it happens Defense
Eavesdropping on the internal network Plaintext traffic behind the load balancer, or from services to the database, is captured TLS on every hop, verifying the other side’s certificate
Man in the middle The database connection only turns on encryption and does not verify the server certificate A fully verifying mode such as VERIFY_IDENTITY
SQL injection dumping a whole table The attacker reads all the data through the application’s database account Application-layer encryption for highly sensitive fields; decryption permission only for the services that need it
Backup leak A backup is copied to an environment with looser permissions Encrypt backups with a KMS key, and manage the key’s permissions separately from the backup’s
Moved ciphertext Someone with write access to the database copies their own ciphertext into someone else’s row AAD and the encryption context bind the data to its location
Passwords in Git A config file or test code gets committed, and the repo is made public or copied Secret scanning; no secrets in the repo; rotate immediately after a leak
Debug endpoint leak /actuator/env and /actuator/heapdump are exposed publicly Expose only the endpoints you need; keep the management port off the public network
Leaked cloud access key A long-lived access key turns up on a laptop, in CI, or in an image Workload identity and short-lived credentials; never issue long-lived keys
Abuse of decryption permission A privileged insider or a compromised service decrypts in bulk KMS audit logs; monitor for unusual decryption counts

When to use it, and when not to

  • Always do: encryption in transit on every hop, storage-layer encryption on all storage, and no secrets in Git or images
  • Use application-layer encryption: for the few fields where a leak has serious consequences, reads are rare, and no database queries are needed
  • Use tokenization: for data that a dedicated service can hold for you, such as credit cards
  • Do not encrypt: fields that need to be queried, sorted, or full-text searched. Forcing encryption on them only produces more blind indexes and plaintext caches; use access control, masking, and auditing instead
  • When to re-evaluate: when regulations or customer contracts require specific data to be encrypted, after a data breach, or when KMS cost and latency start to affect the main request path

References

Comments