Created
November 23, 2023 13:39
-
-
Save SofianeHamlaoui/078e8002556cb28dccbca0907a38e042 to your computer and use it in GitHub Desktop.
AES usage in Python using the cryptography python module
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
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')) |
Author
SofianeHamlaoui
commented
Nov 23, 2023
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment