Skip to content

Instantly share code, notes, and snippets.

@tinshade
Created May 9, 2021 10:11
Show Gist options
  • Save tinshade/a3a8f63a968e583f7992e058bed027f0 to your computer and use it in GitHub Desktop.
Save tinshade/a3a8f63a968e583f7992e058bed027f0 to your computer and use it in GitHub Desktop.
Simple AES cryptography using Python
#!/usr/bin/python3
# python AES_Cryptography.py -e/-d <AbsolutePathToFile>
from Crypto import Random
from Crypto.Cipher import AES
import os
import os.path
from os import listdir
from os.path import isfile, join
import hashlib
import sys
class Encryptor:
def __init__(self, key):
self.key = key
def pad(self, s):
return s + b"\0" * (AES.block_size - len(s) % AES.block_size)
def encrypt(self, message, key, key_size=256):
message = self.pad(message)
iv = Random.new().read(AES.block_size)
cipher = AES.new(key, AES.MODE_CBC, iv)
return iv + cipher.encrypt(message)
def encrypt_file(self, file_name):
with open(file_name, 'rb') as fo:
plaintext = fo.read()
enc = self.encrypt(plaintext, self.key)
with open(file_name + ".e2nc", 'wb') as fo:
fo.write(enc)
os.remove(file_name)
def decrypt(self, ciphertext, key):
iv = ciphertext[:AES.block_size]
cipher = AES.new(key, AES.MODE_CBC, iv)
plaintext = cipher.decrypt(ciphertext[AES.block_size:])
return plaintext.rstrip(b"\0")
def decrypt_file(self, file_name):
with open(file_name, 'rb') as fo:
ciphertext = fo.read()
dec = self.decrypt(ciphertext, self.key)
print(file_name)
with open(file_name[:-4], 'wb') as fo:
fo.write(dec)
os.remove(file_name)
def driver():
file_path=sys.argv[2]
if sys.argv[1] == '-e':
def startenc(file_path):
file_name = file_path.split('\\')[-1]
key=bytes(hashlib.sha256(file_name.encode('utf-8')).hexdigest()[:32], 'utf-8')
enc = Encryptor(key)
enc.encrypt_file(file_path)
print(200,flush=True)
elif sys.argv[1] == '-d':
def startdec(file_path):
file_name = file_path.split('\\')[-1].split('.e2nc')[0]
key=bytes(hashlib.sha256(file_name.encode('utf-8')).hexdigest()[:32], 'utf-8')
enc = Encryptor(key)
enc.decrypt_file(f'{file_name}.e2nc')
print(200,flush=True)
else:
print(404, flush=True)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment