-
-
Save nw4869/dea1da574922d777c40cac569160e862 to your computer and use it in GitHub Desktop.
python AES with CBC/PKCS5Padding
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment