Index: pyAES.txt =================================================================== --- pyAES.txt (revision 15) +++ pyAES.txt (working copy) @@ -1,6 +1,7 @@ #!/usr/bin/python2.5 import sys, hashlib, string, getpass from copy import copy +from random import randint # The actual Rijndael specification includes variable block size, but # AES uses a fixed block size of 16 bytes (128 bits) @@ -332,7 +333,9 @@ block = [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0] # plaintext ciphertext = [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0] # ciphertext # Initialization Vector - IV = [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0] + IV = [] + for i in range(16): + IV.append(randint(0, 255)) # convert password to AES 256-bit key aesKey = passwordToKey(password) @@ -359,6 +362,18 @@ print "pyAES: unable to open output file -", filename sys.exit() + # write IV to outfile + for byte in IV: + outfile.write(chr(byte)) + + # get the file size (bytes) + # if the file size is a multiple of the block size, we'll need + # to add a block of padding at the end of the message + fp.seek(0,2) + filesize = fp.tell() + # put the file pointer back at the beginning of the file + fp.seek(0) + # begin reading in blocks of input to encrypt firstRound = True block = getBlock(fp) @@ -378,6 +393,10 @@ # grab next block from input file block = getBlock(fp) + # if the message ends on a block boundary, we need to add an + # extra block of padding + if filesize % 16 == 0: + outfile.write(16*chr(16)) # close file pointers fp.close() outfile.close() @@ -387,8 +406,6 @@ def decrypt(myInput, password, outputfile=None): block = [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0] # ciphertext plaintext = [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0] # plaintext container - # Initialization Vector - IV = [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0] # convert password to AES 256-bit key aesKey = passwordToKey(password) @@ -400,13 +417,6 @@ print "pyAES: unable to open input file -", myInput sys.exit() - # get the file size (bytes) in order to handle the - # padding at the end of the file - fp.seek(0,2) - filesize = fp.tell() - # put the file pointer back at the beginning of the file - fp.seek(0) - # create handle for file to be decrypted try: fp = open(myInput, "rb") @@ -433,6 +443,16 @@ print "pyAES: unable to open output file -", filename sys.exit() + # recover Initialization Vector, the first block in file + IV = getBlock(fp) + + # get the file size (bytes) in order to handle the + # padding at the end of the file + fp.seek(0,2) + filesize = fp.tell() + # put the file pointer back at the first block of ciphertext + fp.seek(16) + # begin reading in blocks of input to decrypt firstRound = True block = getBlock(fp)