Android app for code obfuscation example detailed _android

Source: Internet
Author: User
Tags static class

Received a new task to confuse existing projects with code. There has been some understanding of confusion before, but it's not detailed and complete, and it's tricky to know something is confusing. But fortunately the current project is not too complex (for the confusion of this piece), completed in advance ~ ~ Now summed up.

First part

Introduction to the operating process (Eclipse):

1. Open obfuscation: Locate the Project.Properties file under the root directory of the project, and "#proguard. Config=${sdk.dir}/tools/proguard/proguard-android.txt: Proguard-project.txt "This line before the" # "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 critical;

3, save the relevant files for later use: mainly exported apk files, the project root directory under the Proguard directory files (mainly mapping.txt) and project source code;

4, the project runs the process error processing: According to the error message and the 3rd step saves the mapping to locate the wrong position.

Knowing this, we unfold it. Open Eclipse and create a new project, creating Proguard-project.txt and Project.Properties 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 confusing to the code, even if we do not write the content in Proguard-project.txt. Here's my test code:

public class Mainactivity extends activity {private String mname;
    @Override protected 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 () {@Override public void run ()
      {Scorealertdialog.showdialog (mainactivity.this);
  }, 2000); public static class Scorealertdialog {public static void ShowDialog (final activity activity) {if (acti
      Vity.isfinishing ()) {return;
        try {alertdialog.builder Builder = new Alertdialog.builder (activity);
        Builder.settitle (Alert_title); Builder.setneGativebutton (cancel, null); Builder.setpositivebutton (Submit, New Dialoginterface.onclicklistener () {@Override public void onclic K (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:


Analysis of the above code we will find that the custom method names are replaced with no special meaning of the short letter, and the activity of the OnCreate () method has not changed; the last Testerror () method was removed because we did not call. These are the default obfuscation strategies. See here, feel confused or small case of HA ~ ~

Continue down, we will log off of the Testerror () open, package run this time will be an error, the message is as follows:

Java.lang.ArithmeticException:divide by Zero in com.ttdevs.proguard.mainactivity.b (Unknown Source) at Com.ttdevs.pro Guard. 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)
 

Because this example is simpler, it's easy to see where the problem is, but it can be used to illustrate the problem we want to express: How to restore the error message of the confusing code. To achieve this, we need three files: android-sdk-windows Oolsproguardin etrace.bat, Mapping.txt, and the error message above (Log.txt). Then execute the following command (Window System):

Retrace.bat Mapping.txt Log.txt


It is clear from the above figure that the B () method in the error log is the SetName () method in our actual code.

Note that each export 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. The entire confusing process has been introduced.

Reference:

Official documents: http://developer.android.com/tools/help/proguard.html

Official translation of the document: Http://www.cnblogs.com/over140/archive/2011/04/22/2024528.html (I would like to go over one, the results found a long time ago the farmer uncle has been translated, this direct quote and thanks)

Part II

The first part of how to operate, referring to official documents, the basic will master. The hardest part of the rest is the writing of proguard-project.txt documents. For this part, two processing strategies: write and use the others. First say how to use other people to write good, we refer to the Third-party library whether open source or closed sources if there are special circumstances, we can find the configuration of confusing code in his user guide, such as we quote 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 Android.content.broadcastreceiver-keep public class * extends Android.content.ContentProvid Er-keep public class * extends Android.app.backup.backupagenthelper-keep public class * extends Android.preference.Prefe Rence-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 *;}
 </init></init></methods>

With this part of the code, we can directly copy into our project. This approach is still copy-style. Let's take a small example to see how to write code control is confusing. Or in the first part of the example, we add the following lines in the project's Proguard-project.txt file (previously empty) (Proguard-project.txt "#" in the comments):

#-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're exporting apk and then decompile it and 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 not to be confused. You can also try the two lines that are annotated in the above confusing code to see what the effect is.

Now that this has begun to involve the core of Proguard, the rest is to study Proguard's documentation, master his grammar and use it. I was looking for a complete Proguard translation document, but looking for a long time did not find a, and even the fragmented translation is very small, recently 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 temporarily pushed back. Here is a brief introduction to the Keep command:

-keep [, modifier,...] Class_specification

Specify the members (properties and methods) of the class or class that are retained as pointcuts in your code. For example, to keep an application, you can specify the main class and his main method. To work with a library, you need to elaborate on the elements of his public access.

There is also a simple overview of Keep and the syntax specification. Class specification tells you how to represent construction methods, attributes and methods, and the difference between "* *" and so on. For example, * indicates matching any class name but excluding the package delimiter, while * * matches any class name and includes any number of package delimiters. So the code we're commenting on above means the following: First line: All methods of preserving classes under Com.ttdevs.proguard and subclasses are not confused, and the second row retains all methods and member variables of all classes under Com.ttdevs.proguard and the class under the child package.
TODO details are many, such as-libraryjars,-dontwarn,-keepattributes, etc., to be continued.

Through this article hope to help readers to the confusion of code, thank you for your support to this site!

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.