Skip to content

Instantly share code, notes, and snippets.

@omariosouto
Forked from lopes/aes-cbc.py
Last active April 17, 2023 02:49
Show Gist options
  • Save omariosouto/7c11fabc11eb56c046a6eb37998bcc77 to your computer and use it in GitHub Desktop.
Save omariosouto/7c11fabc11eb56c046a6eb37998bcc77 to your computer and use it in GitHub Desktop.
Simple Python example of AES in CBC mode.
#!/usr/bin/env python3
#
# This is a simple script to encrypt a message using AES
# with CBC mode in Python 3.
# Before running it, you must install pycryptodome:
#
# $ python -m pip install PyCryptodome
#
# Author.: José Lopes
# Date...: 2019-06-14
# License: MIT
##
from hashlib import md5
from base64 import b64decode
from base64 import b64encode
from Crypto.Cipher import AES
from Crypto.Random import get_random_bytes
from Crypto.Util.Padding import pad, unpad
class AESCipher:
def __init__(self, key):
self.key = md5(key.encode('utf8')).digest()
def encrypt(self, data):
iv = get_random_bytes(AES.block_size)
self.cipher = AES.new(self.key, AES.MODE_CBC, iv)
return b64encode(iv + self.cipher.encrypt(pad(data.encode('utf-8'),
AES.block_size)))
def decrypt(self, data):
raw = b64decode(data)
self.cipher = AES.new(self.key, AES.MODE_CBC, raw[:AES.block_size])
return unpad(self.cipher.decrypt(raw[AES.block_size:]), AES.block_size)
msg = 'xxxxxxxxxxxxxxxxxxxxxxxx12345678'
pwd = 'Nice passphraseNice_passphrase__'
print('Encrypt:', AESCipher(pwd).encrypt(msg).decode('utf-8'))
print('Descript:', AESCipher(pwd).decrypt(cte).decode('utf-8'))
@gb-dsingh
Copy link

cte is not defined

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