Skip to content

Instantly share code, notes, and snippets.

@komuw
Created February 15, 2016 14:19
Show Gist options
  • Save komuw/70211c54358d1eca45f2 to your computer and use it in GitHub Desktop.
Save komuw/70211c54358d1eca45f2 to your computer and use it in GitHub Desktop.
python AES with CBC/PKCS5Padding
from Crypto.Cipher import AES
from Crypto import Random
import base64
block_size = AES.block_size
#unpad = lambda s : s[0:-ord(s[-1])]
def pad(plain_text):
"""
func to pad cleartext to be multiples of 8-byte blocks.
If you want to encrypt a text message that is not multiples of 8-byte blocks,
the text message must be padded with additional bytes to make the text message to be multiples of 8-byte blocks.
"""
number_of_bytes_to_pad = block_size - len(plain_text) % block_size
ascii_string = chr(number_of_bytes_to_pad)
padding_str = number_of_bytes_to_pad * ascii_string
padded_plain_text = plain_text + padding_str
return padded_plain_text
key='some-key'
plain='plain_text'
plain = pad(plain)
iv = Random.new().read(AES.block_size)
cipher = AES.new(key, AES.MODE_CBC, iv )
encrypted_text = cipher.encrypt( plain )
print encrypted_text
@gajjar8055
Copy link

How can we decrypt it ?

@vinaysagarsd-bhat
Copy link

why import base64?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment