Last active
March 10, 2019 06:31
-
-
Save phuocphn/a9d26b0a1f9445ef7885170478360010 to your computer and use it in GitHub Desktop.
Encryption using pycrypto, AES, and PKCS5 padding
This file contains 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
''' | |
Author: komuw/pycrypto_AES.py | |
Security issues: | |
+ https://stackoverflow.com/questions/2641720/for-aes-cbc-encryption-whats-the-importance-of-the-iv | |
+ https://defuse.ca/cbcmodeiv.htm | |
+ https://passingcuriosity.com/2009/aes-encryption-in-python-with-m2crypto/ | |
''' | |
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='b'* 32 | |
plain="Hence, it wants a string of 8-bit bytes. You create those in Python 3 with the b'' syntax." | |
plain = pad(plain) | |
#iv = b'0000000000000000' | |
iv = b'\0'* 16 | |
cipher = AES.new(key.encode("utf-8"), AES.MODE_CBC, iv ) | |
encrypted_text = cipher.encrypt( plain.encode("utf-8") ) | |
print (base64.b64encode(encrypted_text).decode("utf-8")) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment