In modern applications, protecting user data isn’t optional—it’s a responsibility. Here’s a practical breakdown of how we implement data encryption in production systems, along with the trade-offs every engineering team should understand.

Enable EXTENSION in Postgrsql

CREATE EXTENSION IF NOT EXISTS pgcrypto;

-- Generate secret_key
SELECT encode(gen_random_bytes(32), 'base64') as your_secret_key;

CREATE TABLE customers (
    id SERIAL PRIMARY KEY,
    name TEXT,
    mobile_encrypted BYTEA
);


INSERT INTO customers (name, mobile_encrypted)
VALUES (
    'John Doe',
    pgp_sym_encrypt('9876543210', 'your_secret_key', 'cipher-algo=aes256')
);

SELECT
    id,
    name,
    pgp_sym_decrypt(mobile_encrypted, 'your_secret_key') AS mobile
FROM customers;


SELECT * FROM customers;



UPDATE customers
SET mobile_encrypted =
    pgp_sym_encrypt(mobile, 'your_secret_key', 'cipher-algo=aes256');
	
	
SELECT
    'XXXXXX' || RIGHT(pgp_sym_decrypt(mobile_encrypted, 'your_secret_key'),4)
FROM customers;

How to Encrypt Data in Production

1. Encrypt Sensitive Data at Rest

2. Never Store Plaintext Secrets

3. Enable Secure Lookups with Hashing

4. Encrypt in Transit

5. Restrict Decryption

6. Add Audit Logging

Pros of Encryption

Cons / Trade-offs

Pro Tips from Production Experience

Bottom Line

Encryption is not just a feature—it’s a system design decision. Done right, it protects your users, your business, and your reputation.

If you're building systems handling sensitive data, this should be your baseline—not an afterthought.