Skip to content

Instantly share code, notes, and snippets.

@SofianeHamlaoui
Created November 23, 2023 13:39
Show Gist options
  • Save SofianeHamlaoui/078e8002556cb28dccbca0907a38e042 to your computer and use it in GitHub Desktop.
Save SofianeHamlaoui/078e8002556cb28dccbca0907a38e042 to your computer and use it in GitHub Desktop.
AES usage in Python using the cryptography python module
from cryptography.hazmat.primitives.ciphers import Cipher, algorithms, modes
from cryptography.hazmat.primitives.padding import PKCS7
from cryptography.hazmat.backends import default_backend
import base64
def aesencrypt(plaintext, key):
cipher = Cipher(algorithms.AES(key), modes.ECB(), backend=default_backend())
encryptor = cipher.encryptor()
padder = PKCS7(algorithms.AES.block_size).padder()
padded_data = padder.update(plaintext) + padder.finalize()
ciphertext = encryptor.update(padded_data) + encryptor.finalize()
encodedciphertext = base64.b64encode(ciphertext)
return encodedciphertext
def aesdecrypt(ciphertext, key):
cipher = Cipher(algorithms.AES(key), modes.ECB(), backend=default_backend())
decryptor = cipher.decryptor()
decodedciphertext = base64.b64decode(ciphertext)
padded_data = decryptor.update(decodedciphertext) + decryptor.finalize()
unpadder = PKCS7(algorithms.AES.block_size).unpadder()
plaintext = unpadder.update(padded_data) + unpadder.finalize()
return plaintext
# Usage :
# key = os.urandom(32)
# plaintext = input("Enter the plaintext: ").encode()
# enc = aesencrypt(plaintext, key)
# print("The encrypted message is :", enc)
# dec = aesdecrypt(enc, key)
# print("The decrypted message is:", dec.decode('utf-8'))
@SofianeHamlaoui
Copy link
Author

image

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