Jump to content

Model Encrypter system


Recommended Posts

 Hi everyone,

I've been working on a Model Encrypter system and successfully created a script for it. All the steps for encoding and decoding were implemented correctly, and everything works as expected. However, unfortunately, it doesn't seem to be supported in MTA.

I also checked out systems like pcrypt and even created a similar one using Python. While the encoding and decoding processes work perfectly, it still doesn't function properly within MTA.

 

If anyone can help with this or has a sample code for implementing such a system, please share it. Thanks!

 

@Patrick

Link to comment

I once tried to do something similar. My method was to use MTA’s built-in encode/decode functions to read the file contents, encode them, and save the result. The already encoded file would then be downloaded by the client and decoded afterward.

For me, this worked fine, and as far as I remember, it only affected the model's loading time slightly, but not in a significant way. The model itself loaded perfectly without any bugs or performance drops.

However, I feel like my method isn't the best, and there’s probably a better approach. But as an option, it might still be possible. 🤷‍♀️

Link to comment

Could you share your script that you've already started so we can find the bugs and fix them? Also, note that at some point the model will always be decoded and loaded into memory, so a player with the right tools can still get it.

Link to comment
import os
import random
import logging
import argparse


class KeyManager:
    def __init__(self, key_file="key.pcrypt"):
        self.key_file = key_file

    def generate_random_key(self):
        """Generates a random key and saves it to the key file."""
        key = random.randint(0, 255)
        self.save_key(key)
        return key

    def load_key(self):
        """Loads the encryption key from the key file, or generates a new one if not found."""
        if os.path.exists(self.key_file):
            return self.read_key_from_file()
        return self.generate_random_key()

    def read_key_from_file(self):
        """Reads the key from the key file."""
        try:
            with open(self.key_file, "rb") as f:
                return ord(f.read(1))
        except Exception as e:
            logging.error(f"Error reading key from file: {e}")
            raise

    def save_key(self, key):
        """Saves the encryption key to the key file."""
        try:
            with open(self.key_file, "wb") as f:
                f.write(bytes([key]))
        except Exception as e:
            logging.error(f"Error saving key to file: {e}")
            raise


class FileProcessor:
    def __init__(self, key_manager):
        self.key_manager = key_manager
        self.key = self.key_manager.load_key()

    def xor_encrypt_decrypt(self, data, key):
        """Encrypts or decrypts data using the XOR operation."""
        return bytes(byte ^ key for byte in data)

    def process_file(self, file_path):
        """Encrypts a file and saves the encrypted version with the '.pcrypt' extension."""
        try:
            with open(file_path, "rb") as file:
                data = file.read()

            encrypted_data = self.xor_encrypt_decrypt(data, self.key)

            encrypted_file_path = f"{file_path}.pcrypt"
            with open(encrypted_file_path, "wb") as encrypted_file:
                encrypted_file.write(encrypted_data)

            logging.info(f"File '{file_path}' encrypted and saved as '{encrypted_file_path}'")
        except Exception as e:
            logging.error(f"Error processing file '{file_path}': {e}")

    def encrypt_files_in_directory(self, directory):
        """Encrypts all files in the given directory and its subdirectories."""
        for root, _, files in os.walk(directory):
            for file in files:
                file_path = os.path.join(root, file)
                self.process_file(file_path)


class DirectoryHandler:
    def __init__(self, directory=None):
        self.directory = directory

    def get_directory_from_user(self):
        """Prompts the user to enter a directory path if not provided."""
        if not self.directory:
            self.directory = input("Please enter the directory path to encrypt files: ").strip()
        if not os.path.isdir(self.directory):
            logging.error(f"The provided directory '{self.directory}' is invalid.")
            raise ValueError(f"The directory '{self.directory}' is invalid.")
        return self.directory


class EncryptionApp:
    def __init__(self, directory=None):
        self.directory_handler = DirectoryHandler(directory)
        self.key_manager = KeyManager()
        self.file_processor = FileProcessor(self.key_manager)

    def run(self):
        """Runs the encryption process."""
        try:
            target_directory = self.directory_handler.get_directory_from_user()
            self.file_processor.encrypt_files_in_directory(target_directory)
            logging.info("Encryption process completed successfully.")
        except Exception as e:
            logging.error(f"Encryption process failed: {e}")


def parse_arguments():
    """Parse command line arguments using argparse."""
    parser = argparse.ArgumentParser(description="Encrypt all files in a directory using XOR encryption.")
    parser.add_argument("-d", "--directory", type=str, help="Directory to encrypt files in.")
    return parser.parse_args()


if __name__ == "__main__":
    logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(message)s')

    # Parse arguments to handle optional directory input from the user via CLI
    args = parse_arguments()

    # Initialize and run the encryption application
    app = EncryptionApp(args.directory)
    app.run()

 

XOR Encryption Script Overview

This script uses the XOR algorithm to encrypt and decrypt files. It operates with a single-byte key (0-255), which is used to transform the file data by applying the XOR operation.

Key Features:

  • Key Management: The key is either loaded from a file (key.pcrypt) or randomly generated if not found.
  • File Encryption: Each file in the specified directory is read, XOR-encrypted with the key, and saved with a .pcrypt extension.
  • Directory Handling: The user is prompted to enter the directory path, and all files in that directory are encrypted.

Technical Details:

  • The XOR algorithm is reversible, so the same key can be used for both encryption and decryption.
  • The files are saved with the .pcrypt extension to signify they are encrypted.
Link to comment

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
  • Recently Browsing   0 members

    • No registered users viewing this page.
×
×
  • Create New...