Android and "Proguard"--code confusion for Android

Source: Internet
Author: User
Tags modifiers

In this article, I remember when I was in the company internship, the first formal, really meaningful task-the company will release the APK for code confusion.


What is code obfuscation

Confusion is the re-organization and processing of the published program, so that the processed code and the pre-processing code to complete the same function, and the confusing code is difficult to decompile, even if the anti-compilation success is difficult to derive the true semantics of the program. The obfuscated program code, still in accordance with the original file format and instruction set, the execution result is the same as before, but the confusion of all the variables, functions, classes in the code to the name of the short English letter code, in the absence of the corresponding function name and program comments, even if it is anti-compilation, it will be difficult to read. At the same time confusion is irreversible, in the process of confusion, some information that does not affect the normal operation will be lost permanently, the loss of this information makes the program more difficult to understand.


Why do you want to confuse code>java is a cross-platform, interpreted language in which Java source code is compiled into an intermediate "bytecode" stored in a class file. Because of the cross-platform requirements, Java bytecode contains a lot of source code information, such as variable name, method name, and through these names to access variables and methods, these symbols with a lot of semantic information, it is easy to decompile the Java source code. To prevent this, we can use Java obfuscation to confuse Java bytecode.
The role of the > obfuscation is not just to protect the code, it also has the function of simplifying the size of the compiled program. Taking "Proguard" as an example, the main function of "Proguard" is to confuse, and it can reduce the size and optimization of bytecode. Because the variable name and the method name are reduced, and the previously mentioned part does not affect the normal operation of the information will be lost, so that the volume of the compiled jar file is reduced, the file is streamlined.
How to do code obfuscationAt present, the mainstream code confusion is the use of "Proguard", at the same time, you can search the Internet code confusion, code reinforcement and other services, you can easily find such as "360 reinforcement", "Love Encryption" and other third-party services. So where are the differences between them:1> Use the tool, is on your own computer, through the configuration of "Proguard" and other tools, their own code confusion, compiling themselves, debugging themselves. The use of third-party services, is to upload your own apk, to their site, they help you to confuse, confusion/reinforcement completed, and then the confusion of the APK sent back to you.2> using tools, apk from start to finish in your own hands, if the use of third-party services, the original apk will need to pass to others, which adds to the insecurity, of course, you may say, others so big company how to covet your apk? The view on this issue is different for each person, like my internship at that time to deal with my company's project, my "leader" specifically requires that they use the tool manually confused, can not use the third-party services, can not pass the APK to others.
What is "Proguard"?"Proguard" is an open source project that confuses code. Its main role is to confuse, of course, it can also reduce the size of bytecode, optimization, etc., but for us, volume compression and optimization function, is not the most important. What we really care about is his confusing function. This is the "proguard" profile, if you want to see the details, here is attached to the official website address: http://proguard.sourceforge.net/

What optimizations can be made for "Proguard"?

The following information from the network:

In addition to the useless classes, fields, and methods that are removed by the compression operation, "Proguard" also provides performance optimizations at the bytecode level, with internal methods:> Constant expression evaluation. > Delete unnecessary field access. > Remove unnecessary method calls. > Delete unnecessary branches. > Remove unnecessary comparisons and instanceof validation. > Remove Unused code. > Delete a write-only segment. > Remove Unused method parameters. > A variety of peephole optimizations like Push/pop simplification. > Add the static and final modifiers to the class, if possible. > Add private, Static, and final modifiers to the method, if possible. > Make the Get/set method inline, where possible. > Replace the interface when it has only one implementation class. > Selective deletion of log code.

The actual optimization effect is dependent on your code and the virtual machine that executes the code. A simple virtual machine is more efficient than an advanced virtual machine with a complex JIT compiler. In any case, your bytecode will get smaller.
There are still a few technologies that are obviously needed to be optimized not supported:

> Makes a non-final constant field inline.

> makes other methods inline just like the Get/set method.

> Moves a constant expression outside of the loop.


How to use "Proguard"The cause and meaning of the confusing code, and the various benefits of "Proguard" are described, and now we can use this tool. First, the following instructions are all based on the Eclipse development environment, Android2.3 later versions.

Before Android 2.3, it was very inconvenient to confuse Android code by manually adding Proguard for code obfuscation. After 2.3, Google has added this tool to the SDK's toolset. The specific path to the tool: Sdk\tools\proguard. When you create a new Android project, a proguard configuration file proguard.cfg appears under the root path of the project directory. In other words, we can use the simple configuration to confuse Android engineering directly with Proguard in our Elipse project.

How to start "Proguard"

In the project root path, find the "project-properties.txt" file, the source code is as follows:

# This file was automaticallygenerated by Android Tools.

# Do not modify the This file--yourchanges'll be erased!

#

# This file must is checked inversion Control Systems.

#

# to customize properties used bythe Ant build system Edit

# "Ant.properties", andoverride values to adapt the script to your

# project structure.

#

# to enable Proguard to shrink andobfuscate your code,uncomment this (available properties:sdk.dir,user.home):

# proguard.config=${sdk.dir}/tools/proguard/proguard-android.txt:proguard-project.txt

# Project Target.

target=android-22

You just put the blue piece of Code, the "#" in front of the "#" to remove, you can start the "proguard" tool, of course, the blue is not the original color of this file, I am in the article in order to explain the added. Now for the guided package operation, Eclipse automatically uses the Proguard tool during the guide. Another point to note is that your direct "run" to the device's application is not confused, even if you have launched the "Proguard" tool, only manual boot after the obtained apk, is the obfuscation tool has been processed.
How to configure "Proguard" to confuse filesI said earlier how to start the "Proguard" tool, for some very simple project (no reference to third-party libraries, no custom view, no call "native" layer method), such as one of your test "demo", may not have to configure what, as long as the tool is started, The confusing work is done. But for more complex projects, we need to manually configure something to ensure that the obfuscation process is complete properly, and that the APK runs after the confusion. So why do complex projects have to be manually configured? The root cause is: Not everything can be confused, some code confusion, its corresponding function can not be used. This is mainly reflected in two places:1> all third-party reference libraries can not be confused, as long as the confusion, the basic error. 2> such as custom "View", "native" layer of the method, and so on can not be confused, the corresponding function of confusion after the error, this kind of code is more, I only listed two here, I will detail some of the following. Configure the obfuscation file is to tell the system, something can not be confused, so that my app will be wrong, now in detail how to configure the "Proguard" confused files.
Two configuration files related to obfuscation1> default configuration: When the project was first created, the development environment has been configured by default to confuse settings, you can find a "proguard-android.txt" file under the "Eclipse Path \sdk\tools\proguard\" path, This file is a development environment auto-configuration, confusing settings, which is why for very simple projects, they do not have to be configured separately, the system default configuration can be satisfied. For the default configuration here only path introduction, followed by the focus of the problem, how to according to the specific situation of the project, self-configuration confusing files.2> Custom configuration: Under the root path of the project, there is a file: Proguard-project.txt. This file is the place to configure manually. We need to write the file according to the actual situation of the project, according to certain grammatical rules, so as to pass the confusing process normally.
Specific rules for custom configuration

In the "proguard-project.txt" file to write the confusion rules, there is only one purpose: If a class is confused, will cause the app to not run properly (or some of the function does not work properly) then in the configuration file, declare not to confuse these classes. I do not care why these classes are confused and then go wrong, only care about which classes make mistakes after they are confused, and then declare in the file not to confuse these classes. Of course, if you have to be inquisitive, you can also find more detailed information on the Internet.

General rules

The following is a common class of classes that almost all projects have to avoid (the so-called avoidance is to declare these classes not to be confused):


> Four components and the basic API of the system do not confuse.

Syntax rules:-keep public class * extends xxxx

code example:

#所有 "Activity" and its subclasses do not confuse, in the same vein, all "Service", "Broadcastreceiver" and so on system-level classes, do not confuse. -keep public class * Extendsandroid.app.activity-keep public class * Extendsandroid.app.application-keep public class * EX Tendsandroid.app.service-keep public class * Extendsandroid.content.broadcastreceiver-keep public class * Extendsandroid.content.contentprovider-keep public class * Extendsandroid.app.backup.backupagenthelper-keep public Class * Extendsandroid.preference.preference-keep public Classcom.android.vending.licensing.ILicensingService


> Keep the "native" layer in a way that does not confuse.

-keepclasseswithmembernamesclass * {         native<methods>;}


> Keep the custom control, and specify the format construction method do not confuse.

-keepclasseswithmembers class * {public    <init> (Android.content.Context, android.util.AttributeSet);  #保持自定义控件类不被混淆, the constructor of the specified format does not confuse}-keepclasseswithmembers class * {public    <init> (Android.content.Context, Android.util.AttributeSet, int);}


> The method of keeping the specified rule is not confused (the OnClick method configured for the control in the Android layout file cannot be confused)

-keepclassmembersclass * extends android.app.Activity {public    void * (Android.view.View);}

> Keep custom controls from being confused by specifying rules

-keeppublic class * extends Android.view.View {     public<init> (android.content.Context);    Public<init> (Android.content.Context, android.util.AttributeSet);    Public<init> (Android.content.Context, android.util.AttributeSet, int);    public void set* (...);}


> Do not confuse all enum types

-keepclassmembers enum * {public    static **[] values ();   public static * * VALUEOF (java.lang.String);}

> classes that require serialization and deserialization cannot be confused (note: Classes used by Java reflection cannot be confused)

Classes that #保持实现 the "Serializable" interface are not confused-keepnamesclass * Implements java.io.serializable# protection implements the interface Serializable class, The class member that specifies the rule is not confused-keepclassmembersclass * Implements Java.io.Serializable {    static final long serialversionuid;    private static finaljava.io.objectstreamfield[] serialpersistentfields;    ! Static!transient <fields>;    Private Voidwriteobject (Java.io.ObjectOutputStream);    Private Voidreadobject (Java.io.ObjectInputStream);    Java.lang.Object writereplace ();    Java.lang.Object readresolve ();}


> Keep classes that implement the "parcelable" interface not to be confused

-keepclass * Implements android.os.Parcelable {public     static finalandroid.os.parcelable$creator *;}


> All generics cannot be confused

-keepattributes Signature

> If the project is useful to annotations, you should include this line of configuration

-keepattributes *annotation*


> keep R files from being confused, otherwise, your reflection is not getting the resource ID

-keep class * *. r$*{*;}


> Protection webview the API for HTML pages is not confused

-keep class * *. webview2jsinterface {*;}

> If you're using WebView's complex operations in your project, it's a good idea to join

-keepclassmembers class * extends Android.webkit.WebViewClient {public       void * (Android.webkit.WebView, JAVA.LANG.STRING,ANDROID.GRAPHICS.BITMAP);     public Boolean * (android.webkit.webview,java.lang.string);} -keepclassmembers class * extends Android.webkit.WebChromeClient {public       void * (Android.webkit.WebView, java.lang.String);}
At this point, the main general rules have been introduced, you can directly copy into the "proguard" configuration file, these rules are common.
Keep third-party reference libraries (third-party jar packages) from being confusedThe previous article has discussed the confusion of general rules, if a project, no reference to the third-party library, basically you just put the previous rules according to the situation to copy up, confusion is not a basic problem. But now most of the projects (especially the company's projects) will more or less introduce a third-party library, the previous article has already mentioned that all third-party reference libraries can not be confused, so we will talk about how to keep the third-party library is not confused.

In fact, it is not complicated to keep the third-party library, the most important thing is to be careful + patient. Why is it? Keeping the third-party library from being confused is to put all of the third-party libraries you reference, in a certain syntax format, in a confusing configuration file, simply by referring to all third-party references in your "Eclipse" project under the "Android Private Libraries" directory, In the given syntax format, all (note All) is written in your "proguard.project.txt" file. Let's look at the picture and talk.


A picture wins thousands of words, then we summarize, for each third party import package, we just: >-libraryjars Libs/xxxx.jar>-dontwarn package name. **>-keep class Package name. * * {*;} Most of the third-party packages can be configured according to this rule, some third-party referral packages, on their official website will have confusing code configuration instructions, such as the high-gold map, this time you copy it up. All right, now let's put all the third-party packages on, and write them down.
Run the program, check the leakIn general, the obfuscation process will pass normally (without error) following the configuration of the rules we discussed earlier. Unfortunately, the confusion does not mean that you can run the app, as we mentioned before, some things can not be confused, when you confuse his function will be wrong. When you're done with the confusion, just run your app, and each function is pressed and played, and it's possible that something strange will happen. That's why we need to do a leak check.After first performing the confusion, we were able to find a new four files that appeared under the path "Proguard":

>mapping.txt: This is a very important file that represents a comparison of the code before and after the confusion. If your code is confusing and generates a bug, the log hint is a confusing code, and if you want to locate the source code, you can reverse it by mapping.txt. Keep it up every time you publish it to facilitate the issue of this version of the log for troubleshooting, it can be based on the version number or the name of the publication time to save or put into the code version control.

>dump.txt: Describes the internal structure of all class files within the APK.
>seeds.txt: Lists classes and members that are not confused.
>usage.txt: Lists code in the source code that does not exist in the APK.

After I finished confusing the code on my own project, two strange things happened, and now I'm going to talk about how to use these files for resolution.> After the confusion of the app, all the data in the list (ListView) is not displayed, after confirming that the data has indeed been received, is not displayed, in the Usage.txt file, found all "ListView" adapter, that is, after the confusion of the APK, There is no adapter in the code, so the display failed, and what I did was to add the following code in the obfuscation configuration file (proguard.project) file:
#保持所有适配器类不被混淆, in this application, without this will cause the adapter class to fail to load, and all list items cannot be displayed-keep public class * extends Android.widget.BaseAdapter

But this is not a confusing configuration rule, because my other one is similar to my project structure, but he did not add this sentence, his list is showing normal. This is an example of using the "Usage.txt" file to check for leaks.> Confusion after the app, the more the card (in fact, is the memory leak), with the use of mobile phone will be inexplicably crashed, not only the application card dead, the whole cell phone is not moving. Whatever you do in the app will cause the app to kill the phone. This exception is ultimately not solved by the previous four files, but by considering the app functionality. Based on the phenomenon, it can be seen that there must be something global, confusion after the error occurred, resulting in the global function can not run, but continue to request, eventually exhausted system resources. The final reason for this is that the push and IM functionality of our app is not working after the confusion, eventually exhausting system resources. The solution, then, is to declare that he is not to be confused.
SummarizeWe talked about so many things, first introduced what is called code obfuscation, then introduced the obfuscation options, followed by how to start and configuration confusion, the most important of course is configuration confusion. These include general rules, third-party packages, and gaps in the search for leaks based on confusing documents. At this point, the code of the app to confuse the basis, the introduction is complete.

Android and "Proguard"--code confusion for Android

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.