Welcome to the python mini-series. In the mini-series, I will cover some small pieces of python which I found useful in the past. Maybe this is also useful for you.
A common use case for applications (e.g. Web Apps) is to store and validate user credentials. This includes the password. User passwords should NEVER be stored in plain text. This means you usually need to hash or encrypt a password.
A simple hashing of a password is usually not recommended as this can be easily reverse-engineered.
Therefore, you should make sure that your password is salted. In python, you have many possibilities to do so. You could use the standard werkzeug library. I, however, found that the library Bcrypt is more comfortable and easier to use, it is, in fact, leveraging the werkzeug library. It takes care of everything and you do not need to worry about how to properly hash and salt the passwords. This package is usually used in combination with Flask as it supports the framework. However, it can very comfortably be used without it. If you are lazy as me you will appreciate it.
To use Bcrypt you need to install the package. The most simple way is to run:
pip install Bcrypt
With only 4 lines of code you can cover encryption and validation of the stored value against an entered password.
from flask_bcrypt import Bcrypt inst = Bcrypt() password_encrypted = inst.generate_password_hash(“test password”) inst.check_password_hash(password_encrypted, “test password”)
Here the explanation of the code:
from flask_bcrypt import Bcrypt
inst = Bcrypt()
password_encrypted = inst.generate_password_hash(“test password”)
inst.check_password_hash(password_encrypted, “test password”)
And that’s it! If you want an example script you can download a basic script from my bitbucket repo here.
I hope this small article was useful. If you know a better or simpler way how to do this let me know 🙂 I am always happy to learn new things!
Jan 2nd 22
No one left a comment yet. Be the first!