Home |

Trigat

Python File Encryption Script - 357.py

03-02-2019

Script that allows you to encrypt and decrypt files. Uses pyAesCrypt which is a Python 3 file-encryption module and script that uses AES256-CBC to encrypt/decrypt files and binary streams. This is a modified version of the example at https://pypi.org/project/pyAesCrypt/

Encrypt:
python3 357.py -e FILE

Decrypt:
python3 357.py -d FILE

Language or Platform: Python

Code:

import pyAesCrypt
import getpass
import argparse
from os import stat, remove
import os
import sys

# overwrite file with random data to securely wipe it
def secure_wipe(path, passes=1):
    with open(path, "ba+") as delfile:
        length = delfile.tell()
        for i in range(passes):
            delfile.seek(0)
            delfile.write(os.urandom(length))
    os.remove(path)

# encryption/decryption buffer size - 64K
bufferSize = 64 * 1024

def encrypt(password, filename):
    path = filename
    with open(path, "rb") as Orig:
        with open(path +".aes", "wb") as OrigEnc:
            pyAesCrypt.encryptStream(Orig, OrigEnc, password, bufferSize)
    secure_wipe(path)

def decrypt(password, filename):

    # get encrypted file size
    encFileSize = stat(filename).st_size
    # make sure output filename doesn't already exist
    # so you don't accidentally overwrite a file
    try:
        check_file = open(filename.replace(".aes", ""), 'r')
        print("Error: This action would overwrite a file that already exists.")
    except FileNotFoundError:
        with open(filename, "rb") as enc: # check if you can use filename instead of path
            with open(filename.replace(".aes", "", 1), "wb") as dec:  # create output file
                try:
                    # decrypt file stream
                    pyAesCrypt.decryptStream(enc, dec, password, bufferSize, encFileSize)
                except ValueError:
                    # remove output file on error
                    enc.close()
                    dec.close()
                    secure_wipe(filename.replace(".aes", ""))
                    print("Error: Password not valid.")
                    sys.exit()
        secure_wipe(filename)

def main():
    parser = argparse.ArgumentParser()
    parser.add_argument("-e", help="ENCRYPT EXAMPLE: -e filename", required=False)
    parser.add_argument("-d", help="DECRYPT EXAMPLE: -d filename", required=False)
    args = parser.parse_args()
    try:
        password = getpass.getpass()
    except Exception as error: 
        print('ERROR', error) 
    print("\nConfirm")
    try:
        password2 = getpass.getpass()
    except Exception as error: 
        print('ERROR', error) 
    if password == password2:
        if args.e:
            filename = args.e
            encrypt(password, filename)
        if args.d:
            filename = args.d
            if filename.endswith(".aes"):
                decrypt(password, filename)
            else:
                print("\nError: Make sure file you are decrypting ends with .aes extension.\n")
    else:
        print("\nPassword does not match.")
main()

Back