Подпишитесь на наш Telegram-канал, чтобы всегда быть в курсе важных обновлений! Перейти

Часть функционала AutoCfg | Expensive 3.1

Начинающий
Начинающий
Статус
Оффлайн
Регистрация
17 Фев 2025
Сообщения
121
Реакции
2
Выберите загрузчик игры
  1. OptiFine
По факту на югейме я не видел автокфг под экспу(нет не верьте мне я видел но в них нет автозагрузки) так что выкладываю свой мега селфкодд
AutoCfg.java:
Expand Collapse Copy
package wtf.mimi.love.Storage;

import com.google.gson.GsonBuilder;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import net.minecraft.client.Minecraft;

import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;
import java.io.*;
import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.util.ArrayList;
import java.util.Base64;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;

public class HashedConfigSave {
    public final Logger logger = Logger.getLogger(HashedConfigSave.class.getName());

    public final File CONFIG_DIR = new File(Minecraft.getInstance().gameDir, "\\mimi.love\\configs");
    public final File AUTOCFG_DIR = new File(CONFIG_DIR, "autocfg.mimilove");
    public final JsonParser jsonParser = new JsonParser();
    private static final String ALGORITHM = "AES";
    private static final String SECRET_KEY = "defaultKey12345678";
    private boolean initialized = false;
    private final Minecraft mc = Minecraft.getInstance();

    public void init() throws IOException {
        if (initialized) return;
        initialized = true;
        setupFolder();
        loadAutoConfig();
        Runtime.getRuntime().addShutdownHook(new Thread(this::saveAutoConfig));
    }

    public void loadAutoConfig() {
        if (AUTOCFG_DIR.exists()) {
            loadConfiguration("autocfg", SECRET_KEY);
            logger.log(Level.INFO, "Auto-config loaded successfully");
        } else {
            logger.log(Level.INFO, "No auto-config found, creating default");
            writeDefaultConfig();
        }
    }

    public void saveAutoConfig() {
        saveConfiguration("autocfg", SECRET_KEY);
        logger.log(Level.INFO, "Auto-config saved successfully");
    }

    public void writeDefaultConfig() {
        String json = """
                {
                  "Modules": {
                  },
                  "styles": {
                  },
                  "draggables": [
                  ]
                }
                """;

        try (FileWriter writer = new FileWriter(AUTOCFG_DIR)) {
            writer.write(json);
            writer.flush();
            logger.log(Level.INFO, "Created default system configuration!");
        } catch (IOException e) {
            logger.log(Level.INFO, "Failed to create default system configuration file", e);
        }
    }

    public void setupFolder() {
        if (!CONFIG_DIR.exists()) {
            CONFIG_DIR.mkdirs();
        }

        if (!AUTOCFG_DIR.exists()) {
            try {
                AUTOCFG_DIR.createNewFile();
            } catch (IOException e) {
                logger.log(Level.SEVERE, "Failed to create autocfg file", e);
            }
        }
    }

    public boolean isEmpty() {
        return getConfigs().isEmpty();
    }

    public List<Config> getConfigs() {
        List<Config> configs = new ArrayList<>();
        File[] configFiles = CONFIG_DIR.listFiles();

        if (configFiles != null) {
            for (File configFile : configFiles) {
                if (configFile.isFile() && configFile.getName().endsWith(".mimilove")) {
                    String configFunction = configFile.getName().replace(".mimilove", "");
                    Config config = findConfig(configFunction);
                    if (config != null) {
                        configs.add(config);
                    }
                }
            }
        }

        return configs;
    }

