Using Proguard in Android Application

 

Proguard is an optimizer for java bytecode. It detects and removes unused code from app and included libraries, also optimizes the bytecode. Proguard obfuscate code makes difficult to reverse engineer.

Proguard is a valuable tool for working around the 64k reference limit. Resource shrinking also works well in conjunction with code shrinking.

To enable code shrinking add minifyEnabled true to the release build type in build.gradle file.

android
{
	buildTypes
	{
		release
		{
			minifyEnabled true
			proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
		}
	}
...
}

Add custom proguard rules in proguard-rules.pro i.e. next to build.gradle file. Following common lines used in proguard-rules.pro file:-

To keeping source file and line number to view crash logs in crashlytics (Fabrics or Firebase)

-keepattributes SourceFile,LineNumberTable

Rename attributes to make it difficult for reverse engineering the file and package name.

-renamesourcefileattribute ANYNAME

For Jackson library add following lines:-

-dontwarn com.fasterxml.jackson.databind.**
-keepnames class com.fasterxml.jackson.** { *; }
-keep class com.fasterxml.jackson.databind.ObjectMapper {
public ;
protected ;
}
-keep class com.fasterxml.jackson.databind.ObjectWriter {
public ** writeValueAsString(**);
}

Also remove network model classes and methods from obfuscation as these class and method names are used by Jackson library for JSON parsing

-keepclassmembers class PACKAGE_NAME.responsemodel.* {
private ;
}
-keepclassmembers class PACKAGE_NAME.requestmodel.* {
private ;
}
-keep public class PACKAGE_NAME.responsemodel.* {
public void set*(***);
public *** get*();
}
-keep public class PACKAGE_NAME.requestmodel.* {
public void set*(***);
public *** get*();
}

For Facebook Library

-keep class com.facebook.** { *; }
-keepattributes Signature

Similarly for other libraries/sdk, we can check documentation for proguard setting and add these in our proguard-rules.pro file.

Decode obfuscated stack trace: Proguard creates a mapping.txt in the app /build/outputs/mapping/release/ directory. This mapping file is required to convert obfuscated stack trace to readable format. On Windows we can use retrace.bat for conversion to readable format (retrace.sh on Mac/Linux).

retrace.bat -verbose mapping.txt obfuscated_trace.txt

It is important to keep this mapping.txt file whenever we release build on play store. Firebase crash reporting also use this file to convert obfuscated stack trace into readable text.

Leave a Reply