Encryption and Decryption With the PyCrypto Module Using the AES Cipher in Python
While I’m learning a lot about encryption at the moment, I wanted to test out encryption with the PyCrypto module in Python using the Advanced Encryption Standard (AES) Symmetric Block Cipher.
Installing PyCrypto:
1
$ pip install pycrypto --user
PyCrypto Example:
Our AES Key needs to be either 16, 24 or 32 bytes long and our Initialization Vector needs to be 16 Bytes long. That will be generated using the random and string modules.
Encrypting:
12345678910111213141516
>>>fromCrypto.CipherimportAES>>>importrandom,string,base64>>>key=''.join(random.choice(string.ascii_uppercase+string.ascii_lowercase+string.digits)forxinrange(32))>>>iv=''.join(random.choice(string.ascii_uppercase+string.ascii_lowercase+string.digits)forxinrange(16))>>>print(key,len(key))('BLhgpCL81fdLBk23HkZp8BgbT913cqt0',32)>>>print(iv,len(iv))('OWFJATh1Zowac2xr',16)>>>enc_s=AES.new(key,AES.MODE_CFB,iv)>>>cipher_text=enc_s.encrypt('this is a super important message')>>>encoded_cipher_text=base64.b64encode(cipher_text)>>>print(encoded_cipher_text)'AtBa6zVB0UQ3U/50ogOb6g09FlyPdpmJB7UzoCqxhsQ6'