    public void loadConfiguration(String configuration, String secretKey) {
        Config config = findConfig(configuration);
        Config.currentConfig = configuration;
        if (config == null) {
            logger.log(Level.WARNING, "Шоккк! Конфигурация не найдена! " + configuration);
            return;
        }

        try (BufferedReader reader = new BufferedReader(new FileReader(config.getFile()))) {
            String encryptedContent = reader.readLine();

            if (encryptedContent == null || encryptedContent.isEmpty()) {
                logger.log(Level.WARNING, "Что ты хочешь загрузть если там нихуя нет?");
                return;
            }

            String decryptedContent = decrypt(encryptedContent, secretKey);
            JsonObject object = (JsonObject) jsonParser.parse(decryptedContent);
            config.loadConfig(object);
            logger.log(Level.INFO, "Кайф спастил кфг!" + configuration);

        } catch (FileNotFoundException e) {
            logger.log(Level.WARNING, "Заебал" + config.getFile().getName(), e);
        } catch (Exception e) {
            logger.log(Level.WARNING, "Зачем я пишу эти подсказки", e);
        }
    }
    public void saveConfiguration(String configuration, String secretKey) {
        Config config = new Config(configuration);
        String contentPrettyPrint = new GsonBuilder().setPrettyPrinting().create().toJson(config.saveConfig());

        try (FileWriter writer = new FileWriter(config.getFile())) {
            if (contentPrettyPrint.isEmpty()) {
                logger.log(Level.WARNING, "");
                return;
            }

            String encryptedContent = encrypt(contentPrettyPrint, secretKey);
            writer.write(encryptedContent);
            logger.log(Level.INFO, "" + configuration);

        } catch (IOException e) {
            logger.log(Level.WARNING, "", e);
        } catch (Exception e) {
            logger.log(Level.WARNING, "", e);
        }
    }

    public Config findConfig(String configName) {
        if (configName == null) return null;
        File configFile = new File(CONFIG_DIR, configName + ".mimilove");
        if (configFile.exists()) {
            return new Config(configName);
        }
        return null;
    }

    public String encrypt(String data, String secretKey) throws Exception {
        Cipher cipher = Cipher.getInstance(ALGORITHM);
        SecretKeySpec key = new SecretKeySpec(hashKey(secretKey), ALGORITHM);
        cipher.init(Cipher.ENCRYPT_MODE, key);
        byte[] encryptedData = cipher.doFinal(data.getBytes(StandardCharsets.UTF_8));
        return Base64.getEncoder().encodeToString(encryptedData);
    }

    public String decrypt(String encryptedData, String secretKey) throws Exception {
        Cipher cipher = Cipher.getInstance(ALGORITHM);
        SecretKeySpec key = new SecretKeySpec(hashKey(secretKey), ALGORITHM);
        cipher.init(Cipher.DECRYPT_MODE, key);
        byte[] decryptedData = cipher.doFinal(Base64.getDecoder().decode(encryptedData));
        return new String(decryptedData, StandardCharsets.UTF_8);
    }

    private byte[] hashKey(String key) throws Exception {
        MessageDigest sha = MessageDigest.getInstance("SHA-256");
        return sha.digest(key.getBytes(StandardCharsets.UTF_8));
    }
}

SS - зачем?
Фикс драгов
 
По факту на югейме я не видел автокфг под экспу(нет не верьте мне я видел но в них нет автозагрузки) так что выкладываю свой мега селфкодд
AutoCfg.java:
Expand Collapse Copy
package wtf.mimi.love.Storage;

import com.google.gson.GsonBuilder;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import net.minecraft.client.Minecraft;

import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;
import java.io.*;
import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.util.ArrayList;
import java.util.Base64;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;

public class HashedConfigSave {
    public final Logger logger = Logger.getLogger(HashedConfigSave.class.getName());

    public final File CONFIG_DIR = new File(Minecraft.getInstance().gameDir, "\\mimi.love\\configs");
    public final File AUTOCFG_DIR = new File(CONFIG_DIR, "autocfg.mimilove");
    public final JsonParser jsonParser = new JsonParser();
    private static final String ALGORITHM = "AES";
    private static final String SECRET_KEY = "defaultKey12345678";
    private boolean initialized = false;
    private final Minecraft mc = Minecraft.getInstance();

    public void init() throws IOException {
        if (initialized) return;
        initialized = true;
        setupFolder();
        loadAutoConfig();
        Runtime.getRuntime().addShutdownHook(new Thread(this::saveAutoConfig));
    }

    public void loadAutoConfig() {
        if (AUTOCFG_DIR.exists()) {
            loadConfiguration("autocfg", SECRET_KEY);
            logger.log(Level.INFO, "Auto-config loaded successfully");
        } else {
            logger.log(Level.INFO, "No auto-config found, creating default");
            writeDefaultConfig();
        }
    }

    public void saveAutoConfig() {
        saveConfiguration("autocfg", SECRET_KEY);
        logger.log(Level.INFO, "Auto-config saved successfully");
    }

    public void writeDefaultConfig() {
        String json = """
                {
                  "Modules": {
                  },
                  "styles": {
                  },
                  "draggables": [
                  ]
                }
                """;

        try (FileWriter writer = new FileWriter(AUTOCFG_DIR)) {
            writer.write(json);
            writer.flush();
            logger.log(Level.INFO, "Created default system configuration!");
        } catch (IOException e) {
            logger.log(Level.INFO, "Failed to create default system configuration file", e);
        }
    }

    public void setupFolder() {
        if (!CONFIG_DIR.exists()) {
            CONFIG_DIR.mkdirs();
        }

        if (!AUTOCFG_DIR.exists()) {
            try {
                AUTOCFG_DIR.createNewFile();
            } catch (IOException e) {
                logger.log(Level.SEVERE, "Failed to create autocfg file", e);
            }
        }
    }

    public boolean isEmpty() {
        return getConfigs().isEmpty();
    }

    public List<Config> getConfigs() {
        List<Config> configs = new ArrayList<>();
        File[] configFiles = CONFIG_DIR.listFiles();

        if (configFiles != null) {
            for (File configFile : configFiles) {
                if (configFile.isFile() && configFile.getName().endsWith(".mimilove")) {
                    String configFunction = configFile.getName().replace(".mimilove", "");
                    Config config = findConfig(configFunction);
                    if (config != null) {
                        configs.add(config);
                    }
                }
            }
        }

        return configs;
    }

    public void loadConfiguration(String configuration, String secretKey) {
        Config config = findConfig(configuration);
        Config.currentConfig = configuration;
        if (config == null) {
            logger.log(Level.WARNING, "Шоккк! Конфигурация не найдена! " + configuration);
            return;
        }

        try (BufferedReader reader = new BufferedReader(new FileReader(config.getFile()))) {
            String encryptedContent = reader.readLine();

            if (encryptedContent == null || encryptedContent.isEmpty()) {
                logger.log(Level.WARNING, "Что ты хочешь загрузть если там нихуя нет?");
                return;
            }

            String decryptedContent = decrypt(encryptedContent, secretKey);
            JsonObject object = (JsonObject) jsonParser.parse(decryptedContent);
            config.loadConfig(object);
            logger.log(Level.INFO, "Кайф спастил кфг!" + configuration);

        } catch (FileNotFoundException e) {
            logger.log(Level.WARNING, "Заебал" + config.getFile().getName(), e);
        } catch (Exception e) {
            logger.log(Level.WARNING, "Зачем я пишу эти подсказки", e);
        }
    }
    public void saveConfiguration(String configuration, String secretKey) {
        Config config = new Config(configuration);
        String contentPrettyPrint = new GsonBuilder().setPrettyPrinting().create().toJson(config.saveConfig());

        try (FileWriter writer = new FileWriter(config.getFile())) {
            if (contentPrettyPrint.isEmpty()) {
                logger.log(Level.WARNING, "");
                return;
            }

            String encryptedContent = encrypt(contentPrettyPrint, secretKey);
            writer.write(encryptedContent);
            logger.log(Level.INFO, "" + configuration);

        } catch (IOException e) {
            logger.log(Level.WARNING, "", e);
        } catch (Exception e) {
            logger.log(Level.WARNING, "", e);
        }
    }

    public Config findConfig(String configName) {
        if (configName == null) return null;
        File configFile = new File(CONFIG_DIR, configName + ".mimilove");
        if (configFile.exists()) {
            return new Config(configName);
        }
        return null;
    }

    public String encrypt(String data, String secretKey) throws Exception {
        Cipher cipher = Cipher.getInstance(ALGORITHM);
        SecretKeySpec key = new SecretKeySpec(hashKey(secretKey), ALGORITHM);
        cipher.init(Cipher.ENCRYPT_MODE, key);
        byte[] encryptedData = cipher.doFinal(data.getBytes(StandardCharsets.UTF_8));
        return Base64.getEncoder().encodeToString(encryptedData);
    }

