小言_互联网的博客

Gradle 自定义Plugin插件之360加固

326人阅读  评论(0)

之前发布的文章:Gradle 自定义Plugin插件之上传APK到蒲公英。让我们知道了自定义插件的一些功能。

一般来说,在发布的时候,我们的APK都需要加固的,毕竟安全点。这里,我们就结合之前的插件,再定义一个加固APK的任务。然后,让我们自动化的步伐可以更大一点。打包–→加固–→上传蒲公英

既然是,自动化的部署,我们肯定就不能用图形化的加固操作工具了。

操作步骤:

一、下载360加固保

既然是加固,首先,我们需要到360官网注册,并下载加固保:官方网站 (腾讯的加固好像不支持本地上传APK)。

解压目录

这里,我们要通过命令行执行jiagu.jar来完成我们的自动化apk加固。

help.txt里面是一些加固的命令,有兴趣的,可以都试试。

有了360加固保以后,就要开始编写我们的加固Task任务了。

二、创建加固的Task任务

加固Task的创建跟上传Task一样,都是继承DefaultTask,然后,在方法上通过注解@TaskAction 来让我们的任务执行。

创建加固任务,我们主要做下面几个事:

  • 1,给我们加固Task设置一个组,这里放到跟上传Task一个组里。
  • 2,创建一个Model类,存放加固时需要的一些参数
    比如, 加固jar包文件,账号密码;签名信息;apk加固前,加固后路径等。
  • 3,执行加固时,获取这个Model类的参数信息
  • 4,执行360加固所需要的命令
    比如,登陆,导入签名,加固,设置自动签名等等

public class ReinforceTask extends DefaultTask {

    private BaseVariant mVariant;
    private Project mTargetProject;

    //加固相关的信息
    public static class ReinforceModel {

        //加固包的位置(jiagu.jar) 及登录账号密码
        public File reinforceJarFile;
        public String reinforceUsername;
        public String reinforcePassword;

        //签名文件 密码等信息
        public File signStoreFile;
        public String signPassword;
        public String signKeyAlias;
        public String signKeyPassword;

        //打包apk路径及加固后apk的路径
        public File inputApkFile;
        public File outputApkFile;
    }


    public void init(BaseVariant variant, Project project) {
        this.mVariant = variant;
        this.mTargetProject = project;
        setDescription("reinforce for apk");
        setGroup(TestJavaPlugin.PLUGIN_EXTENSION_NAME);
    }

    @TaskAction
    public void reinforceApk() {
        System.out.println("==============start JiaGu");

        ReinforceModel request = initReinforceModel();

        String loginCmdData = "java -jar %s -login %s %s";
        String loginExec = String
            .format(loginCmdData, request.reinforceJarFile, request.reinforceUsername,
                request.reinforcePassword);
        String loginMessage = exec(loginExec);
        System.out.println("==========exe JiaGu Result: " + loginMessage);

        String signCmdData = "java -jar %s -importsign %s %s %s %s";
        String signExec = String
            .format(signCmdData, request.reinforceJarFile, request.signStoreFile,
                request.signPassword,
                request.signKeyAlias, request.signKeyPassword);
        //导入签名
        String signResult = exec(signExec);
        System.out.println("===========exe JiaGu Sign Result: " + signResult);
        //自动签名
        String suffixCmd = " -autosign ";

        if (!request.outputApkFile.exists()) {
            request.outputApkFile.mkdirs();
        }
        //jiagu.jar ,input apk file path, output apk dir
        String reinforceCmdData = "java -jar %s -jiagu %s %s";
        String reinforceExec = String
            .format(reinforceCmdData, request.reinforceJarFile, request.inputApkFile,
                request.outputApkFile);
        //reinforce
        String jiaguResult = exec(reinforceExec + suffixCmd);

        System.out.println("=========exe APK JiaGu Result : " + jiaguResult);
    }

    @NotNull
    private ReinforceModel initReinforceModel() {
        Extension extension = Extension.getConfig(mTargetProject);

        ReinforceModel request = new ReinforceModel();
        request.outputApkFile = extension.outputFile;
        request.reinforceJarFile = extension.reinforceJarFile;
        request.reinforceUsername = extension.reinforceUsername;
        request.reinforcePassword = extension.reinforcePassword;

        NamedDomainObjectContainer<SigningConfig> signingConfigs = ((AppExtension) mTargetProject
            .getExtensions().findByName(TestJavaPlugin.ANDROID_EXTENSION_NAME)).getSigningConfigs();

        if (signingConfigs == null) {
            throw new IllegalArgumentException("please config your sign info.");
        }

        for (SigningConfig config : signingConfigs) {
            request.signStoreFile = config.getStoreFile();
            request.signPassword = config.getStorePassword();
            request.signKeyAlias = config.getKeyAlias();
            request.signKeyPassword = config.getKeyPassword();
        }

        for (BaseVariantOutput output : mVariant.getOutputs()) {
            request.inputApkFile = output.getOutputFile();
            if (request.inputApkFile == null || !request.inputApkFile.exists()) {
                throw new GradleException("apk file is not exist!");
            }
        }

        if (request.signStoreFile == null || !request.signStoreFile.exists()) {
            throw new IllegalArgumentException("please config your sign info.");
        }
        return request;
    }

    private String exec(String command) {
        StringBuilder resultBuilder = new StringBuilder();
        Process pro = null;
        BufferedReader input = null;
        Runtime runTime = Runtime.getRuntime();
        if (runTime == null) {
            throw new NullPointerException("reinforce task failed,Runtime is null");
        }
        try {
            pro = runTime.exec(command);
            input = new BufferedReader(new InputStreamReader(pro.getInputStream()));
            String line;
            while ((line = input.readLine()) != null) {
                resultBuilder.append(line).append("\n");
            }
        } catch (IOException ex) {
            ex.printStackTrace();
        } finally {
            if (pro != null) {
                pro.destroy();
            }
            if (input != null) {
                try {
                    input.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return resultBuilder.toString();
    }
}

这里我们看到:

1,通过ReinforceModel来保存加固需要的参数信息。
2,在初始化init()方法里设置了分组
3,在initReinforceModel()方法里面,获取我们加固需要的账号,签名等等信息。
4,通过reinforceApk()方法,就会分别执行,登陆,导入签名,加固,自动签名命令。

到这里,我们自定义的加固Task就完成了。

下面,我们就结合之前的自动上传到蒲公英Task任务,来实现 打包—加固–上传 ,这个流程。

三、修改插件的Extension扩展

要完成打包–加固–上传的流程,我们需要修改上篇文章中的Extension类,把360加固需要的参数添加上,来确保我们可以完成加固任务。


public class Extension {


  public String uKey;
  public String apiKey;
  public String appName;

  //==========加固相关的信息
	//指向加固的jar包
  public File reinforceJarFile;
  //登陆用户名
  public String reinforceUsername;
  //登陆密码
  public String reinforcePassword;
  //输出apk的目录
  public File outputFile;

  public Extension() {
  }

  public Extension(String uKey, String apiKey, String appName, File reinforceJarFile,
      String reinforceUsername, String reinforcePassword, File outputFile) {
    this.uKey = uKey;
    this.apiKey = apiKey;
    this.appName = appName;
    this.reinforceJarFile = reinforceJarFile;
    this.reinforceUsername = reinforceUsername;
    this.reinforcePassword = reinforcePassword;
    this.outputFile = outputFile;
  }
  public Extension(String appName, String uKey, String apiKey) {
    this.uKey = uKey;
    this.apiKey = apiKey;
    this.appName = appName;
  }
  public static Extension getConfig(Project project) {
    Extension extension = project.getExtensions().findByType(Extension.class);
    if (extension == null) {
      extension = new Extension();
    }
    return extension;
  }

}


这里,我们看到,我们只添加了加固jar包的文件,用户名,密码,加固后的apk路径,并没有添加签名信息等。这是因为,这些参数,我们可以通过系统的扩展来获取到。

添加加固后的apk路径,是为了修改后面上传到蒲公英的时候,上传的是加固的包。不然的话,上传的包依然是我们加固前的包。

四,修改上传Task的apk路径

之前上传的Task,是直接获取的系统打包的路径。我们要修改成加固后,输入的apk路径。


public class PGYUploadTask extends DefaultTask {

  private BaseVariant mVariant;
  private Project mTargetProject;

  public static class PGYRequest {

    public String uKey;
    public String apiKey;
    //1,install by public 2,install by password 3,install by invite
    public String installType;
  }

  public void init(BaseVariant variant, Project project) {
    this.mVariant = variant;
    this.mTargetProject = project;
    setDescription("upload to pgy");
    setGroup(TestJavaPlugin.PLUGIN_EXTENSION_NAME);
  }

  @TaskAction
  public void uploadToPGY() {
    Extension extension = Extension.getConfig(mTargetProject);

    PGYRequest request = new PGYRequest();
    request.apiKey = extension.apiKey;
    request.uKey = extension.uKey;
    File apkDir = extension.outputFile;
    if (apkDir == null || !apkDir.exists()) {
      upload(request);
    } else {
      File[] files = apkDir.listFiles();
      if (files != null && files.length > 0) {
        upload(request.uKey, request.apiKey, files[0]);
      }else{
        upload(request);
      }
    }

//    for (BaseVariantOutput output : mVariant.getOutputs()) {
//      File file = output.getOutputFile();
//      if (file == null || !file.exists()) {
//        throw new GradleException("apk file is not exist!");
//      }
//      Extension extension = Extension.getConfig(mTargetProject);
//
//      PGYRequest request = new PGYRequest();
//      request.apiKey = extension.apiKey;
//      request.uKey = extension.uKey;
//      upload(request.uKey, request.apiKey, file);
//    }

  }

  private void upload(PGYRequest request) {
    for (BaseVariantOutput output : mVariant.getOutputs()) {
      File file = output.getOutputFile();
      if (file == null || !file.exists()) {
        throw new GradleException("apk file is not exist!");
      }
      upload(request.uKey, request.apiKey, file);
    }
  }

  private void upload(String ukey, String apiKey, File apkFile) {
    //builder
    MultipartBody.Builder bodyBuilder = new MultipartBody.Builder().setType(MultipartBody.FORM);
    //add part
    bodyBuilder.addFormDataPart("uKey", ukey);
    bodyBuilder.addFormDataPart("_api_key", apiKey);
    //add file
    bodyBuilder.addFormDataPart("file", apkFile.getName(), RequestBody
        .create(MediaType.parse("*/*"), apkFile));

    //request

    Request request = new Request.Builder()
        .url("http://upload.pgyer.com/apiv1/app/upload")
        .post(bodyBuilder.build())
        .build();

    OkHttpClient client = new OkHttpClient();
    try {
      Response response = client.newCall(request).execute();
      String result = response.body().string();
      System.out.println("upload result: " + result);
    } catch (IOException e) {
      e.printStackTrace();
    } catch (Exception e) {

    }
  }

}


这里我们根据定义在Extension中的加固后apk路径,选择一个apk来上传(360支持多渠道打包)。

其他内容,有不明白的,可以看下Gradle 自定义Plugin插件之上传APK到蒲公英

最后,我们在修改下任务的依赖关系就完成了,我们的流程,打包–加固–上传。

五、修改插件的依赖关系

这里,我们只需要修改插件里,任务的依赖关系就可以了。


public class TestJavaPlugin implements Plugin<Project> {

  public static final String PLUGIN_EXTENSION_NAME = "uploadHelperJava";
  public static final String ANDROID_EXTENSION_NAME = "android";
  @Override
  public void apply(Project project) {
    Extension customExtension = project.getExtensions().create(PLUGIN_EXTENSION_NAME, Extension.class);
    //    project.getExtensions().create(PLUGIN_EXTENSION_NAME, Extension.class, project);
    //项目编译完成后,回调
    project.afterEvaluate(new Action<Project>() {
      @Override
      public void execute(Project project) {
        DomainObjectSet<ApplicationVariant> appVariants = ((AppExtension) project
            .getExtensions().findByName(ANDROID_EXTENSION_NAME)).getApplicationVariants();
        for (ApplicationVariant variant : appVariants) {
          //release apk
          if (variant.getBuildType().getName().equalsIgnoreCase("uploadRelease") ) {
            String variantName =
                variant.getName().substring(0, 1).toUpperCase() + variant.getName().substring(1);
            PGYUploadTask uploadTask = project.getTasks()
                .create("uploadJavaFor" + variantName, PGYUploadTask.class);
            uploadTask.init(variant, project);

            ReinforceTask reinforceTask = project.getTasks()
                .create("reinforceFor" + variantName, ReinforceTask.class);
            reinforceTask.init(variant,project);

            //依赖关系
            variant.getAssembleProvider().get().dependsOn(project.getTasks().findByName("clean"));
            reinforceTask.dependsOn(variant.getAssembleProvider().get());
            uploadTask.dependsOn(reinforceTask);

          }
        }
      }
    });
  }
}

我们让 加固的Task dependon 打包Task,然后,上传Task dependon 加固Task。这样,就完成了我们整个的流程。 clean—打包—加固—上传。

六、项目调用

这里,主要有发布插件,把加固包copy到项目中,然后,引用插件,填写参数,调用。

1,首先,我们重新发布下,我们的插件

点击,alone_plugin下面的uploadArchives。

2,要使用的项目,引入360加固保

我们把加固保的解压文件都copy的项目的libs文件夹下(文件名随意,只要在配置reinforceJarFile时,指向它就可以)

这里,我们的加固命令,都是通过jiagu.jar来完成的。

参数命令都在help.txt里面,这里就不介绍了

3,项目下的build.gradle引入插件

测试项目引入,我们的加固上传插件

buildscript {
    repositories {
        google()
        jcenter()
        maven{
            url uri('./repo/')
        }
    }
    dependencies {
        classpath 'com.android.tools.build:gradle:3.3.1'
        classpath 'com.liu.alone.plugin:java-plugin:1.0.0'
    }
}
allprojects {
    repositories {
        google()
        jcenter()
    }
}
task clean(type: Delete) {
    delete rootProject.buildDir
}

4,app的module引入插件

app的build.gradle

android {
  	...
    signingConfigs {
        release {
            storeFile file('xxx.jks')
            storePassword "xxx"
            keyAlias "xxx"
            keyPassword "xxx"
        }
    }


    buildTypes {
        release {
            minifyEnabled false
            signingConfig signingConfigs.release
            proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
        }
        uploadRelease {
            minifyEnabled false
            signingConfig signingConfigs.release
            proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
        }
    }
}
	...
apply plugin: 'com.liu.alone.plugin'
uploadHelperJava {
    appName = "testGradle"

    uKey = "c9d2625c0cf221d8f4a98738f4c05e9a"

    apiKey = "fac8875534d045a2be3f229abd46cc3e"

    //加固相关的信息
    reinforceJarFile = file("../libs/jiagu.jar")
    reinforceUsername = "xxx"
    reinforcePassword = "xxx"
    outputFile = file("${buildDir.getAbsolutePath()}\\jiagu")

}

引用我们写的插件,及配置上传加固等等需要的参数信息
reinforceJarFile 这个加固文件就是指向了libs下的jiagu.jar。如果,加固保放到其他的目录下,修改这里就可以了。

5,最后调用任务

执行Gradle里面Tasks任务的uploadJavaForUploadRelease,我们定义的这个任务。

打印结果

任务完成_已签名


> Task :app:uploadJavaForUploadRelease
upload result: {"code":0,"message":"","data":{"appKey":"bb2b8b14f405d9024b0e18954beaadb8","userKey":"c9d2625c0cf221d8f4a98738f4c05e9a","appType":"2","appIsLastest":"2","appFileSize":"2206305","appName":"ObjectAnimatorTest","appVersion":"1.0","appVersionNo":"1","appBuildVersion":"9","appIdentifier":"com.liu.objectanimatortest","appIcon":"825df8e761ed960f5c3237e9af332df7","appDescription":"","appUpdateDescription":"","appScreenshots":"","appShortcutUrl":"t6rG","appCreated":"2020-01-02 11:19:53","appUpdated":"2020-01-02 11:19:53","appQRCodeURL":"http:\/\/www.pgyer.com\/app\/qrcodeHistory\/5dea8789700159c1d2804374dc80293b2e3f5e5ffd53531b777cfc4a33843c29"}}

打印日志,看到先完成签名,然后,执行了上传任务,最后,返回上传结果

其他

1,插件的build.gradle

apply plugin: 'java-library'
apply plugin: 'maven'
dependencies {
    compile gradleApi()
    compile localGroovy()
    compile 'com.android.tools.build:gradle:3.3.1'
    implementation("com.squareup.okhttp3:okhttp:3.8.1")
}
repositories {
    mavenCentral()

}

group = 'com.liu.alone.plugin'
version = '1.0.0'
archivesBaseName = 'java-plugin'
//upload
uploadArchives {
    repositories {
        mavenDeployer {
            repository(url: uri('../repo'))
        }
    }
}

主要有java的依赖库,及okhttp的上传库,插件发布的内容。

2,插件的整体结构

主要就是build.gradle,properties文件,一个插件类,2个任务类,一个扩展属性类。

到这里,我们的流程:打包–加固–上传就完成。

如果,我们上传前,不一定需要加固呢,我们是不是可以在Extension里面定义一个变量来控制呢,只需要修改插件的依赖关系,上传Task的apk上传路径即可。


转载:https://blog.csdn.net/ecliujianbo/article/details/103801481
查看评论
* 以上用户言论只代表其个人观点,不代表本网站的观点或立场