from Crypto.
Cipher import AES
from Crypto.Util.Padding import pad, unpad
import os
def aes_encrypt(key, plaintext):
cipher = AES.new(key, AES.MODE_CBC)
iv = cipher.iv
ciphertext = cipher.encrypt(pad(plaintext.encode(), AES.block_size))
return iv + ciphertext
def aes_decrypt(key, ciphertext):
iv = ciphertext[:16] # Extract the IV
cipher = AES.new(key, AES.MODE_CBC, iv)
plaintext = unpad(cipher.decrypt(ciphertext[16:]), AES.block_size)
return plaintext.decode()
# Example usage
key = os.urandom(16) # Key must be either 16, 24, or 32 bytes long
plaintext = "Hello, World!"
ciphertext = aes_encrypt(key, plaintext)
decrypted = aes_decrypt(key, ciphertext)
print("Ciphertext:", ciphertext)
print("Decrypted:", decrypted)
from Crypto.Cipher import DES3
from Crypto.Util.Padding import pad, unpad
import os
def des3_encrypt(key, plaintext):
cipher = DES3.new(key, DES3.MODE_CBC)
iv = cipher.iv
ciphertext = cipher.encrypt(pad(plaintext.encode(), DES3.block_size))
return iv + ciphertext
def des3_decrypt(key, ciphertext):
iv = ciphertext[:8] # Extract the IV
cipher = DES3.new(key, DES3.MODE_CBC, iv)
plaintext = unpad(cipher.decrypt(ciphertext[8:]), DES3.block_size)
return plaintext.decode()
# Example usage
key = DES3.adjust_key_parity(os.urandom(24)) # Key must be 16 or 24
bytes long
plaintext = "Hello, World!"
ciphertext = des3_encrypt(key, plaintext)
decrypted = des3_decrypt(key, ciphertext)
print("Ciphertext:", ciphertext)
print("Decrypted:", decrypted)