Skip to content

Instantly share code, notes, and snippets.

@LynxBcn
Forked from lopes/aes-ecb.py
Created May 30, 2018 10:33
Show Gist options
  • Save LynxBcn/e6edd4ae41eabf54878f41bcd769b5a3 to your computer and use it in GitHub Desktop.
Save LynxBcn/e6edd4ae41eabf54878f41bcd769b5a3 to your computer and use it in GitHub Desktop.
Simple Python example of AES in ECB mode.
from hashlib import md5
from base64 import b64decode
from base64 import b64encode
from Crypto.Cipher import AES
# Padding for the input string --not
# related to encryption itself.
BLOCK_SIZE = 16 # Bytes
pad = lambda s: s + (BLOCK_SIZE - len(s) % BLOCK_SIZE) * \
chr(BLOCK_SIZE - len(s) % BLOCK_SIZE)
unpad = lambda s: s[:-ord(s[len(s) - 1:])]
class AESCipher:
"""
Usage:
c = AESCipher('password').encrypt('message')
m = AESCipher('password').decrypt(c)
Tested under Python 3 and PyCrypto 2.6.1.
"""
def __init__(self, key):
self.key = md5(key.encode('utf8')).hexdigest()
def encrypt(self, raw):
raw = pad(raw)
cipher = AES.new(self.key, AES.MODE_ECB)
return b64encode(cipher.encrypt(raw))
def decrypt(self, enc):
enc = b64decode(enc)
cipher = AES.new(self.key, AES.MODE_ECB)
return unpad(cipher.decrypt(enc)).decode('utf8')
##
# MAIN
# Just a test.
msg = input('Message...: ')
pwd = input('Password..: ')
print('Ciphertext:', AESCipher(pwd).encrypt(msg))
@DanielHemmati
Copy link

i added this part: (for decrypt)

 cipher = input("what is the cipher: ")
 print("diphertext: ", AESCipher(pwd).decrypt(cipher))

thanks 🤗

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