Android優(yōu)雅的進(jìn)行混淆——使用@Keep注解

不能混淆的項(xiàng)

在AndroidManifest中配置的類萌朱,比如四大組件
JNI調(diào)用的方法
反射用到的類
WebView中JavaScript調(diào)用的方法
Layout文件引用到的自定義View
一些引入的第三方庫(kù)

使用工具AndroidStudio

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

使用proguard混淆代碼是對(duì)產(chǎn)品本身的一種保護(hù)采桃,常見(jiàn)的方法就是編寫projuard-rules.pro配置文件

# This is a configuration file for ProGuard.
# http://proguard.sourceforge.net/index.html#manual/usage.html

//混淆時(shí)不使用大小寫混合類名
-dontusemixedcaseclassnames
//不跳過(guò)library中的非public的類
-dontskipnonpubliclibraryclasses
//打印混淆的詳細(xì)信息
-verbose
 
# Optimization is turned off by default. Dex does not like code run
# through the ProGuard optimize and preverify steps (and performs some
# of these optimizations on its own).
//不進(jìn)行優(yōu)化哆档,建議使用此選項(xiàng)睛琳,理由見(jiàn)上
-dontoptimize
//不進(jìn)行預(yù)校驗(yàn)汇四,預(yù)校驗(yàn)是作用在Java平臺(tái)上的,Android平臺(tái)上不需要這項(xiàng)功能咐柜,去掉之后還可以加快混淆速度
-dontpreverify
# Note that if you want to enable optimization, you cannot just
# include optimization flags in your own project configuration file;
# instead you will need to point to the
# "proguard-android-optimize.txt" file instead of this one from your
# project.properties file.
 
//保留注解參數(shù)
-keepattributes *Annotation*
//保留Google原生服務(wù)需要的類
-keep public class com.google.vending.licensing.ILicensingService
-keep public class com.android.vending.licensing.ILicensingService
 
# For native methods, see http://proguard.sourceforge.net/manual/examples.html#native
//保留native方法的類名和方法名
-keepclasseswithmembernames class * {
    native <methods>;
}
 
# keep setters in Views so that animations can still work.
# see http://proguard.sourceforge.net/manual/examples.html#beans
//保留自定義View,如"屬性動(dòng)畫"中的set/get方法
-keepclassmembers public class * extends android.view.View {
   void set*(***);
   *** get*();
}
 
# We want to keep methods in Activity that could be used in the XML attribute onClick
//保留Activity中參數(shù)是View的方法兼蜈,如XML中配置android:onClick=”buttonClick”屬性,Activity中調(diào)用的buttonClick(View view)方法
-keepclassmembers class * extends android.app.Activity {
   public void *(android.view.View);
}
 
# For enumeration classes, see http://proguard.sourceforge.net/manual/examples.html#enumerations
//保留混淆枚舉中的values()和valueOf()方法
-keepclassmembers enum * {
    public static **[] values();
    public static ** valueOf(java.lang.String);
}
 
//Parcelable實(shí)現(xiàn)類中的CREATOR字段是絕對(duì)不能改變的拙友,包括大小寫
-keepclassmembers class * implements android.os.Parcelable {
  public static final android.os.Parcelable$Creator CREATOR;
}
 
//R文件中的所有記錄資源id的靜態(tài)字段
-keepclassmembers class **.R$* {
    public static <fields>;
}
 
# The support library contains references to newer platform versions.
# Dont warn about those in case this app is linking against an older
# platform version.  We know about them, and they are safe.
//忽略support包因?yàn)榘姹炯嫒莓a(chǎn)生的警告
-dontwarn android.support.**

Proguard關(guān)鍵字

關(guān)鍵字                      描述
keep                        保留類和類中的成員为狸,防止被混淆或移除
keepnames                   保留類和類中的成員,防止被混淆遗契,成員沒(méi)有被引用會(huì)被移除
keepclassmembers            只保留類中的成員辐棒,防止被混淆或移除
keepclassmembernames        只保留類中的成員,防止被混淆牍蜂,成員沒(méi)有引用會(huì)被移除
keepclasseswithmembers      保留類和類中的成員漾根,防止被混淆或移除,保留指明的成員
keepclasseswithmembernames  保留類和類中的成員鲫竞,防止被混淆辐怕,保留指明的成員,成員沒(méi)有引用會(huì)被移除

Proguard通配符

