Sitemap
System Weakness

System Weakness is a publication that specialises in publishing upcoming writers in cybersecurity and ethical hacking space. Our security experts write to make the cyber universe more secure, one vulnerability at a time.

Obfuscating code in Java

18 min readJun 25, 2024

--

Introduction

Definition of Obfuscation:

Obfuscation is a software programming technique that alters code to make it more challenging for humans to understand without affecting its functionality. This technique is commonly used in applications containing sensitive information or proprietary algorithms to deter unauthorized access and reverse engineering.

This is a technique largely utilized in applications that have sensitive information or complex algorithms that need to be protected from being unauthorized copied or suffering malicious attacks. This works by applying transformations in the original code, these transformations can include, names without sense, insertion of instructions that are not necessary or redundant, addition of dead codes, or updates on the logic structure of the program. It`s important to know that these changes don`t affect the workflow of the code.

Also, obfuscation has a lot of benefits for the developers, the main ones are the protection of the code from suffering reverse engineering, the protection as well sensitive information like passwords, cryptography keys, and proprietary algorithms, and the extraction by analysis of code.

Press enter or click to view image in full size
Image: Reproduction/Internet

Problems that obfuscation can bring:

While obfuscation offers significant benefits, it also introduces challenges. Excessive obfuscation can lead to diminished code readability and efficiency. For example, renaming variables excessively or applying aggressive code transformations may obscure the original logic to the point where debugging and maintenance become cumbersome. Furthermore, over-optimization through obfuscation can inadvertently increase application size or degrade runtime performance in certain scenarios. It’s crucial for developers to find a balance that protects their intellectual property without compromising code manageability and performance.

Why Obfuscate Code in Java?

So, you can talk! Why do I need to obfuscate my Java code? Because Java already compiles my code to a bytecode that it’s too hard to understand. Well, let’s work with the following example. Let’s suppose that I have this code on Java:

package com.example.obfuscation.obfuscation_example;

import java.io.*;
import java.security.*;
import javax.crypto.*;
import java.util.Arrays;
import java.util.Objects;

public class EncryptDecryptRSA {

public static final String ALGORITHM = "RSA";
public static final String PRIVATE_KEY_PATH = "C:/keys/private.key";
public static final String PUBLIC_KEY_PATH = "C:/keys/public.key";

public static void generateKeys() {
try {
KeyPairGenerator keyGen = KeyPairGenerator.getInstance(ALGORITHM);
keyGen.initialize(1024);
KeyPair keyPair = keyGen.generateKeyPair();

File privateKeyFile = new File(PRIVATE_KEY_PATH);
privateKeyFile.getParentFile().mkdirs(); // Ensure parent directory exists
privateKeyFile.createNewFile();

ObjectOutputStream privateKeyOS = new ObjectOutputStream(new FileOutputStream(privateKeyFile));
privateKeyOS.writeObject(keyPair.getPrivate());
privateKeyOS.close();

File publicKeyFile = new File(PUBLIC_KEY_PATH);
publicKeyFile.getParentFile().mkdirs(); // Ensure parent directory exists
publicKeyFile.createNewFile();

ObjectOutputStream publicKeyOS = new ObjectOutputStream(new FileOutputStream(publicKeyFile));
publicKeyOS.writeObject(keyPair.getPublic());
publicKeyOS.close();

} catch (Exception e) {
System.out.println("Exception occurred during key generation".concat(e.getMessage()));
}
}

public static boolean checkIfKeysExist() {
File privateKeyFile = new File(PRIVATE_KEY_PATH);
File publicKeyFile = new File(PUBLIC_KEY_PATH);

return privateKeyFile.exists() && publicKeyFile.exists();
}

public static byte[] encrypt(String plainText, PublicKey key) {
try {
Cipher cipher = Cipher.getInstance(ALGORITHM);
cipher.init(Cipher.ENCRYPT_MODE, key);
return cipher.doFinal(plainText.getBytes());
} catch (Exception e) {
System.out.println("Exception occurred during encryption".concat(e.getMessage()));
return null;
}
}

public static String decrypt(byte[] encryptedText, PrivateKey key) {
try {
Cipher cipher = Cipher.getInstance(ALGORITHM);
cipher.init(Cipher.DECRYPT_MODE, key);
byte[] decryptedText = cipher.doFinal(encryptedText);
return new String(decryptedText);
} catch (Exception e) {
System.out.println("Exception occurred during encryption".concat(e.getMessage()));
return null;
}
}

public static void main(String[] args) {
try {
if (!checkIfKeysExist()) {
generateKeys();
}

final String originalMessage = "Example message";
ObjectInputStream inputStream;

inputStream = new ObjectInputStream(new FileInputStream(PUBLIC_KEY_PATH));
PublicKey publicKey = (PublicKey) inputStream.readObject();
byte[] encryptedMessage = encrypt(originalMessage, publicKey);

inputStream = new ObjectInputStream(new FileInputStream(PRIVATE_KEY_PATH));
PrivateKey privateKey = (PrivateKey) inputStream.readObject();
String decryptedMessage = decrypt(encryptedMessage, privateKey);

System.out.println("Original Message: ".concat(originalMessage));
System.out.println("Encrypted Message: ".concat(Arrays.toString(encryptedMessage)));
System.out.println("Decrypted Message: ".concat(Objects.requireNonNull(decryptedMessage)));

} catch (Exception e) {
System.out.println("Exception occurred in main method".concat(e.getMessage()));
}
}
}

So, now, I will compile this code, using this:

javac EncryptDecryptRSA.java

After the bytecode is generated, let’s look into that using the following command:

javap -c EncryptDecryptRSA

So now, we have the following content:

Compiled from "EncryptDecryptRSA.java"
public class com.example.obfuscation.obfuscation_example.EncryptDecryptRSA {
public static final java.lang.String ALGORITHM;

public static final java.lang.String PRIVATE_KEY_PATH;

public static final java.lang.String PUBLIC_KEY_PATH;

public com.example.obfuscation.obfuscation_example.EncryptDecryptRSA();
Code:
0: aload_0
1: invokespecial #1 // Method java/lang/Object."<init>":()V
4: return

public static void generateKeys();
Code:
0: ldc #9 // String RSA
2: invokestatic #11 // Method java/security/KeyPairGenerator.getInstance:(Ljava/lang/String;)Ljava/security/KeyPairGenerator;
5: astore_0
6: aload_0
7: sipush 1024
10: invokevirtual #17 // Method java/security/KeyPairGenerator.initialize:(I)V
13: aload_0
14: invokevirtual #21 // Method java/security/KeyPairGenerator.generateKeyPair:()Ljava/security/KeyPair;
17: astore_1
18: new #25 // class java/io/File
21: dup
22: ldc #27 // String C:/keys/private.key
24: invokespecial #29 // Method java/io/File."<init>":(Ljava/lang/String;)V
27: astore_2
28: aload_2
29: invokevirtual #32 // Method java/io/File.getParentFile:()Ljava/io/File;
32: invokevirtual #36 // Method java/io/File.mkdirs:()Z
35: pop
36: aload_2
37: invokevirtual #40 // Method java/io/File.createNewFile:()Z
40: pop
41: new #43 // class java/io/ObjectOutputStream
44: dup
45: new #45 // class java/io/FileOutputStream
48: dup
49: aload_2
50: invokespecial #47 // Method java/io/FileOutputStream."<init>":(Ljava/io/File;)V
53: invokespecial #50 // Method java/io/ObjectOutputStream."<init>":(Ljava/io/OutputStream;)V
56: astore_3
57: aload_3
58: aload_1
59: invokevirtual #53 // Method java/security/KeyPair.getPrivate:()Ljava/security/PrivateKey;
62: invokevirtual #59 // Method java/io/ObjectOutputStream.writeObject:(Ljava/lang/Object;)V
65: aload_3
66: invokevirtual #63 // Method java/io/ObjectOutputStream.close:()V
69: new #25 // class java/io/File
72: dup
73: ldc #66 // String C:/keys/public.key
75: invokespecial #29 // Method java/io/File."<init>":(Ljava/lang/String;)V
78: astore 4
80: aload 4
82: invokevirtual #32 // Method java/io/File.getParentFile:()Ljava/io/File;
85: invokevirtual #36 // Method java/io/File.mkdirs:()Z
88: pop
89: aload 4
91: invokevirtual #40 // Method java/io/File.createNewFile:()Z
94: pop
95: new #43 // class java/io/ObjectOutputStream
98: dup
99: new #45 // class java/io/FileOutputStream
102: dup
103: aload 4
105: invokespecial #47 // Method java/io/FileOutputStream."<init>":(Ljava/io/File;)V
108: invokespecial #50 // Method java/io/ObjectOutputStream."<init>":(Ljava/io/OutputStream;)V
111: astore 5
113: aload 5
115: aload_1
116: invokevirtual #68 // Method java/security/KeyPair.getPublic:()Ljava/security/PublicKey;
119: invokevirtual #59 // Method java/io/ObjectOutputStream.writeObject:(Ljava/lang/Object;)V
122: aload 5
124: invokevirtual #63 // Method java/io/ObjectOutputStream.close:()V
127: goto 146
130: astore_0
131: getstatic #74 // Field java/lang/System.out:Ljava/io/PrintStream;
134: ldc #80 // String Exception occurred during key generation
136: aload_0
137: invokevirtual #82 // Method java/lang/Exception.getMessage:()Ljava/lang/String;
140: invokevirtual #86 // Method java/lang/String.concat:(Ljava/lang/String;)Ljava/lang/String;
143: invokevirtual #92 // Method java/io/PrintStream.println:(Ljava/lang/String;)V
146: return
Exception table:
from to target type
0 127 130 Class java/lang/Exception

public static boolean checkIfKeysExist();
Code:
0: new #25 // class java/io/File
3: dup
4: ldc #27 // String C:/keys/private.key
6: invokespecial #29 // Method java/io/File."<init>":(Ljava/lang/String;)V
9: astore_0
10: new #25 // class java/io/File
13: dup
14: ldc #66 // String C:/keys/public.key
16: invokespecial #29 // Method java/io/File."<init>":(Ljava/lang/String;)V
19: astore_1
20: aload_0
21: invokevirtual #97 // Method java/io/File.exists:()Z
24: ifeq 38
27: aload_1
28: invokevirtual #97 // Method java/io/File.exists:()Z
31: ifeq 38
34: iconst_1
35: goto 39
38: iconst_0
39: ireturn

public static byte[] encrypt(java.lang.String, java.security.PublicKey);
Code:
0: ldc #9 // String RSA
2: invokestatic #100 // Method javax/crypto/Cipher.getInstance:(Ljava/lang/String;)Ljavax/crypto/Cipher;
5: astore_2
6: aload_2
7: iconst_1
8: aload_1
9: invokevirtual #105 // Method javax/crypto/Cipher.init:(ILjava/security/Key;)V
12: aload_2
13: aload_0
14: invokevirtual #109 // Method java/lang/String.getBytes:()[B
17: invokevirtual #113 // Method javax/crypto/Cipher.doFinal:([B)[B
20: areturn
21: astore_2
22: getstatic #74 // Field java/lang/System.out:Ljava/io/PrintStream;
25: ldc #117 // String Exception occurred during encryption
27: aload_2
28: invokevirtual #82 // Method java/lang/Exception.getMessage:()Ljava/lang/String;
31: invokevirtual #86 // Method java/lang/String.concat:(Ljava/lang/String;)Ljava/lang/String;
34: invokevirtual #92 // Method java/io/PrintStream.println:(Ljava/lang/String;)V
37: aconst_null
38: areturn
Exception table:
from to target type
0 20 21 Class java/lang/Exception

public static java.lang.String decrypt(byte[], java.security.PrivateKey);
Code:
0: ldc #9 // String RSA
2: invokestatic #100 // Method javax/crypto/Cipher.getInstance:(Ljava/lang/String;)Ljavax/crypto/Cipher;
5: astore_2
6: aload_2
7: iconst_2
8: aload_1
9: invokevirtual #105 // Method javax/crypto/Cipher.init:(ILjava/security/Key;)V
12: aload_2
13: aload_0
14: invokevirtual #113 // Method javax/crypto/Cipher.doFinal:([B)[B
17: astore_3
18: new #87 // class java/lang/String
21: dup
22: aload_3
23: invokespecial #119 // Method java/lang/String."<init>":([B)V
26: areturn
27: astore_2
28: getstatic #74 // Field java/lang/System.out:Ljava/io/PrintStream;
31: ldc #117 // String Exception occurred during encryption
33: aload_2
34: invokevirtual #82 // Method java/lang/Exception.getMessage:()Ljava/lang/String;
37: invokevirtual #86 // Method java/lang/String.concat:(Ljava/lang/String;)Ljava/lang/String;
40: invokevirtual #92 // Method java/io/PrintStream.println:(Ljava/lang/String;)V
43: aconst_null
44: areturn
Exception table:
from to target type
0 26 27 Class java/lang/Exception

public static void main(java.lang.String[]);
Code:
0: invokestatic #122 // Method checkIfKeysExist:()Z
3: ifne 9
6: invokestatic #125 // Method generateKeys:()V
9: new #128 // class java/io/ObjectInputStream
12: dup
13: new #130 // class java/io/FileInputStream
16: dup
17: ldc #66 // String C:/keys/public.key
19: invokespecial #132 // Method java/io/FileInputStream."<init>":(Ljava/lang/String;)V
22: invokespecial #133 // Method java/io/ObjectInputStream."<init>":(Ljava/io/InputStream;)V
25: astore_1
26: aload_1
27: invokevirtual #136 // Method java/io/ObjectInputStream.readObject:()Ljava/lang/Object;
30: checkcast #140 // class java/security/PublicKey
33: astore_2
34: ldc #142 // String Example message
36: aload_2
37: invokestatic #144 // Method encrypt:(Ljava/lang/String;Ljava/security/PublicKey;)[B
40: astore_3
41: new #128 // class java/io/ObjectInputStream
44: dup
45: new #130 // class java/io/FileInputStream
48: dup
49: ldc #27 // String C:/keys/private.key
51: invokespecial #132 // Method java/io/FileInputStream."<init>":(Ljava/lang/String;)V
54: invokespecial #133 // Method java/io/ObjectInputStream."<init>":(Ljava/io/InputStream;)V
57: astore_1
58: aload_1
59: invokevirtual #136 // Method java/io/ObjectInputStream.readObject:()Ljava/lang/Object;
62: checkcast #148 // class java/security/PrivateKey
65: astore 4
67: aload_3
68: aload 4
70: invokestatic #150 // Method decrypt:([BLjava/security/PrivateKey;)Ljava/lang/String;
73: astore 5
75: getstatic #74 // Field java/lang/System.out:Ljava/io/PrintStream;
78: ldc #154 // String Original Message:
80: ldc #142 // String Example message
82: invokevirtual #86 // Method java/lang/String.concat:(Ljava/lang/String;)Ljava/lang/String;
85: invokevirtual #92 // Method java/io/PrintStream.println:(Ljava/lang/String;)V
88: getstatic #74 // Field java/lang/System.out:Ljava/io/PrintStream;
91: ldc #156 // String Encrypted Message:
93: aload_3
94: invokestatic #158 // Method java/util/Arrays.toString:([B)Ljava/lang/String;
97: invokevirtual #86 // Method java/lang/String.concat:(Ljava/lang/String;)Ljava/lang/String;
100: invokevirtual #92 // Method java/io/PrintStream.println:(Ljava/lang/String;)V
103: getstatic #74 // Field java/lang/System.out:Ljava/io/PrintStream;
106: ldc #164 // String Decrypted Message:
108: aload 5
110: invokestatic #166 // Method java/util/Objects.requireNonNull:(Ljava/lang/Object;)Ljava/lang/Object;
113: checkcast #87 // class java/lang/String
116: invokevirtual #86 // Method java/lang/String.concat:(Ljava/lang/String;)Ljava/lang/String;
119: invokevirtual #92 // Method java/io/PrintStream.println:(Ljava/lang/String;)V
122: goto 141
125: astore_1
126: getstatic #74 // Field java/lang/System.out:Ljava/io/PrintStream;
129: ldc #172 // String Exception occurred in main method
131: aload_1
132: invokevirtual #82 // Method java/lang/Exception.getMessage:()Ljava/lang/String;
135: invokevirtual #86 // Method java/lang/String.concat:(Ljava/lang/String;)Ljava/lang/String;
138: invokevirtual #92 // Method java/io/PrintStream.println:(Ljava/lang/String;)V
141: return
Exception table:
from to target type
0 122 125 Class java/lang/Exception
}

Now that we have our Java code compiled, let’s explore why obfuscating it is crucial. Java compiles its source code into bytecode, an intermediate form that closely resembles the original source and contains significant amounts of meaningful information. This bytecode can be decompiled back into readable Java source code with relative ease, especially in scenarios where obfuscation techniques haven’t been applied effectively.

Bytecode in Java serves as an intermediate representation of the source code, maintaining much of its structure and logic. Unlike lower-level machine code, bytecode isn’t directly executable and retains symbolic references to classes, methods, and variables. Decompilers can use this information to reconstruct Java source code, albeit with limitations such as losing parameter names and local variables. This vulnerability makes bytecode susceptible to reverse engineering attempts, underscoring the importance of effective obfuscation.

When malicious parties attempt to decompile code, they often search for embedded strings in application or server logs. This unethical practice allows them to pinpoint specific functionalities within the codebase easily. Since bytecode stores strings in plain text, they can comb through all “.class” files for sensitive information. For instance, if an exception message like “invalid username” appears, it becomes a target for their search, potentially compromising security and intellectual property. Furthermore, visible strings in the graphical user interface and other labels may also be exploited to gain unauthorized insights into the application’s operations.

Obfuscation mitigates these risks by obscuring bytecode, making it harder for humans to comprehend and reverse-engineer. This process involves removing details such as debugging information (e.g., variable tables, line numbers) and renaming packages, classes, and methods. While debugging information aids in matching bytecode to its original source during decompilation, it’s optional for code execution. Despite alterations made by advanced obfuscators, the obfuscated bytecode remains valid and functional while presenting a formidable barrier to reverse engineering.

Advanced obfuscators may go beyond renaming and structural alterations to insert dummy code snippets that do not affect functionality but obfuscate the code’s logical flow. Despite these modifications, obfuscated bytecode retains its intended functionality and remains executable.

Obfuscators analyze Java class files, apply predefined rules to modify internal structures, and save them as new files. These transformed files behave identically to the originals during execution but pose a significant challenge to reverse engineering due to their altered format and obscured logic.

Now, you understand that it’s too important to obfuscate code in Java right?

Image: Reproduction/Internet

Another Benefit of obfuscation is that can optimize code size and improve runtime performance by removing unused code and renaming classes, methods, and variables. Follow how it does:

  1. Firstly, one significant benefit of obfuscation is the removal of unused code paths and resources. During the obfuscation process, tools analyze the application’s codebase and eliminate portions of code that are unreachable or redundant. This reduction in code size directly translates to improved runtime performance because the runtime environment has fewer instructions to process and manage.
  2. Secondly, obfuscation often involves renaming classes, methods, and variables to shorter, less descriptive names. While this primarily serves to obscure the code’s logic and hinder reverse engineering, it can also positively impact performance. Smaller and more concise identifiers can lead to reduced memory usage and faster execution times, especially in environments with limited resources or under heavy load(thinking of decreasing costs of cloud storage usage for example).
  3. Additionally, obfuscation tools may optimize bytecode structure and organization, leading to more streamlined execution paths. By restructuring the code’s flow and eliminating unnecessary branches or checks, obfuscation can enhance the efficiency of critical operations within the application.

