Bcrypt 哈希返回类型错误(“在哈希之前必须对 Unicode 对象进行编码”)和无效的盐

2023-11-25

我已经查看了与此相关的所有 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

问题是您正在从 SQLAlchemy 获取值String列并将其传递给bcrypt.checkpw. String适用于 Unicode 字符串,它提供的值如下str. But bcrypt仅适用于字节字符串,因此它需要一个bytes。这就是TypeError“Unicode 对象必须在散列之前进行编码”就是在告诉您。

根据您使用的数据库后端和 DB-API 库(对于某些后端,还取决于数据库的配置方式),当您保存bytes value s to a String列,它可能会节省s.decode(),在这种情况下你可以使用user.password.encode()取回相同的字节,但可能不会。例如,它也可以只保存,比如说,str(s)。在这种情况下,如果哈希值是bytes value b'abcd',列值将是字符串"b'abcd'",所以并调用encode这让你b"b'abcd'", not b'abcd'.

The cleanest way to handle this is to use a Binary column1—or, maybe better, Binary(60)2—to store your hashes, instead of a String column. Any DB-API that supports Binary will just store a bytes as-is, and return it as a bytes, which is exactly what you want.


1. Binary is an optional type. If it isn't present for your DB-ABI, the same type may be available as BINARY. If not, look through the list of types and try other types that inherit from _Binary. The ones without "large" in their name or acronym will probably be more efficient, but otherwise any of them should work.

2. With the default settings, bcrypt printable digests will always be exactly 60 bytes. Databases can generally store fixed-width fields like BINARY(60) more compactly, and search them more quickly than variable-width fields like VARBINARY. Just using plain BINARY may be fine, but it may also work like VARBINARY, or it may waste space and work like BINARY(255), etc.

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

