Video in progress

Strong Middle 🐻 Hibernate and JPA

How does database-level column encryption with `@ColumnTransformer` (for example, pgcrypto) work, and what are its limitations?

@ColumnTransformer wraps the column in a SQL expression on read and write: pgp_sym_encrypt(?, key) when writing, pgp_sym_decrypt(column, key) when reading. The entity keeps a plain String. But you can't search an encrypted column with an index, the key travels through the SQL, and native queries don't know about this transformation.

📖 Answer

@Entity
class Patient {
    @Id Long id;

    @ColumnTransformer(
        read  = "pgp_sym_decrypt(passport, current_setting('app.enc_key'))",
        write = "pgp_sym_encrypt(?, current_setting('app.enc_key'))")
    @Column(name = "passport", columnDefinition = "bytea")
    private String passport;
}

Hibernate uses the read expression on every SELECT and the write expression on every INSERT/UPDATE. Even if you write where p.passport = :x in JPQL, the condition is applied to the decrypted value.

Don't write the key as a literal: it ends up in the SQL log, in pg_stat_statements and in the code. In the example above the key is taken from a session setting, which has to be set when the connection is opened (set app.enc_key = ...), and that has its own complexity.

Limitations:

  • where pgp_sym_decrypt(passport, ...) = ? decrypts every row, and no index works. If you need to search, you store an HMAC (a blind index) in a separate column;
  • native SQL, reports and other services don't know about the transformation;
  • the encryption happens on the database server, so the plaintext value travels from the application to the database over the network (you need TLS) and is visible in the database's memory.

The alternative is application-level encryption (AES-GCM inside an AttributeConverter, with the key from a KMS). The database then sees only encrypted bytes, but searching again goes through a blind index. I often choose this one: the key never reaches the database at all. @ColumnTransformer is also a useful tool for small changes (for example, storing with lower(email)).