-
Notifications
You must be signed in to change notification settings - Fork 16
Expand file tree
/
Copy pathfile_compressor.py
More file actions
43 lines (37 loc) · 1.51 KB
/
file_compressor.py
File metadata and controls
43 lines (37 loc) · 1.51 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
import json
import zlib
import os
class FileCompressor:
@staticmethod
def obfuscate(data, password):
return bytes(
[b ^ ord(password[i % len(password)]) for (i, b) in enumerate(data)]
)
@staticmethod
def compress_string(string_data, zip_path, password):
compressed_data = zlib.compress(string_data.encode("utf-8"))
obfuscated_data = FileCompressor.obfuscate(compressed_data, password)
with open(zip_path, "wb") as zipf:
zipf.write(obfuscated_data)
@staticmethod
def decompress_to_string(zip_path, password):
with open(zip_path, "rb") as zipf:
obfuscated_data = zipf.read()
compressed_data = FileCompressor.obfuscate(obfuscated_data, password)
return zlib.decompress(compressed_data).decode("utf-8")
@staticmethod
def compress_to_json(data, zip_path, password):
try:
json_string = json.dumps(data, indent=4, ensure_ascii=False)
FileCompressor.compress_string(json_string, zip_path, password)
except Exception as e:
print(f"Compression failed: {e}")
@staticmethod
def decompress_from_json(zip_path, password):
try:
if not os.path.exists(zip_path):
raise FileNotFoundError(f"{zip_path} does not exist")
json_string = FileCompressor.decompress_to_string(zip_path, password)
return json.loads(json_string)
except Exception as e:
print(f"Decompression failed: {e}")