Skip to content

Instantly share code, notes, and snippets.

@mjuenema
Last active December 4, 2018 17:28
Show Gist options
  • Save mjuenema/087711e51ad17889e26036b8adb09190 to your computer and use it in GitHub Desktop.
Save mjuenema/087711e51ad17889e26036b8adb09190 to your computer and use it in GitHub Desktop.

AES encryption with PKCS5 padding

NOTE: Possible use the Cryptography package instead.

Install Python pycrypto package.

$ pip install pycrypto

Encrypt.

from Crypto.Cipher import AES

cleartext = 'this is clear text'
key = 'abcdef0123456789'               # AES-128
iv = chr(0) * AES.block_size

# Need to pad `cleartext` to multiple length of AES block size. The
# padding character is `chr(x)` where `x` is the length of padding (PKCS5)
#
# Example
#
# Clear text: this is clear text'
# Lenght of clear text: 18
# AES block size: 16
# Length of padding: 14 (32-18)
# Padding character: chr(14)
#
padlen = AES.block_size - len(cleartext) % AES.block_size
padchar = chr(padlen)
padded_cleartext = cleartext + padchar * padlen

# Encrypt
#
encrypted = AES.new(key, AES.MODE_CBC, iv).encrypt(padded_cleartext)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment