Encrypt message using AES256

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 need to encrypt messages 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 straightforward method to encrypt messages.

To encrypt 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 pad the message to ensure the message length in bytes is a multiple of 16. Next, we encrypt the message using the method, encrypt( ).

The first thing to do is create a method to pad the message so it is a multiple of 16. Here is a straight forward method to do so:

    def pad(  string ) :
         padded_string = string + ( 16 -len( string ) % 16 ) * chr( 16 -len( string ) % 16 )
         return( padded_string )


Once you have the method written, we will write a new method to do the encryption. In our example, we will call the method "encrypt_msg" so we don't confuse it with the pycrypto method encrypt( ). We will use pad method we just created and the built in encrypt method. Note the key is the passphrase that will be used to encrypt the message and to decrypt it is here:

    def encrypt_msg( message ) :
       key = "KEY_TO_ENCODE_MSG"
       padded_message = pad( message )
       iv = Random.new( ).read( AES.block_size )
       encoder = AES.new( key, AES.MODE_CBC, iv)
       encrypted_string = base64.b64encode( iv + encoder.encrypt( padded_message ) )
       return( encrypted_string )

Finally, you can encrypt messages by calling the method :

   foo = encrypt_msg( "SOME_TEXT" )