0

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.

bereal
  • 32,519
  • 6
  • 58
  • 104
excessive
  • 3
  • 2

1 Answers1

0

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.

bereal
  • 32,519
  • 6
  • 58
  • 104
  • My mistake. It's passlib, indeed. My question is am I doing the verifying right by comparing the already saved hash and the plain text comming from the second form by using `pbkdf2_sha256.verify` ? – excessive Nov 18 '19 at 07:15
  • @excessive In your posted code you compare the password and its confirmation, you already have both in plain text, so just plaintext comparison without any hashing is good enough. But later for authentication you'll need to use `verify`. – bereal Nov 18 '19 at 07:28
  • Thanks, that's what I was wondering. Just wanted to make sure that I'm doing the things right way. – excessive Nov 18 '19 at 07:39