Android code obfuscation for apps

Source: Internet
Author: User

Receive a new task to code-mix existing projects. There has been some understanding of the confusion, but not enough detail and completeness, knowing that some things are tricky to mix up. But fortunately the current project is not too complex (for confusing this piece), the early completion ~ ~ Now summarized.


The first part

Introduction to the operating procedure (Eclipse):

1. Open the obfuscation: Locate the Project.Properties file under the project root directory and "#proguard. Config=${sdk.dir}/tools/proguard/proguard-android.txt: Proguard-project.txt "#" Before this line can be deleted;

2, modify the confusing configuration file: Find the project root directory under the Proguard-project.txt file, modify the code, this part is the most important;

3, save the relevant files for later use: The main export APK file, the project root directory under the Proguard directory of files (mainly mapping.txt) and project source;

4, the project operation process error handling: According to the error message and the 3rd step saved in the mapping location error.


Once we know this, we'll start with it. Open Eclipse and create a new project, Proguard-project.txt and Project.Properties are created by default. Write our code and then proguard-project.txt the "#proguard. Config=${sdk.dir}/tools/proguard/proguard-android.txt: Proguard-project.txt "#" Before this line is deleted, the final export can be confused with the code, even if we did not write the content in the Proguard-project.txt. Here is my test code:

public class Mainactivity extends Activity {private String mname; @Overrideprotected void OnCreate (Bundle Savedinstancestate) {super.oncreate (savedinstancestate); Setcontentview (r.layout.activity_main); mName = "Ttdevs"; GetString (Mname); SetName (mname); ShowDialog ();//Testerror ();} public string getString (string name) {return "Hello" + Name;} public void SetName (String name) {System.out.println ("I ' m" + name);} private void ShowDialog () {new Handler (). postdelayed (New Runnable () {@Overridepublic void run () { Scorealertdialog.showdialog (Mainactivity.this);}}, 2000);}  public static class Scorealertdialog {public static void ShowDialog (final activity activity) {if (activity.isfinishing ()) {return;} try {alertdialog.builder Builder = new Alertdialog.builder (activity); Builder.settitle ("Alert_title"); Builder.setnegativebutton ("Cancel", null); Builder.setpositivebutton ("Submit", new Dialoginterface.onclicklistener () {@Overridepublic void OnClick (dialoginterface dialog, int which) {try {toast.maketext (ACTivity, "Welcome", Toast.length_long). Show (); catch (Exception e) {e.printstacktrace ();}}}); Builder.show ();} catch (Exception e) {e.printstacktrace ();}}} private void Testerror () {try {int error = 1/0;} catch (Exception e) {e.printstacktrace ()}}}

Package, decompile, and finally we get the following code:


Analyzing the above code we will find that the custom method name is replaced with a short letter with no special meaning, and the activity's OnCreate () method does not change, and the last Testerror () method is eliminated because we did not call it. These are the default obfuscation strategies. See here, feel confused or small case of HA ~ ~

Continue down, we will log off the Testerror () open, packaging run this time will be an error message, errors are as follows:

