Skip to Content
Learn
Introduction to Accounts
Introduction to Hashing

An important rule of application development is to never store sensitive user data as plain text. Plain text data is a security risk, as a data breach or hack would allow sensitive data to fall into the wrong hands.

How can we store sensitive user data, such as passwords, in a more secure format? Step in hashing! Hashing is the process of taking text input and creating a new sequence of characters out of it that cannot be easily reverse-engineered.

When we hash user passwords, we can store the hashed format rather than the original plain text passwords. If a hack were to occur, the hackers would not be able to exploit the stolen information without knowing the hashing function that was used to encrypt the data.

We can add hashing functionality to a Flask application using the security module of the Werkzeug package.

To hash a password:

hashed_password = generate_password_hash("noONEwillEVERguessTHIS")
  • generate_password_hash() takes a string as an argument and returns a hash of the string

We can also check a user-entered password against our hashed password to check for a match:

hash_match = check_password_hash(hashed_password, "IloveTHEcolorPURPLE123") print(hash_match) # will print False hash_match = check_password_hash(hashed_password, "noONEwillEVERguessTHIS") print(hash_match) # will print True
  • check_password_hash() takes two arguments: the hashed string and a new string which we are checking the hash against. It returns a boolean indicating if the string was a match to the hash.

While we are hardcoding our passwords here, in later exercises we will see how to collect this information using a Form.

Instructions

1.

Import generate_password_hash and check_password_hash from werkzeug.security.

2.

A (not so great) password hardcoded_password_string, representing a user-entered password upon signing up for your application, is provided in app.py.

Hash hardcoded_password_string with the generate_password_hash() function, and save the result to a variable hashed_password. Print hashed_password to the terminal.

3.

The same user returns to your application and enters a password password_attempt_one, provided in app.py. Check the hash hashed_password against password_attempt_one with the check_password_hash() function.

Save the result to a variable hash_match_one, and print it to the terminal.

4.

Looks like the user entered their password for a different site accidentally. They took a second attempt with a different password password_attempt_two, also provided in app.py.

Check the hash hashed_password against password_attempt_two with the check_password_hash() function.

Save the result to a variable hash_match_two, and print it to the terminal. Did the user get the password right this time?

Folder Icon

Sign up to start coding

Already have an account?