Video in progress

Staff 🌱 Spring

Encrypting personal data (passport number, phone) in the database is now required. How do you build this in a Spring/JPA application, and how do you manage the keys?

If disk encryption isn't enough, I encrypt fields in the application itself (an AttributeConverter or the service layer), with keys in a KMS/Vault using envelope encryption. For search you need a separate blind index, and for key rotation a versioned encrypted value.

📖 Answer

First pin down the threat model, because the kind of encryption depends on it:

  • If a disk or backup is stolen, encrypting the database/disk (TDE, storage encryption in the cloud) is enough and doesn't touch the application.
  • Reads by a DBA, a database dump or SQL injection: only application-level encryption protects you, because the database holds only encrypted bytes.

At the application level, a JPA converter:

@Converter
class EncryptedStringConverter implements AttributeConverter<String, String> {
    private final FieldCipher cipher;   // a Spring bean; in Boot 3 injection into converters works

    @Override public String convertToDatabaseColumn(String plain) {
        return plain == null ? null : cipher.encrypt(plain);   // "v2:" + base64(iv + ciphertext)
    }
    @Override public String convertToEntityAttribute(String stored) {
        return stored == null ? null : cipher.decrypt(stored);
    }
}

@Convert(converter = EncryptedStringConverter.class)
private String passportNumber;
  • The algorithm is AES-GCM, with a random IV for every value.
  • A key version in front of the value, so the key can be changed later.

Key management is envelope encryption: you encrypt with a data key (DEK), and the DEK is itself encrypted by a master key (KEK) in a KMS or Vault. The master key never leaves for the application. Keeping a key in application.yml cancels out the protection. Vault's Transit engine does the encryption itself, so the application never sees the key, but every operation becomes a network call.

The hard parts:

  • Search. Because of the random IV, WHERE passport = ? doesn't work. The solution is a blind index: in a separate column, HMAC(key2, normalize(value)), unique, and you search on that column. LIKE and sorting are not possible at all, and you need to tell the business that up front.
  • Key rotation. New records use the new version; a background job re-encrypts the old ones in batches.
  • Leak channels: logs, error messages, the cache (plain text in Redis), the analytics warehouse, backups. Encrypted fields must be masked in toString() and in logs.
  • The right to be forgotten: encrypting with a per-user key and then deleting the key (crypto-shredding) makes the data useless in all copies.

The cost is CPU, limited search capabilities and operational complexity. That is why I apply encryption not to all fields but to the truly sensitive ones, identified through data classification.