excessive
excessive

Reputation: 3

Proper way of using passlib with Flask

Using Python and Flask I've created register page with name, email, password and confirm password fields. In order to store passwords in the DB in encrypted format I went for passlib. I've reached a point where this code doesn't work which is to be expected according to the documentation:

        name = request.form['name']
        email = request.form['email']
        password = pbkdf2_sha256.hash(str(request.form['pass']))
        confirm = pbkdf2_sha256.hash(str(request.form['confirm']))
        if password == confirm:
            cur = mysql.connection.cursor()
            cur.execute("INSERT INTO users(name, email, password) VALUES(%s, %s, %s)", (name, email, password))
            mysql.connection.commit()

but this works

        name = request.form['name']
        email = request.form['email']
        password = pbkdf2_sha256.hash(str(request.form['pass']))
        confirm = request.form['confirm']
        if pbkdf2_sha256.verify(confirm, password):
            cur = mysql.connection.cursor()
            cur.execute("INSERT INTO users(name, email, password) VALUES(%s, %s, %s)", (name, email, password))
            mysql.connection.commit()

Although I'm not sure if this is the right way to do it. I'd appreciate some advices.

Upvotes: 0

Views: 820

Answers (1)

bereal
bereal

Reputation: 34252

This library produces a salted hash of the password, so that it the output will be different every time for the same input:

> pbkdf2_sha256.hash('password')
'$pbkdf2-sha256$29000$1pozZkyJUQrB.D.nNAYAwA$Vg8AJWGDIv2LxOUc7Xkx/rTfuaWnxqzlOC30p11KKxQ'

> pbkdf2_sha256.hash('password')
'$pbkdf2-sha256$29000$aa31XmttTek9p5Rybo3Rug$FCaAMh.T6g5FM76XD3omh3rcQgGpAiLzeqRl0wg4E.A'

So, direct comparison won't work. On the other hand, because the salt is stored in the output, the function verify can re-use it to generate the same hash and compare the result.

Upvotes: 0

Related Questions