如何在Python中使用sha256哈希

use*_*683 15 python sha256

我想读一个密码文件.然后我尝试计算每个密码的哈希值,并将其与我已经拥有的哈希值进行比较,以确定我是否发现了密码.但是我不断得到的错误消息是"TypeError:必须在散列之前对Unicode对象进行编码".这是我的代码:

from hashlib import sha256

with open('words','r') as f:
    for line in f:

        hashedWord = sha256(line.rstrip()).hexdigest()

        if hashedWord == 'ca52258a43795ab5c89513f9984b8f3d3d0aa61fb7792ecefe8d90010ee39f2':
            print(line + "is one of the words!")
Run Code Online (Sandbox Code Playgroud)

有人可以帮忙并提供解释吗?

Clo*_*Cho 22

如果您想从文件中以 unicode 字符串形式读取信息,则此代码行将起作用:
hashedWord = sha256(line.encode('utf-8')).hexdigest()


aba*_*ert 15

错误消息的含义正是它所说的:您有一个Unicode字符串.你不能SHA-256哈希一个Unicode字符串,你只能哈希字节.

但为什么你有一个Unicode字符串?因为您在文本模式下打开文件,这意味着您隐式要求Python将该文件中的字节(使用您的默认编码)解码为Unicode.如果要获取原始字节,则必须使用二进制模式.

换句话说,只需更改此行:

with open('words','r') as f:
Run Code Online (Sandbox Code Playgroud)

… 至:

with open('words', 'rb') as f:
Run Code Online (Sandbox Code Playgroud)

您可能会注意到,一旦解决了这个问题,该print行就会引发异常.为什么?因为你正试图添加bytes一个str.你也错过了一个空间,而你正在打印未剥离的线.你可以通过使用两个参数来解决所有这些问题print(如print(line.rstrip(), "is one of the words")).

但是,b'\xc3\x85rhus' is one of the words当你想要打印输出时,你会得到输出Århus is one of the words.那是因为你现在有字节,而不是字符串.由于Python不再为您解码,因此您需要手动执行此操作.要使用在未指定编码时有时可用的相同默认编码open,只需在decode不带参数的情况下调用.所以:

print(line.rstrip().decode(), "is one of the words")
Run Code Online (Sandbox Code Playgroud)