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 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 :) 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.

Sign up to request clarification or add additional context in comments.

Comments

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.