Return to site

☕🔐 How to ENCRYPT and DECRYPT DATA with HIBERNATE

Your Java entity can stay readable while your database stores ciphertext. 👀

· jakartaee

🔸 TLDR

Hibernate's @ColumnTransformer can transform a column automatically when reading and writing it.

With PostgreSQL + pgcrypto:

▪️ Java writes plain text

▪️ PostgreSQL encrypts it

▪️ The database stores encrypted bytes

▪️ Hibernate decrypts it automatically when reading

Example:

@ColumnTransformer(
     read = """
         pgp_sym_decrypt(
             storage,
             current_setting('encrypt.key')
         )
         """,
     write = """
         pgp_sym_encrypt(
             ?,
             current_setting('encrypt.key')
         )
         """ )
 @Column(columnDefinition = "bytea")
 private String storage;

So your application can simply do:

vault.setStorage("my_secret_key");

But PostgreSQL stores something looking like:

ww0EBwMC3If4VmIUn2x+0j4BKrKR...

Then:

Vault vault =
     entityManager.find(Vault.class, 1L);
  vault.getStorage();

returns:

my_secret_key

🔸 HOW DOES IT WORK?

Hibernate applies the write expression when generating SQL for INSERT/UPDATE:

pgp_sym_encrypt(?, ...)

And the read expression when selecting the column:

pgp_sym_decrypt(storage, ...)

Your domain model therefore doesn't need explicit:

encrypt();
decrypt();

logic everywhere. ✅

🔸 POSTGRESQL SIDE

Enable pgcrypto:

CREATE EXTENSION pgcrypto;

This gives you functions such as:

pgp_sym_encrypt(...) 
pgp_sym_decrypt(...)

🔸 ⚠️ DON'T HARDCODE THE KEY

Putting this inside your mapping would be a terrible idea:

"super-secret-key"

The original example uses a PostgreSQL setting accessed through:

current_setting('encrypt.key')

But even storing the secret in postgresql.conf should NOT be considered a production-grade key-management strategy.

Production systems should normally rely on proper secrets/key management and appropriate rotation/access controls. 🔑

🔸 TAKEAWAYS

▪️ @ColumnTransformer transforms SQL reads and writes transparently

▪️ Encryption can stay outside your Java business logic

▪️ PostgreSQL pgcrypto can encrypt sensitive columns

▪️ Your entity sees plaintext while the database stores ciphertext

▪️ Encryption key management is just as important as encryption itself

▪️ JPA portability is useful, but Hibernate-specific features can solve very real problems elegantly

Sometimes using your JPA provider's native capabilities is much cleaner than rebuilding everything yourself. 🚀

#java #hibernate #jpa #postgresql #security #encryption #javadeveloper #database #softwareengineering #backenddevelopment #javaprogramming

Go further with Java certification:

Java👇

Spring👇

SpringBook👇

JavaFullstackBook👇