    public String decrypt(String encryptedData, String secretKey) throws Exception {
        Cipher cipher = Cipher.getInstance(ALGORITHM);
        SecretKeySpec key = new SecretKeySpec(hashKey(secretKey), ALGORITHM);
        cipher.init(Cipher.DECRYPT_MODE, key);
        byte[] decryptedData = cipher.doFinal(Base64.getDecoder().decode(encryptedData));
        return new String(decryptedData, StandardCharsets.UTF_8);
    }

    private byte[] hashKey(String key) throws Exception {
        MessageDigest sha = MessageDigest.getInstance("SHA-256");
        return sha.digest(key.getBytes(StandardCharsets.UTF_8));
    }
}

SS - зачем?
Фикс драгов
итак, хеширование кфг из экселента у тебя это мега селфкод, автокфг вообще можно легче написать и смысла в этом дерьме нет
 
Последнее редактирование:
По факту на югейме я не видел автокфг под экспу(нет не верьте мне я видел но в них нет автозагрузки) так что выкладываю свой мега селфкодд
AutoCfg.java:
Expand Collapse Copy
package wtf.mimi.love.Storage;

import com.google.gson.GsonBuilder;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import net.minecraft.client.Minecraft;

import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;
import java.io.*;
import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.util.ArrayList;
import java.util.Base64;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;

public class HashedConfigSave {
    public final Logger logger = Logger.getLogger(HashedConfigSave.class.getName());

    public final File CONFIG_DIR = new File(Minecraft.getInstance().gameDir, "\\mimi.love\\configs");
    public final File AUTOCFG_DIR = new File(CONFIG_DIR, "autocfg.mimilove");
    public final JsonParser jsonParser = new JsonParser();
    private static final String ALGORITHM = "AES";
    private static final String SECRET_KEY = "defaultKey12345678";
    private boolean initialized = false;
    private final Minecraft mc = Minecraft.getInstance();

    public void init() throws IOException {
        if (initialized) return;
        initialized = true;
        setupFolder();
        loadAutoConfig();
        Runtime.getRuntime().addShutdownHook(new Thread(this::saveAutoConfig));
    }

    public void loadAutoConfig() {
        if (AUTOCFG_DIR.exists()) {
            loadConfiguration("autocfg", SECRET_KEY);
            logger.log(Level.INFO, "Auto-config loaded successfully");
        } else {
            logger.log(Level.INFO, "No auto-config found, creating default");
            writeDefaultConfig();
        }
    }

    public void saveAutoConfig() {
        saveConfiguration("autocfg", SECRET_KEY);
        logger.log(Level.INFO, "Auto-config saved successfully");
    }

    public void writeDefaultConfig() {
        String json = """
                {
                  "Modules": {
                  },
                  "styles": {
                  },
                  "draggables": [
                  ]
                }
                """;

        try (FileWriter writer = new FileWriter(AUTOCFG_DIR)) {
            writer.write(json);
            writer.flush();
            logger.log(Level.INFO, "Created default system configuration!");
        } catch (IOException e) {
            logger.log(Level.INFO, "Failed to create default system configuration file", e);
        }
    }

    public void setupFolder() {
        if (!CONFIG_DIR.exists()) {
            CONFIG_DIR.mkdirs();
        }

        if (!AUTOCFG_DIR.exists()) {
            try {
                AUTOCFG_DIR.createNewFile();
            } catch (IOException e) {
                logger.log(Level.SEVERE, "Failed to create autocfg file", e);
            }
        }
    }

    public boolean isEmpty() {
        return getConfigs().isEmpty();
    }

    public List<Config> getConfigs() {
        List<Config> configs = new ArrayList<>();
        File[] configFiles = CONFIG_DIR.listFiles();

        if (configFiles != null) {
            for (File configFile : configFiles) {
                if (configFile.isFile() && configFile.getName().endsWith(".mimilove")) {
                    String configFunction = configFile.getName().replace(".mimilove", "");
                    Config config = findConfig(configFunction);
                    if (config != null) {
                        configs.add(config);
                    }
                }
            }
        }

        return configs;
    }