 Java.lang.ArithmeticException:divide by zero at com.ttdevs.proguard.mainactivity.b (Unknown Source) at Com.ttdevs.proguard.MainActivity.onCreate (Unknown Source) at Android.app.Activity.performCreate (Activity.java : 4531) at Android.app.Instrumentation.callActivityOnCreate (instrumentation.java:1071) at Android.app.ActivityThread.performLaunchActivity (activitythread.java:2150) at Android.app.ActivityThread.handleLaunchActivity (activitythread.java:2229) at android.app.activitythread.access$ (activitythread.java:139) at Android.app.activitythread$h.handlemessage (activitythread.java:1261) at Android.os.Handler.dispatchMessage (handler.java:99) at Android.os.Looper.loop (looper.java:154) at Android.app.ActivityThread.main (activitythread.java:4945) at java.lang.reflect.Method.invokeNative (Native Method) At Java.lang.reflect.Method.invoke (method.java:511) at Com.android.internal.os.zygoteinit$methodandargscaller.run (zygoteinit.java:784) at Com.android.internal.os.ZygoteInit.main (Zygoteinit.java: 551) at Dalvik.system.NativeStart.main (Native Method) 

As this example is simple, it is easy to see where the problem is, but it can be used to illustrate the problem we want to express: How to restore the confusing code error message. To achieve this, we need three files: Android-sdk-windows\tools\proguard\bin\retrace.bat, Mapping.txt, and the above error message (Log.txt). Then execute the following command (Window System):

Retrace.bat Mapping.txt Log.txt


From there you can see clearly that the B () method in the error log is the SetName () method in our actual code.

It is important to note that each time you export the APK will generate a corresponding mapping file under the Proguard folder in the project directory, so for each apk we need to save the corresponding mapping file. At this point the entire confusing process is complete.

Reference:

Official Document: Http://developer.android.com/tools/help/proguard.html

Official Document translation: Http://www.cnblogs.com/over140/archive/2011/04/22/2024528.html (I would like to go through one, the results found a long time ago, the farmer uncle has translated, directly quoted and thanks)


Part II


The first part tells how to operate, according to the official documents, basically will master. The rest is the hardest thing to do is to write the Proguard-project.txt file. For this part, two processing strategies: write yourself and use someone else to write well. First of all, how to use someone else to write well, we refer to the third-party library whether open source or closed sources if there is a special case we can find in his user guide the configuration of the confusing code, as we quoted the famous Guillep Pulltorefresh, We can find the following code in his document:

-optimizationpasses 5- Dontusemixedcaseclassnames-dontskipnonpubliclibraryclasses-dontpreverify-verbose-optimizations!code/ Simplification/arithmetic,!field/*,!class/merging/*-keep public class * extends Android.app.activity-keep public Class * Extends Android.app.application-keep public class * extends Android.app.service-keep public class * extends Androi D.content.broadcastreceiver-keep public class * extends Android.content.contentprovider-keep public class * extends Android.app.backup.backupagenthelper-keep public class * extends Android.preference.preference-keep public class Com.android.vending.licensing.ilicensingservice-keepclasseswithmembernames class * {native <methods>;} -keepclasseswithmembernames class * {public <init> (Android.content.Context, android.util.AttributeSet);} -keepclasseswithmembernames class * {public <init> (Android.content.Context, android.util.AttributeSet, int);}    -keepclassmembers enum * {public static **[] values (); Public static * * VALUEOF (java.lang.String);} -keep class * Implements android.os.Parcelable {public static final Android.os.parcelable$creator *;}
With this part of the code we can directly copy into our project. This method is still copy-style. Let's take a little example to see how we can write our own code to control confusion. In the first part of the example, we add the following lines ("#" in Proguard-project.txt for comments) in the project's Proguard-project.txt file (previously empty):

#-keep public class com.ttdevs.proguard.** {*;} #-keepclasseswithmembers public class com.ttdevs.proguard.** {*;} -keep public class Com.ttdevs.proguard.MainActivity {java.lang.String getString (java.lang.String);}
Then we export the APK and then decompile it to get the following code:



In contrast to previous comparisons, we found that the GetString method was not confused. Yes, the above proguard-project.txt means to keep the mainactivity GetString () method from being confused. You can also try the above-mentioned confusion in the code of the two lines are commented on what effect.

This has begun to involve the core of Proguard, and the rest is to study Proguard's documentation, to master his grammar and to use it. I want to find a complete proguard translation documents, but found a n long did not find a, and even fragmented translation is very little, the recent time is very tight, coupled with limited capacity, want to translate a few commonly used commands are also very sleepy, so the idea of fine reading can only be pushed backwards. Here is a brief introduction to the following Keep command:

-keep [, modifier,...] Class_specification

Specify the classes or members of the class (properties and methods) that are retained as pointcuts in your code. For example, to maintain an application, you can specify the main class and his main method. In order to process a library, you need to specify the elements of his public access.

There is also a brief overview of Keep and the syntax of the specification. Class specification will show you how to represent the construction methods, properties and methods, the difference between "*" and "* *", and so on. For example, "*" means matching any class name but does not include the package delimiter, while "* *" matches any class name and includes any number of package delimiters. So the code we commented on above means the following: the first line: all methods that keep all classes under Com.ttdevs.proguard and sub-packages are not confused, and the second row keeps all methods and member variables of the class under Com.ttdevs.proguard and all the classes under the sub-package are not confused.

There are many TODO details, such as-libraryjars,-dontwarn,-keepattributes, and so on.

Reference:

Proguard 5.0:http://proguard.sourceforge.net (Proguard 4.7)


Android code obfuscation for apps

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.