6

Is there a way to encrypt files (.zip, .doc, .exe, ... any type of file) with Python?

I've looked at a bunch of crypto libraries for Python including pycrypto and ezpycrypto but as far as I see they only offer string encryption.

3
  • Related: Create an encrypted ZIP file in Python
    – miku
    Commented May 30, 2010 at 13:18
  • 7
    In Python 2, strings are really byte-strings, so you can just read in the file as binary, encrypt it, then write as binary. Commented May 30, 2010 at 13:22
  • 1
    Ugh.. how come I couldn't think that. Thanks :)
    – Pinkie
    Commented May 30, 2010 at 13:31

2 Answers 2

2

In Python versions prior to version 3.0, the read method of a file object will return a string, provide this string to the encryption library of your choice, the resulting string can be written to a file.

Keep in mind that on Windows-based operating systems, the default mode used when reading files may not accurately provide the contents of the file. I suggest that you be familiar with the nuances of file modes and how they behave on Windows-based OSes.

1

You can read the complete file into a string, encrypt it, write the encrypted string in a new file. If the file is too large, you can read in chunks.

Every time you .read from a file, you get a string (in Python < 3.0).

Not the answer you're looking for? Browse other questions tagged or ask your own question.