Skip to content

Instantly share code, notes, and snippets.

@cbscribe
Created May 25, 2021 03:14
Show Gist options
  • Save cbscribe/92b13f91985013b442405b8c6f85bbe8 to your computer and use it in GitHub Desktop.
Save cbscribe/92b13f91985013b442405b8c6f85bbe8 to your computer and use it in GitHub Desktop.
Python AES encrypt/decrypt
from Crypto.Cipher import AES
from Crypto.Random import get_random_bytes
from Crypto.Util.Padding import pad, unpad
import base64
key = input("Key: ").encode()
def encrypt():
iv = get_random_bytes(AES.block_size)
cipher = AES.new(key, AES.MODE_CBC, iv)
input_file = input("Cleartext file: ")
with open(input_file) as file:
cleartext = file.read()
ciphertext = iv + cipher.encrypt(pad(cleartext.encode('utf-8'),
AES.block_size))
output_file = input("Ciphertext file: ")
with open(output_file, "w") as file:
file.write(base64.b64encode(ciphertext).decode())
def decrypt():
input_file = input("Ciphertext file: ")
with open(input_file) as file:
ciphertext = file.read().encode()
ciphertext = base64.b64decode(ciphertext)
try:
cipher = AES.new(key, AES.MODE_CBC, ciphertext[:AES.block_size])
cleartext = unpad(cipher.decrypt(ciphertext[AES.block_size:]), AES.block_size)
print(cleartext.decode())
except:
print("Decryption failed.")
choice = input("(E)ncrypt or (D)ecrypt: ").lower()
if choice == "e":
encrypt()
elif choice == "d":
decrypt()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment