Purpose: To learn to store passwords securely. In Project Part 6, you will store a salted password hash in your database.
Authentication: There are several options to authenticate users. Generally, a user is recognized because of one of three factors: (1) something the user knows, (2) something the user has, or (3) something the user is. Single-factor authentication means using one of those three categories to authenticate a user. Multi-factor authentication means using at least two of those categories. In this class, we will practice single-factor authentication using passwords. Passwords fall into the first category ("something the user knows"), although technically they could fall into the second category ("something the user has") if the password is stored on the user's computer and the user uses but does not remember the password.
One-Way Hash: The most common method for storing passwords securely is to use a one-way hash (also called an asymmetric hash). The hash is called "one-way" because it cannot be reversed, both because the inverse function is not computable in a reasonable amount of time (it would require searching through a number of possibilities on the order of 10^300 power or so) and also because many values hash to the same result. If you use a one-way hash, not even the system administrator can look up a user's password. The password can be changed or reset, but never looked up. People sometimes refer to this as a "no-knowledge system" for passwords.
Salt:Also, to enhance security, before a password is hashed, a string of random characters is added to it, to prevent hackers from using pre-computed tables to guess passwords (especially in the case where multiple users might choose the same password). This string of random characters is called a "salt." The salt is stored along with the hash so it can be applied during checking. The purpose of the salt is to make it so the final hashed value is different each time. Another common word used for "salt" is "initialization vector" or "IV" for short.
The Flask werkzeug.security library has convenient functions for a one-way hash using the popular SHA-256 algorithm, which is implemented for you by weerkzeug (werkzeug also has other algorithms you may choose from). In this exercise, you will use Python console mode to hash and unhash passwords.
Use the following code to practice password hashing and checking in Python console mode:
See what the final salted hash looks like:
Now, see how the check works:
Then, ensure that the check will catch a wrong password:
Finally, experience how the password hashes are different because they are salted. Look carefully to see the differences: