1

I'm curious as to how I can encrypt and decrypt binary files using python. I looked at the pycrypto library and some of the block ciphers seem to need the file length to be a multiple of 8/16/etc -- not sure how to handle this when dealing with files of arbitrary length (possibly misaligned). I considered shelling out to GPG but if I can do this in python that would be great.

Thanks in advance.

coleifer
  • 24,887
  • 6
  • 60
  • 75

2 Answers2

1

As the name suggests, all block ciphers - of any library - work on a block of data of a certain size, no more and no less. The most famous ones, TDES and AES, operate respectively on pieces of 8 and 16 bytes.

In order to work with lengths other than that, you must also select an operation mode. All modes are such that the data can be longer (or even shorter) than the block size. For some though, data must remain aligned to it (e.g. CBC). For others (e.g. CTR with segment size 1) you have no constraints at all.

This is how you use PyCrypto in the latter case (from the API description):

from Crypto.Cipher import AES
from Crypto import Random

key = b'Sixteen byte key'
iv = Random.new().read(AES.block_size)
cipher = AES.new(key, AES.MODE_CFB, iv)
msg = iv + cipher.encrypt(b'Attack at dawn')

As you can see, the message is 14 bytes long (!= 16) and it could take any size.

0

Use PythonAES: https://github.com/caller9/pythonaes

Here's a demo showing how to encrypt/decrypt a file. I'm assuming it works on any file size: https://github.com/caller9/pythonaes/blob/master/demo.py

DigitalGhost
  • 773
  • 1
  • 5
  • 14