AES Encryption/Decryption in Python

This is a snippet in using the PyCrypto package in Python to encrypt and decrypt with AES. The first one implements AES CFB mode – padding is not required for byte alignment. The second one implements AES CBC and PKCS7 padding to byte align the secret message.

PyCrypto Reference: https://www.dlitz.net/software/pycrypto/api/current/

Salt – randomizes the hash of the key; prevents rainbow table attacks against the key
IV (initialization vector) – randomizes the encrypted message; prevents rainbow table attacks against the message
Derived Key – lengthens and strengthens the key via hashing; used instead of the original key; slows down brute-force attacks against the key

AES CFB

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
from Crypto.Cipher import AES
from Crypto.Protocol.KDF import PBKDF2
from Crypto import Random

key_size = 32 #AES256
iterations = 10000
key = b'password'
secret = b'a very secret message'

salt = Random.new().read(key_size) #salt the hash
iv = Random.new().read(AES.block_size)
derived_key = PBKDF2(key, salt, key_size, iterations)
cipher = AES.new(derived_key, AES.MODE_CFB, iv)

encodedtext = iv + cipher.encrypt(secret)
decodedtext = str(cipher.decrypt(encodedtext))[16:] #remove iv

AES CBC

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
from Crypto.Cipher import AES
from Crypto.Protocol.KDF import PBKDF2
from Crypto import Random

key_size = 32 #AES256
iterations = 10000
key = b'password'
secret = b'a very secret message'

length = 16 - (len(secret) % 16) #PKCS7 adds bytes of the length of padding
secret += chr(length) * length

salt = Random.new().read(key_size) #salt the hash
iv = Random.new().read(AES.block_size)
derived_key = PBKDF2(key, salt, key_size, iterations)
cipher = AES.new(derived_key, AES.MODE_CBC, iv)

encodedtext = iv + cipher.encrypt(secret)
decodedtext = str(cipher.decrypt(encodedtext))[16:-ord(decodedtext[-1])] #remove iv and padding
This entry was posted in Uncategorized and tagged , , . Bookmark the permalink.

Leave a Reply

Your email address will not be published. Required fields are marked *