Skip to content

Commit

Permalink
parse_java functionized
Browse files Browse the repository at this point in the history
  • Loading branch information
namaek2 committed Aug 2, 2024
1 parent e32f7ea commit 294b905
Show file tree
Hide file tree
Showing 14 changed files with 837 additions and 28 deletions.
310 changes: 310 additions & 0 deletions src/main/resources/jumbotron-image.1920e0770dc6.svg
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
12 changes: 9 additions & 3 deletions src/main/resources/pyscripts/check_hash
Original file line number Diff line number Diff line change
@@ -1,3 +1,9 @@
main 96c29c93a496e6dbd73414157005a3f8
removeComments 3c77e514c7a6095124abc318b6093150
taintAnalysis 19202341a70ad86d09009a4653ca79a8
stringSearch 0874410948a51042828b856410115e86
main 50161042ab273d6dbf31845f33513254
stringEncrypt f41b4195de585aac72cdd0fc7285f48c
keyObfuscate 676fb4f92742441da501bbc27038a204
stringObfuscate bf859f2f4f0c9117e99876726bfeed21
stringInsert 0983fd34b3420bc1c654304cbc8c267c
removeComments a7b260d4aa940c7cc818c321167cd1de
taintAnalysis 7e55b0e079c4b4bfe3b88e980de0d7a6
obfuscateTool bc032265f457512a38a4222dd1f7d085
1 change: 1 addition & 0 deletions src/main/resources/pyscripts/create_hash.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ def calculate_md5(file_path):
md5_hash.update(byte_block)
return md5_hash.hexdigest()


def hash_files_in_directory(directory_path, exclude_file='create_hash.py', output_file='check_hash'):
"""디렉토리 내의 .py 파일들의 MD5 해시값을 계산하고 결과를 output_file에 저장합니다."""
with open(directory_path + output_file, 'w') as output:
Expand Down
66 changes: 66 additions & 0 deletions src/main/resources/pyscripts/keyDecrypt.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,66 @@
public static List<byte[]> keySchedule(byte[] key, int rounds) throws NoSuchAlgorithmException {
List<byte[]> schedule = new ArrayList<>();
schedule.add(key);

MessageDigest digest = MessageDigest.getInstance("SHA-256");
for (int i = 1; i < rounds; i++) {
byte[] newKey = digest.digest(schedule.get(schedule.size() - 1));
schedule.add(Arrays.copyOf(newKey, 16)); // 16바이트로 제한
}
return schedule;
}

public static byte[] inverseFeistelNetwork(byte[] block, byte[] roundKey) {
byte[] left = Arrays.copyOfRange(block, 0, 8);
byte[] right = Arrays.copyOfRange(block, 8, 16);
byte[] f_result = new byte[8];
for (int i = 0; i < 8; i++) {
f_result[i] = (byte) (left[i] ^ roundKey[i]);
}
byte[] newLeft = new byte[8];
for (int i = 0; i < 8; i++) {
newLeft[i] = (byte) (right[i] ^ f_result[i]);
}
return concatenate(newLeft, left);
}

public static byte[] keyDecryptAlg(byte[] data, byte[] key, int rounds) throws NoSuchAlgorithmException {
List<byte[]> keySched = keySchedule(key, rounds);
byte[] decrypted = new byte[data.length];
for (int i = 0; i < data.length; i += 16) {
byte[] block = Arrays.copyOfRange(data, i, i + 16);
for (int j = keySched.size() - 1; j >= 0; j--) {
block = inverseFeistelNetwork(block, keySched.get(j));
}
System.arraycopy(block, 0, decrypted, i, 16);
}
return removePadding(decrypted);
}

public static byte[] concatenate(byte[] a, byte[] b) {
byte[] result = new byte[a.length + b.length];
System.arraycopy(a, 0, result, 0, a.length);
System.arraycopy(b, 0, result, a.length, b.length);
return result;
}

public static byte[] removePadding(byte[] data) {
int i = data.length - 1;
while (i >= 0 && data[i] == 0) {
i--;
}
return Arrays.copyOf(data, i + 1);
}