Bcrypt 哈希返回类型错误(“在哈希之前必须对 Unicode 对象进行编码”)和无效的盐 的相关文章

  • Gunicorn 工作人员无论如何都会超时

    我正在尝试通过gunicorn运行一个简单的烧瓶应用程序 但是无论我做什么 我的工作人员都会超时 无论是否有针对应用程序的活动 工作人员在我设置任何内容后总是会超时timeout值到 是什么导致它们超时 当我发出请求时 请求成功通过 但工作
  • 在 Celery 任务中调用 Google Cloud API 永远不会返回

    我正在尝试拨打外部电话Google Cloud Natural Language API从一个内Celery任务 使用google cloud python包裹 问题是对 API 的调用永远不会返回 挂起 celery task def g
  • pandas DataFrame.join 的运行时间是多少(大“O”顺序)?

    这个问题更具概念性 理论性 与非常大的数据集的运行时间有关 所以我很抱歉没有一个最小的例子来展示 我有一堆来自两个不同传感器的数据帧 我需要最终将它们连接成两个very来自两个不同传感器的大数据帧 df snsr1 and df snsr2
  • PyQt 使用 ctrl+Enter 触发按钮

    我正在尝试在我的应用程序中触发 确定 按钮 我当前尝试的代码是这样的 self okPushButton setShortcut ctrl Enter 然而 它不起作用 这是有道理的 我尝试查找一些按键序列here http ftp ics
  • Tensorboard SyntaxError:语法无效

    当我尝试制作张量板时 出现语法错误 尽管开源代码我还是无法理解 我尝试搜索张量板的代码 但不清楚 即使我不擅长Python 我这样写路径C Users jh902 Documents logs因为我正在使用 Windows 10 但我不确定
  • GUI(输入和输出矩阵)?

    我需要创建一个 GUI 将数据输入到矩阵或表格中并读取此表单数据 完美的解决方案是限制输入表单仅允许float 例如 A 1 02 0 25 0 30 0 515 0 41 1 13 0 15 1 555 0 25 0 14 1 21 2
  • 打印包含字符串和其他 2 个变量的变量

    var a 8 var b 3 var c hello my name is var a and var b bye print var c 当我运行程序时 var c 会像这样打印出来 hello my name is 8 and 3 b
  • Python 内置的 super() 是否违反了 DRY?

    显然这是有原因的 但我没有足够的经验来认识到这一点 这是Python中给出的例子docs http docs python org 2 library functions html super class C B def method se
  • 无法导入 langchain.agents.load_tools

    我正在尝试使用 LangChain Agents 但无法导入 load tools 版本 langchain 0 0 27 我尝试过这些 from langchain agents import initialize agent from
  • 未知错误:Chrome 无法启动:异常退出

    当我使用 chromedriver 对 Selenium 运行测试时 出现此错误 selenium common exceptions WebDriverException Message unknown error Chrome fail
  • 尽管我已在 python ctypes 中设置了信号处理程序,但并未调用它

    我尝试过使用 sigaction 和 ctypes 设置信号处理程序 我知道它可以与python中的信号模块一起使用 但我想尝试学习 当我向该进程发送 SIGTERM 时 但它没有调用我设置的处理程序 只打印 终止 为什么它不调用处理程序
  • Pandas 组合不同索引的数据帧

    我有两个数据框df 1 and df 2具有不同的索引和列 但是 有一些索引和列重叠 我创建了一个数据框df索引和列的并集 因此不存在重复的索引或列 我想填写数据框df通过以下方式 for x in df index for y in df
  • Python - 如何确定解析的 XML 元素的层次结构级别?

    我正在尝试使用 Python 解析 XML 文件中具有特定标记的元素并生成输出 excel 文档 该文档将包含元素并保留其层次结构 我的问题是我无法弄清楚每个元素 解析器在其上迭代 的嵌套深度 XML 示例摘录 3 个元素 它们可以任意嵌套
  • Protobuf 如何编码 oneof 消息结构

    对于这个 python 程序 在编码时运行 protobuf 编码会给出以下输出 0a 10 08 7f8a 0104 08 02 10 0392 0104 08 02 10 03 18 01 我不明白的是为什么8a后面有一个01 为什么9
  • 如何以正确的方式为独立的Python应用程序制作setup.py?

    我读过几个类似的主题 但还没有成功 我觉得我错过或误解了一些基本的事情 这就是我失败的原因 我有一个用 python 编写的 应用程序 我想在标准 setup py 的帮助下进行部署 由于功能复杂 它由不同的 python 模块组成 但单独
  • 重新分配唯一值 - pandas DataFrame

    我在尝试着assign unique值在pandas df给特定的个人 For the df below Area and Place 会一起弥补unique不同的价值观jobs 这些值将分配给个人 总体目标是使用尽可能少的个人 诀窍在于这
  • Firebase Firestore:获取文档的生成 ID (Python)

    我可以创建一个新文档 带有自动生成的 ID 并存储对其的引用 如下所示 my data key value doc ref db collection u campaigns add my data 我可以像这样访问数据本身 print d
  • 等待子进程使用 os.system

    我用了很多os system在 for 循环内调用创建后台进程 如何等待所有后台进程结束 os wait告诉我没有子进程 ps 我使用的是Solaris 这是我的代码 usr bin python import subprocess imp
  • 根据 Pandas 中的列表选择数据框行的子集

    我有一个数据框df1并列出x In 22 import pandas as pd In 23 df1 pd DataFrame C range 5 B range 10 20 2 A list abcde In 24 df1 Out 24
  • JSON:TypeError:Decimal('34.3')不是JSON可序列化的[重复]

    这个问题在这里已经有答案了 我正在运行一个 SQL 查询 它返回一个小数列表 当我尝试将其转换为 JSON 时 出现类型错误 查询 res db execute SELECT CAST SUM r SalesVolume 1000 0 AS

