Decrypt AES256 encoded message

walden systems, geeks corner, programming, languages, Python, scope, local scope, global scope, hoisting, functions, variables, developer, scripting, decrypt, aes256, encrypt, pycrypto, pip
Python is a programming language that lets you work quickly and integrate systems more effectively.

Sometimes you have a message that is AES256 encrypted and you need to decrypt it in Python. There are many ways to accomplish this task and I would like to discuss one of the ways we are using here at Walden Systems, because we believe this is the most straight forward method to decrypt messages.

To decrypt messages, you can use AES256 encryption. In order to use encryption, you must have pycrypto installed. The easiest way to install pycrypto is to use Pip, an add in package manager for Python. If you are using Python2, versions 2.7.9 or higher already Pip installed. If you are using Python3, versions 3.4 or higher already have Pip installed.

To install pycrypto, type in the following command :

    pip install pycrypto

Once you have pycrypto installed, we need to create a method to unpad the message since the encrypted message length is a multiple of 16 bytes. Next, we decrypt the message using the method, decrypt( ).

The first thing to do is create a method to unpad the message since the encrypted message is a multiple of 16 bytes but the actual message may not be. Here is a straight forward method to do so:

    def unpad(  string ) :
        unpadded_str = string[ : - ord( string[ len( string ) -1 : ] ) ]
        return( unpadded_str )


Once you have the method written, we will write a new method to do the decryption. In our example, we will call the method "decrypt_msg". We will use unpad method we just created and the built in decrypt method. Note, we will need the passphrase originally used to encrypt the message :

    def decrypt_msg( message ) :
       string = base64.b64decode( message )
       iv = string[ : AES.block_size ]
       decryptor = AES.new( "KEY_USED_TO_ENCRYPT", AES.MODE_CBC, iv )
       decrypted_msg = unpad( decryptor.decrypt( string[ AES.block_size: ] ) ).decode( 'utf-8' )
       return( decrypted_msg )

Finally, you can decrypt messages by calling the method :

   foo = decrypt_msg( "SOME_ENCYPTED_TEXT" )