Created
October 14, 2021 17:30
-
-
Save jhuamanchumo/8feedef632b60018a0c7427d8f168408 to your computer and use it in GitHub Desktop.
AES Encryption - Python
This file contains hidden or 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
#!/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