Scrivio Interview library
DesignIntermediate6 min read · updated 12 November 2026

A service stores national ID numbers and bank details in PostgreSQL. The database volume is already encrypted. What else would you do, and how would you implement field-level encryption in a Spring Data JPA application?

Volume encryption only protects against someone stealing a disk or a snapshot file; anyone who can query the database or the application sees plain values. So we add field-level encryption in the application: national ID and bank fields are encrypted with AES-GCM using data keys protected by a KMS or Vault (envelope encryption), through a JPA AttributeConverter that encrypts on write, decrypts on read and stores the key id with the ciphertext. Because ciphertext cannot be searched, we add a keyed hash (HMAC) column for equality lookups, and we limit who can decrypt and log every access.

Why this question is asked

National ID numbers and bank details are exactly the data that turns a breach into a front-page story and a regulatory fine. Teams often answer "the disk is encrypted" and stop there, but that answers a different threat. Interviewers ask this design question to see whether we can name which attacker each layer stops, and whether we can implement application-level encryption in Spring Data JPA without breaking queries. In this answer, we will see what disk encryption does and does not protect, design envelope encryption with a KMS, implement it with an AttributeConverter, solve lookups with a blind index, and finish with access control and auditing.

1What Volume Encryption Protects, and What It Does Not

Volume or disk encryption, such as encrypted EBS volumes or a cloud database's storage encryption, encrypts blocks on disk. The database engine reads them decrypted, so to everything above the storage layer the data looks normal. That stops one attacker: someone who gets the physical disk, a backup file copied without its key, or a snapshot shared by mistake.

It does nothing against the attackers we see most often: SQL injection in the application, a stolen database password, an over-privileged analyst account, a replica or export that ends up in the wrong place, or a developer running SELECT * on production. Each of them reads plain national IDs. Field-level encryption moves the protection up so that the database only ever holds ciphertext for these columns, and only the application, with access to the keys, can turn it back into values.

Which layer stops which attacker
AttackerDisk encryptionField encryption
Stolen disk or snapshotProtectedProtected
Stolen database passwordNot protectedProtected (sees ciphertext)
SQL injection in another endpointNot protectedProtected unless it reaches decrypt
Analyst with read accessNot protectedProtected
Compromised application with key accessNot protectedNot protected

2Envelope Encryption With a KMS

We do not want the master key in the application, and we do not want to call the KMS for every row. Envelope encryption solves both. The KMS (AWS KMS, Google Cloud KMS, or Vault's transit engine) holds a key encryption key (KEK) that never leaves it. The application asks the KMS for a data encryption key (DEK): it gets the DEK in plain form to use in memory and the same DEK encrypted by the KEK to store.

The application encrypts fields with the DEK using AES-GCM, and stores the wrapped DEK, or an id that points to it, alongside. To decrypt, it sends the wrapped DEK to the KMS once, caches the plain DEK in memory for a while, and decrypts many rows locally. Rotating the KEK only means rewrapping DEKs, not re-encrypting every row.

Step throughEnvelope encryption for one field
ApplicationKMSPostgreSQL
GenerateDataKey(kek: customer-pii)
plain DEK + wrapped DEK, id k7
AES-GCM encrypt national ID with DEK
INSERT ciphertext with key id k7
SELECT row later
ciphertext, key id k7
Decrypt(wrapped DEK k7) if not cached
AES-GCM decrypt, value in memory

8 messages in order. Play them, or step through them one at a time.

The KMS never sees the data, and the database never sees a usable key.

3Implementing It With a JPA AttributeConverter

JPA's AttributeConverter converts an entity attribute to a database column and back. Hibernate calls convertToDatabaseColumn on insert and update, and convertToEntityAttribute when it loads a row, so encryption becomes invisible to the rest of the code. We store a small self-describing value: a version byte, the key id, the 12-byte IV and the ciphertext with its tag, Base64 encoded into a text column (or kept as bytea).

Java
@Converter
public class PiiConverter implements AttributeConverter<String, String> {
private final FieldCrypto crypto; // wraps AES-GCM and the DEK cache; injected by Spring
public PiiConverter(FieldCrypto crypto) { this.crypto = crypto; }
@Override public String convertToDatabaseColumn(String plain) {
return plain == null ? null : crypto.encrypt(plain); // "v1:k7:<base64 iv+ciphertext+tag>"
}
@Override public String convertToEntityAttribute(String stored) {
return stored == null ? null : crypto.decrypt(stored); // reads k7, finds the DEK, decrypts
}
}
@Entity
class Customer {
@Id Long id;
@Convert(converter = PiiConverter.class) String nationalId; // column holds ciphertext
@Convert(converter = PiiConverter.class) String iban;
String nationalIdHash; // HMAC for lookups, see below
}

Spring Boot with Hibernate 6 can inject Spring beans into converters, because Boot configures Hibernate to use Spring's bean container; check your setup if the converter is created with a no-argument constructor instead. Notice that each value carries its key id. That is what makes key rotation possible later: old rows still say which key decrypts them. We can also pass the column name as associated data to GCM, so a ciphertext copied from the iban column into nationalId fails to decrypt.

4Searching Encrypted Fields With a Keyed Hash

AES-GCM with a random IV gives a different ciphertext every time, even for the same value. That is what we want for security, but it means WHERE national_id = ? can never match. The usual answer is a blind index: a separate column holding HMAC-SHA256 of the normalised value with a secret key kept in the KMS or Vault. The same input always gives the same HMAC, so equality lookups work, but without the HMAC key nobody can test guesses, which matters because national IDs have a small, guessable format.

Notice the limits. A blind index supports exact matches only, not LIKE, ranges or sorting, and it reveals which rows share a value. For most uses of national IDs, finding the customer with this exact ID, that is enough.

Java
String normalised = input.replaceAll("[^0-9A-Z]", "").toUpperCase(); // "AB 12 34 56 C" -> "AB123456C"
Mac mac = Mac.getInstance("HmacSHA256");
mac.init(blindIndexKey); // from KMS or Vault, not the DEK
String hash = HexFormat.of().formatHex(mac.doFinal(normalised.getBytes(StandardCharsets.UTF_8)));
customers.findByNationalIdHash(hash); // indexed equality lookup

5Limiting Who Can Decrypt and Logging Access

Encryption moves the question from who can read the table to who can use the key. So we narrow that: only the customer service's workload identity may call Decrypt on this KEK in the KMS policy, and within the service, only the endpoints that really need the clear national ID decrypt it. A listing page can show the last four characters, stored separately, without decrypting anything.

Every decrypt is logged with who, when and why, in two places: the KMS audit trail records the service using the key, and the application logs which user or job asked for which customer record. Spikes in decrypt calls are alerted on, because a sudden export of 50,000 national IDs looks very different from normal support traffic.

6Follow-up questions

Why not use PostgreSQL's pgcrypto instead?

pgcrypto encrypts inside the database, so the key has to be sent to the database in the query, where it can appear in logs, pg_stat_statements or memory dumps of the database server. Doing it in the application keeps keys out of the database entirely, which is the point of protecting against database-level attackers.

What about Hibernate's @ColumnTransformer?

It wraps column reads and writes in SQL expressions, which again usually means database-side functions and keys passed to the database. An AttributeConverter keeps cryptography in Java, where we control the library, the IV and the key handling.

How does this affect performance?

AES-GCM in modern JDKs uses hardware instructions and encrypts a short field in microseconds. The cost that matters is KMS calls, which is why we cache DEKs for a limited time and reuse one DEK for many rows.

7Conclusion

In this answer, we saw that volume encryption protects only against stolen disks and snapshots, not against anyone with database or application access. We added field-level encryption with envelope encryption, data keys protected by a KMS or Vault, implemented with a JPA AttributeConverter that stores the key id with each ciphertext. A keyed HMAC column restores equality lookups, and KMS policies, minimal decryption and access logging limit who can see the clear values.

What to say in the interviewAbout 90 seconds aloud

Open with

Disk encryption only protects against a stolen disk, snapshot or backup file. The database decrypts blocks transparently, so anyone with a database login, an injection bug or a copy of a replica reads national IDs in clear text.

Then, if they want more

For data this sensitive I would add field-level encryption in the application. I would use envelope encryption: a key encryption key in a KMS or Vault transit that never leaves it, and data keys that the KMS generates and wraps.

The application encrypts each field with AES-GCM and a random IV using a cached data key, and stores the key id with the ciphertext.

In Spring Data JPA the clean way is an AttributeConverter on the nationalId and iban fields, so Hibernate encrypts on write and decrypts on read, and the stored value looks like a version, a key id, then the IV and ciphertext.

Because each encryption gives different output, normal WHERE clauses stop working, so I add a blind index column, an HMAC-SHA256 of the normalised value with a separate secret key, which supports exact-match lookups without letting anyone test guesses.

Then I limit decryption: only this service's identity may use the key in the KMS policy, only screens that really need the full value decrypt it, and others show a masked suffix. Every decrypt is logged in the KMS audit trail and the application log, and I alert on unusual volumes.

About this answer

Last updated
12 November 2026
Versions it names
Hibernate 6
Checked
Its structure and format are checked automatically. Use it as a carefully prepared study note: where a detail matters, confirm it against the documentation below. What the checks cover
Where the question comes from
Written by Scrivio for practice. It is not taken from an interview.
Official documentation
Spring Security reference
Report an issue with this answer

Copy the line below and send it to the author with what you found. It carries the address of this page.

Issue with "A service stores national ID numbers and bank details in PostgreSQL. The database volume...": https://scrivio-interview-library.netlify.app/spring-boot/secrets-and-crypto/76d7f86f90/