bcrypt 哈希返回 typeError( "Unicode-objects must be encoded before hashing" ) 和无效的盐



我已经查看了与此相关的所有StackOverflow问题,但我似乎无法弄清楚这一点。当我对密码进行哈希处理并对其进行检查时,它会使用当前代码返回 TypeError "Unicode 对象必须在哈希之前进行编码":

from scripts import tabledef
from flask import session
from sqlalchemy.orm import sessionmaker
from contextlib import contextmanager
import bcrypt
(Unrelated Python code...)
def hash_password(password):
return bcrypt.hashpw(password.encode('utf8'), bcrypt.gensalt())

def credentials_valid(username, password):
with session_scope() as s:
user = s.query(tabledef.User).filter(
tabledef.User.username.in_([username])).first()
if user:
return bcrypt.checkpw(password.encode('utf8'), user.password)
else:
return False

当我尝试通过设置user.password= user.password.encode('utf8')来修复此错误时,我得到"无效的盐"。

这段代码有什么问题?

更新: 我通过用户的 Flask 输入存储密码:

import json
import sys
import os
import plotly
import pandas as pd
import numpy as np
import plotly.graph_objs as go

from scripts import tabledef
from scripts import forms
from scripts import helpers
from flask import Flask, redirect, url_for, render_template, request, session, flash, Markup
from flask_socketio import SocketIO, emit
@app.route('/', methods=['GET', 'POST'])
def login():
if not session.get('logged_in'):
form = forms.LoginForm(request.form)
if request.method == 'POST':
username = request.form['username'].lower()
password = request.form['password']
if form.validate():
if helpers.credentials_valid(username, password):
session['logged_in'] = True
session['username'] = username
session['email'] = request.form['email']
session['password'] = request.form['password']
return json.dumps({'status': 'Login successful'})
return json.dumps({'status': 'Invalid user/pass'})
return json.dumps({'status': 'Both fields required'})
return render_template('login.html', form=form)
user = helpers.get_user()
return render_template('home.html', user=user)
@app.route('/signup', methods=['GET', 'POST'])
def signup():
if not session.get('logged_in'):
form = forms.LoginForm(request.form)
if request.method == 'POST':
username = request.form['username'].lower()
password = helpers.hash_password(request.form['password'])
email = request.form['email']
if form.validate():
if not helpers.username_taken(username):
helpers.add_user(username, password, email)
session['logged_in'] = True
session['username'] = username
session['email'] = request.form['email']
session['password'] = request.form['password']
return json.dumps({'status': 'Signup successful'})
return json.dumps({'status': 'Username taken'})
return json.dumps({'status': 'User/Pass required'})
return render_template('login.html', form=form)
return redirect(url_for('login'))

这是我得到的错误:

/lib/python3.5/site-packages/flask/app.py", line 1718, in handle_user_exception
reraise(exc_type, exc_value, tb)
File "/home/suraj/Documents/Programming/current-projects/GW_Dining_Tracker/env/lib/python3.5/site-packages/flask/_compat.py", line 35, in reraise
raise value
File "/home/suraj/Documents/Programming/current-projects/GW_Dining_Tracker/env/lib/python3.5/site-packages/flask/app.py", line 1813, in full_dispatch_request
rv = self.dispatch_request()
File "/home/suraj/Documents/Programming/current-projects/GW_Dining_Tracker/env/lib/python3.5/site-packages/flask/app.py", line 1799, in dispatch_request
return self.view_functions[rule.endpoint](**req.view_args)
File "/home/suraj/Documents/Programming/current-projects/GW_Dining_Tracker/Flaskex-master/app.py", line 34, in login
if helpers.credentials_valid(username, password):
File "/home/suraj/Documents/Programming/current-projects/GW_Dining_Tracker/Flaskex-master/scripts/helpers.py", line 64, in credentials_valid
return bcrypt.checkpw(password.encode('utf8'), user.password)
File "/home/suraj/Documents/Programming/current-projects/GW_Dining_Tracker/env/lib/python3.5/site-packages/bcrypt/__init__.py", line 101, in checkpw
raise TypeError("Unicode-objects must be encoded before checking")
TypeError: Unicode-objects must be encoded before checking

问题是您正在从 SQLAlchemyString列中获取值并将其传递给bcrypt.checkpwString用于 Unicode 字符串,它提供的值为str。但是bcrypt仅适用于字节字符串,因此它期望bytes。这就是"Unicode对象必须在散列之前进行编码"的TypeError告诉你的。

根据您使用的数据库后端和 DB-API 库(以及某些后端,数据库的配置方式(,当您将bytess保存到String列时,它可能会保存s.decode(),在这种情况下,您可以使用user.password.encode()来获取相同的字节,但可能不会。例如,它也可以只是保存,比如说,str(s).在这种情况下,如果哈希是b'abcd'bytes值,则列值将是字符串"b'abcd'",因此调用encode会让您b"b'abcd'",而不是b'abcd'

处理此问题的最干净方法是使用Binary1(或者更好的是Binary(60)2(来存储哈希,而不是String列。任何支持Binary的 DB-API 都将按原样存储bytes,并将其作为bytes返回,这正是您想要的。


1.Binary是可选类型。如果您的 DB-ABI 不存在它,则相同的类型可能与BINARY相同。如果没有,请查看类型列表并尝试从_Binary继承的其他类型。名称或首字母缩略词中没有"大"的那些可能会更有效率,但除此之外,它们中的任何一个都应该有效。

2.使用默认设置,bcrypt可打印摘要将始终正好为60字节。数据库通常可以更紧凑地存储固定宽度字段(如BINARY(60)(,并且搜索它们的速度比可变宽度字段(如VARBINARY(更快。仅使用普通BINARY可能没问题,但它也可能像VARBINARY一样工作,或者可能会浪费空间并像BINARY(255)一样工作,等等。

最新更新