# Hashing Passwords – Python Cryptography Examples

Lane Wagner
·Dec 9, 2021·

By Lane Wagner – @wagslane on Twitter

Building a from-scratch server or using a lightweight framework is empowering. With that power comes responsibility, specifically the responsibility to securely store user’s passwords.

Not understanding the security implications of password storage can lead to devastating breaches and leaks. If you are building an application and need to store user credentials, learn about hash functions.
Click To Tweet

## Can I Store Passwords In Plain Text?

– somePa\$\$wordHere

– otherPlainTextPass

Now the attacker can go to other websites, and because a majority of people reuse passwords on different websites, they can hack other systems.

## Solution – Hashing

A hash function (or more specifically in our case, a key derivation function) deterministically creates a strong key from a password. Because hashes are one-way, the attacker can’t re-create the plaintext password from the hash. Now the attacker would find something like this in the database:

– cab864878af008fbc550087940ffacdb79a7f82201725e3350e25d6cfbdd4255

– 42a7fd2b639d18b3aba5db8504d4530f1f1ab58ab9615414b7629d6ec5c157b8

In Python, Bcrypt is a strong key derivation function that can be used in production systems:

``````import bcrypt
``````

## Rainbow Tables and Salts

You may have wondered in the above code snippet what the gensalt() function does. If we were to hash passwords without salts, an attacker could do a rainbow table attack in order to find the original plain text.

A salt is a random string of data hashed alongside a password to keep the hash result unique. Salts should be recreated each time a new password is saved, and the salt is stored alongside the hashed result so that it can be used again for comparison. Libraries like bcrypt are smart enough to store the salt IN the resulting string so that developers don’t need to do the extra work.

For example, let’s say that LoveMatchingToday wisened up and started hashing passwords, but didn’t include unique salts. An attacker could have a precomputed table of hashes:

They could then check each hash they find and see if a hash matches an entry in their table. If so, they can effectively “reverse” the hash and learn the original plaintext.

For this reason, we need to salt passwords. Luckily Bcrypt handles salting automagically. For the sake of learning, however, let’s assume they didn’t. If they didn’t, our pseudocode would look something like this:

``````# Save new password
salt = creatRandomSalt()

else:
failure()
``````

However, since Bcrypt stores the salt automatically with the hashed result in the “{salt}{hashed}” format, we can just use the following code:

``````import bcrypt

# save "hashAndSalt" in data base

# To check:
``````