我正在使用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: Data to decrypt must be bytes; you cannot use a string because no string encoding will accept all possible characters.

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))。您将在第一个参数中传递文本以进行加密/解密,在第二个参数中传递密钥。只需颠倒该顺序即可使用。

工作示例:

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/

10-10 10:02