Custom code obfuscation plug-in based on ProGuard-Maven-Plugin and proguardmaven Obfuscation

Source: Internet
Author: User

Custom code obfuscation plug-in based on ProGuard-Maven-Plugin and proguardmaven Obfuscation
Introduction

You may encounter some code-sensitive project scenarios. At this time, it is not good to see Code decompilation. In this case, you need code obfuscation plug-ins to confuse the code.

Maven-based projects generally consider using proguard-maven-plugin. However, this plug-in only supports Jar packages and does not support War packages.

So I used the free time to modify part of the logic on the basis of proguard-maven-plugin. I can confuse the code when the project was built, and support packaging jar packages and war packages.

Post it for you now.

Project address

Https://github.com/lovethegirl/code-hidding-plugin

Modify part

Tool class for compressing and extracting War packages

Package com. github. wvengen. maven. proguard; import java. io. bufferedInputStream; import java. io. bufferedOutputStream; import java. io. file; import java. io. fileInputStream; import java. io. fileNotFoundException; import java. io. fileOutputStream; import java. io. IOException; import java. io. outputStream; import java. util. iterator; import org. apache. commons. compress. archivers. archiveException; import org. apa Che. commons. compress. archivers. archiveInputStream; import org. apache. commons. compress. archivers. archiveOutputStream; import org. apache. commons. compress. archivers. archiveStreamFactory; import org. apache. commons. compress. archivers. jar. jarArchiveEntry; import org.apache.commons.compress.archivers.zip. zipArchiveEntry; import org. apache. commons. compress. utils. IOUtils; import org. apache. commons. io. fileU Tils;/*** tool class for processing WAR files. Compress or decompress the WAR file. ** @ Author Xiong Shuhong (shelltea@gmail.com) */public class WarUtils {public static void unzip (String warPath, String unzipPath) {File warFile = new File (warPath ); try {BufferedInputStream bufferedInputStream = new BufferedInputStream (new FileInputStream (warFile); ArchiveInputStream in = new ArchiveStreamFactory (). createArchiveInputStream (ArchiveStreamFactory. JAR, bufferedInputStream); Jar ArchiveEntry entry = null; while (entry = (JarArchiveEntry) in. getNextEntry ())! = Null) {File file = new File (unzipPath, entry. getName (); if (file. exists () {file. delete ();} if (entry. isDirectory () {file. mkdir ();} else {OutputStream out = FileUtils. openOutputStream (file); IOUtils. copy (in, out); out. close () ;}} in. close ();} catch (FileNotFoundException e) {System. err. println ("war file not found");} catch (ArchiveException e) {System. err. println ("unsupported compression Formats");} catch (iow.t Ion e) {System. err. println ("File write error") ;}} public static void zip (String destFile, String zipDir) {File outFile = new File (destFile); try {outFile. createNewFile (); BufferedOutputStream bufferedOutputStream = new BufferedOutputStream (new FileOutputStream (outFile); ArchiveOutputStream out = new ArchiveStreamFactory (). createArchiveOutputStream (ArchiveStreamFactory. JAR, bufferedOutputStream); I F (zipDir. charAt (zipDir. length ()-1 )! = '/') {ZipDir + = '/';} Iterator <File> files = FileUtils. iterateFiles (new File (zipDir), null, true); while (files. hasNext () {File file = files. next (); ZipArchiveEntry zipArchiveEntry = new ZipArchiveEntry (file, file. getPath (). replace (zipDir. replace ("/", "\"), ""); out. putArchiveEntry (zipArchiveEntry); IOUtils. copy (new FileInputStream (file), out); out. closeArchiveEntry ();} out. finish (); out. close ();} catch (IOException e) {System. err. println ("failed to create file");} catch (ArchiveException e) {System. err. println ("unsupported compression format ");}}}

Modify the code in ProGuardMojo. java and pack the mixed code into the war package. You can view the project down from Git.

If (attach &&! SameArtifact) {// operation war decompression, and a series of operations such as String absolutePath = outJarFile. getAbsolutePath (); getLog (). info ("--- absolutePath --" + absolutePath); String unzipPath = outJarFile. getParent () + "/proguard-war"; getLog (). info ("delete path" + absolutePath); deleteDir (unzipPath); File unZipFile = new File (unzipPath); unZipFile. mkdir (); String targetWar = mavenProject. getBuild (). getDirectory () + "/" + mavenProject. getBuild (). getFinalName () + ". war "; getLog (). info (targetWar); WarUtils. unzip (targetWar, unzipPath); // Delete path "deleteDir (unzipPath +"/WEB-INF/classes "); WarUtils. unzip (absolutePath, unzipPath + "/WEB-INF/classes"); outJarFile. delete (); WarUtils.zip (absolutePath, outJarFile. getParent () + "/proguard-war"); getLog (). info ("--- absolutePath --" + absolutePath); if (useArtifactClassifier () {projectHelper. attachArtifact (mavenProject, attachArtifactType, attachArtifactClassifier, outJarFile);} else {projectHelper. attachArtifact (mavenProject, attachArtifactType, null, outJarFile );}}

After running maven install, you can see the mixed war package in the repository directory.

Usage

Install Maven first
Then add the dependency of this plug-in to the project that requires obfuscation of code.

<Plugin> <groupId> com. jiujie </groupId> <artifactId> code-hidding-plugin </artifactId> <version> 1.0 </version> <executions> <execution> <phase> package </phase> <goals> <goal> proguard </goal> </goals> </execution> </executions> <configuration> <obfuscate> true </obfuscate> <attach> true </attach> <injar> classes </injar> <attachArtifactClassifier> pg </attachArtifactClassifier> attach installs and deploys the generated pg files during install and deploy. <proguardInclude> $ {basedir}/proguard. conf </proguardInclude> <outjar >$ {project. build. finalName}-pg </outjar> <libs> <lib >$ {java. home}/lib/rt. jar </lib> <lib >$ {java. home}/lib/jsse. jar </lib> </libs> <addMavenDescriptor> false </addMavenDescriptor> </configuration> </plugin>

Add the project configuration file proguard. conf to the project root directory.

# Classes # Run with a specified number of optimizations #-optimizationpasses n # classes #-optimizationpasses 3 # classes of different types are not generated during obfuscation #-dontusemixedcaseclassnames # classes #-dontusemixedcaseclassnames # libraries # specify not to ignore non-public library classes #-dontskipnonpubliclibraryclasses # libraries # not pre-verified #-dontpreverify # libraries #-dontpreverify # ignore all alarms-ignorewarnings # Do not do shrink # no optimize-dontoptimize # outputs # output generation information #-verbose # ---------------------------------verbose # application intrusive overload during obfuscation #-overloadaggressively # access and modify modifier classes and class member #-allowaccessmodification # determine the name of the unified obfuscation class member to add obfuscation # Add the class you do not need to confuse here #-keep class com. showjoy. common. cache. ** {*;}-keepclasseswithmembers class com. showjoy. cart. service. ** {<fields >;}-keepclasseswithmembers class com. showjoy. cart. ui. cart. ** {<fields >;}-keepclassmembers class com. showjoy. cart. cartControllerHandler {<fields >;}-keepclassmembers class com. showjoy. cart. cartExceptionHandler {<fields >;}-keep class com. showjoy. cart. util. encodeUtil {*;} #-keep public class * extends javax. servlet. servlet #-keepdirectories ** #-keepattributes ** #-useuniqueclassmembernames # maintain the source code name and line number (with clear stack information when exceptions occur). Annotations (all annotations are filtered out by default, -keepattributes SourceFile, LineNumberTable, * Annotation * # Keep package Annotation class-keepattributes Signature #-keepnames class * implements java. io. serializable # --------- protect the field names in all entities ---------- #-keepclassmembers class * implements java. io. serializable {# <fields >;#}# --------- all method names in the protection class ------------ #-keepclassmembers class * {# public <methods> ;#}
ProGuard description and Configuration

Official Website: http://proguard.sourceforge.net/
ProGuard is used:

1. Create compact code documentation for faster network transmission, fast loading, and smaller memory usage.
2. It is difficult to use reverse engineering to create programs and libraries.
3. Therefore, it can delete code not called from the source file.
4. Make full use of the advantages of rapid loading of Java 6 to detect and return class files in Java 6 in advance.


Parameters:
-Include {filename}: Read the configuration parameters from the specified file.
-Basedirectory {directoryname}: Specify the base directory as the file name.
-Injars {class_path} specifies the application jar, war, ear, and directory to be processed.
-Outjars {class_path} specifies the name of the jar, war, ear, and directory to be output after processing.
-Libraryjars {classpath} specifies the application jar, war, ear, and library files required by the Directory to be processed.
-Dontskipnonpubliclibraryclasses specifies that non-public library classes are not ignored.
-Dontskipnonpubliclibraryclassmembers specifies that the visible Library Class Members of the package are not ignored.


Retain option
-Keep {Modifier} {class_specification} protects specified class files and Class Members
-Keepclassmembers {modifier} {class_specification} protects the members of the specified class. If this class is protected, it will be better protected.
-Keepclasseswithmembers {class_specification} protects the specified class and class members, but the condition is that all specified classes and Class Members must exist.
-Keepnames {class_specification} protects the names of members of the specified class and class (if they are not compressed and deleted in the step)
-Keepclassmembernames {class_specification} protects the names of members of the specified class (if they are not removed from the compression step)
-Keepclasseswithmembernames {class_specification} protects the names of specified classes and Class Members. If all specified class members are present (after the compression step)
-Printseeds {filename} lists the Member-keep options of classes and classes, and outputs them to the specified files.


Compression
-Dontshrink does not compress input class files
-Printusage {filename}
-Whyareyoukeeping {class_specification}


Optimization
-Dontoptimize: the input class file is not optimized.
-Assumenosideeffects {class_specification}: the specified method is assumed during optimization without any side effects.
-Allowaccessmodification: allows access to and modification of modifier classes and class members during optimization.

Obfuscation
-Dontobfuscate does not confuse input class files
-Printmapping {filename}
-Added obfuscation when applymapping {filename} is reused.
-Obfuscationdictionary {filename} uses the keyword in the given file as the name of the method to be confused
-Overloadaggressively: Application intrusive overload during Obfuscation
-Useuniqueclassmembernames: Determine the names of members of a unified obfuscation class to add obfuscation.
-Flattenpackagehierarchy {package_name} repacks all renamed packages and stores them in a given single package.
-Repackageclass {package_name} repacks all renamed class files and stores them in a given single package.
-Dontusemixedcaseclassnames does not produce a variety of class names when obfuscation is performed.
-Keepattributes {attribute_name,...} protects specified optional attributes, such as LineNumberTable, LocalVariableTable, SourceFile, Deprecated, Synthetic, Signature, and InnerClasses.
-Renamesourcefileattribute {string}: Set the given string constant in the source file.

Because we developed a project with the webwork + spring + hibernate architecture, all of which require detailed configuration. (Summary after n failures)


Example:
-Injars <project>. jar
-Outjars <project> _ out. jar
-Libraryjars <Java. home>/lib/rt. jar
-Libraryjars <project. home>/webroot/WEB-INF/lib/webwork. jar
.......

# Retain public, friendly, private, public, and friendly methods in the Action interface class. All others are compressed, optimized, and obfuscated.
# Because the class name in the configuration file is a complete class name, this class may not be found after processing.
# Attributes are required for jsp pages. If the jsp page is processed, data in the action cannot be obtained.
-Keep public class * implements com. opensymphony. xwork. Action {
Public protected private <fields>;
Public protected <methods>;
}
# Reserved public, friendly, and private members (attributes and methods) in the Serializable Interface Class)
# This configuration mainly corresponds to the object class configuration.
-Keep public class * implements java. io. Serializable {
Public protected private *;
}
......

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.