尝试加密文本时出现错误"AttributeError: 'list' object has no attribute 'encrypt'"



我试图用Python编写一个有趣的小程序:

#secret text be like:
from cryptography.fernet import Fernet
g = open("ygr.data")
message = g.readlines()
key = Fernet.generate_key()
# Instance the Fernet class with the key
fernet = Fernet(key)
h = open("key.keysbois", "w")
h.write(str(key))
# then use the Fernet class instance
# to encrypt the string string must must
# be encoded to byte string before encryption
encMessage = fernet.encrypt(message.encrypt())
f = open("totallysecrettext.rushe", "w")
f.write(encMessage)

我可能是愚蠢的,但我得到错误AttributeError: 'list' object has no attribute 'encrypt'时,我试图运行它。有什么建议吗?

另外,是否可以使用奇怪的文件扩展名(即file.rushe,file.data,file.key)

您正在使用readlines()读取文件的内容。这将返回一个列表文件中的行。

message = g.readlines()

然后尝试在列表上调用encrypt,这没有意义-因为您已经在fernet对象上调用了它:

fernet.encrypt(message.encrypt())
^-- this is a list of lines from the file - not what you want

相反,使用read()读取文件的内容。您还必须确保以二进制格式读取文件,以便获得可以发送到internet的字节:

g = open("ygr.data", "rb")
message = g.read()

. .然后加密内容:

encMessage = fernet.encrypt(message)

最新更新