4.3. Passwords#
In a web application, storing passwords in plain text is a serious security risk. If a database is compromised, attackers can immediately see all user passwords. This would allow attackers to login to the site acting as other users.
It also may compromise passwords for other applications and websites since users commonly re-use passwords.
Note
Password reuse is a serious issue. If you reuse passwords across websites you might be at risk. You can find out if your password for websites has been leaked on https://haveibeenpwned.com.
4.3.1. Hashing Passwords#
To protect passwords in the database, we can store their hashes instead of the plain text. In particular, if we use a cryptographic hash function it becomes very difficult to determine the original plain text.
When registering a user we:
ask for or assign a password
hash the password
store the hash value as the password
To authenticate a user we:
ask for their password
hash the entered password
check that the hash value matches for the user
We can see how this change is reflected in a User table:
Before
User ID |
Username |
Password |
|---|---|---|
1 |
alice123 |
mypassword123 |
2 |
bob_smith |
securepass456 |
3 |
admin |
superadmin789 |
After
User ID |
Username |
Password |
|---|---|---|
1 |
alice123 |
342sckjn812123 |
2 |
bob_smith |
s0d9sucsxicbn9 |
3 |
admin |
cgasd8g123e9hs |