android 资源混淆

方案选择:

1.微信混淆方案(AndResGuard)
2.美团混淆方案

区别:

微信的方案是通过修改aapt在处理资源文件相关的源码达到资源文件的替换;而美团主要通过直接修改resources.arsc文件达到资源文件混淆的目的。微信从aapt的原理上着手,而美团只是在已有的方案上优化,相比之下,微信的混淆更彻底。

什么是AndResGuard
  AndResGuard是一个缩小APK大小的工具,它的原理类似Java Proguard,但是只针对资源。它会将原本冗长的资源路径变短,例如将res/drawable/wechat变为r/d/a。

在以往的开发中,我们通常只混淆了代码,资源文件却暴露在他人面前,res文件夹下所有文件名的可读性过强。

微信的开源库AndResGuard正好解决这种问题,对资源进行混淆,保护res资源文件的可读性,同时,可以减少APP的大小

AndResGuard的配置

  1. 项目根目录下build.gradle中,添加插件的依赖:
 dependencies {
        classpath 'com.tencent.mm:AndResGuard-gradle-plugin:1.2.10'
    }
    
  1. app模块中build.gradle中,添加相关配置
apply plugin: 'AndResGuard'

andResGuard {
    // mappingFile = file("./resource_mapping.txt")
    mappingFile = null
    use7zip = false
    useSign = true
    // It will keep the origin path of your resources when it's true
    keepRoot = false
    // If set, name column in arsc those need to proguard will be kept to this value
    fixedResName = "arg"
    // It will merge the duplicated resources, but don't rely on this feature too much.
    // it's always better to remove duplicated resource from repo
    mergeDuplicatedRes = true
    whiteList = [
            // your icon
            "R.drawable.ic_launcher*",
            "R.anim.umeng*",
            "R.string.umeng*",
    ]
    compressFilePattern = [
            "*.png",
            "*.jpg",
            "*.jpeg",
            "*.gif",
            "*.webp",
    ]
    sevenzip {
        artifact = 'com.tencent.mm:SevenZip:1.2.20'
        //path = "/usr/local/bin/7za"
    }

    /**
     * Optional: if finalApkBackupPath is null, AndResGuard will overwrite final apk
     * to the path which assemble[Task] write to
     **/
    // finalApkBackupPath = "${project.rootDir}/final.apk"

    /**
     * Optional: Specifies the name of the message digest algorithm to user when digesting the entries of JAR file
     * Only works in V1signing, default value is "SHA-1"
     **/
    // digestalg = "SHA-256"
}

其中whiteList(白名单)中指定不需要进行混淆的资源路径规则,主要是针对第三方SDK,因为有些SDK的代码中通过getIdentifier()的方式引用到对应的资源文件,如果对其进行混淆,会导致找不到对应资源文件,出现crash。

androId寻找资源方式:

resources.arsc结构:


image.png
  1. 通过包名(package name),类型(type,如dimen,drawable,color,string等),资源名(name)在表resources.arsc中查找对应资源的Id.

  2. 然后通过getResources().getDrawable(resourceId)或者getResources().getDimensionPixelSize(resourceId)等方法拿到对应的资源.

而一旦进行资源混淆后,资源名发生变化,会导致找不到资源id。

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容