使用Python和Flask,我创建了包含名称、电子邮件、密码和确认密码字段的注册页面。为了将密码以加密格式存储在数据库中,我选择了passlib。我已经到了这个代码不起作用的地步,这是根据文档所预期的:
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()
但这对有效
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()
尽管我不确定这样做是否正确。我很感激你的建议。
这个库生成一个带盐的密码哈希,这样每次相同输入的输出都会不同:
> pbkdf2_sha256.hash('password')
'$pbkdf2-sha256$29000$1pozZkyJUQrB.D.nNAYAwA$Vg8AJWGDIv2LxOUc7Xkx/rTfuaWnxqzlOC30p11KKxQ'
> pbkdf2_sha256.hash('password')
'$pbkdf2-sha256$29000$aa31XmttTek9p5Rybo3Rug$FCaAMh.T6g5FM76XD3omh3rcQgGpAiLzeqRl0wg4E.A'
所以,直接比较是行不通的。另一方面,因为salt存储在输出中,所以函数verify
可以重用它来生成相同的散列并比较结果。