public static byte[] keyDecrypt(String key, String key2) throws NoSuchAlgorithmException {
byte[] deckey = Base64.getDecoder().decode(key);
byte[] deckey2 = Base64.getDecoder().decode(key2);

byte[] decrypted_key = keyDecryptAlg(deckey, deckey2, 16);

return decrypted_key;
}




61 changes: 61 additions & 0 deletions src/main/resources/pyscripts/keyObfuscate.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,61 @@
import hashlib

class KeyObfuscate:
def __init__(self, aes_key, enc_key):
self.enc_aes_key = self.__key_encrypt(aes_key, enc_key)


def __key_schedule(self, key, rounds):
schedule = [key]
for i in range(1, rounds):
new_key = hashlib.sha256(schedule[-1]).digest()
schedule.append(new_key[:16]) # 16바이트로 제한
return schedule


def __feistel_network(self, block, round_key):
left, right = block[:8], block[8:]
f_result = bytes(a ^ b for a, b in zip(right, round_key[:8]))
new_right = bytes(a ^ b for a, b in zip(left, f_result))
return right + new_right


def __inverse_feistel_network(self, block, round_key):
left, right = block[:8], block[8:]
f_result = bytes(a ^ b for a, b in zip(left, round_key[:8]))
new_left = bytes(a ^ b for a, b in zip(right, f_result))
return new_left + left


def __encrypt(self, data, key, rounds=16):
key_sched = self.__key_schedule(key, rounds)
encrypted = bytearray()
for i in range(0, len(data), 16):
block = data[i:i+16]
if len(block) < 16:
block = block.ljust(16, b'\x00')
for round_key in key_sched:
block = self.__feistel_network(block, round_key)
encrypted.extend(block)
return bytes(encrypted)


def __decrypt(self, data, key, rounds=16):
key_sched = self.__key_schedule(key, rounds)
decrypted = bytearray()
for i in range(0, len(data), 16):
block = data[i:i+16]
for round_key in reversed(key_sched):
block = self.__inverse_feistel_network(block, round_key)
decrypted.extend(block)
return bytes(decrypted).rstrip(b'\x00')


def __key_encrypt(self, aes_key, key2):
enc2_aes_key = self.__encrypt(aes_key, key2)
return enc2_aes_key


def __key_decrypt(self, enc2_aes_key, key2):
enc_aes_key = self.__decrypt(enc2_aes_key, key2)
return enc_aes_key
3 changes: 3 additions & 0 deletions src/main/resources/pyscripts/main.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,8 @@

from taintAnalysis import taintAnalysis
from removeComments import removeComments
from stringObfuscate import stringObfuscate


def create_taint_result(output_path, flows):
with open(output_path + "result.txt", 'w', encoding='utf-8') as file: # 결과 파일 생성
Expand Down Expand Up @@ -32,6 +34,7 @@ def main(java_folder_path, output_folder):
create_taint_result(output_folder, tainted.flows)

removeComments(output_folder)
stringObfuscate(output_folder)


if __name__ == '__main__':
Expand Down
32 changes: 32 additions & 0 deletions src/main/resources/pyscripts/obfuscateTool.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
import random
import javalang
import os

class obfuscateTool :
def random_class(class_list, random_count):
leng = len(class_list)
random_indices = [random.randint(0, leng - 1) for _ in range(random_count)]

random_class = [class_list[i] for i in random_indices]

return random_class


def parse_java_files(folder_path):
java_files = []

for root, _, files in os.walk(folder_path):
for file_name in files:
if file_name.endswith('.java'):
file_path = os.path.join(root, file_name)
with open(file_path, 'r', encoding='utf-8') as file:
source_code = file.read()
try:
tree = javalang.parse.parse(source_code)
java_files.append((file_path, tree, source_code))
except javalang.parser.JavaSyntaxError as e:
print(f"Syntax error in file {file_path}: {e}")
except Exception as e:
print(f"Error parsing file {file_path}: {e}")
return java_files

37 changes: 12 additions & 25 deletions src/main/resources/pyscripts/removeComments.py
Original file line number Diff line number Diff line change
@@ -1,37 +1,27 @@
from re import sub
import os

from obfuscateTool import obfuscateTool


class removeComments:
def __init__(self, project_path):
print("주석 제거 작업 시작...")
self.__find_java_files(project_path)
self.__process_file(project_path)
print("주석 제거 완료.")

def __process_file(self, project_path):
java_files = obfuscateTool.parse_java_files(project_path)

def __find_java_files(self, project_path):
for root, _, files in os.walk(project_path):
for file in files:
if file.endswith('.java'):
file_path = os.path.join(root, file)
self.__process_file(file_path)


def __process_file(self, file_path):
with open(file_path, 'r', encoding='utf-8') as file:
java_code = file.read()

cleaned_code = self.__remove_comments(java_code)
for path, tree, source_code in java_files:
cleaned_code = self.__remove_comments(source_code)
with open(path, 'w', encoding='utf-8') as file:
file.write(cleaned_code)
print(f"Processed: {path}")

with open(file_path, 'w', encoding='utf-8') as file:
file.write(cleaned_code)

print(f"Processed: {file_path}")


def __remove_comments(self, java_code):
# 문자열 내부의 주석 기호를 임시로 대체
code = sub(r'(".*?(?<!\\)")', lambda m: m.group(0).replace('//', '@@').replace('/*', '##').replace('*/', '%%'),
java_code)
java_code)

# 한 줄 주석 제거
code = sub(r'//.*', '', code)
Expand All @@ -46,6 +36,3 @@ def __remove_comments(self, java_code):
code = '\n'.join(line for line in code.splitlines() if line.strip())

return code



26 changes: 26 additions & 0 deletions src/main/resources/pyscripts/stringDecrypt.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
import java.util.Base64;
import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;

public static String stringDecrypt(String encryptedText, byte[] key) {
try {
SecretKeySpec secretKey = new SecretKeySpec(key, "AES");

Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
cipher.init(Cipher.DECRYPT_MODE, secretKey);
byte[] decryptedBytes = cipher.doFinal(Base64.getDecoder().decode(encryptedText));
String decrypted_str = new String(decryptedBytes, "UTF-8")
.replace("\\n", "\n")
.replace("\\t", "\t")
.replace("\\r", "\r")
.replace("\\b", "\b")
.replace("\\f", "\f")
.replace("\\\"", "\"")
.replace("\\'", "'")
.replace("\\\\", "\\");
return decrypted_str.substring(1, decrypted_str.length() - 1);
} catch (Exception e) {
throw new RuntimeException("Decryption failed", e);
}
}

37 changes: 37 additions & 0 deletions src/main/resources/pyscripts/stringEncrypt.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
import os
import base64
from Crypto.Cipher import AES
from Crypto.Util.Padding import pad
from keyObfuscate import KeyObfuscate

class stringEncrypt:
def __init__(self,Literals):
self.encrypted_Literals = self.encrypt_string_literals(Literals)


def encrypt_string(self, plain_text, key):
cipher = AES.new(key, AES.MODE_ECB)
padded_text = pad(plain_text.encode('utf-8'), AES.block_size)
encrypted_text = cipher.encrypt(padded_text)
return base64.b64encode(encrypted_text).decode('utf-8')


# 암호화
def encrypt_string_literals(self, string_literals):
encrypted_Literals = []

for p,c,strings in string_literals:
aes_key = os.urandom(16)
enc_aes_key = os.urandom(8)

ko = KeyObfuscate(aes_key, enc_aes_key)
encrypted_aes_key = ko.enc_aes_key

encrypted_aes_key = base64.b64encode(encrypted_aes_key).decode('utf-8').replace("=","")
enc_aes_key = base64.b64encode(enc_aes_key).decode('utf-8').replace("=","")

encrypted_Literals.append([p,c,encrypted_aes_key,enc_aes_key,[(self.encrypt_string(literal, aes_key),_) for literal, _ in strings]])

return encrypted_Literals


Loading

0 comments on commit 294b905

Please sign in to comment.