gpt4 book ai didi

python - SimpleCrypt Python 错误

转载 作者:行者123 更新时间:2023-12-01 05:10:51 24 4
gpt4 key购买 nike

我正在使用simplecrypt library加密文件,但是我似乎无法以 simplecrypt 可以解码的方式读取该文件。

加密代码:

from simplecrypt import encrypt, decrypt
def encrypt_file(file_name, key):
with open(file_name, 'rb') as fo:
plaintext = fo.read()
enc = encrypt(plaintext, key)
with open(file_name + ".enc", 'wb') as fo:
fo.write(enc)

encrypt_file("test.txt", "securepass")

这工作正常并且运行没有任何错误,但是一旦我尝试解码它,我就会收到此错误(使用下面的代码)

simplecrypt.DecryptionException:要解密的数据必须是字节;您不能使用字符串,因为没有字符串编码可以接受所有可能的字符。

from simplecrypt import encrypt, decrypt
def decrypt_file(file_name, key):
with open(file_name, 'rb') as fo:
ciphertext = fo.read()
dec = decrypt(ciphertext, key)
with open(file_name[:-4], 'wb') as fo:
fo.write(dec)
decrypt_file("test.txt.enc", "securepass")

最佳答案

啊哈...小错误:-)

根据the link中的文档您在问题中提供的 symplecrypt.encryptsimplecrypt.decrypt 的参数是 ('password', text)。在您的代码中,您已经颠倒了( (text, key) )。您在第一个参数中传递要加密/解密的文本,在第二个参数中传递 key 。只要颠倒这个顺序就可以了。

工作示例:

from simplecrypt import encrypt, decrypt
def encrypt_file(file_name, key):
with open(file_name, 'rb') as fo:
plaintext = fo.read()
print "Text to encrypt: %s" % plaintext
enc = encrypt(key, plaintext)
with open(file_name + ".enc", 'wb') as fo:
fo.write(enc)

def decrypt_file(file_name, key):
with open(file_name, 'rb') as fo:
ciphertext = fo.read()
dec = decrypt(key, ciphertext)
print "decrypted text: %s" % dec
with open(file_name[:-4], 'wb') as fo:
fo.write(dec)

if __name__ == "__main__":
encrypt_file("test.txt", "securepass")
decrypt_file("test.txt.enc", "securepass")

关于python - SimpleCrypt Python 错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24264874/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com