SteelReed

Search

Search posts, questions…

5. Spring Boot

Storing passwords and encrypting personal data: salts, Argon2id, AES-GCM and blind indexes

Two data-protection case studies: storing passwords (salt, pepper, Argon2id/bcrypt, upgrading legacy hashes) and encrypting personal data (where to encrypt, AES-GCM with nonces and AAD, envelope encryption, binary vs Base64, blind indexes).

18 Nov 20268 min readSenior

–

1. The problem

A backup forgotten in a public bucket leaks the users table: 2 million rows of unsalted md5(password), 60% reversed in one afternoon. The national ID column is plaintext, so it leaks too.

2. Key idea

Every table leaks someday. The goal: when it does, the attacker gets as little as possible.

2.1 How do you store passwords?

The system only needs to check whether a password is right or wrong, so hash one-way, don't encrypt.

Option Problem
Encryption The key lives on the server; lose the server, lose everything
Fast hash (MD5, SHA-256) Rainbow tables reverse it; GPUs try billions per second
Fast hash with salt No rainbow tables, but each account is still quick to brute-force
Argon2id, scrypt, bcrypt, PBKDF2 Deliberately slow, tunable cost (~100–500 ms)

The salt (16 random bytes per record) is already embedded in bcrypt/Argon2id strings. A pepper is a shared secret kept in a KMS, not the DB. Bcrypt is not obsolete but only uses the first 72 bytes. A slow hash won't save 123456: you still need rate limiting and MFA.

2.2 Where do you encrypt personal data?

Encrypt in Use when Don't use when
Database (TDE, disk encryption) always on, cheap, protects lost disks/snapshots thinking it stops SQL injection: anyone who can SELECT reads plaintext
Application (AES-GCM per column) the few most sensitive columns (ID, phone) columns needing LIKE, sorting, range search
Client (end-to-end) chat, private notes the server must process or search the data
  • AES-GCM is authenticated encryption: tampered ciphertext fails to decrypt. A (key, nonce) pair must never repeat.
  • AAD bound to customer:42:phone: ciphertext copied to another row is rejected.
  • Envelope encryption: data is encrypted with a DEK, and the DEK is wrapped by a KEK in the KMS. Delete one customer's DEK and every copy in backups becomes garbage.
  • A blind index (an HMAC column of the value) allows equality search on an encrypted column.
Blind indexes: searching encrypted data

Random nonces mean WHERE phone_enc = ? never matches. Add an email_bidx column = HMAC-SHA256 (its own key, not the encryption key) of the normalised value (trim, lowercase), truncated to 16 bytes and indexed. Search with WHERE email_bidx = :bidx, then decrypt for display.

Aspect Reality
Queries equality only: no LIKE, ranges, sorting
Leakage reveals which rows share a value; never for low-cardinality columns (gender, province)
Reducing leakage truncate the HMAC to force collisions, filter again after decrypting

Store ciphertext as binary (bytea, VARBINARY); Base64 adds 33%.

3. In Java

JAVA
@Bean
PasswordEncoder passwordEncoder() {      // new hashes use bcrypt: "{bcrypt}$2a$10$..."
    return PasswordEncoderFactories.createDelegatingPasswordEncoder();  // still verifies {pbkdf2}, {argon2}...
}
 
static byte[] encrypt(SecretKey dek, byte[] plain, byte[] aad) throws Exception {
    byte[] nonce = new byte[12];
    RNG.nextBytes(nonce);                                  // SecureRandom, fresh EVERY time
    Cipher c = Cipher.getInstance("AES/GCM/NoPadding");    // plain "AES" is ECB: leaks patterns, no integrity
    c.init(Cipher.ENCRYPT_MODE, dek, new GCMParameterSpec(128, nonce));
    c.updateAAD(aad);                                      // "customer:42:phone"
    byte[] ct = c.doFinal(plain);
    return ByteBuffer.allocate(12 + ct.length).put(nonce).put(ct).array();
}
// 10-char phone -> 38-byte blob (12 nonce + 10 + 16 tag); wrong AAD -> AEADBadTagException

On a successful login, if upgradeEncoding(stored) returns true, rehash with the new algorithm.

Bcrypt: 72 bytes and DoS
  • @Size(max = 72) counts characters, bcrypt counts bytes: 72 accented characters can be 216 UTF-8 bytes. Check password.getBytes(UTF_8).length <= 72, or use Argon2id. Recent Spring Security releases (fix for CVE-2025-22228) make BCryptPasswordEncoder reject passwords over 72 bytes.
  • Don't feed a binary SHA-256 digest into bcrypt (a zero byte truncates it); Base64 it first if you must.
  • Each check burns 100–300 ms of CPU by design, so the login endpoint is a cheap DoS target: cap the length, rate-limit by IP and account, verify in a bounded pool.

4. Working with AI

Delegate to AI: an AttributeConverter that encrypts a column, a migration job for legacy hashes, tests for decrypting with the wrong AAD.

Check yourself:

  • Passwords go through a PasswordEncoder, not hand-rolled SHA-256.
  • Cipher.getInstance("AES/GCM/NoPadding"), not bare "AES".
  • Nonces come from SecureRandom each time, never fixed, never Random.
  • Keys come from a KMS/secret manager, not application.yml; ciphertext carries a key_id.

5. Exercises

Exercise 1: Move legacy MD5 to bcrypt today

2 million accounts store unsalted md5(password). AI suggests "rehash with bcrypt when users log in". Is that enough? Propose something safe today.

Solution to Exercise 1

Not enough: accounts that never log in stay on MD5 forever.

  1. Run a job now: for each row compute bcrypt(md5_hex), store it with a {bcrypt-md5} prefix, delete the MD5. From now on a DB leak means cracking bcrypt.
  2. At login: for {bcrypt-md5} hashes, check bcrypt.matches(md5Hex(input), legacy); if it matches, rehash input with the current encoder.

You can register {bcrypt-md5} as a custom encoder in DelegatingPasswordEncoder to avoid a separate branch.

Exercise 2: Review "secure AES-256" encryption

AI wrote: Cipher c = Cipher.getInstance("AES"); c.init(ENCRYPT_MODE, key); return Base64.getEncoder().encodeToString(c.doFinal(pii));, with key read from application.yml. Find three problems.

Solution to Exercise 2
  1. "AES" defaults to ECB: equal values give equal ciphertext, leaking patterns; no integrity, so tampering decrypts to garbage silently. Switch to AES/GCM/NoPadding, a 12-byte nonce, AAD.
  2. The key sits in config that ships with the code: use a KMS and envelope encryption, with a key_id on the ciphertext.
  3. Base64 in a text column costs 33% more: use bytea/VARBINARY.

Test: encrypting the same value twice must give two different blobs; decrypting with another row's AAD must throw AEADBadTagException.

Summary

  • Passwords: slow salted hash (Argon2id, bcrypt), not encryption, not SHA-256.
  • An algorithm prefix lets you upgrade hashes gradually.
  • Personal data: AES-GCM in the app, nonces never repeat, AAD bound to the row id.
  • Keys in a KMS via envelope encryption; delete the DEK to "erase" from backups.
  • Blind indexes: equality only, leak which rows share a value.

Next: Part 3: Web attacks and the OWASP Top 10.

Practice interview questions on this topic

All Security questions →

Loading comments…