package fun.nursultan.config;
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 ConfigStorage {
public final Logger logger = Logger.getLogger(ConfigStorage.class.getName());
public final File CONFIG_DIR = new File(Minecraft.getInstance().gameDir, "\\expensive\\configs");
public final File AUTOCFG_DIR = new File(CONFIG_DIR, "autocfg.cfg");
public final JsonParser jsonParser = new JsonParser();
private static final String ALGORITHM = "AES";
public void init() throws IOException {
setupFolder();
}
public void setupFolder() {
if (!CONFIG_DIR.exists()) {
CONFIG_DIR.mkdirs();
} else if (AUTOCFG_DIR.exists()) {
loadConfiguration("system", "defaultKey12345678");
logger.log(Level.SEVERE, "Load system configuration...");
} else {
logger.log(Level.SEVERE, "Creating system configuration...");
try {
AUTOCFG_DIR.createNewFile();
logger.log(Level.SEVERE, "Created!");
} catch (IOException e) {
logger.log(Level.SEVERE, "Failed to create system configuration 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(".cfg")) {
String configName = configFile.getName().replace(".cfg", "");
Config config = findConfig(configName);
if (config != null) {
configs.add(config);
}
}
}
}
return configs;
}
public void loadConfiguration(String configuration, String secretKey) {
Config config = findConfig(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);
} 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);
} 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 + ".cfg");
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));
}
}