77.Android Code Obfuscation

Source: Internet
Author: User

reprint: http://www.jianshu.com/p/7436a1a32891Brief introduction

As an Android developer, if you don't want to open up your app, you'll need to obfuscate the code before the app is released, making our code hard to read, even if it's deserialized. Confusing concept although easy, but a lot of beginners are just online search some molding confusion rules pasted into their own projects, and no confusion has a deep understanding. The purpose of this article is to let a beginner after reading, can without any help in the case, independently write the appropriate code for their own confusion rules.

Say in front

Here we use directly Android Studio to illustrate how to confuse, Android Studio self-integration Java language Proguard as a compression, optimization and obfuscation tools, with Gradle build tool use is very simple, You only need to set minifyenabled to true in the Gradle file of the project application directory. Then we can proguard-rules.pro add our confusion rule to the file.

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

The example code above indicates that the release version will be confused with the line. Let's take a brief introduction to the three functions of Proguard, and briefly describe the commands they commonly use.

Proguard effect

compression (Shrinking): enabled by default to reduce the application volume, remove unused classes and members, and execute again after the optimization action is performed (because some unused classes and members may be exposed again after optimization).

-dontshrink 关闭压缩

optimization (optimization): Enabled by default, performs optimizations at the bytecode level to make the app run faster.

-dontoptimize  关闭优化-optimizationpasses n 表示proguard对代码进行迭代优化的次数,Android一般为5

obfuscation (obfuscation): Default on, increase the difficulty of anti-compilation, class and class members will be randomly named unless protected with Keep.

-dontobfuscate 关闭混淆

Confusion after the default will generate a file in the project directory app/build/outputs/mapping/release mapping.txt , this is the confusion rule, we can according to this file to reverse the confusing code back to the source of the code, so this file is very important, pay attention to protection. In principle, the confusion of the code after the chaos of the better, but there are some places we want to avoid confusion, or the program will run error, so we have to teach you the following, how to make their own part of the code to avoid confusion and prevent errors.

Basic rules

Look at the following two more commonly used commands, many children's shoes may be more confusing the difference between the following two.

class cn.hadcn.test.**-keep class cn.hadcn.test.*

A star means just keeping the class name under the package, the class name under the sub-package is still confusing, and the two stars hold the class names under the package and the included sub-packages, and you will find that the class name is not confused, but the specific method and variable name are changed if you want to keep the class name. and want to keep the contents of the content not to be confused, we need the following methods

-keep class cn.hadcn.test.* {*;}

Based on this, we can also use Java's basic rules to protect certain classes from being confused, such as extend the Java rules we can use, and implement so on. The following example avoids the confusion of all classes that inherit activity

-keep public class * extends android.app.Activity

If we want to keep the inner class in a class from being confused, we need to use a $ symbol, as shown in the following example, to keep all public content in the Scriptfragment inner class javascriptinterface from being confused.

class cc.ninty.chat.ui.fragment.ScriptFragment$JavaScriptInterface { public *;}

Furthermore, if you don't want to keep the whole content from being confused in a class, but just want to protect the specific content under the class, you can use

<init>;     //匹配所有构造器<fields>;   //匹配所有域<methods>;  //匹配所有方法方法

You can also <fields> <methods> add private , public , and native wait to further specify what is not to be confused, such as

class cn.hadcn.test.One { public <methods>;}

Oneall methods under the class are public not confused, and of course you can add arguments, such as the following: constructors that use jsonobject as arguments are not confused

class cn.hadcn.test.One { public <init>(org.json.JSONObject);}

Sometimes you think, I do not need to maintain the class name, I just need to keep the specific method under the class is not confused, then you can not use the Keep method, the Keep method will keep the class name, and need to use keepclassmembers , so that the class name will not be maintained, in order to facilitate the understanding of these rules, The following form is given on the website

renamed renamed
reserved prevented from being removed orPrevent being
Class and Class members -keep -keepnames
Class Members Only -keepclassmembers -keepclassmembernames
If you have a member, keep the class and class members -keepclasseswithmembers -keepclasseswithmembernames

Remove refers to whether the compression (Shrinking) is deleted. The above content in the confusion rules need to focus on, after understanding, basic all the confusion rules file you should be able to understand. Together with the following considerations,

Precautions

The 1,jni method is not confusing, because this method needs to be consistent with the native method;

class * { # 保持native方法不被混淆        native <methods>;}

2, the reflected class is not confused (otherwise reflection may be problematic);

The classes in the 3,androidmainfest are not confusing, so the classes of the four components and the application subclasses and the framework layer are not confused by default . Custom View defaults will not be confused, so many of the rules that exclude custom view like online stickers, or the four components that are confused, are not required to be added to Android studio;

4, when interacting with the server, using Gson, Fastjson and other frameworks to parse the server data, the JSON object class is not confused, otherwise the JSON can not be parsed into the corresponding object;

5, the use of third-party open Source Library or reference to other third-party SDK packages, if there is a special requirement, also need to add the corresponding confusion in the confusing file rules;

6, useful to WebView JS Call also need to ensure that the interface method is not confused, the reason and the same as the first article;

7,parcelable and creator static member variables are not confused, otherwise the Android.os.BadParcelableException exception will occur;

class * implements Android.os.Parcelable { # 保持Parcelable不被混淆 public static final Android.os.Parcelable$Creator *;}

8, the use of enum type should be careful to avoid the following two methods of confusion, because of the specificity of the Enum class, the following two methods will be reflected call, see the second rule.

enum * {      public static **[] values();      public static ** valueOf(java.lang.String); }
Written in the last

To publish an app in addition to setting it, minifyEnabled ture you should also set it to zipAlignEnabled true , like Google Play forcing developers to upload an app that must be zipalign, zipalign can align the resources in the installation package by 4 bytes, This reduces the memory consumption of the app at run time.

77.Android Code Obfuscation

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.