-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathILBytearraysConvert.py
More file actions
69 lines (59 loc) · 1.81 KB
/
ILBytearraysConvert.py
File metadata and controls
69 lines (59 loc) · 1.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
import os
import re
import sys
import codecs
from binascii import unhexlify
def il_escape(s):
replacements = [
('\\', '\\\\'),
('"', '\\"'),
('\b', '\\b'),
('\n', '\\n'),
('\r', '\\r'),
('\t', '\\t'),
]
for orig, repl in replacements:
s = s.replace(orig, repl)
return s
def process_bytearray(hex_block):
try:
no_comment = re.sub(r'//.*', '', hex_block, flags=re.MULTILINE)
if (no_comment == hex_block):
return f'bytearray({hex_block})'
clean_hex = re.sub(r'[^0-9A-Fa-f]', '', no_comment, flags=re.IGNORECASE)
if len(clean_hex) % 2 != 0:
clean_hex += '0'
byte_data = unhexlify(clean_hex)
decoded = byte_data.decode('utf-16-le', errors='surrogatepass')
escaped = il_escape(decoded)
final = []
for c in escaped:
cp = ord(c)
if cp < 32 or (0x7F <= cp <= 0x9F) or (0xD800 <= cp <= 0xDFFF):
final.append(f'\\x{cp:02x}' if cp <= 0xFF else f'\\x{cp:04x}')
else:
final.append(c)
if (f'bytearray({hex_block})' != f'"{ "".join(final) }"'):
print(f"bytearray({hex_block}) found and replaced with { "".join(final) }")
return f'"{ "".join(final) }"'
except Exception as e:
print(f"Failed: {str(e)}", file=sys.stderr)
return f'bytearray({hex_block})'
def convert_il_file(input_path):
pattern = re.compile(
r'(ldstr\s+)bytearray\s*\(\s*((?:.|\n)*?)\)',
re.DOTALL | re.IGNORECASE
)
with open(input_path, 'r', encoding='utf-8-sig') as f:
content = f.read()
new_content = pattern.sub(
lambda m: f'{m.group(1)}{process_bytearray(m.group(2))}',
content
)
os.makedirs(os.path.dirname(input_path)+"/Repacked/",exist_ok=True)
with codecs.open(os.path.dirname(input_path)+"/Repacked/"+os.path.basename(input_path), 'w', encoding='utf-8-sig') as f:
f.write(new_content)
file = input("File: ").replace("\\","/")
if (file.endswith("/")):
file = dir[:-1]
convert_il_file(file)