0

我将 passlib==1.7.1 与以下导入一起使用:

from passlib.apps import custom_app_context as pwd_context

然后使用以下内容对密码进行哈希处理:

pwd_context.encrypt(password)

然后我验证:

pwd_context.verify(password, self.password_hash)

这很好,但是某些字符的验证失败。例如“£”或“$”。

请问有谁知道为什么会这样?

谢谢!


更新:

非常感谢大家。有了这些信息,我进行了更多调查,似乎问题不是 passlib,而是位于 angular4 之间的某个位置,我将 base64 授权标头发送到烧瓶应用程序。

我目前正在使用以下内容来执行此操作:

let headers: Headers = new Headers({
        'Content-Type': 'application/json',
        'Authorization': 'Basic ' + btoa(userLoginRequest.username + ':' + userLoginRequest.password)
    });

我今天读了很多关于 unescape 的内容(它是对 decodeURI() 的贬值)。我还阅读了很多关于 base64 编码中对 unicode 的支持。我尝试了这些东西的多种组合,但没有任何区别。我现在真的很困惑!

为了测试发生了什么,我执行以下操作。在 angular4 中,我执行以下操作:

let encodedString = btoa('doug:Tree£9')
console.log(encodedString)
console.log(atob(encodedString))

正如预期的那样,这会将以下内容打印到控制台。

ZG91ZzpUcmVlozk=
doug:Tree£9

所以编码和解码显然没问题。

在 Python 中执行相同的过程...

import base64
encoded = base64.b64encode('doug:Tree£9')
print encoded
print base64.b64decode(encoded)

我在终端中得到以下信息。

ZG91ZzpUcmVlwqM5
doug:Tree£9

我注意到“ZG91ZzpUcmVlozk=”和“ZG91ZzpUcmVlwqM5”不一样。但是,这两种方法都适用于它们自己的语言。

如果我将 "ZG91ZzpUcmVlozk=" 编码字符串从 javascript 放入 python 并解码如下......

import base64
print base64.b64decode("ZG91ZzpUcmVlozk=")

我得到:

doug:Tree�9

请注意,£ 字符现在已被捣碎。

其他 Unicode 字符也失败了。

所以我认为问题是如何对 Authorization 标头进行编码,以便 python 正确识别 £ 字符,以及用户为密码选择的任何其他字符?

非常感谢!


编辑:已解决!

我发现这个Using Javascript's atob to decode base64 doesn't proper decode utf-8 strings这涉及到一些细节。我使用@brandonscript 推荐的以下方法解决了这个问题。

b64EncodeUnicode(str) : string{
    return btoa(encodeURIComponent(str).replace(/%([0-9A-F]{2})/g, function(match, p1) {
        return String.fromCharCode(parseInt(p1, 16))
    }))
}

完美运行!呸!

4

2 回答 2

0
# -*- coding: utf-8 -*-
from passlib.apps import custom_app_context as pwd_contex

password='£$'

encrypted=pwd_contex.encrypt(password)

print(pwd_contex.verify('£$', encrypted))
print(pwd_contex.verify('john', encrypted))

True
False

在我的系统上运行良好。也许您需要# -*- coding: utf-8 -*-在脚本顶部设置默认编码

于 2018-06-01T08:57:19.087 回答
0

我猜您在文档中遇到了编码问题,

http://passlib.readthedocs.io/en/stable/narr/hash-tutorial.html#hashing

使用 PasswordHash.hash() 对密码进行哈希处理。这个调用负责unicode 编码....

from passlib.hash import pbkdf2_sha256

hash = pbkdf2_sha256.hash("$password")
pbkdf2_sha256.verify("$password", hash)
# True
于 2018-06-01T05:55:55.517 回答