- Notifications
You must be signed in to change notification settings - Fork 9
Expand file tree
/
Copy pathBAHardCodeEncoder.py
More file actions
Latest commit
301 lines (250 loc) · 11.1 KB
/
Copy pathBAHardCodeEncoder.py
File metadata and controls
301 lines (250 loc) · 11.1 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
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
#!/usr/bin/python
# -*- coding: UTF-8 -*-
instructions='''
Encode all hard code string in objective-c project.
How to use:
1. put files in /oc-class into your project
2. edit key & iv for encrypt and decrypt action in this script and NSString+BAHCCategory.h
3. edit exception settings in this script: file name, file prefix, file suffix, folder name, folder prefix, folder suffix, string format specifiers
4. pipenv install
5. start encode/decode action by command: python param1 --encode/--decode param2
param1: path of this script
param2: root path of project
6. import NSString+BAHCCategory.h and BAHCDefenitions.h globally
PS:
1. length of Key and iv for encrypt action must be a multiple of 16
2. you must skip these files: NSString+BAHCCategory.h, NSString+BAHCCategory.m, BAHCDefenitions.h, GTMBase64.h, GTMBase64.m, GTMDefines.h
3. use option --encrypt/--decrypt to encrypt/decrypt individual content
'''
#**************** Settings for defenitions & log file ***************
DefenitionFileName='BAHCDefenitions.h'
EncodeLogFileName='BAHCEncodeLog.json'
#**********************************************************************
#**************** Settings for encrypt & decrypt ********************
Key_salt='abcdef'
AES_key='9Jvae2bFOYL$JoTt'
AES_iv='yg@t2lLZXmP8&J7r'
#**********************************************************************
#******************** Settings for exception ************************
Exception_File_Names= ['NSString+BAHCCategory.h',
'NSString+BAHCCategory.m',
'BAHCDefenitions.h',
'GTMBase64.h',
'GTMBase64.m',
'GTMDefines.h']
Exception_File_Prefix= []
Exception_File_Suffix= [r'\.a', r'\.framework']
Exception_Folder_Names= ['node_modules',
'.idea',
'.git',
'Pods']
Exception_Folder_Prefix= []
Exception_Folder_Suffix= []
Exception_String_Format_Specifiers= ['%@', '%%', '%d', '%D', '%u', '%U', '%x', '%X',
'%o', '%O', '%f', '%e', '%E', '%g', '%G', '%c',
'%C', '%s', '%S', '%p', '%a', '%A', '%F', '%zd']
Encode_Escape_Characters_Key= ['\\\n', '\\n', '\\a', '\\b', '\\f', '\\r', '\\t', '\\v', '\\"', '\\0', '\\\\']
Encode_Escape_Characters_Value= ['', '\n', '\a', '\b', '\f', '\r', '\t', '\v', '\"', '', '\\']
#**********************************************************************
importsys, os, hashlib, json
fromService.BAFileDecoderimportBAFileDecoder
fromService.BAFileEncoderimportBAFileEncoder
fromService.BAExceptionHelperimportBAExceptionHelper
fromUtils.BAFileUtilimportBAFileUtil
fromUtils.BAErrorUtilimportBAErrorUtil, BAErrorGrade
fromUtils.BAEncryptUtilimportBAEncryptUtil
fromBAAlgorithmUtils.SBOMUtilimportSBOMUtil
def__decodeAction(rootName, rootDir, stringSearchUtil, replaceDic, exceptionHelper):
ifstringSearchUtil==None:
return
ifreplaceDic==Noneorlen(replaceDic) ==0:
return
ifexceptionHelper.shouldSkipFolder(rootName, rootDir) ==True:
return
forfileNameinos.listdir(rootDir):
filePath=os.path.join(rootDir, fileName)
if (os.path.isdir(filePath)):
__decodeAction(fileName, filePath, stringSearchUtil, replaceDic, exceptionHelper)
else:
ifexceptionHelper.shouldSkipFile(fileName, filePath) ==True:
BAErrorUtil.printError(BAErrorGrade.normal, 'Skip file: '+filePath)
continue
fileHandler=open(filePath, 'r')
newFileContent=fileHandler.read()
fileHandler.close()
searchResult=stringSearchUtil.search(newFileContent)
ifsearchResult==Noneorlen(searchResult) ==0:
BAErrorUtil.printError(BAErrorGrade.normal, 'Skip file: '+filePath)
continue
needRewrite=False
forkey, indexsinsearchResult.items():
ifindexs!=Noneandlen(indexs) >0andkeyinreplaceDic:
newFileContent=newFileContent.replace(key, '@"'+replaceDic[key] +'"')
needRewrite=True
else:
BAErrorUtil.printError(BAErrorGrade.normal, 'Skip file: '+filePath)
ifneedRewrite==True:
BAErrorUtil.printError(BAErrorGrade.success, 'Decoded: '+filePath)
newFileHandler=open(filePath, 'w')
newFileHandler.seek(0)
newFileHandler.truncate()
newFileHandler.write(newFileContent)
newFileHandler.close()
def__decode(rootPath):
BAErrorUtil.printError(BAErrorGrade.normal, '👉 Decode action, here we go!')
ifrootPath==None:
BAErrorUtil.printError(BAErrorGrade.error, 'ERROR: Project root path None!')
return
tmpRootPath=rootPath+'/'
tmpRootPath=tmpRootPath.replace("//", "/")
#check key and iv length
ifAES_key==NoneorAES_iv==None:
BAErrorUtil.printError(BAErrorGrade.error, "ERROR: Key and iv for encrypt action can't be null!")
return
iflen(AES_key) %16!=0orlen(AES_iv) %16!=0:
BAErrorUtil.printError(BAErrorGrade.error, 'ERROR: Length of key and iv for encrypt action must be a multiple of 16!')
return
#find encode log file
possiblePaths=BAFileUtil.findTargetPaths(EncodeLogFileName, False, tmpRootPath)
ifpossiblePaths==Noneorlen(possiblePaths) ==0:
BAErrorUtil.printError(BAErrorGrade.error, "ERROR: Can't find BAHCDefenitions.h !")
return
encodeLogFilePath=possiblePaths[0]
#read contents in encode log file
encodeLogFileFileHandler=open(encodeLogFilePath, 'r')
ifencodeLogFileFileHandler==None:
BAErrorUtil.printError(BAErrorGrade.error, "ERROR: Can't read BAHCDefenitions.h !")
return
encodeLogContent=encodeLogFileFileHandler.read()
encodeLogFileFileHandler.close()
encodeLog=json.loads(encodeLogContent)
replaceDic= {}
sbomUtil=SBOMUtil()
forlogIteminencodeLog:
key=logItem['key']
sbomUtil.train(key)
replaceDic[key] =logItem['oldUnCleanContent']
sbomUtil.prepare()
exceptionHelper=BAExceptionHelper()
exceptionHelper.excFolderNames=Exception_Folder_Names
exceptionHelper.excFolderPrefixes=Exception_Folder_Prefix
exceptionHelper.excFolderSuffixes=Exception_Folder_Suffix
exceptionHelper.excFileNames=Exception_File_Names
exceptionHelper.excFilePrefixes=Exception_File_Prefix
exceptionHelper.excFileSuffixes=Exception_File_Suffix
#start decode
__decodeAction('', tmpRootPath, sbomUtil, replaceDic, exceptionHelper)
BAErrorUtil.printError(BAErrorGrade.normal, '👌 Finished!')
def__convertEscapeCharacterForEncode(source):
result=source
foriinrange(len(Encode_Escape_Characters_Key)):
result=result.replace(Encode_Escape_Characters_Key[i], Encode_Escape_Characters_Value[i])
returnresult
def__encryptFunc(content, unCleanContent, filePath, line, column):
ifcontent==Noneorlen(content) ==0:
returnNone, None
key='BAHCKey'+hashlib.md5((Key_salt+'NEW_NAME_FOR_'+content+'_OF_'+filePath+'_AT_'+str(line) +':'+str(column)).encode(encoding='UTF-8')).hexdigest()
newContent='[@"'+BAEncryptUtil.AESEncrypt(__convertEscapeCharacterForEncode(content), AES_key, AES_iv) +'" BAHC_Decrypt]'
returnkey, newContent
def__encodeAction(rootName, rootDir, outputFileHandler, logFileHandler, encoder, exceptionHelper):
ifexceptionHelper.shouldSkipFolder(rootName, rootDir) ==True:
return
forfileNameinos.listdir(rootDir):
filePath=os.path.join(rootDir, fileName)
if (os.path.isdir(filePath)):
__encodeAction(fileName, filePath, outputFileHandler, logFileHandler, encoder, exceptionHelper)
else:
ifexceptionHelper.shouldSkipFile(fileName, filePath) ==True:
BAErrorUtil.printError(BAErrorGrade.normal, 'Skip file: '+filePath)
continue
logs, newContent, error=encoder.encode(fileName, filePath)
iferror!=None:
BAErrorUtil.printErrorModel(error)
eliflen(logs) >0:
tmpFileHandler=open(filePath, 'w')
tmpFileHandler.seek(0)
tmpFileHandler.truncate()
tmpFileHandler.write(newContent)
tmpFileHandler.close()
ifoutputFileHandler:
forlogIteminlogs:
outputFileHandler.write('#define '+logItem['key'] +' '+logItem['newContent'] +'\n')
iflogFileHandler:
logString=json.dumps(logs)
logFileHandler.write(logString[1: len(logString) -1] +',')
BAErrorUtil.printError(BAErrorGrade.success, 'Encoded: '+filePath)
else:
BAErrorUtil.printError(BAErrorGrade.normal, 'Skip file: '+filePath)
def__encode(rootPath):
BAErrorUtil.printError(BAErrorGrade.normal, '👉 Encode action, Here we go!')
ifrootPath==None:
BAErrorUtil.printError(BAErrorGrade.error, 'ERROR: Project root path None!')
return
rootPathTmp=rootPath.replace("//", "/")
#check key and iv length
ifAES_key==NoneorAES_iv==None:
BAErrorUtil.printError(BAErrorGrade.error, "ERROR: Key and iv for encrypt action can't be null!")
return
iflen(AES_key) %16!=0orlen(AES_iv) %16!=0:
BAErrorUtil.printError(BAErrorGrade.error, "ERROR: Length of key and iv for encrypt action must be a multiple of 16!")
return
#check key & value of escape characters
ifisinstance(Encode_Escape_Characters_Key, list) ==Falseorisinstance(Encode_Escape_Characters_Value, list) ==False:
BAErrorUtil.printError(BAErrorGrade.error, "ERROR: List escape characters key or value can't be None!")
return
iflen(Encode_Escape_Characters_Key) !=len(Encode_Escape_Characters_Value):
BAErrorUtil.printError(BAErrorGrade.error, "ERROR: Length of escape characters key and value list must be equal!")
return
#creat defenition file
defenitionFilePath=rootPathTmp+'/'+DefenitionFileName
defenitionFilePath=defenitionFilePath.replace("//", "/")
ifos.path.exists(defenitionFilePath):
os.remove(defenitionFilePath)
#creat log file
logFilePath=rootPathTmp+'/'+EncodeLogFileName
logFilePath=logFilePath.replace("//", "/")
ifos.path.exists(logFilePath):
os.remove(logFilePath)
#start analyze
encoder=BAFileEncoder()
encoder.excChars=Exception_String_Format_Specifiers
encoder.encryptFunc=__encryptFunc
exceptionHelper=BAExceptionHelper()
exceptionHelper.excFolderNames=Exception_Folder_Names
exceptionHelper.excFolderPrefixes=Exception_Folder_Prefix
exceptionHelper.excFolderSuffixes=Exception_Folder_Suffix
exceptionHelper.excFileNames=Exception_File_Names
exceptionHelper.excFilePrefixes=Exception_File_Prefix
exceptionHelper.excFileSuffixes=Exception_File_Suffix
defenitionFilePathHandler=open(defenitionFilePath, 'w+')
logFilePathHandler=open(logFilePath, 'w+')
logFilePathHandler.write('[')
__encodeAction('', rootPathTmp, defenitionFilePathHandler, logFilePathHandler, encoder, exceptionHelper)
logFilePathHandler.seek(logFilePathHandler.tell()-1, 0)
logFilePathHandler.truncate()
logFilePathHandler.write(']')
logFilePathHandler.close()
defenitionFilePathHandler.close()
BAErrorUtil.printError(BAErrorGrade.normal, '👌 Finished!')
if__name__=='__main__':
iflen(sys.argv) <2:
quit()
firstParam=sys.argv[1]
iffirstParam=='--encrypt':
content=input('\033[1;32mContent: \033[0m')
key=input('\033[1;32mKey: \033[0m')
iv=input('\033[1;32mIV: \033[0m')
print(BAEncryptUtil.AESEncrypt(content, key, iv))
quit()
iffirstParam=='--decrypt':
content=input('\033[1;32mContent: \033[0m')
key=input('\033[1;32mKey: \033[0m')
iv=input('\033[1;32mIV: \033[0m')
print(BAEncryptUtil.AESDecrypt(content, key, iv))
quit()
iflen(sys.argv) >=3:
iffirstParam=='--decode':
__decode(sys.argv[2])
pass
eliffirstParam=='--encode':
__encode(sys.argv[2])