Skip to content

Instantly share code, notes, and snippets.

@jhuamanchumo
Created October 14, 2021 17:30
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jhuamanchumo/8feedef632b60018a0c7427d8f168408 to your computer and use it in GitHub Desktop.
Save jhuamanchumo/8feedef632b60018a0c7427d8f168408 to your computer and use it in GitHub Desktop.
AES Encryption - Python
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import base64
from Crypto.Util import Padding
from Crypto.Cipher import AES
def encrypt(plain_text, key, iv):
try:
cipher = AES.new(key.encode(), AES.MODE_CBC, iv.encode())
raw = Padding.pad(data_to_pad=plain_text.encode(),
block_size=AES.block_size, style='pkcs7')
encrypted_text = cipher.encrypt(raw)
return base64.encodebytes(encrypted_text).decode().rstrip()
except Exception as error:
raise EncryptorError(error)
def decrypt(encrypted_text, key, iv):
try:
cipher = AES.new(key.encode(), AES.MODE_CBC, iv.encode())
plain_text = cipher.decrypt(
base64.b64decode(encrypted_text)).decode()
return Padding.unpad(padded_data=plain_text.encode(), block_size=AES.block_size, style='pkcs7').decode()
except Exception as error:
raise EncryptorError(error)
class Error(Exception):
"""Base class for other exceptions"""
pass
class EncryptorError(Exception):
def __init__(self, message):
self.message = message
super().__init__(self.message)
key = 'secretKey'
iv = 'vectorInit'
plain = 'hola'
encrypted = encrypt(plain, key, iv)
decrypted = decrypt(encrypted, key, iv)
print("plain: {}".format(plain))
print("encrypted: {}".format(encrypted))
print("decrypted: {}".format(decrypted))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment