目前我正在做一个项目,我做了一个连接到MySQL数据库的注册表。这个项目是用Python和Flask写的。
我已经知道了如何将信息发送到数据库,以及如何对注册页面上选择的密码进行哈希处理。然而,我很难找到如何用哈希密码登录账户。
如果我尝试用一个带有哈希密码的账户登录,我首先需要用未哈希的密码登录,然后对密码进行哈希,并与数据库中的哈希密码进行比较。但这是行不通的。
根据我的理解,这是你找到用户名和密码的地方,而用户名和密码是在登录页面填写的。
username = request.form['username']
password = request.form['password']
所以,在这一步之后,你应该把它加密,以匹配数据库中的哈希密码。
password = b'password'
hashed_password = bcrypt.hashpw(password, bcrypt.gensalt())
然后,你应该比较它。
if bcrypt.checkpw(password, hashed_password):
print("It matches!")
return redirect(url_for('home'))
else:
print("Didn't match")
但这是行不通的 我无法用给定的密码登录,只能用哈希密码登录。加密时哪里出错了?完整的片段代码。
def login():
# Output message if something goes wrong...
msg = ''
# Check if "username" and "password" POST requests exist (user submitted form)
if request.method == 'POST' and 'username' in request.form and 'password' in request.form:
# Create variables for easy access
username = request.form['username']
password = request.form['password']
password = b'password'
hashed_password = bcrypt.hashpw(password, bcrypt.gensalt())
# Check if account exists using MySQL
cursor = mysql.connection.cursor(MySQLdb.cursors.DictCursor)
cursor.execute('SELECT * FROM accounts WHERE username = %s AND password = %s', (username, hashed_password))
# Fetch one record and return result
account = cursor.fetchone()
# If account exists in accounts table in our database
if account:
# Create session data, we can access this data in other routes
session['loggedin'] = True
session['id'] = account['id']
session['username'] = account['username']
# Redirect to home page
return redirect(url_for('home'))
else:
# Account doesnt exist or username/password incorrect
msg = 'Incorrect username/password!'
# Show the login form with message (if any)
return render_template('index.html', msg=msg)
由于你使用的是MySQL,我建议你宁可使用md5来验证数据库中表的用户。
cursor.execute('SELECT * FROM accounts WHERE username = %s AND password = md5(%s)', (username, hashed_password))
并转换所有未加密的纯文本密码 运行以下查询。
UPDATE accounts SET password = MD5(password);