1

I am using the simplecrypt library to encrypt a file, however I cannot seem to read the file in a way that simplecrypt can decode it.

Encryption code:

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")

This works fine and runs without any errors, however as soon as i try to decode it i get this error (using the below code)

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")
ollierexx
  • 511
  • 1
  • 5
  • 15
  • Could you take a look to the indentation? It looks like the `encrypt_file` and `decrypt_file` functions are unindented? – Savir Jun 17 '14 at 13:17
  • Sorry about that, the code did not translate into stack overflow very well. The indentation is fine (the encrypt works fine, and decrypt works till the error is thrown) – ollierexx Jun 17 '14 at 13:21

1 Answers1

2

Aha... Minor mistake :-)

According to the docs in the link you provided in your question, the arguments to symplecrypt.encrypt and simplecrypt.decrypt are ('password', text). In your code you've got that inverted ( (text, key) ). You're passing the text to encrypt/decrypt in the first argument and the key in the second. Just reverse that order and will work.

Working example:

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")  
Savir
  • 17,568
  • 15
  • 82
  • 136