# -*- coding: utf-8 -*-
import sys, os, struct
from Crypto.Cipher import AES
 
#Get the key from the user
key = raw_input("Input decryption key (16, 24 or 32 bytes): ")
 
if ( len(key) / 8 < 2 or len(key) / 8 > 4 ) or len(key) % 8 != 0:
	print "Invalid decryption key size:", len(key)
	exit()
 
#Define the AES mode
mode = AES.MODE_CBC
 
#Add 'org' to the end of the decrypted file
FILEOUT_name = sys.argv[1][:-3] + 'org'
#Set the chunk size for AES (same as with encrypt.py)
chunksize=AES.block_size * 16
 
#Open the encrypted file
with open(sys.argv[1], 'rb') as FILEIN:
	#Get the size of the original file
	size = struct.unpack('<Q', FILEIN.read(struct.calcsize('Q')))[0]
	#Initialize cipher
	cipher = AES.new(key, mode)
	#Open the decrypted file for writing
	with open(FILEOUT_name, 'wb') as FILEOUT:
		while True:
			#Read the file with defined chunksize
			chunk = FILEIN.read(chunksize)
			#Nothing to read
			if len(chunk) == 0:
				break
			#Decrypt and add the result to the file
			FILEOUT.write(cipher.decrypt(chunk))
		#Truncate the file size to match the original file (remove padding)
		FILEOUT.truncate(size)
 
FILEIN.close()
FILEOUT.close()
Last modified: 2014/02/04 15:52