Here's an implementation of a Java bytecode obfuscator using ASM that includes string encryption, number encryption, and control flow flattening:
import org.objectweb.asm.*;
import org.objectweb.asm.tree.*;
import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.util.*;
public class Obfuscator {
private static final String ENCRYPTION_KEY = "ObfuscationKey123"; // 16-byte key for AES
private static final Random random = new Random();
public static void main(String[] args) {
if (args.length != 2) {
System.out.println("Usage: java Obfuscator <input.class> <output.class>");
return;
}
try {
// Read the class file
FileInputStream fis = new FileInputStream(args[0]);
ClassReader cr = new ClassReader(fis);
ClassNode cn = new ClassNode();
cr.accept(cn, 0);
// Apply transformations
obfuscateStrings(cn);
obfuscateNumbers(cn);
flattenControlFlow(cn);
// Write the modified class
ClassWriter cw = new ClassWriter(ClassWriter.COMPUTE_MAXS | ClassWriter.COMPUTE_FRAMES);
cn.accept(cw);
FileOutputStream fos = new FileOutputStream(args[1]);
fos.write(cw.toByteArray());
fos.close();
} catch (Exception e) {
e.printStackTrace();
}
}
// String encryption transformation
private static void obfuscateStrings(ClassNode cn) {
for (MethodNode mn : cn.methods) {
Iterator<AbstractInsnNode> it = mn.instructions.iterator();
while (it.hasNext()) {
AbstractInsnNode insn = it.next();
if (insn instanceof LdcInsnNode) {
LdcInsnNode ldc = (LdcInsnNode) insn;
if (ldc.cst instanceof String) {
String encrypted = encryptString((String) ldc.cst);
ldc.cst = encrypted;
// Insert decryption method call
InsnList decrypt = new InsnList();
decrypt.add(new MethodInsnNode(Opcodes.INVOKESTATIC, cn.name,
"decryptString", "(Ljava/lang/String;)Ljava/lang/String;", false));
mn.instructions.insert(ldc, decrypt);
}
}
}
}
// Add decryption method
addStringDecryptionMethod(cn);
}
// Number encryption transformation
private static void obfuscateNumbers(ClassNode cn) {
for (MethodNode mn : cn.methods) {
Iterator<AbstractInsnNode> it = mn.instructions.iterator();
while (it.hasNext()) {
AbstractInsnNode insn = it.next();
if (insn instanceof IntInsnNode) {
IntInsnNode intInsn = (IntInsnNode) insn;
int original = intInsn.operand;
int key = random.nextInt();
int encrypted = original ^ key;
// Replace with encrypted value and XOR operation
InsnList decrypt = new InsnList();
decrypt.add(new LdcInsnNode(encrypted));
decrypt.add(new LdcInsnNode(key));
decrypt.add(new InsnNode(Opcodes.IXOR));
mn.instructions.insert(intInsn, decrypt);
mn.instructions.remove(intInsn);
}
}
}
}
// Control flow flattening transformation
private static void flattenControlFlow(ClassNode cn) {
for (MethodNode mn : cn.methods) {
if (mn.instructions.size() == 0) continue;
// Create a state variable
LabelNode[] labels = new LabelNode[mn.instructions.size()];
for (int i = 0; i < labels.length; i++) {
labels[i] = new LabelNode();
}
// Create switch table
InsnList newInstructions = new InsnList();
LabelNode defaultLabel = new LabelNode();
// Add state variable
newInstructions.add(new InsnNode(Opcodes.ICONST_0));
newInstructions.add(new VarInsnNode(Opcodes.ISTORE, mn.maxLocals));
// Main loop
LabelNode loopStart = new LabelNode();
newInstructions.add(loopStart);
newInstructions.add(new VarInsnNode(Opcodes.ILOAD, mn.maxLocals));
// Create switch statement
TableSwitchInsnNode switchInsn = new TableSwitchInsnNode(0, labels.length - 1,
defaultLabel, labels);
newInstructions.add(switchInsn);
// Add original instructions with state transitions
int state = 0;
for (AbstractInsnNode insn = mn.instructions.getFirst(); insn != null;
insn = insn.getNext()) {
newInstructions.add(labels[state]);
newInstructions.add(insn.clone(null));
if (insn.getNext() != null) {
newInstructions.add(new LdcInsnNode(state + 1));
newInstructions.add(new VarInsnNode(Opcodes.ISTORE, mn.maxLocals));
newInstructions.add(new JumpInsnNode(Opcodes.GOTO, loopStart));
}
state++;
}
newInstructions.add(defaultLabel);
mn.instructions = newInstructions;
mn.maxLocals++;
}
}
// String encryption helper methods
private static String encryptString(String input) {
try {
Cipher cipher = Cipher.getInstance("AES");
SecretKeySpec key = new SecretKeySpec(ENCRYPTION_KEY.getBytes(), "AES");
cipher.init(Cipher.ENCRYPT_MODE, key);
byte[] encrypted = cipher.doFinal(input.getBytes());
return Base64.getEncoder().encodeToString(encrypted);
} catch (Exception e) {
return input;
}
}
private static void addStringDecryptionMethod(ClassNode cn) {
MethodNode mn = new MethodNode(Opcodes.ACC_PRIVATE | Opcodes.ACC_STATIC,
"decryptString", "(Ljava/lang/String;)Ljava/lang/String;", null, null);
InsnList il = new InsnList();
// Try-catch block for decryption
LabelNode tryStart = new LabelNode();
LabelNode tryEnd = new LabelNode();
LabelNode catchHandler = new LabelNode();
il.add(tryStart);
// Create cipher instance
il.add(new LdcInsnNode("AES"));
il.add(new MethodInsnNode(Opcodes.INVOKESTATIC, "javax/crypto/Cipher",
"getInstance", "(Ljava/lang/String;)Ljavax/crypto/Cipher;", false));
il.add(new VarInsnNode(Opcodes.ASTORE, 1));
// Create key
il.add(new LdcInsnNode(ENCRYPTION_KEY));
il.add(new MethodInsnNode(Opcodes.INVOKEVIRTUAL, "java/lang/String",
"getBytes", "()[B", false));
il.add(new TypeInsnNode(Opcodes.NEW, "javax/crypto/spec/SecretKeySpec"));
il.add(new InsnNode(Opcodes.DUP));
il.add(new LdcInsnNode("AES"));
il.add(new MethodInsnNode(Opcodes.INVOKESPECIAL, "javax/crypto/spec/SecretKeySpec",
"<init>", "([BLjava/lang/String;)V", false));
il.add(new VarInsnNode(Opcodes.ASTORE, 2));
// Initialize cipher
il.add(new VarInsnNode(Opcodes.ALOAD, 1));
il.add(new InsnNode(Opcodes.ICONST_2));
il.add(new VarInsnNode(Opcodes.ALOAD, 2));
il.add(new MethodInsnNode(Opcodes.INVOKEVIRTUAL, "javax/crypto/Cipher",
"init", "(ILjava/security/Key;)V", false));
// Decrypt
il.add(new VarInsnNode(Opcodes.ALOAD, 0));
il.add(new MethodInsnNode(Opcodes.INVOKESTATIC, "java/util/Base64",
"getDecoder", "()Ljava/util/Base64$Decoder;", false));
il.add(new MethodInsnNode(Opcodes.INVOKEVIRTUAL, "java/util/Base64$Decoder",
"decode", "(Ljava/lang/String;)[B", false));
il.add(new VarInsnNode(Opcodes.ALOAD, 1));
il.add(new MethodInsnNode(Opcodes.INVOKEVIRTUAL, "javax/crypto/Cipher",
"doFinal", "([B)[B", false));
il.add(new TypeInsnNode(Opcodes.NEW, "java/lang/String"));
il.add(new InsnNode(Opcodes.DUP_X1));
il.add(new InsnNode(Opcodes.SWAP));
il.add(new MethodInsnNode(Opcodes.INVOKESPECIAL, "java/lang/String",
"<init>", "([B)V", false));
il.add(new InsnNode(Opcodes.ARETURN));
il.add(tryEnd);
// Catch block - return original string if decryption fails
il.add(catchHandler);
il.add(new VarInsnNode(Opcodes.ALOAD, 0));
il.add(new InsnNode(Opcodes.ARETURN));
mn.instructions = il;
mn.tryCatchBlocks.add(new TryCatchBlockNode(tryStart, tryEnd, catchHandler,
"java/lang/Exception"));
mn.maxStack = 4;
mn.maxLocals = 3;
cn.methods.add(mn);
}
}
This obfuscator implements three main transformations:
- String Encryption:
- Encrypts all string constants using AES encryption
- Adds a decryption method to the class
- Replaces string constants with their encrypted versions and adds decryption calls
- Number Encryption:
- Encrypts integer constants using XOR with random keys
- Adds decryption operations inline in the code
- Control Flow Flattening:
- Converts normal control flow into a state machine
- Uses a switch statement to jump between basic blocks
- Makes the code flow harder to follow
To use the obfuscator:
javac -cp asm-9.2.jar Obfuscator.java
java -cp .:asm-9.2.jar Obfuscator input.class output.class
Note that you'll need the ASM library in your classpath to compile and run the obfuscator.
Some important considerations:
- This is a basic implementation and might need adjustments for complex classes.
- The transformations might not work with all Java features and could break some code patterns.
- The obfuscator doesn't handle method signatures, annotations, or other metadata.
- You might want to add more transformations like:
- Method renaming
- Class hierarchy flattening
- Dead code injection
- Instruction substitution
To make the obfuscator more robust, you could:
- Add more sophisticated encryption algorithms
- Implement method inlining
- Add random dead code insertion
- Implement more complex control flow transformations
- Add support for handling multiple classes
- Add verification steps to ensure the transformed code works correctly
Remember that obfuscation is not a substitute for proper security measures, but rather an additional layer of protection against reverse engineering.