Secure Passwords in Python
Why wouldn't you! Your top priority when making anything with login capabilities should be to keep the users data safe. No matter how small the project or how popular it may be, you should always make sure you do this right.
You may be tempted to use Pythons
hashlib module for this. While this does hash the password, it doesn't use modern techniques. We want a strong, salted hash that we can store. A hash that can't be broken at the click of a finger.
This is one of those times where we can't just make the program, well, unless you know all there is to know about encryption. Let's leave this one to the professionals, and have our passwords as secure as possible.
Passlib is what we need to help in our fight for security. It's simple to use and uses high end algorithms with salt! Wait a second, what are we using and what does it do? Glad you asked.
To import Passlib, all we have to do is choose our algoritm on import:
from passlib.hash import argon2
We will be using argon2 which has been around since 2013, which is pretty new for a hashing algorithm. We will then be adding salting into the mixture.
When you hash a password, it will always look the same, this makes it easy to get all the same passwords from a list. That's why we salt them. Salting changes that hash, so even if we hash the same password, the result is different. Pretty cool if I say so myself.
argon2-cffi which can be installed using pip or Repl's Package Manager. If you choose a different hashing algorithm which needs an external package, an error will be risen to notify you.
As I said before, Passlib makes this process easy for us to do. So let's look at some code!
# Generate new salt and hash a password hash1 = argon2.hash("password") hash2 = argon2.hash("password") # These two will show different hashes even though they are the same password print(hash1) print(hash2)
argon2.hash(password) takes in the string we want to hash, in this case the users password.
# Verifying the password test1 = argon2.verify("password", hash1) test2 = argon2.verify("notpassword", hash1) # hash1 will return True, has2 will return False as only password 1 is equal to the hash. print(test1) print(test2)
We can then compare the hash to the password entered by the user using
You can see this code on the docs here.
It's so easy that there is no point not doing it. Not only that, but it's good practice to keep any sensitive data secure, and gives the user peace of mind. Hope you fond this tutorial useful!
Have a great day!
If you have any suggestions for tutorials, leave them in the comments and I'll be sure to have a look. If you like one in the comments, then give it an up vote to show that you want to see it. It makes my life so much more easier. Thanks in advance!