31 lines
1.4 KiB
Python
31 lines
1.4 KiB
Python
from cryptography.hazmat.backends import default_backend
|
|
from cryptography.hazmat.primitives.ciphers import Cipher, algorithms, modes
|
|
from cryptography.hazmat.primitives import padding
|
|
|
|
|
|
class AESEncryptor:
|
|
def __init__(self, key):
|
|
if not isinstance(key, bytes):
|
|
key = key.encode('utf-8') # Assuming UTF-8 encoding, adjust if needed
|
|
if len(key) != 16:
|
|
raise ValueError("AES key must be 16 bytes in length")
|
|
self.key = key
|
|
|
|
def encrypt(self, plaintext):
|
|
cipher = Cipher(algorithms.AES(self.key), modes.ECB(), backend=default_backend())
|
|
encryptor = cipher.encryptor()
|
|
plaintext = plaintext.encode('utf-8')
|
|
padder = padding.PKCS7(algorithms.AES.block_size).padder()
|
|
padded_plaintext = padder.update(plaintext) + padder.finalize()
|
|
ciphertext = encryptor.update(padded_plaintext) + encryptor.finalize()
|
|
return ciphertext.hex()
|
|
|
|
def decrypt(self, ciphertext):
|
|
cipher = Cipher(algorithms.AES(self.key), modes.ECB(), backend=default_backend())
|
|
decryptor = cipher.decryptor()
|
|
ciphertext = bytes.fromhex(ciphertext)
|
|
decrypted_data = decryptor.update(ciphertext) + decryptor.finalize()
|
|
unpadder = padding.PKCS7(algorithms.AES.block_size).unpadder()
|
|
unpadded_data = unpadder.update(decrypted_data) + unpadder.finalize()
|
|
return unpadded_data.decode('utf-8')
|