    public void loadConfiguration(String configuration, String secretKey) {
        Config config = findConfig(configuration);
        Config.currentConfig = configuration;
        if (config == null) {
            logger.log(Level.WARNING, "Шоккк! Конфигурация не найдена! " + configuration);
            return;
        }

        try (BufferedReader reader = new BufferedReader(new FileReader(config.getFile()))) {
            String encryptedContent = reader.readLine();

            if (encryptedContent == null || encryptedContent.isEmpty()) {
                logger.log(Level.WARNING, "Что ты хочешь загрузть если там нихуя нет?");
                return;
            }

            String decryptedContent = decrypt(encryptedContent, secretKey);
            JsonObject object = (JsonObject) jsonParser.parse(decryptedContent);
            config.loadConfig(object);
            logger.log(Level.INFO, "Кайф спастил кфг!" + configuration);

        } catch (FileNotFoundException e) {
            logger.log(Level.WARNING, "Заебал" + config.getFile().getName(), e);
        } catch (Exception e) {
            logger.log(Level.WARNING, "Зачем я пишу эти подсказки", e);
        }
    }
    public void saveConfiguration(String configuration, String secretKey) {
        Config config = new Config(configuration);
        String contentPrettyPrint = new GsonBuilder().setPrettyPrinting().create().toJson(config.saveConfig());

        try (FileWriter writer = new FileWriter(config.getFile())) {
            if (contentPrettyPrint.isEmpty()) {
                logger.log(Level.WARNING, "");
                return;
            }

            String encryptedContent = encrypt(contentPrettyPrint, secretKey);
            writer.write(encryptedContent);
            logger.log(Level.INFO, "" + configuration);

        } catch (IOException e) {
            logger.log(Level.WARNING, "", e);
        } catch (Exception e) {
            logger.log(Level.WARNING, "", e);
        }
    }

    public Config findConfig(String configName) {
        if (configName == null) return null;
        File configFile = new File(CONFIG_DIR, configName + ".mimilove");
        if (configFile.exists()) {
            return new Config(configName);
        }
        return null;
    }

    public String encrypt(String data, String secretKey) throws Exception {
        Cipher cipher = Cipher.getInstance(ALGORITHM);
        SecretKeySpec key = new SecretKeySpec(hashKey(secretKey), ALGORITHM);
        cipher.init(Cipher.ENCRYPT_MODE, key);
        byte[] encryptedData = cipher.doFinal(data.getBytes(StandardCharsets.UTF_8));
        return Base64.getEncoder().encodeToString(encryptedData);
    }

    public String decrypt(String encryptedData, String secretKey) throws Exception {
        Cipher cipher = Cipher.getInstance(ALGORITHM);
        SecretKeySpec key = new SecretKeySpec(hashKey(secretKey), ALGORITHM);
        cipher.init(Cipher.DECRYPT_MODE, key);
        byte[] decryptedData = cipher.doFinal(Base64.getDecoder().decode(encryptedData));
        return new String(decryptedData, StandardCharsets.UTF_8);
    }

    private byte[] hashKey(String key) throws Exception {
        MessageDigest sha = MessageDigest.getInstance("SHA-256");
        return sha.digest(key.getBytes(StandardCharsets.UTF_8));
    }
}

SS - зачем?
Фикс драгов
что за чудо, не легче просто создать метод, инитнуть в закрытии майна и в нем сделать ConfigStorage.saveConfig("autocfg")? Дефолт система сама этот конфиг подгрузит при запуске
 
что за чудо, не легче просто создать метод, инитнуть в закрытии майна и в нем сделать ConfigStorage.saveConfig("autocfg")? Дефолт система сама этот конфиг подгрузит при запуске
Ана крашет
 
Обратите внимание, пользователь заблокирован на форуме. Не рекомендуется проводить сделки.
вы че? зайдите в свой инцилизатор создайте 2 метода stop и start прорегайте их в Main.java и ебашьте сохрание/загрузку
 
Назад
Сверху Снизу