bcrypt
A famous super strong library that does Cryptographic Hashing using the Blowfish Cypher which is a salt (i.e. random data) to prevent rainbow attacks and resisting to brute-force attacks
To do all of this we’ll have to install this package.
pip install flask-bcrypt
generate_password_hash( password_string, rounds=None )
A function that generates a hash from the password string and can hash it a number of rounds. The default number of rounds is 12, and the more the rounds increases the more time the process consumes.
[testing pw generation]:
>>> from flask.ext.bcrypt import generate_password_hash >>> generate_password_hash('secret') ' $2a$12$kjas89134huglkjaadsiuop130e8ohad.ojas891 ' >>> generate_password_hash('secret', 15) ' $2a$12$nlvnoiadfioj120ujasldnAOPInfq09q120_8u!EnaLka '
$2a$ the prefix of every password generated by bcrypt
$12 denotes the number of rounds
[testing pw comparison]:
>>> hashed_pw = generate_password_hash('secret') False >>> from flask.ext.bcrypt import check_password_hash >>> check_password_hash( hashed_pw, 'secret' )
It came False the first comparison because the salt add extra data that we don’t know about. To compare passwords with hashed passwords we use the check_password_hash( ) function.
Class Method
[models.py]
import datetime
from flask.ext.bcrypt import generate_password_hash
from flask.ext.login import UserMixin
from peewee import *
DATABASE = SqliteDatabase('social.db')
class User(UserMixin, Model):
username = CharField(unique=True)
email = CharField(unique=True)
password = CharField(max_length=100)
joined_at = DateTimeField(default=datetime.datetime.now)
is_admin = BooleanField(default=False)
class Meta:
database = DATABASE
order_by = ('-joined_at',)
@classmethod
def create_user(cls, username, email, password, admin=False):
try:
cls.create(
username=username,
email=email,
password=generate_password_hash( password ),
is_admin=admin
)
except IntegrityError:
raise ValueError("User already exists")
def create_user( cls, username, email, password, admin=False )
A function that creates users from the User model.
cls
An argument in which the class has been passed into (i.e. similar to self). It creates the user model instance when it runs this method.
cls.create( username=username, ….. )
Creates an instance from cls with the passed attribute values.
raise ValueError( “User already exists” )
@classmethod
A decorator that marks a method responsible for creating the class it belongs to.