SimpleCrypt Python 错误
我正在使用simplecrypt
库来加密一个文件,但我发现无法以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")
1 个回答
2
哦...小错误 :-)
根据你在问题中提供的这个链接的说明,simplecrypt.encrypt
和simplecrypt.decrypt
这两个函数的参数应该是('密码', 文本)
。而在你的代码里,你把这两个参数搞反了,变成了(文本, 密钥)
。你把要加密或解密的文本放在了第一个参数,而把密钥放在了第二个参数。只需要把这个顺序调换一下,就能正常工作了。
可以参考的示例:
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")