随机推荐

  • 如果“if”条件为 false,则语句不会在 chrome 中执行,但会在 Firefox 中执行

    这是我的场景的 plnkr 当我在 Chrome 中调试此代码时 第二个 if 中的语句未执行 但是当我在 Firefox 中调试它时 第二个 if 中的语句被执行 angular module optionsExample control
  • 允许重复的属性名称的目的是什么?

    我正在读MDN JavaScript 参考 因此下面的代码不再返回false function haveES6DuplicatePropertySemantics use strict try prop 1 prop 2 No error
  • Android Instant App:找不到默认活动

    这似乎是明显的合并错误 我正在尝试将现有代码移植到即时应用程序模块 我尝试过的是 将主应用程序模块更改为 baseFeatureModule 创建了一个新模块completeApp 清空completeAppModule的Manifest
  • pandas 将数据框中的多列字符串转换为浮点数

    我是 pandas 的新手 并试图弄清楚如何将格式化为字符串的多个列转换为 float64 目前我正在执行以下操作 但似乎 apply 或 applymap 应该能够更有效地完成此任务 不幸的是 我有点菜鸟无法弄清楚如何 目前 这些值是百分
  • 无需 webRTC 即可访问相机或网络摄像头

    在我的网站中 它需要访问相机或网络摄像头 但基于ios的webview尚不支持webRTChttps forums developer apple com thread 88052 请cmiiw 所以 我正在尝试找到一种无需 webRTC
  • R 中的条件和

    我有一个 200 行 x 6 列的数据框 我感兴趣的是计算 A 列中的值小于特定数字的总次数 该数字可以被硬编码 我不知道从哪里开始 对于稍微复杂一点的问题 使用 which 来告诉 sum 在哪里求和 如果 DF 是数据框 Ozone S
  • 什么是 UICalloutBarButton,为什么它会使我的应用程序崩溃?

    我正在查看我的 iPhone 应用程序的一些崩溃报告 但我对以下内容感到困惑 它很可能在我的代码中的某个地方崩溃 它可能是一个事件处理程序在某个地方调用了错误的选择器 问题是我不知道这段代码在哪里 我不知道 UICalloutBarButt
  • 如何修复预期启动联盟。在命令行上将 JSON 转换为 Avro 时得到 VALUE_NUMBER_INT?

    我正在尝试使用 Avro 架构验证 JSON 文件并写入相应的 Avro 文件 首先 我定义了以下 Avro 架构 名为user avsc namespace example avro type record name user field
  • 在 CodeIgniter 中使用多个数据库

    场景 我正在构建一个 Web 应用程序 它使用 ion auth 来管理所有用户 管理员信息 使用 MySQL 数据库 并且每个用户都有自己的数据库 也有 MySQL 用于核心应用程序目的 我已在 CodeIgniter 内的 applic
  • 用 CGPathRef 屏蔽 CGContext?

    我正在使用 CGContext 进行一些绘图 我目前正在使用这样的 png 文件来屏蔽绘图 UIImage myImage UIImage imageNamed frame png CGContextRef context UIGraphi
  • 如何仅在悬停时显示 CSS 过渡?

    我在 div 上添加了一个过渡 这样当它悬停在上面时 颜色就会改变 有点像这里的例子 http jsfiddle net 78LWT HTML 代码如下 div div 这是 CSS 代码 transition background col
  • JENKINS 中是否有从节点 home 的环境变量?

    我们知道有一个名为 JENKINS HOME 的环境变量 因此我们可以在任何地方使用它作为 JENKINS HOME 但是现在当我在从节点上运行项目时 我需要使用从节点上的jenkins主目录 在定义从节点时名为 remote FS roo
  • Android Studio 3.1.4 Gradle 同步失败

    每当我在 Android Studio 中创建一个新项目时 它都会在 Gradle Sync 中失败 并且总是出现相同的错误 Connection timed out connect org gradle internal resource
  • java.lang.NumberFormatException:对于输入字符串:“20,475.00”

    我正在努力使我的系统保持运行平衡 为此 我从 AMOUNT 列中获取 jtable 中所有数字的总和 并将总和减去 txtLoanAmount 内的值 这是我的代码片段 String LoanAmount txtLoanAmount get
  • Oracle 选择今天之间的日期

    我有一个像这样的 Oracle SELECT 查询 Select From Customer Rooms CuRo Where CuRo Date Enter Between TODAY 12 00 00 PM And TODAY 11 5
  • 在子图网格中重新定位子图

    I am trying to make a plot with 7 subplots At the moment I am plotting two columns one with four plots and the other wit
  • AlarmManager 无法正常工作

    我正在尝试创建一个基于警报的应用程序 我在用着AlarmManager 问题是它根本不可靠 在某些设备中它可以工作 在其他设备中它有时可以工作 而在其他设备中它根本不起作用 当我说它不起作用时 很简单 警报不会响起 例如 在我的小米4中 如
  • 无法向我的应用添加广告。

    所以我按照 admob 和 Google Play 服务的指南进行操作 https developers google com mobile ads sdk docs admob fundamentals play我遇到了一个问题 他们在网
  • 单击 Jquery 打开和关闭子菜单

    我有一个主菜单 它将在 jquery 中显示带有单击事件的子菜单 客户端希望单击而不是悬停 所以我让它工作 但是我仍然不明白一件事 我的菜单和子菜单工作正常 所以当我单击 新闻 时 子菜单会很好地向下滑动 当我重新单击 新闻 时 它会关闭
  • Bcrypt 哈希返回类型错误(“在哈希之前必须对 Unicode 对象进行编码”)和无效的盐

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