Backend security series: 1. Encoding, hashing, encryption and signatures · 2. Storing passwords and encrypting personal data · 3. Web attacks and the OWASP Top 10 · 4. Authentication: sessions, cookies and JWT · 5. Authorization, SSO and OAuth2
Your users table and your customer table will leak one day (a SQL injection, a backup left in a public bucket, a compromised internal account). This post helps you store passwords and encrypt personal data so that the attacker gets as little as possible when it happens, with the costs and the places where the slides are outdated or wrong. Read part 1 first for the difference between hashes, HMACs and encryption.
1. Case study: storing passwords
Key idea: the system never needs to read a password back, only to check it. So use a slow, salted password-hashing function with a cost parameter, so that after a DB leak every guess is too expensive to be worth it (people reuse passwords elsewhere).
The options, from worst to best:
- Plaintext: one leak and everything is gone.
- Encryption: the key sits on the server, so a server breach leaks the key; reversibility is pure liability.
- Fast hash (MD5, SHA-256): the same password gives the same hash, so rainbow tables (precomputed hashes of common passwords) reverse them in bulk and reveal who shares a password. It’s also fast: a million SHA-256 hashes take ~57 ms on one CPU thread; a GPU tries billions of passwords per second.
- Fast hash with a salt: each row gets a salt (16 random bytes) stored next to the hash, and you hash
salt + password. Rainbow tables become useless (they’d have to be rebuilt per salt) and users with the same password get different hashes, but it’s still fast, so each account can be brute-forced (tried guess by guess). - A slow, salted password-hashing function: Argon2id, scrypt, bcrypt, PBKDF2. Deliberately slow with a tunable cost; Argon2id and scrypt are also memory-hard, which takes away the GPU/ASIC advantage.
A salt is like giving every lock its own key cut: nobody can prepare one bunch of keys that opens every door.
flowchart LR
P[User password] --> K[Argon2id or bcrypt with a cost]
S[Random 16-byte salt] --> K
K --> R["Stored string: algorithm, params, salt, hash"]
R --> DB[(users.password_hash)]
In Spring Security, use a PasswordEncoder instead of writing your own:
@Bean
PasswordEncoder passwordEncoder() {
// Encodes new passwords with bcrypt, stored as "{bcrypt}$2a$10$..."
// and can still verify older hashes prefixed {pbkdf2}, {scrypt}, {argon2}...
return PasswordEncoderFactories.createDelegatingPasswordEncoder();
}
The {id} prefix lets you upgrade algorithms gradually: after a successful login, if passwordEncoder.upgradeEncoding(stored) returns true (the stored hash is weaker than the configuration), re-hash the password you have in that request and save it. Spring Security does this automatically when your UserDetailsService also implements UserDetailsPasswordService. The whole login flow with UserDetailsService and PasswordEncoder in a working app is in form login with Spring Security.
PBKDF2 with plain JDK and the measurements
The Java code uses only JDK 21 and has been run; timings were measured on a development laptop and only show orders of magnitude. The JDK has PBKDF2 built in. The code below stores the algorithm, iteration count and salt alongside the hash, so changing parameters later involves no guesswork:
static String hashPassword(char[] pw, int iterations) throws Exception {
byte[] salt = new byte[16];
RNG.nextBytes(salt); // SecureRandom, one salt per row
byte[] dk = pbkdf2(pw, salt, iterations);
var b64 = Base64.getEncoder().withoutPadding();
return "pbkdf2$" + iterations + "$" + b64.encodeToString(salt) + "$" + b64.encodeToString(dk);
}
static byte[] pbkdf2(char[] pw, byte[] salt, int iterations) throws Exception {
var spec = new PBEKeySpec(pw, salt, iterations, 256);
return SecretKeyFactory.getInstance("PBKDF2WithHmacSHA256").generateSecret(spec).getEncoded();
}
static boolean checkPassword(char[] pw, String stored) throws Exception {
String[] p = stored.split("\\$");
var dec = Base64.getDecoder();
byte[] dk = pbkdf2(pw, dec.decode(p[2]), Integer.parseInt(p[1]));
return MessageDigest.isEqual(dk, dec.decode(p[3]));
}
Result: one PBKDF2-SHA256 run with 600,000 iterations took ~140 ms, so a single password guess costs as much as ~2.5 million SHA-256 hashes on the same machine. Hashing the same password twice gives two different strings thanks to the salt.
Bcrypt: the 72-byte limit and the DoS risk
2. Case study: encrypting personal data
Key idea: encrypt the few sensitive columns in the application layer with AES-GCM, with the key held in a KMS. Then a leaked DB or backup only leaks ciphertext.
The customer table holds national ID numbers, phone numbers, addresses. Decree 13/2023 (Vietnam), GDPR (EU) and auditors require them to stay protected even if the DB or a backup leaks. Three questions: where to encrypt, how to store the ciphertext, how to search it.
2.1. Where to encrypt
Key idea: turn on disk encryption in the DB (cheap) and encrypt the handful of most sensitive columns in the application layer; disk encryption alone doesn’t stop SQL injection.
flowchart TB
C[Client] -->|TLS| S[Application server]
S -->|TLS| D[(Database)]
D --> B[Backups, replicas, snapshots]
2.2. AES-GCM, nonces and AAD
Key idea: use AES/GCM/NoPadding with a fresh 12-byte nonce for every encryption, and AAD bound to the row id and column name. GCM is authenticated encryption: tampered ciphertext fails to decrypt instead of turning into garbage.
- Nonce (number used once): stored openly next to the ciphertext, so encrypting the same value twice gives two different blobs.
- AAD (additional authenticated data): not encrypted but authenticated. Bind it to the row id to stop someone with UPDATE rights from copying one person’s encrypted ID number into another person’s row: without AAD the blob still decrypts, with AAD it’s rejected.
- Stored blob =
nonce(12 bytes) || ciphertext || tag(16 bytes).
AES-GCM code with the JDK and the results
// Stored blob = nonce(12 bytes) || ciphertext || tag(16 bytes)
static byte[] encrypt(SecretKey key, byte[] plain, byte[] aad) throws Exception {
byte[] nonce = new byte[12];
RNG.nextBytes(nonce); // a fresh nonce for EVERY encryption
Cipher c = Cipher.getInstance("AES/GCM/NoPadding");
c.init(Cipher.ENCRYPT_MODE, key, new GCMParameterSpec(128, nonce));
c.updateAAD(aad); // e.g. "customer:42:phone"
byte[] ct = c.doFinal(plain);
return ByteBuffer.allocate(12 + ct.length).put(nonce).put(ct).array();
}
static byte[] decrypt(SecretKey key, byte[] blob, byte[] aad) throws Exception {
Cipher c = Cipher.getInstance("AES/GCM/NoPadding");
c.init(Cipher.DECRYPT_MODE, key, new GCMParameterSpec(128, blob, 0, 12));
c.updateAAD(aad);
return c.doFinal(blob, 12, blob.length - 12); // bad tag -> AEADBadTagException
}
Results: a 10-character phone number becomes a 38-byte blob (12 nonce + 10 + 16 tag). Encrypting the same value twice gives two different blobs. Flipping one bit, or decrypting customer 42’s blob with customer 43’s AAD, both throw AEADBadTagException.
2.3. Key management: envelope encryption
Key idea: the master key (KEK) never leaves the KMS; the application encrypts data with a data key (DEK) and only stores the DEK wrapped by the KEK. The course stops at “use AES-256”, but the harder question is where the key lives: a key in application.yml means a code leak is a key leak.
Think of a bank vault holding the key to each filing drawer: steal the cabinet without getting into the vault and you can’t open a single drawer.
- A KEK (key encryption key) lives in a KMS (a key-keeping service: AWS KMS, GCP KMS, HashiCorp Vault Transit) or an HSM (a hardware device that holds keys) and never leaves it.
- The application generates a DEK (data encryption key) to encrypt data, asks the KMS to wrap the DEK with the KEK, and stores the wrapped DEK next to the data (or in a
data_keystable). - To read: have the KMS unwrap the DEK, cache it in memory for a few minutes so you don’t call the KMS per row, then decrypt locally.
flowchart LR
KMS[KMS holds the KEK] -->|unwrap DEK| APP[Application]
APP -->|AES-GCM with DEK| ROW["Row: key_id, ciphertext"]
DK[(data_keys table: wrapped DEKs)] --> APP
The benefits: rotating the KEK only re-wraps the DEKs (a few hundred bytes), not millions of rows; decryption rights are controlled and logged centrally in the KMS. Every ciphertext carries a key_id (or key version) so you know which key decrypts it.
Crypto-shredding: erasing data in backups by deleting the key
2.4. Storing ciphertext as binary or Base64
Key idea: store binary in the DB column (the course picks right); use Base64 only at boundaries that must be text.
- Base64 adds ~33% (the 38-byte blob becomes a 52-character string, verified), and indexes on bigger columns cost more.
- Use
bytea(PostgreSQL),VARBINARY/BLOB(MySQL), mapped tobyte[]in JPA; anAttributeConverter<String, byte[]>that calls the encryption code hides it from business code. - Text boundaries: JSON, headers, URLs, config files. Base64url (no
+or/) for URLs and JWTs.
2.5. Searching encrypted data: blind indexes
Key idea: random nonces mean WHERE phone_enc = ? never matches. A blind index is an extra column holding an HMAC (a keyed hash) of the normalized value, computed with a separate key (not the encryption key), queried by equality.
Normalize before the HMAC (trim, lowercase) so " A@x.com" and "a@x.com" give the same blind index.
CREATE TABLE customer (
id bigint PRIMARY KEY,
email_enc bytea NOT NULL, -- AES-GCM, key_id inside the blob or in its own column
email_bidx char(32) NOT NULL -- HMAC-SHA256 truncated to 16 bytes, hex
);
CREATE INDEX idx_customer_email_bidx ON customer (email_bidx);
-- Lookup: SELECT ... WHERE email_bidx = :bidx, then decrypt email_enc for display
Computing a blind index with the JDK
static String blindIndex(byte[] indexKey, String value) throws Exception {
Mac mac = Mac.getInstance("HmacSHA256");
mac.init(new SecretKeySpec(indexKey, "HmacSHA256"));
byte[] full = mac.doFinal(value.trim().toLowerCase(Locale.ROOT).getBytes(StandardCharsets.UTF_8));
return HexFormat.of().formatHex(Arrays.copyOf(full, 16)); // truncated
}
// " A@x.com" and "a@x.com" give the same blind index (verified)
Exercises
Exercise 1: Move legacy MD5 hashes to bcrypt without forcing password resets
A legacy system stores unsalted md5(password) for 2 million accounts. Propose a way to make it safe today, without waiting for users to log in.
Solution to Exercise 1: wrap MD5 in bcrypt, then upgrade at login
If you only re-hash on login, inactive accounts stay on MD5 forever. Do it in two steps:
- Run a job now: for every row compute
bcrypt(md5_hex), store it with its own prefix such as{bcrypt-md5}, and delete the MD5 value. From now on, a leaked DB means cracking bcrypt. - On login: for a
{bcrypt-md5}hash, checkbcrypt.matches(md5_hex(input), stored); if it matches, re-hashinputwith the current encoder and store it under the new prefix.
boolean login(String input, User u) {
String stored = u.passwordHash();
if (stored.startsWith("{bcrypt-md5}")) {
String legacy = stored.substring("{bcrypt-md5}".length());
if (!bcrypt.matches(md5Hex(input), legacy)) return false;
users.updatePasswordHash(u.id(), passwordEncoder.encode(input)); // upgrade right away
return true;
}
boolean ok = passwordEncoder.matches(input, stored);
if (ok && passwordEncoder.upgradeEncoding(stored)) {
users.updatePasswordHash(u.id(), passwordEncoder.encode(input));
}
return ok;
}
With DelegatingPasswordEncoder you can register {bcrypt-md5} as a custom encoder and skip the special branch. This snippet is a sketch and wasn’t run (it depends on Spring Security’s encoders and a repository).
Exercise 2: Two bugs in an encryption snippet
Review: Cipher c = Cipher.getInstance("AES"); c.init(ENCRYPT_MODE, key); return Base64.getEncoder().encodeToString(c.doFinal(pii)); where key is read from application.yml.
Solution to Exercise 2: ECB, a key in config and Base64
"AES"defaults to ECB (each block encrypted independently): equal values give equal ciphertext, so patterns leak. There’s no authentication, so tampered ciphertext decrypts to garbage without any error. Switch toAES/GCM/NoPaddingwith a 12-byte nonce fromSecureRandomstored with the ciphertext, plus AAD.- The key lives in a config file shipped with the code: use a KMS and envelope encryption, with a
key_idon every ciphertext. - One more: storing Base64 in a text column costs 33% more; use
bytea/VARBINARY.
Remember
- Can you explain why passwords need a slow, salted hash rather than encryption or SHA-256?
- Can you list OWASP’s order and bcrypt’s two weak spots (72 bytes, DoS)?
- Can you tell salt from pepper: where each is stored, and what losing it costs?
- Do you know why AES-GCM needs a never-repeating nonce and AAD?
- Can you sketch envelope encryption and say what a blind index gives and what it leaks?
Interview questions
Junior
Why shouldn’t passwords be stored with SHA-256?
SHA-256 is too fast and unsalted, so both brute force and rainbow tables are cheap.
A GPU tries billions of passwords per second, and without a salt the same password gives the same hash, so they can be reversed in bulk. Use a slow, salted password-hashing function with a cost parameter: Argon2id, scrypt, bcrypt, or PBKDF2 when FIPS is required. In Spring, use DelegatingPasswordEncoder.
What is a salt, and does it need to be secret?
A salt is a random value unique to each password, and it doesn’t need to be secret.
It’s mixed in before hashing so identical passwords give different hashes and rainbow tables become useless. It’s stored right next to the hash (bcrypt and Argon2 embed it in their output string). A shared secret kept outside the DB is called a pepper.
Why hash passwords instead of encrypting them?
Because the system never needs to read a password back; it just hashes the input again and compares.
Encryption means a decryption key exists somewhere on the server, so a server-plus-DB breach exposes every password. One-way hashing with a slow, salted function means that even with the DB in hand, an attacker must guess each password at a high cost.
Mid
What do you watch out for when encrypting a national ID column with AES in Java?
AES/GCM/NoPadding with a fresh nonce and AAD every time, the key in a KMS, stored as binary.
- Never plain
"AES"(ECB). - A 12-byte nonce from
SecureRandomper encryption, stored with the ciphertext; never reuse a nonce under the same key. - AAD bound to the primary key and column name. Store as
bytea/VARBINARY. - Keep the key out of config: envelope encryption with a KMS, and a
key_idon every ciphertext for rotation. - If you need to search, add a blind index.
Which password-hashing algorithm would you pick today? Is bcrypt obsolete?
Argon2id first; bcrypt isn’t obsolete and is still Spring Security’s default.
Following OWASP: Argon2id (CPU- and memory-hard, which removes the GPU advantage), then scrypt, bcrypt with cost ≥ 10, and PBKDF2-HMAC-SHA256 with 600,000 iterations when FIPS is required. With bcrypt, mind the 72-byte limit. Tune parameters so a check takes ~100–500 ms on production hardware, and store algorithm-prefixed strings so you can upgrade gradually.
Senior
Design storage and lookup for encrypted customer phone numbers.
AES-GCM in the application layer with envelope encryption, plus a blind index column for equality lookups.
- Encrypt under a DEK wrapped by a KEK in the KMS, with the DEK cached briefly.
- A
phone_enc byteacolumn holds key_id, nonce, ciphertext and tag; the AAD is the customer id plus the column name. phone_bidx: an HMAC-SHA256 under a separate index key over the normalized value (E.164, the international format like +84…), truncated and indexed. Equality search only; be explicit about the leakage (shared values, frequencies).- Rotating the KEK only re-wraps DEKs; rotating the index key means recomputing the bidx column.
- Also enable disk encryption in the DB, mask numbers on display, and audit every decryption.
You inherit a system that stores unsalted MD5. What’s your upgrade plan?
Don’t wait for logins: wrap every hash in bcrypt(md5) now, then upgrade each user when they log in.
- Wrapping job:
bcrypt(md5)(or Argon2id) under a dedicated prefix, and delete the MD5 values. - On login: verify through the legacy branch, then re-hash the real password with the current encoder.
- In parallel: force resets if there’s any sign the DB has already leaked, block passwords found in breach lists, rate-limit logins, and require MFA for admin accounts.
- Measure hashing time on production hardware to choose the cost.
What happens if you reuse a nonce with AES-GCM, and how do you prevent it?
You lose both secrecy and integrity: the XOR of the plaintexts leaks and the attacker can forge ciphertexts.
Same key and nonce for two messages: XOR-ing the two ciphertexts yields the XOR of the plaintexts, and the authentication key can be recovered. Prevention: random 96-bit nonces from SecureRandom with a cap of ~2^32 encryptions per key, or a persistently stored counter nonce. At high volume, use per-record or per-batch DEKs (envelope encryption), or AES-GCM-SIV, which tolerates nonce reuse.
Useful phrases for interviews
- “We never need to read a password back, so we hash it with a slow, salted function rather than encrypting it.”
- “I’d pick Argon2id for a new system; bcrypt is still fine as long as we respect its 72-byte limit.”
- “The stored hash carries its algorithm prefix, so we can upgrade users transparently at their next login.”
- “Encrypting in the application layer means a leaked database or backup is just ciphertext.”
- “We use AES-GCM with a fresh random nonce per value and bind the row id as additional authenticated data.”
- “The master key never leaves the KMS; we only store wrapped data keys next to the data.”
- “A blind index gives us exact-match lookups at the cost of revealing which rows share a value.”
- “Deleting a customer’s data key is how we honour erasure requests even for data sitting in backups.”
Notes based on the Advanced Backend course (Ronin Engineer), rewritten in my own words.