-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathCSR2FileTool.py
More file actions
100 lines (94 loc) · 5.81 KB
/
CSR2FileTool.py
File metadata and controls
100 lines (94 loc) · 5.81 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
import os
import datetime
import gzip
import json
import hmac
scriptVersion = "1.0.0"
configFilePath = "./CSR2FileTool.cfg"
configObj = {}
hashKey = "4cPw3ZyC"
supportedFiles = ("nsb", "scb")
def generateLog(type, message, enabledLogs):
if enabledLogs == True:
with open("CSR2FileTool.log", "a", encoding="utf-8") as file:
file.write(f"[{type}] {datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")} {message}\n")
def unpackFiles(folderPath = "./", outputFolderPath = "./", enableLogs = False):
generateLog("INFO", f"Loaded config file: {configObj}", enableLogs)
generateLog("INFO", "Starting file unpacking...", enableLogs)
os.makedirs(outputFolderPath, exist_ok = True)
for fileName in os.listdir(folderPath):
if fileName in supportedFiles:
generateLog("INFO", f"Processing {fileName} file...", enableLogs)
try:
generateLog("INFO", f"Reading and decoding {fileName} file data...", enableLogs)
with gzip.open(f"{folderPath}/{fileName}", "r") as file:
generateLog("INFO", f"Extracting unpacked data from {fileName} file.", enableLogs)
fileLines = file.readlines()
fileHash = fileLines[0]
fileData = fileLines[1]
fileDataObj = json.loads(fileData)
try:
generateLog("INFO", f"Writing formatted unpacked data to: {outputFolderPath}/{fileName}.txt", enableLogs)
with open(f"{outputFolderPath}/{fileName}.txt", "w", encoding="utf-8") as file:
json.dump(fileDataObj, file, indent = 4)
except Exception:
generateLog("ERROR", f"Could not write the unpacked data for the {fileName} file.", enableLogs)
raise
except:
generateLog("ERROR", f"Failed to open the {fileName} file, this file might be corrupted or inaccessible.", enableLogs)
raise
os.rename(f"{folderPath}/{fileName}", f"{folderPath}/{fileName}.old")
generateLog("INFO", f"{fileName} file successfully unpacked.", enableLogs)
generateLog("INFO", "Finished unpacking all files.", enableLogs)
def packFiles(folderPath = "./", outputFolderPath = "./", enableLogs = False):
generateLog("INFO", f"Loaded config file: {configObj}", enableLogs)
generateLog("INFO", "Starting file packing...", enableLogs)
os.makedirs(outputFolderPath, exist_ok = True)
for fileName in os.listdir(folderPath):
fileNameDecomposed = fileName.split(".")
if (fileNameDecomposed[0] in supportedFiles) and (fileNameDecomposed[1] == "txt" or fileNameDecomposed[1] == "json"):
generateLog("INFO", f"Processing {fileNameDecomposed[0]} file...", enableLogs)
try:
generateLog("INFO", f"Reading and formatting {fileNameDecomposed[0]} file data...", enableLogs)
with open(f"{folderPath}/{fileName}", "r") as file:
fileDataObj = json.load(file)
minimizedString = json.dumps(fileDataObj, separators = (",", ":"))
generateLog("INFO", f"Encrypting {fileNameDecomposed[0]} file...", enableLogs)
hashStr = hmac.digest(bytes(hashKey, "utf-8"), bytes(minimizedString, "utf-8"), "sha1")
hashStr = hashStr.hex()
generateLog("INFO", f"{fileNameDecomposed[0]} file hash: {hashStr}", enableLogs)
try:
generateLog("INFO", f"Writing packed data to: {outputFolderPath}/{fileNameDecomposed[0]}", enableLogs)
with gzip.open(f"{outputFolderPath}/{fileNameDecomposed[0]}", "wb") as file:
file.write(f"{hashStr}\n{minimizedString}".encode("utf-8"))
except:
generateLog("ERROR", f"Could not write the packed data for the {fileNameDecomposed[0]} file.", enableLogs)
raise
except:
generateLog("ERROR", f"Failed to open the {fileNameDecomposed[0]} file, this file might be corrupted or inaccessible.", enableLogs)
raise
generateLog("INFO", f"{fileNameDecomposed[0]} file successfully packed.", enableLogs)
generateLog("INFO", "Finished packing all files.", enableLogs)
def executeScript():
enabledLogsBool = configObj["enableLogs"] == "true"
if configObj["method"] == "unpack":
unpackFiles(configObj["folderPath"], configObj["outputFolderPath"], enabledLogsBool)
elif configObj["method"] == "pack":
packFiles(configObj["folderPath"], configObj["outputFolderPath"], enabledLogsBool)
else:
generateLog("WARNING", "Invalid method specified in your config file. Please set \"method\" to either \"pack\" or \"unpack\".", True)
def checkConfigFile():
if os.path.isfile(configFilePath) == True:
with open(configFilePath, "r") as file:
for line in file:
line = line.strip()
if line.startswith("#") == False:
key, value = line.split("=", 1)
if (key == "scriptVersion") and (value.strip("\"") != scriptVersion):
generateLog("WARNING", "Your configuration file is outdated. New fields may have been added or changed. You can manually update it or delete the current file and re-run the script to automatically generate a new configuration file.", True)
configObj[key] = value.strip("\"")
executeScript()
else:
with open(configFilePath, "w") as file:
file.write(f"scriptVersion=\"{scriptVersion}\"\nmethod=\"pack or unpack\"\nfolderPath=\"./\"\noutputFolderPath=\"./\"\nenableLogs=\"false\"")
checkConfigFile()