# -*- coding: utf-8 -*-
import sys, os, struct
from Crypto.Cipher import AES
 
 
FILEOUT_name = sys.argv[1] + '.enc'
 
#Get the key from the user
key = raw_input("Input encryption key (16, 24 or 32 bytes): ")
 
if ( len(key) / 8 < 2 or len(key) / 8 > 4 ) or len(key) % 8 != 0:
	print "Invalid encryption key size:", len(key)
	exit()
 
#Define mode for AES and initalize the cipher
mode = AES.MODE_CBC
cipher = AES.new(key, mode)
 
#Get the length of the file
filesize = os.path.getsize(sys.argv[1])
#Define the size of the encryption block
chunksize=AES.block_size * 16
 
#Open both files, decrypted for reading, encrypted for writing
with open(sys.argv[1], 'rb') as FILEIN:
        with open(FILEOUT_name, 'wb') as FILEOUT:
		#Write the size of the file into the beginning
		#Set the integer to be unsigned long long with little endian byte order
		#See http://docs.python.org/2/library/struct.html
		FILEOUT.write(struct.pack('<Q', filesize))
 
		while True:
			#Read the file in blocks of the defined chunksize
			chunk = FILEIN.read(chunksize)
			#If the length of read data is 0 - nothing to read
			if len(chunk) == 0:
				break
			#If the read chunk is not divisable with the aes block size
			elif len(chunk) % AES.block_size != 0:
				#Apply some padding
				chunk += ' ' * (AES.block_size - (len(chunk) % AES.block_size))
			#Encrypt the chunk and append it tho the file
			FILEOUT.write(cipher.encrypt(chunk))
 
FILEIN.close()
FILEOUT.close()
Last modified: 2014/02/04 15:52