The reason you use hash passwords is to provide a layer of data protection.
You should not save any data you don’t want to be responsible for. Passwords are a valuable piece of data, and in the past, many developers saved passwords as plain text in their databases. If those databases got hacked or bad actors got legitimate access to that database, they could easily grab user ids and passwords and impersonate that user on that website and possibly others.
Since most websites use user ids and passwords to allow users to log in, you need to save something that ensures someone logging in has the proper credentials.
So, instead of saving passwords, you can save hashes of passwords.
Hashes are this fantastic product of computer science. Given an input, a hashing function will return a unique value with a predetermined length. Changing the input, even slightly, should return a very different hash.
So any time someone tries to log in, you should hash the password they provide and compare it with the hash stored for that user in the database.
- When a user creates an account or changes their password, you take that password and create a hash of the password.
- Don’t save the password; save the hash with the user’s id and any other information you want.
- When a user attempts to log in, hash the For with the same algorithm and compare it to the hash you saved with the user information. If they match, the user passed in the correct password.
For example, in one of Michael Kennedy’s courses, he uses the third-party package
passlib to hash the passwords like this: