Details about code obfuscation examples in android apps

Source: Internet
Author: User

Details about code obfuscation examples in android apps

Details about code obfuscation examples in android apps

Receives a new task to confuse the code of the existing project. I have had some knowledge about obfuscation before, but it is not detailed or complete enough to know that obfuscation is still tricky. But fortunately, the current project is not too complex (for obfuscation purposes) and can be completed in advance ~~ This is a summary.

Part 1

This section describes the procedure (eclipse ):

1. Open the obfuscator: Find the project under the project root directory. properties file, set "# proguard. config =$ {sdk. dir}/tools/proguard/proguard-android.txt: proguard-project.txt this line before the '#' Delete;

2. Modify the obfuscation configuration file: Find the proguard-project.txt file under the project root directory and modify the code. This part is the most critical;

3. Save the relevant files for future use when an error occurs: the files in the proguarddirectory (the main object is mapping.txt) and the project source code under the project root directory (the main object is mapping.txt;

4. error handling during project running: locate the error location based on the error information and the ing saved in step 1.

After knowing this, we will expand it. After you start eclipsean, a new project will be created, and the project. properties and proguard-project.txt will be created. Compile our code, and then copy the content in "# proguard. config =$ {sdk. dir}/tools/proguard/proguard-android.txt: volumes of proguard-project.txt. The following is my test code:

?

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

46

47

48

49

50

51

52

53

54

55

56

57

58

59

60

61

62

63

64

65

66

67

68

69

70

71

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 ){

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 (){

@ Override

Public 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:

After analyzing the code above, we will find that all the custom method names are replaced with short letters without special meanings, but the onCreate () method of the activity is not changed; the last testError () the method is also removed because it is not called. These are the default obfuscation policies. Here we can see that the confusion is still a small case ~~

Proceed to the next step. Open the logged-out testError () and run the package. An error is returned. The error message is as follows:

?

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

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. javasmcreate (Activity. java: 4531)

At android. app. Instrumentation. callActivityOnCreate (Instrumentation. java: 1071)

At android. app. ActivityThread. javasmlaunchactivity (ActivityThread. java: 2150)

At android. app. ActivityThread. handleLaunchActivity (ActivityThread. java: 2229)

At android. app. ActivityThread. access $600 (ActivityThread. java: 139)

At android. app. ActivityThread $ H. handleMessage (ActivityThread. java: 1261)

At android. OS. Handler. dispatchMessage (Handler. java: 99)

At android. OS. lorule. loop (lorule. 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 simple, it is easy to see that there is a problem anywhere, but it can still be used to illustrate the problem we want to express: how to restore the error message of the obfuscated code. To achieve this goal, we need three files: android-sdk-windows oolsproguardin etrace.bat、mapping.txtand the error information (log.txt ). Then execute the following command (window system ):

Retrace. bat mapping.txt log.txt

We can clearly see that the B () method in the error log is the setName () method in our actual code.

Note that every time the apk is exported, a corresponding mapping file is generated in the proguard folder under the project directory. Therefore, for each apk, we need to save the corresponding mapping file. So far, the entire obfuscation process has been introduced.

Refer:

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

Http://www.cnblogs.com/over140/archive/2011/04/22/2024528.html (I wanted to flip one by myself, the results found that a long time ago the farmer uncle has been translated, here directly reference and thank it)

Part 2

The first part describes how to perform the operation. Refer to the official documentation to learn about the operation. The remaining one is the most difficult to compile the proguard-project.txt file. For this part, there are two processing strategies: Writing by yourself and using the ones written by others. First, let's talk about how to use a third-party library written by others. No matter whether it is open source or closed source, we can find configuration of obfuscated code in its User Guide in special circumstances, if we reference the famous guillep PullToRefresh, we can find the following code in his document:

?

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

-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. 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 *;

} </Init> </methods>

With this part of code, we can directly copy and insert it into our project. This method is still copy. Let's take a small example to see how to write code to control obfuscation. "#" In comment indicates comment ):

?

1

2

3

4

5

6

#-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 decompile it to get the following code:

Compared with the previous one, we found that the getString method is not obfuscated. No error. When proguard-project.txt means that the getString () method of MainActivity should not be confused. You can also try the effect of the two lines commented in the above obfuscation code.

The core part of ProGuard has been involved. The rest is to study the ProGuard documentation, master its syntax, and use it. I wanted to find a complete ProGuard translation document, but I haven't found one after finding N for a long time, and there are very few scattered translations. The recent time is very short, and the ability is limited, it is also difficult to translate several frequently-used commands, so the idea of carefully reading can only be pushed back for the moment. Here is a brief introduction to the keep command:

-Keep [, modifier,...] class_specification

Specify the members (attributes and methods) of the class or class reserved as the starting point in your code ). For example, to maintain an application, you can specify the main class and its main method. To process a library, you need to describe its public access elements in detail.

In addition, there is a brief summary of the keep and a standard in the syntax. The Class Specification will show you how to represent the constructor, attributes, and methods, and the difference between * And. For example, * Indicates matching any class name but not including the package separator, while ** indicates matching any class name and including any number of package separators, therefore, the Code mentioned above is as follows: the first line: Keep com. ttdevs. all classes under proguard are not confused with all methods of classes under the sub-package, and the second line keeps com. ttdevs. all methods and member variables of classes under proguard and sub-packages are not confused.

// There are many more details about TODO, such as-libraryjars,-dontwarn, and-keepattributes.

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.