Explain Codes LogoExplain Codes Logo

Cleansing User Passwords

sql
password-security
hashing-algorithms
sql-injections
Alex KataevbyAlex Kataev·Oct 7, 2024
TLDR

Here's your super quick fix: use a secure hash function for user password updates. Bcrypt is your friend for this:

-- Back up first, friends don't let friends code without a safety net! UPDATE users SET password = crypt('new_password', gen_salt('bf'));

Let's dive deep into securing user passwords for good!

Optimum data type for hashed passwords

When working with hashed passwords, opt for VARCHAR(255) or TEXT. It provides sufficient space and future-proofs against ever-evolving hash formats.

Future-proof hashing algorithms

Toss MD5 to the history books. Instead, go for bcrypt or Argon2. They’re designed to be slow to guarantee resistance against brute force attacks.

Same same but different with password normalization

Before hashing, always apply password normalization according to RFC 7613. This ensures the same password consistently outputs the same hash, regardless of input method or Unicode quirks.

Remember to normalize characters to the NFC form and switching non-standard spaces to regular ones for smashing consistency.

Passwords and SQL injections

When handling passwords, escape_string(), htmlspecialchars(), and addslashes() are archaic relics. With password_hash(), SQL injections become as scary as last year's Halloween pumpkin.

Verifying passwords like a pro

Don’t just compare a user's password like you're checking identical twins. Use password_verify() to safely compare a submitted password against the hashed storehouse.

Backward compatibility and handling passwords

Compatibility pack for PHP < 5.5

It's common to own a vintage PHP version < 5.5. Fret not, remember to implement a compatibility pack for password_hash(). Always stay updated, even if you’re little old-fashioned.

Secure handling of passwords

Individuals love choices

Encourage complex passwords. Show your users you care by not unnecessarily limiting the password length or character options.

Proper storage and comparison

Be generous with storing hashed passwords. They might wish for extra space on special occasions.

When comparing hashed passwords, use timing-safe comparisons. Better safe than hacked.

Passwords are global citizens

Consider all the fancy keyboards and gadgets your users have. Accommodate all input methods for love and world peace.

Embrace security principles

Abracadabra! Implement security best practices for your users' passwords. You're the digital magician they can trust.