Skip to content

Instantly share code, notes, and snippets.

@ppdouble
Last active July 13, 2023 00:40
Show Gist options
  • Save ppdouble/98264955d6a8578b92bc647ee500fca7 to your computer and use it in GitHub Desktop.
Save ppdouble/98264955d6a8578b92bc647ee500fca7 to your computer and use it in GitHub Desktop.
Encrypt Util for AES ECB PKC5 in python3
import base64
import subprocess
from Crypto.Cipher import AES
from Crypto.Util.Padding import pad, unpad
# Python 3.11.3
# pycryptodome-3.18.0-cp35-abi3-manylinux_2_17_x86_64.manylinux2014_x86_64.whl
def pad_pkcs5(byte_array: bytearray, block_size: int):
"""
pkcs5 padding
"""
pad_len = block_size - len(byte_array) % block_size
return byte_array + (bytes([pad_len]) * pad_len)
# pkcs5 - unpadding
def unpad_pkcs5(byte_array: bytearray):
return byte_array[:-ord(byte_array[-1:])]
def encrypt_v2(datastr: str):
"""
Default AES.block_size is 16
Default AES key in this lib is 256bit which is 32bytes
"""
block_size = AES.block_size
# Fixed key is not recommended.
key = b'euuNeCOAFGwJC3py6PZgeSEaXcARv05C'
# datastr = "1d4b77c86241"
# "5SrzefIwG/ClWuJanq8d8g=="
# convert to bytes
# datastr.encode("utf-8")
byte_array = bytearray(datastr.encode("utf-8"))
# pad the message - with pkcs5 style
padded = pad_pkcs5(byte_array, block_size)
# new instance of AES with encoded key
cipher = AES.new(key, AES.MODE_ECB)
# now encrypt the padded bytes
encrypted = cipher.encrypt(padded)
# base64 encode and convert back to string
cipher_text = base64.b64encode(encrypted).decode('utf-8')
return cipher_text
def decrypt_v2():
block_size = AES.block_size
print(block_size)
key = b'euuNeCOAFGwJC3py6PZgeSEaXcARv05C'
# datastr = "1d4b77c86241"
encrypted_datastr = "5SrzefIwG/ClWuJanq8d8g=="
# convert to bytes
encrypted_datastr_bytes = encrypted_datastr.encode("utf-8")
encrypted_data_bytes = base64.b64decode(encrypted_datastr_bytes)
# new instance of AES with encoded key
cipher = AES.new(key, AES.MODE_ECB)
# decrypt and decode
decrypted = bytearray(cipher.decrypt(encrypted_data_bytes))
# unpad_pkcs5 - with pkcs5 style and return
original_text = unpad_pkcs5(decrypted).decode('utf-8')
return original_text
def encrypt_v1():
"""
Using default builtin pad, unpad function
Default pkcs7
"""
block_size = AES.block_size
key = b'euuNeCOAFGwJC3py6PZgeSEaXcARv05C'
datastr = b'1d4b77c86241'
cipher = AES.new(key, AES.MODE_ECB)
ciphertext = cipher.encrypt(pad(datastr, block_size))
return base64.b64encode(ciphertext).decode('utf-8')
def decrypt_v1():
block_size = AES.block_size
key = b'euuNeCOAFGwJC3py6PZgeSEaXcARv05C'
# datastr = b'1d4b77c86241'
encrypted_datastr = "5SrzefIwG/ClWuJanq8d8g=="
encrypted_data_bytes = base64.b64decode(encrypted_datastr)
cipher = AES.new(key, AES.MODE_ECB)
decrypted = cipher.decrypt(encrypted_data_bytes)
origin = unpad(decrypted, block_size)
return origin.decode('utf-8')
@ppdouble
Copy link
Author

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