[英]In Python/SQLite3, How does one define a variable to be used to query a database table?
我有一张三列的桌子
id username password
----------------------
1 Jdoe $2a$12$sv97wrhscHkKVMZ8P/2yw.O/cz8pWUE/1zlTyFNJ9.jCYhR8Nw9Iu
2 user $2a$12$dLeSlYFyPdP1WhA4Tw21ZuX5v5XH55.yK2XApMd4VglUDRJEd4Lmy
我的目的是根据登录时提供的密码对用户进行身份验证。 为此,我编写了如下的Python代码:
from bcrypt import hashpw, gensalt
if request.method == 'POST':
if form.validate() == False:
return render_template('login.html', form = form)
else:
#return render_template('index.html')
password = request.form['password']
password = hashpw(password, gensalt())
con = sql.connect("testDB.db")
cur = con.cursor()
cur.execute("SELECT * FROM mytable where password =?", (password,))
if cur.fetchall():
return "welcome guest"
else:
return "user not found"
但是,当我输入现有密码时,系统将返回消息“找不到用户”。 所需的输出用于消息“ Welcome guest” hashpw
和gensalt()
从bcrypt
导入。
我敢肯定,我错误地定义了变量“密码”。 如何正确定义这样的变量?
您正在生成一个新的hash ,其中的盐完全不同:
password = hashpw(password, gensalt())
您无法通过密码查找用户; 使用加盐散列的全部目的是使黑客无法使用彩虹表(散列普通密码,但不加盐)来匹配散列。 相同的保护措施使您无法预先知道给定用户使用了哪种盐,并且几乎可以保证您将与新盐生成不同的哈希值。
您需要使用用户名立即查找,检索已加盐的密码,然后要求bcrypt.checkpw()
函数针对存储的哈希值安全地测试密码。 哈希值包括盐, bcrypt
将提取盐并使用它来验证是否生成了相同的哈希。 比较需要防止定时攻击,请不要自己重新实现此检查。
您的表单需要发送用户名,而不仅仅是密码:
from bcrypt import checkpw
username = request.form['username']
password = request.form['password']
con = sql.connect("testDB.db")
cur = con.cursor()
cur.execute("SELECT password FROM mytable where username = ?", (username,))
hashed = cur.fetchone()
if hashed is None or not checkpw(password, hashed[0]):
# no such user, *or* the password did not match
return "user not found"
# password matched the hashed value from the database
return "welcome guest"
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.