【问题标题】:'bytes' object has no attribute 'encode'“字节”对象没有属性“编码”
【发布时间】:2016-11-09 19:51:49
【问题描述】:

我试图在将每个文档插入集合之前存储盐和散列密码。但是在编码盐和密码时,它显示以下错误:

 line 26, in before_insert
 document['salt'] = bcrypt.gensalt().encode('utf-8')

AttributeError: 'bytes' object has no attribute 'encode'

这是我的代码:

def before_insert(documents):
    for document in documents:
        document['salt'] = bcrypt.gensalt().encode('utf-8')
        password = document['password'].encode('utf-8')
        document['password'] = bcrypt.hashpw(password, document['salt'])

我在 virtualenv 中使用 eve 框架和 python 3.4

【问题讨论】:

  • 你试过 encode-ing吗?
  • 是的,如果我只使用document['salt'] = bcrypt.gensalt(),它会显示“in hashpw raise TypeError("Unicode-objects must be encrypted before hashing") TypeError: Unicode-objects must be encrypted before hashing”@jonrsharpe
  • 看起来bcrypt 正在返回一个bytes 实例,无法对其进行编码。如果需要,它可以被解码。编码 = strbytes,解码 = bytesstr。 – 究竟在哪里抱怨TypeError
  • 它在bcrypt.hashpw 处显示TypeError 并显示Unicode-objects must be encoded before hashing
  • XYProblem? 您的问题不在于您无法对bcrypt.gensalt() 的结果进行编码。你绝对不能,它已经是一个bytes 对象。你的问题是bcrypt.hashpw中有一个unicode对象!

标签: python python-3.x bcrypt


【解决方案1】:

你正在使用:

bcrypt.gensalt()
此方法似乎生成了一个字节对象。这些对象没有任何编码方法,因为它们仅适用于 ASCII 兼容数据。所以你可以尝试不使用 .encode('utf-8')

Bytes description in python 3 documentation

【讨论】:

  • 这些对象没有encode 方法...因为编码 bytes 对象没有意义。原始bytes 可以根据特定字符集解码字符 (str),而不是相反。
【解决方案2】:

来自.getsalt() 方法的salt 是一个bytes 对象,bcrypt 模块方法中的所有“salt”参数都期望它采用这种特殊形式。无需将其转换为其他内容。

与之相反,bcrypt 模块的方法中的“密码”参数应该是 Unicode 字符串的形式——在 Python 3 中它只是一个 字符串.

所以 - 假设你原来的 document['password'] 是一个字符串,你的代码应该是

def before_insert(documents):
    for document in documents:
        document['salt'] = bcrypt.gensalt()
        password = document['password']
        document['password'] = bcrypt.hashpw(password, document['salt'])

【讨论】:

    猜你喜欢
    • 2019-02-02
    • 2020-09-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-10-10
    • 1970-01-01
    • 1970-01-01
    • 2016-01-27
    相关资源
    最近更新 更多