Overall, while the primary goal of obfuscation is to enhance security by making code harder to understand and reverse engineer, it also offers tangible performance benefits. These include reducing code size, optimizing memory usage, and improving runtime execution speed, which is advantageous in environments where performance optimization is crucial. Thus, obfuscation serves a dual purpose of both safeguarding intellectual property and enhancing the operational efficiency of software applications.

Oh, let’s take a break here, take a cup of water, stretch your legs and Breathe.

Press enter or click to view image in full size
Image: reproduction/internet

Techniques of Obfuscation

  • Classes, Variables, and Functions Renaming: This technique involves replacing classes, variables, and function names with nonsensical names, making the code harder to understand. For example, a class named UserService, which is clear and descriptive, might be renamed to something like a, b, or c. Similarly, method names like getUserById could be renamed to a, b, or c, while variable names such as userId could become a, b, or c.
  • Insertion of Unnecessary Instructions: This technique adds unnecessary instructions to the code, such as empty loops or redundant mathematical operations. These instructions do not affect the software’s functionality but complicate code comprehension.
  • Addition of Dead Code: This technique involves adding code segments that will never be executed during the program’s execution. These code segments do not affect the software’s functionality but make code analysis more difficult.
  • Modification of Program’s Logical Structure: This technique involves altering the program’s logical structure to make it harder to understand. For example, the code can be reorganized to obscure control flows and conditional structures.
  • Code Simplification: Highlight techniques that remove debugging information, comments, and formatting to make the code more compact and less readable, that can be: Removal of Debugging Information(This helps reduce the size of the compiled code and removes information that aids reverse engineering.), Comment Removal(This reduces the amount of textual information available in the source code, making it less informative to someone analyzing it.), Formatting Minimization (This not only reduces file size but also makes the code harder to read by removing visual cues like indentation and spacing.), Consolidation of Redundant Code(This simplifies the codebase by reducing the number of lines and improving maintainability without affecting functionality.), Inline Expansion(This optimization technique can improve runtime performance by eliminating the overhead associated with function calls.), Dead Code Elimination(By eliminating dead code, the size of the executable or bytecode is reduced, and the codebase becomes cleaner and more efficient). Theese techniques
  • String Encryption: Have methods to encrypt strings used in the code to prevent straightforward extraction of sensitive information, like Symmetric Encryption with AES (Advanced Encryption Standard), Obfuscation with Custom Encryption Algorithms, Dynamic Decryption at Runtime, Key Management, and Secure Storage, Integration with Code Obfuscation Techniques, and other ways to encrypt that I will not spend a lot of time explaining this here, because that’s not the objective, if you like, you can follow to other articles about this specific topic, or ask in Chat GPT for some information about these techniques that it will give you some summary.

Popular Java Obfuscation Tools

Among the available obfuscators, popular choices include Klassmaster, ProGuard, Retro Guard, Dash-O, and JShrink. Klassmaster and Retro Guard are paid options, while ProGuard, Dash-O, and JShrink are free.

Klassmaster stands out among paid options for its comprehensive feature set, including removing debug information, name obfuscation, string encoding, inserting corrupted code, eliminating unused code, bytecode optimization, and unique control flow alteration capabilities. It’s a recommended investment for robust code obfuscation, typically priced around $200.

ProGuard, a leading free obfuscator, offers essential functionalities like removing debug information, name obfuscation, and eliminating unused code. However, it lacks features such as string encoding and control flow alteration.

For our study case, we will use ProGuard:

ProGuard

ProGuard is primarily used for code shrinking, optimization, and obfuscation.

Key Features of ProGuard:

  • Automatic Optimization: ProGuard optimizes bytecode by removing unused code and applying performance enhancements, leading to significant improvements in application performance.
  • Customizable Configuration: Developers can tailor ProGuard’s behavior using configuration files, specifying which classes, methods, or fields should be preserved from optimization or obfuscation.
  • Library Support: ProGuard seamlessly processes commonly used Java libraries and frameworks, ensuring consistent application of optimizations and obfuscations across dependencies.
  • Build Tool Integration: ProGuard integrates smoothly with popular Java build tools like Ant, Maven, and Gradle, facilitating automated integration into build pipelines for optimization and obfuscation.
  • Compatibility: ProGuard supports Java bytecode versions up to Java 11, ensuring compatibility with modern Java applications and libraries.
  • Guardian Classes: ProGuard can generate guardian classes to protect obfuscated code from reflection-based attacks, enhancing overall security measures.

Best Practices and Considerations

Although obfuscation tools generally do a good job, we must be cautious when using them, as there are situations where problems can arise due to obfuscation. Among these, we need to pay attention to dynamically loaded classes using Class.forName() or ClassLoader.loadClass(), passing the original class name that is not obfuscated. Reflection can also pose issues since it requires compile-time knowledge of method and field names. Additionally, serialization problems and violations of EJB patterns that require methods with specific names and signatures can occur.

Best Practices and Considerations

While obfuscation tools generally enhance security, caution is advised:

  • Selective Obfuscation: Obfuscate critical parts of the code selectively to maintain readability for debugging and maintenance purposes.
  • Testing and Verification: Thoroughly test applications post-obfuscation to ensure expected behavior and performance.
  • Legal Implications: Consider legal aspects and licensing requirements when obfuscating third-party libraries or components.

Now, it’s time:

image: reproduction/internet

Case Study:

Now, we are applying ProGuard to this Project.
We will use the following Maven plugin:

First of all, create a simple maven project, here I will use a spring boot maven project so simple, after I create this project, I will add to my pom.xml the following plugin in the plugins section inside the build section:

<plugin>
<groupId>com.github.wvengen</groupId>
<artifactId>proguard-maven-plugin</artifactId>
<executions>
<execution>
<phase>package</phase>
<goals><goal>proguard</goal></goals>
</execution>
</executions>
....
</plugin>

Let me explain a little bit about this structure, first of all, I’m using the proguard.maven.plugin hosted on com.github.wvengen, and in the executions section, I’m specifying the phase package from maven that executes on goal the Proguard. This part it’s straightforward, so, following, we have the configurations section:

<plugin>
...
<configuration>
<obfuscate>true</obfuscate>
<injar>${project.build.finalName}.jar</injar>
<outjar>${project.build.finalName}-small.jar</outjar>
<outputDirectory>${project.build.directory}</outputDirectory>
<proguardInclude>${basedir}/proguard.conf</proguardInclude>
<injarNotExistsSkip>true</injarNotExistsSkip>
<options>
<option>-libraryjars &lt;java.home&gt;/lib/</option>
</options>
<libs>
<lib>${java.home}/jmods/java.base.jmod</lib>
<lib>${java.home}/lib/jrt-fs.jar</lib>
</libs>
</configuration>
...
</plugin>

Here we have to specify the configurations that we would like to be executed by Proguard, so at first, we use <obfuscate>true</obfuscate>to specify that we will obfuscate the project. <injar tag we put the name of the jar that is generated by the clean package before be obfuscated, we are repackaging the project with Proguard in the next steps, so for this reason, we put <outjar> with a similar name with something to differentiate like "-small” or "-obfuscated”suffix. We specify <outputDirectory>to let Proguard know where the directory of the application is built.

<proguardInclude> It`s an essential thing here, we are specifying to Proguard that we will include Proguard configuration files that will include each important specific configuration for our projects, think that the configurations on pom.xml are the most general configurations that will be very similar for any project that you will work with Proguard, and this "proguard.conf” it will contain a lot of other configs that are only specific to your current project, we will take a look at this file soon.

<injarNotExistsSkip>true</injarNotExistsSkip>just say to skip when doesn’t find a jar on dependencies of our project. <options> section we only put one option that we will let Proguard know where it’s our library jars on Java home. We will do the same for the libs section but specify the java.base.jmod file and jrt-fs.jar file (if you are using Java 8 or before, you will need to specify in another way) something like:

<libs>
<lib>${java.home}/jre/lib/rt.jar</lib>
<lib>${java.home}/jre/lib/jsse.jar</lib>
<lib>${java.home}/jre/lib/jce.jar</lib>
<!-- Add more libraries as needed for your application -->
</libs>

this are the configuration steps.

Finally, you need to put the dependencies section specifying the Proguard version, at the time, I’m using version 7.2.2:

<plugin>
...
<dependencies>
<dependency>
<groupId>com.guardsquare</groupId>
<artifactId>proguard-base</artifactId>
<version>${proguard.version}</version>
</dependency>
</dependencies>
....
</plugin>

After I add another plugin configuration for the Maven spring project to define my main method, this is very important to recognize where the start of the application is to work the project after the jar is obfuscated.

<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
<executions>
<execution>
<goals>
<goal>repackage</goal>
</goals>
<configuration><mainClass>com.example.obfuscation.obfuscation_example.ObfuscationExampleApplication</mainClass></configuration>
</execution>
</executions>
</plugin>

Remember that I said before that we will repackage the application? It’s very necessary to specify here, the goals of the spring-boot-maven-plugin, and in configuration, I’m specifying the main class to Proguard recognize the entry point of my application.

So now, we will have something like this in our build section:

 <build>
<plugins>
<plugin>
<groupId>com.github.wvengen</groupId>
<artifactId>proguard-maven-plugin</artifactId>
<executions>
<execution>
<phase>package</phase>
<goals><goal>proguard</goal></goals>
</execution>
</executions>
<configuration>
<obfuscate>true</obfuscate>
<injar>${project.build.finalName}.jar</injar>
<outjar>${project.build.finalName}-small.jar</outjar>
<outputDirectory>${project.build.directory}</outputDirectory>
<proguardInclude>${basedir}/proguard.conf</proguardInclude>
<injarNotExistsSkip>true</injarNotExistsSkip>
<options>
<option>-libraryjars &lt;java.home&gt;/lib/</option>
</options>
<libs>
<lib>${java.home}/jmods/java.base.jmod</lib>
<lib>${java.home}/lib/jrt-fs.jar</lib>
</libs>
</configuration>
<dependencies>
<dependency>
<groupId>com.guardsquare</groupId>
<artifactId>proguard-base</artifactId>
<version>${proguard.version}</version>
</dependency>
</dependencies>
</plugin>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
<executions>
<execution>
<goals>
<goal>repackage</goal>
</goals>
<configuration><mainClass>com.example.obfuscation.obfuscation_example.ObfuscationExampleApplication</mainClass></configuration>
</execution>
</executions>
</plugin>
</plugins>
</build>

Now, it’s time to configure our Proguard file proguard.conf.I created the file on the root directory of the project and added the following lines:

# proguard.conf

# Keep public classes and their main methods (if any)
-keep public class com.example.obfuscation.obfuscation_example.EncryptDecryptRSA {
public static void main(java.lang.String[]);
}

# Keep serialization-related classes and members
-keepclassmembers class * implements java.io.Serializable {
static final long serialVersionUID;
private static final java.io.ObjectStreamField[] serialPersistentFields;
private void writeObject(java.io.ObjectOutputStream);
private void readObject(java.io.ObjectInputStream);
java.lang.Object writeReplace();
java.lang.Object readResolve();
}

-keep it a reserved word to specify to Proguard that these classes are important to our project run, I’m saying that I’m using this in some place of my business logic code (remember the class that we saw previously on this article EncryptDecryptRSA). We use here to specify the main method inside this class(different from our main spring method) by the pattern:
-keep + declaration of the type of filepublic class+ Package com.example.obfuscation.obfuscation_example.EncryptDecryptRSA+ open and close keys operator that is used to define the content inside of this class we need to keep here we specify the main method with your parameters public static void main(java.lang.String[]);

-keepclassmembersworks similarly, but we specify the members inside a class that it`s necessary for our application to run class * implements java.io.Serializablewe pass how it’s declared the class, using wildcard *that we are saying here to Proguard, that we need all classes that implement java.io.Serializable. We open and close keys to inform the necessary methods and properties, here I put:

static final long serialVersionUID;
private static final java.io.ObjectStreamField[] serialPersistentFields;
private void writeObject(java.io.ObjectOutputStream);
private void readObject(java.io.ObjectInputStream);
java.lang.Object writeReplace();
java.lang.Object readResolve();

see that I don`t need to specify the implementation only the method signature. If I want, I can remove all these lines and put the wildcard operator * to say to Proguard that I need all from these classes, but I like to explain the two ways.

Get italo gouveia’s stories in your inbox

Join Medium for free to get updates from this writer.

Finally added these configurations, you can run a: mvn clean package on your project and you will have a generated jar obfuscated.

Checking the generated obfuscated files:

  1. Extract the JAR File: Use any zip extraction tool (like WinRAR, 7-Zip, or command-line tools) to extract the contents of the JAR file to a directory on your system.
mkdir jar_contents
cd jar_contents
jar xf path/to/your-jar-file.jar

Look for Obfuscated Classes: Navigate through the extracted directory structure to find the .class files. Obfuscated classes typically have names that are not easily recognizable (such as single characters or random strings) compared to their original names in the source code.

cd jar_contents
find . -name "*.class"
(or just go to the file if this find doesn`t work)

Finally, we will have this obfuscated code, if you go to your file system and search the file, you will see this:

�������A���w�x�z�{�|�}�~��������������������������������������������� ��V

�

�D

�

�E

��B

��H

��J

��P

��U

��B

��?

��@

��X

��A

��F

��[

��W

��O

��>

��C

��G

��L

��Q

��R

��K

��M

��T

��Z

��Y

��I

��N

��S �v�b �v�g �v�h �v�i �v�o �v�r ���p ���t ���b ���l ���c ���s ���c ���_ ���d ���m ���n ���^ ���\ ���` ���a ���f ���e ���c ���� ���o ���] ���j ���q ���k�()Ljava/io/File;�()Ljava/lang/Object;�()Ljava/lang/String;�()Ljava/security/KeyPair;�()Ljava/security/PrivateKey;�()Ljava/security/PublicKey;�()V�()Z�()[B�(I)V�(ILjava/security/Key;)V�(Ljava/io/File;)V�(Ljava/io/InputStream;)V�(Ljava/io/OutputStream;)V�&(Ljava/lang/Object;)Ljava/lang/Object;�(Ljava/lang/Object;)V�&(Ljava/lang/String;)Ljava/lang/String;�4(Ljava/lang/String;)Ljava/security/KeyPairGenerator;�)(Ljava/lang/String;)Ljavax/crypto/Cipher;�(Ljava/lang/String;)V�/(Ljava/lang/String;Ljava/security/PublicKey;)[B�([B)Ljava/lang/String;�([B)V�([B)[B�0([BLjava/security/PrivateKey;)Ljava/lang/String;�([Ljava/lang/String;)V�<init>�C:/keys/private.key�C:/keys/public.key�Code�Decrypted Message: �Encrypted Message: �Example message�$Exception occurred during encryption�(Exception occurred during key generation�!Exception occurred in main method�Ljava/io/PrintStream;�!Original Message: Example message�RSA�

StackMapTable�[B�[Ljava/lang/String;�a�close�=com/example/obfuscation/obfuscation_example/EncryptDecryptRSA�concat�

createNewFile�doFinal�exists�generateKeyPair�getBytes� getInstance�

getMessage�

getParentFile�

getPrivate� getPublic�init�

initialize� java/io/File�java/io/FileInputStream�java/io/FileOutputStream�java/io/ObjectInputStream�java/io/ObjectOutputStream�java/io/PrintStream�java/lang/Exception�java/lang/Object�java/lang/String�java/lang/System�java/security/KeyPair�java/security/KeyPairGenerator�java/security/PrivateKey�java/security/PublicKey�java/util/Arrays�java/util/Objects�javax/crypto/Cipher�main�mkdirs�out�println�

readObject�requireNonNull�toString� writeObject�!�

��������v�b��y��������*��0������

���p��y���M�����’

��<YM+��=,*��3��;�M��,��/��2��.������������� ��������

���t��y���S�����-

��<YM+��=,*��;K��Y*��1�M��,��/��2��.������������� �������� ���u��y��e����/��Y��”K��Y��”L*��$��+��$�������

��7YK���8*��6L��Y��”YK��%��&W*��#W��Y��Y*��(��+YK+��4��-*��,��Y��”YK��%��&W*��#W��Y��Y*��(��+YK+��5��-*��,��K��*��/��2��.��Y��Y��’��)YK��*��K*�� L��Y��Y��’��)YK��*��K+*��!K�� ��.��+��9��2��.��*��:����2��.�K��*��/��2��.���*�����������������&@��}���h���

image: reproduction/internet

Here I cannot do a good indentation because the medium code block tool does not recognize more like code, see how it’s hardest to do reverse engineering now. Almost impossible.

So, you now have your code obfuscated, practice by yourself, check documentation and the options that are possible to you.

We will discuss these possibilities in a future article.

Summary:

In this article, we covered:

  • What is Obfuscation and its role in protecting Java code.
  • ProGuard, a powerful tool for Java code obfuscation.
  • Best Practices for implementing obfuscation techniques.
  • Case Study using ProGuard in a Maven project to secure Java applications.

Next Steps

Explore advanced configurations in ProGuard, such as custom optimizations and further obfuscation techniques tailored to specific project needs. Stay tuned for more insights and updates on cybersecurity practices and tools.

How to Stay Updated:

  • Follow Security Blogs and Publications: Stay informed on emerging obfuscation techniques.
  • Attend Security Conferences and Webinars: Participate in events discussing cybersecurity advancements.
  • Engage with the Security Community: Join forums and communities dedicated to cybersecurity discussions.
  • Monitor Vendor Updates: Stay updated on software updates and new security features.
  • Continuous Learning: Keep learning through courses and certifications to stay abreast of evolving cybersecurity trends.

Share Your Experience:

Have you implemented obfuscation in your projects? Share your approach and experiences in the comments. If this article has been helpful, leave a comment and like it! Follow for more updates and articles.

Press enter or click to view image in full size
Image: Reproduction/Internet

References

Repository from this project:

https://github.com/italo-gouveia/obfuscation-example

Other references:

--

--

Written by italo gouveia

I have 𝟔+ 𝐲𝐞𝐚𝐫𝐬 as a full-stack developer, in the banking, health insurance, and telecommunications sectors.

Published in System Weakness

System Weakness is a publication that specialises in publishing upcoming writers in cybersecurity and ethical hacking space. Our security experts write to make the cyber universe more secure, one vulnerability at a time.