通配符      描述
<field>     匹配類中的所有字段
<method>    匹配類中所有的方法
<init>      匹配類中所有的構(gòu)造函數(shù)
*           匹配任意長(zhǎng)度字符从绘,不包含包名分隔符(.)
**          匹配任意長(zhǎng)度字符寄疏,包含包名分隔符(.)
***         匹配任意參數(shù)類型
...

指定混淆時(shí)可使用字典

-applymapping filename 指定重用一個(gè)已經(jīng)寫好了的map文件作為新舊元素名的映射。
-obfuscationdictionary filename 指定一個(gè)文本文件用來(lái)生成混淆后的名字僵井。
-classobfuscationdictionary filename 指定一個(gè)混淆類名的字典
-packageobfuscationdictionary filename 指定一個(gè)混淆包名的字典
-overloadaggressively 混淆的時(shí)候大量使用重載赁还,多個(gè)方法名使用同一個(gè)混淆名(慎用)

    # 這里巧妙地使用java中的關(guān)鍵字作字典,混淆之后的代碼更加不利于閱讀
    #
    # This obfuscation dictionary contains reserved Java keywords. They can't
    # be used in Java source files, but they can be used in compiled class files.
    # Note that this hardly improves the obfuscation. Decent decompilers can
    # automatically replace reserved keywords, and the effect can fairly simply be
    # undone by obfuscating again with simpler names.
    # Usage:
    #     java -jar proguard.jar ..... -obfuscationdictionary keywords.txt
    #
    
    do
    if
    for
    int
    new
    try
    byte
    case
    char
    else
    goto
    long
    this
    void
    break
    catch
    class
    const
    final
    float
    short
    super
    throw
    while
    double
    import
    native
    public
    return
    static
    switch
    throws
    boolean
    default
    extends
    finally
    package
    private
    abstract
    continue
    strictfp
    volatile
    interface
    protected
    transient
    implements
    instanceof
    synchronized

使用proguardgui對(duì)jar包進(jìn)行混淆

proguardgui工具支持Shrinking(壓縮)驹沿、Optimization(優(yōu)化)、Obfuscation(混淆)蹈胡、Preverification(預(yù)校驗(yàn))四項(xiàng)操作

詳細(xì)步驟:
    1 Load configuration --> Next
    2 Add input/Add output
    3 添加jar包依賴
        JAVA_HOME/jre/lib/rt.jar
        Android_SDK/platfroms/android-23/android.jar
        AndroidStudioProjects/ProjectName/app/build/intermediates/exploded-aar/com.android.support/appcompat-v7/23.4.0/jars/classes.jar
        AndroidStudioProjects/ProjectName/app/build/intermediates/exploded-aar/com.android.support/support-v4/23.4.0/jars/classes.jar
        AndroidStudioProjects/ProjectName/app/build/intermediates/exploded-aar/com.android.support/support-v4/23.4.0/jars/libs/internal_impl-23.4.0.jar
        其他第三方j(luò)ar文件
    4 Don`t use Shrink --> Next
    5 Add --> Extends/implements class --> android.app.Activity --> ok --> Next
    6 Next
    7 Next
    8 View configuration
tips:
    AndroidStudio中生成jar文件方法:
    jar -cvf filename.jar -C app/build/intermediates/classes/debug

5分鐘快速混淆

#-------------------------------------------定制化區(qū)域----------------------------------------------
#---------------------------------1.實(shí)體類---------------------------------

-keep class com.demo.login.bean.** { *; }
-keep class com.demo.main.bean.** { *; }

#-------------------------------------------------------------------------

#---------------------------------2.第三方包-------------------------------

#eventBus
-keepattributes *Annotation*
-keepclassmembers class ** {
    @org.greenrobot.eventbus.Subscribe <methods>;
}
-keep enum org.greenrobot.eventbus.ThreadMode { *; }
-keepclassmembers class * extends org.greenrobot.eventbus.util.ThrowableFailureEvent {
    <init>(java.lang.Throwable);
}

#glide
-keep public class * implements com.bumptech.glide.module.GlideModule
-keep public enum com.bumptech.glide.load.resource.bitmap.ImageHeaderParser$** {
  **[] $VALUES;
  public *;
}

#log4j
-libraryjars log4j-1.2.17.jar
-dontwarn org.apache.log4j.**
-keep class  org.apache.log4j.** { *;}

#-------------------------------------------------------------------------

#---------------------------------3.與js互相調(diào)用的類------------------------

-keepclasseswithmembers class com.demo.login.bean.ui.MainActivity$JSInterface { 
      <methods>; 
}

#-------------------------------------------------------------------------

#---------------------------------4.反射相關(guān)的類和方法-----------------------
# 有
#----------------------------------------------------------------------------
#---------------------------------------------------------------------------------------------------

#-------------------------------------------基本不用動(dòng)區(qū)域--------------------------------------------
#---------------------------------基本指令區(qū)----------------------------------
-optimizationpasses 5
-dontusemixedcaseclassnames
-dontskipnonpubliclibraryclasses
-dontskipnonpubliclibraryclassmembers
-dontpreverify
-verbose
-printmapping proguardMapping.txt
-optimizations !code/simplification/cast,!field/*,!class/merging/*
-keepattributes *Annotation*,InnerClasses
-keepattributes Signature
-keepattributes SourceFile,LineNumberTable
#----------------------------------------------------------------------------

#---------------------------------默認(rèn)保留區(qū)---------------------------------
-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 * extends android.view.View
-keep public class com.android.vending.licensing.ILicensingService
-keep class android.support.** {*;}

-keepclasseswithmembernames class * {
    native <methods>;
}
-keepclassmembers class * extends android.app.Activity{
    public void *(android.view.View);
}
-keepclassmembers enum * {
    public static **[] values();
    public static ** valueOf(java.lang.String);
}
-keep public class * extends android.view.View{
    *** get*();
    void set*(***);
    public <init>(android.content.Context);
    public <init>(android.content.Context, android.util.AttributeSet);
    public <init>(android.content.Context, android.util.AttributeSet, int);
}
-keepclasseswithmembers class * {
    public <init>(android.content.Context, android.util.AttributeSet);
    public <init>(android.content.Context, android.util.AttributeSet, int);
}
-keep class * implements android.os.Parcelable {
  public static final android.os.Parcelable$Creator *;
}
-keepclassmembers class * implements java.io.Serializable {
    static final long serialVersionUID;
    private static final java.io.ObjectStreamField[] serialPersistentFields;
    private void writeObject(java.io.ObjectOutputStream);
    private void readObject(java.io.ObjectInputStream);
    java.lang.Object writeReplace();
    java.lang.Object readResolve();
}
-keep class **.R$* {
 *;
}
-keepclassmembers class * {
    void *(**On*Event);
}
#----------------------------------------------------------------------------

#---------------------------------webview------------------------------------
-keepclassmembers class fqcn.of.javascript.interface.for.Webview {
   public *;
}
-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.WebViewClient {
    public void *(android.webkit.WebView, jav.lang.String);
}
#----------------------------------------------------------------------------
#---------------------------------------------------------------------------------------------------

# 刪除代碼中Log相關(guān)的代碼
-assumenosideeffects class android.util.Log {
    public static boolean isLoggable(java.lang.String, int);
    public static int v(...);
    public static int i(...);
    public static int w(...);
    public static int d(...);
    public static int e(...);
}

網(wǎng)上有很多5分鐘完成混淆規(guī)則的教程渊季,但如何更優(yōu)雅的完成這一枯燥的過(guò)程朋蔫,即使用@Keep注解,使混淆變得輕松愉快

在proguard-rules.pro配置文件中加入以下規(guī)則

#手動(dòng)啟用support keep注解
#http://tools.android.com/tech-docs/support-annotations
-dontskipnonpubliclibraryclassmembers
-printconfiguration
-keep,allowobfuscation @interface android.support.annotation.Keep

-keep @android.support.annotation.Keep class *
-keepclassmembers class * {
    @android.support.annotation.Keep *;
}

哪里不對(duì)@Keep哪里却汉,媽媽再也不用擔(dān)心我不會(huì)混淆啦……

參考資料
http://blog.csdn.net/guolin_blog/article/details/50451259
http://www.reibang.com/p/60e82aafcfd0

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
  • 序言:七十年代末驯妄,一起剝皮案震驚了整個(gè)濱河市,隨后出現(xiàn)的幾起案子合砂,更是在濱河造成了極大的恐慌青扔,老刑警劉巖,帶你破解...
    沈念sama閱讀 221,576評(píng)論 6 515
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件翩伪,死亡現(xiàn)場(chǎng)離奇詭異微猖,居然都是意外死亡,警方通過(guò)查閱死者的電腦和手機(jī)缘屹,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 94,515評(píng)論 3 399
  • 文/潘曉璐 我一進(jìn)店門凛剥,熙熙樓的掌柜王于貴愁眉苦臉地迎上來(lái),“玉大人轻姿,你說(shuō)我怎么就攤上這事犁珠。” “怎么了互亮?”我有些...
    開封第一講書人閱讀 168,017評(píng)論 0 360
  • 文/不壞的土叔 我叫張陵犁享,是天一觀的道長(zhǎng)。 經(jīng)常有香客問(wèn)我豹休,道長(zhǎng)炊昆,這世上最難降的妖魔是什么? 我笑而不...
    開封第一講書人閱讀 59,626評(píng)論 1 296
  • 正文 為了忘掉前任慕爬,我火速辦了婚禮窑眯,結(jié)果婚禮上,老公的妹妹穿的比我還像新娘医窿。我一直安慰自己磅甩,他們只是感情好,可當(dāng)我...
    茶點(diǎn)故事閱讀 68,625評(píng)論 6 397
  • 文/花漫 我一把揭開白布姥卢。 她就那樣靜靜地躺著卷要,像睡著了一般。 火紅的嫁衣襯著肌膚如雪独榴。 梳的紋絲不亂的頭發(fā)上僧叉,一...
    開封第一講書人閱讀 52,255評(píng)論 1 308
  • 那天,我揣著相機(jī)與錄音棺榔,去河邊找鬼瓶堕。 笑死,一個(gè)胖子當(dāng)著我的面吹牛症歇,可吹牛的內(nèi)容都是我干的郎笆。 我是一名探鬼主播谭梗,決...
    沈念sama閱讀 40,825評(píng)論 3 421
  • 文/蒼蘭香墨 我猛地睜開眼,長(zhǎng)吁一口氣:“原來(lái)是場(chǎng)噩夢(mèng)啊……” “哼宛蚓!你這毒婦竟也來(lái)了激捏?” 一聲冷哼從身側(cè)響起,我...
    開封第一講書人閱讀 39,729評(píng)論 0 276
  • 序言:老撾萬(wàn)榮一對(duì)情侶失蹤凄吏,失蹤者是張志新(化名)和其女友劉穎远舅,沒(méi)想到半個(gè)月后,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體痕钢,經(jīng)...
    沈念sama閱讀 46,271評(píng)論 1 320
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡图柏,尸身上長(zhǎng)有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 38,363評(píng)論 3 340
  • 正文 我和宋清朗相戀三年,在試婚紗的時(shí)候發(fā)現(xiàn)自己被綠了盖喷。 大學(xué)時(shí)的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片爆办。...
    茶點(diǎn)故事閱讀 40,498評(píng)論 1 352
  • 序言:一個(gè)原本活蹦亂跳的男人離奇死亡,死狀恐怖课梳,靈堂內(nèi)的尸體忽然破棺而出距辆,到底是詐尸還是另有隱情,我是刑警寧澤暮刃,帶...
    沈念sama閱讀 36,183評(píng)論 5 350
  • 正文 年R本政府宣布跨算,位于F島的核電站,受9級(jí)特大地震影響椭懊,放射性物質(zhì)發(fā)生泄漏诸蚕。R本人自食惡果不足惜,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 41,867評(píng)論 3 333
  • 文/蒙蒙 一氧猬、第九天 我趴在偏房一處隱蔽的房頂上張望背犯。 院中可真熱鬧,春花似錦盅抚、人聲如沸漠魏。這莊子的主人今日做“春日...
    開封第一講書人閱讀 32,338評(píng)論 0 24
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽(yáng)柱锹。三九已至,卻和暖如春丰包,著一層夾襖步出監(jiān)牢的瞬間禁熏,已是汗流浹背。 一陣腳步聲響...
    開封第一講書人閱讀 33,458評(píng)論 1 272
  • 我被黑心中介騙來(lái)泰國(guó)打工邑彪, 沒(méi)想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留瞧毙,地道東北人。 一個(gè)月前我還...
    沈念sama閱讀 48,906評(píng)論 3 376
  • 正文 我出身青樓,卻偏偏與公主長(zhǎng)得像宙彪,于是被迫代替她去往敵國(guó)和親撑柔。 傳聞我的和親對(duì)象是個(gè)殘疾皇子,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 45,507評(píng)論 2 359

推薦閱讀更多精彩內(nèi)容