Created
January 21, 2019 13:48
-
-
Save kingardor/cff845f374eb58ee54385184c5faa939 to your computer and use it in GitHub Desktop.
Encryption and Decryption of text/files using pycrypto
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
#!/usr/bin/python3 | |
import sys | |
from Crypto import Random | |
from Crypto.Cipher import AES | |
import argparse | |
class Initialize: | |
def argsparser(self): | |
''' | |
To use arguments from command line. | |
''' | |
parser = argparse.ArgumentParser(description='') | |
parser.add_argument('--input', dest='input', default='yolov3.weights', help='Input video source', type=str) | |
parser.add_argument('--encrypt', dest='encrypt', default=False, help='To Encrypt', action='store_true') | |
parser.add_argument('--decrypt', dest='decrypt', default=False, help='To Decrypt', action='store_true') | |
return parser.parse_args() | |
def __init__(self): | |
self.args = self.argsparser() | |
if(self.args.encrypt and self.args.decrypt) or (not self.args.encrypt and not self.args.decrypt): | |
print('Please Select a valid input') | |
sys.exit() | |
class Security: | |
def pad(self, s): | |
return s + b"\0" * (AES.block_size - len(s) % AES.block_size) | |
def encrypt(self, message): | |
message = self.pad(message) | |
iv = Random.new().read(AES.block_size) | |
cipher = AES.new(self.key, AES.MODE_CBC, iv) | |
return iv + cipher.encrypt(message) | |
def decrypt(self, ciphertext): | |
iv = ciphertext[:AES.block_size] | |
cipher = AES.new(self.key, AES.MODE_CBC, iv) | |
plaintext = cipher.decrypt(ciphertext[AES.block_size:]) | |
return plaintext.rstrip(b"\0") | |
def encrypt_file(self, file_name): | |
with open(file_name, 'rb') as fo: | |
plaintext = fo.read() | |
enc = self.encrypt(plaintext) | |
with open(file_name + ".enc", 'wb') as fo: | |
fo.write(enc) | |
def decrypt_file(self, file_name): | |
with open(file_name, 'rb') as fo: | |
ciphertext = fo.read() | |
dec = self.decrypt(ciphertext) | |
with open(file_name[:-4], 'wb') as fo: | |
fo.write(dec) | |
def __init__(self): | |
self.key = 'Add a key here' | |
self.key_size = 256 | |
if __name__ == '__main__': | |
init = Initialize() | |
sec = Security() | |
if(init.args.encrypt): | |
sec.encrypt_file(init.args.input) | |
if(init.args.decrypt): | |
sec.decrypt_file(init.args.input) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment