Middle+
How do you view the process of code obfuscation?
sobes.tech AI
Answer from AI
Code obfuscation on Android is the process of modifying source code or bytecode in such a way that it becomes difficult to understand and decompile without losing functionality. This is done to protect intellectual property and prevent hacking.
Main goals of obfuscation:
- IP protection: Making reverse engineering more difficult for competitors or malicious actors.
- Reducing APK size: Removing unused code (optimization with ProGuard/R8).
In Android, the standard tools for obfuscation and optimization are ProGuard or its more modern version R8.
Principles of ProGuard/R8:
- Shrinking: Removing unused classes, fields, methods, and attributes.
- Optimizing: Analyzing and optimizing bytecode, e.g., inlining short methods.
- Obfuscating: Renaming classes, fields, and methods to short, meaningless names.
- Preverifying: Adding preverification information to speed up class loading in JVM.
How to configure obfuscation:
Use the proguard-rules.pro file (for ProGuard) or r8-rules.pro (for R8).
// Keep rules by default.
// See http://developer.android.com/intl/en/tools/help/proguard.html
-keepattributes InnerClasses
-keepattributes Signature
-keepattributes *Annotation*
// Don't warn about missing native libraries
-dontwarn sun.misc.Unsafe
-dontwarn kotlin.**
-dontwarn kotlinx.**
-dontwarn com.google.**
// General rules for code preservation
// For example, keep all activities
-keep public class * extends android.app.Activity
// Keep a specific class by full name
-keep class com.example.MyClass
// Keep all public methods of a specific class
-keep public class com.example.MyClass {
public <methods>;
}
// Exclude class packaging (for some dependencies)
-dontwarn com.squareup.picasso.**
// Examples of keeping models for JSON parsing
-keepclassmembers class com.example.models.** {
*; // Keep all members (fields and methods)
}
// Keep enums for reflection
-keepclassmembers enum * {
public static **[] values();
public static ** valueOf(java.lang.String);
}
// Additional rules for third-party libraries
// (often provided by library authors)
Important aspects:
- Keep rules: Carefully configure
-keeprules to preserve code accessed via reflection, native libraries, dynamically loaded classes, serialization/deserialization models (JSON, XML), and other parts of the app that cannot be statically analyzed by the compiler. - Debugging: When errors occur after obfuscation, the
mapping.txtfile can be used to map obfuscated names back to original names for debugging. - Size: Obfuscation, including code shrinking, can significantly reduce APK size.
- Performance: Bytecode optimization can improve performance.
- Compatibility: Incorrect obfuscation rules can cause app crashes.
ProGuard and R8 operate at the Java bytecode level. Native code (NDK) requires other tools for obfuscation.