28 |
29 |
30 |
--------------------------------------------------------------------------------
/android-pack-plugin/.idea/misc.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
9 |
10 |
11 |
12 |
--------------------------------------------------------------------------------
/android-pack-plugin/.idea/uiDesigner.xml:
--------------------------------------------------------------------------------
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 |
72 |
73 |
74 |
75 |
76 |
77 |
78 |
79 |
80 |
81 |
82 |
83 |
84 |
85 |
86 |
87 |
88 |
89 |
90 |
91 |
92 |
93 |
94 |
95 |
96 |
97 |
98 |
99 |
100 |
101 |
102 |
103 |
104 |
105 |
106 |
107 |
108 |
109 |
110 |
111 |
112 |
113 |
114 |
115 |
116 |
117 |
118 |
119 |
120 |
121 |
122 |
123 |
124 |
--------------------------------------------------------------------------------
/android-pack-plugin/.idea/vcs.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
--------------------------------------------------------------------------------
/android-pack-plugin/build.gradle:
--------------------------------------------------------------------------------
1 | buildscript {
2 | repositories {
3 | jcenter()
4 | mavenCentral()
5 | google()
6 | }
7 | dependencies {
8 | classpath 'com.android.tools.build:gradle:3.2.1'
9 | classpath "org.jfrog.buildinfo:build-info-extractor-gradle:4.5.2"
10 | classpath 'com.github.dcendents:android-maven-gradle-plugin:1.4.1'
11 | classpath 'com.jfrog.bintray.gradle:gradle-bintray-plugin:1.+'
12 |
13 | }
14 | }
15 |
16 | allprojects {
17 | repositories {
18 | jcenter()
19 | mavenCentral()
20 | google()
21 | }
22 | }
23 |
--------------------------------------------------------------------------------
/android-pack-plugin/gradle/wrapper/gradle-wrapper.jar:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/zengcanxiang/Android-pack-plugin/a44c4680932ee2cf5cb41478ec7fcba8cd8af7d9/android-pack-plugin/gradle/wrapper/gradle-wrapper.jar
--------------------------------------------------------------------------------
/android-pack-plugin/gradle/wrapper/gradle-wrapper.properties:
--------------------------------------------------------------------------------
1 | distributionBase=GRADLE_USER_HOME
2 | distributionPath=wrapper/dists
3 | distributionUrl=https\://services.gradle.org/distributions/gradle-5.4.1-bin.zip
4 | zipStoreBase=GRADLE_USER_HOME
5 | zipStorePath=wrapper/dists
6 |
--------------------------------------------------------------------------------
/android-pack-plugin/gradlew:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env sh
2 |
3 | ##############################################################################
4 | ##
5 | ## Gradle start up script for UN*X
6 | ##
7 | ##############################################################################
8 |
9 | # Attempt to set APP_HOME
10 | # Resolve links: $0 may be a link
11 | PRG="$0"
12 | # Need this for relative symlinks.
13 | while [ -h "$PRG" ] ; do
14 | ls=`ls -ld "$PRG"`
15 | link=`expr "$ls" : '.*-> \(.*\)$'`
16 | if expr "$link" : '/.*' > /dev/null; then
17 | PRG="$link"
18 | else
19 | PRG=`dirname "$PRG"`"/$link"
20 | fi
21 | done
22 | SAVED="`pwd`"
23 | cd "`dirname \"$PRG\"`/" >/dev/null
24 | APP_HOME="`pwd -P`"
25 | cd "$SAVED" >/dev/null
26 |
27 | APP_NAME="Gradle"
28 | APP_BASE_NAME=`basename "$0"`
29 |
30 | # Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
31 | DEFAULT_JVM_OPTS=""
32 |
33 | # Use the maximum available, or set MAX_FD != -1 to use that value.
34 | MAX_FD="maximum"
35 |
36 | warn () {
37 | echo "$*"
38 | }
39 |
40 | die () {
41 | echo
42 | echo "$*"
43 | echo
44 | exit 1
45 | }
46 |
47 | # OS specific support (must be 'true' or 'false').
48 | cygwin=false
49 | msys=false
50 | darwin=false
51 | nonstop=false
52 | case "`uname`" in
53 | CYGWIN* )
54 | cygwin=true
55 | ;;
56 | Darwin* )
57 | darwin=true
58 | ;;
59 | MINGW* )
60 | msys=true
61 | ;;
62 | NONSTOP* )
63 | nonstop=true
64 | ;;
65 | esac
66 |
67 | CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar
68 |
69 | # Determine the Java command to use to start the JVM.
70 | if [ -n "$JAVA_HOME" ] ; then
71 | if [ -x "$JAVA_HOME/jre/sh/java" ] ; then
72 | # IBM's JDK on AIX uses strange locations for the executables
73 | JAVACMD="$JAVA_HOME/jre/sh/java"
74 | else
75 | JAVACMD="$JAVA_HOME/bin/java"
76 | fi
77 | if [ ! -x "$JAVACMD" ] ; then
78 | die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME
79 |
80 | Please set the JAVA_HOME variable in your environment to match the
81 | location of your Java installation."
82 | fi
83 | else
84 | JAVACMD="java"
85 | which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
86 |
87 | Please set the JAVA_HOME variable in your environment to match the
88 | location of your Java installation."
89 | fi
90 |
91 | # Increase the maximum file descriptors if we can.
92 | if [ "$cygwin" = "false" -a "$darwin" = "false" -a "$nonstop" = "false" ] ; then
93 | MAX_FD_LIMIT=`ulimit -H -n`
94 | if [ $? -eq 0 ] ; then
95 | if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then
96 | MAX_FD="$MAX_FD_LIMIT"
97 | fi
98 | ulimit -n $MAX_FD
99 | if [ $? -ne 0 ] ; then
100 | warn "Could not set maximum file descriptor limit: $MAX_FD"
101 | fi
102 | else
103 | warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT"
104 | fi
105 | fi
106 |
107 | # For Darwin, add options to specify how the application appears in the dock
108 | if $darwin; then
109 | GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\""
110 | fi
111 |
112 | # For Cygwin, switch paths to Windows format before running java
113 | if $cygwin ; then
114 | APP_HOME=`cygpath --path --mixed "$APP_HOME"`
115 | CLASSPATH=`cygpath --path --mixed "$CLASSPATH"`
116 | JAVACMD=`cygpath --unix "$JAVACMD"`
117 |
118 | # We build the pattern for arguments to be converted via cygpath
119 | ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null`
120 | SEP=""
121 | for dir in $ROOTDIRSRAW ; do
122 | ROOTDIRS="$ROOTDIRS$SEP$dir"
123 | SEP="|"
124 | done
125 | OURCYGPATTERN="(^($ROOTDIRS))"
126 | # Add a user-defined pattern to the cygpath arguments
127 | if [ "$GRADLE_CYGPATTERN" != "" ] ; then
128 | OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)"
129 | fi
130 | # Now convert the arguments - kludge to limit ourselves to /bin/sh
131 | i=0
132 | for arg in "$@" ; do
133 | CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -`
134 | CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option
135 |
136 | if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition
137 | eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"`
138 | else
139 | eval `echo args$i`="\"$arg\""
140 | fi
141 | i=$((i+1))
142 | done
143 | case $i in
144 | (0) set -- ;;
145 | (1) set -- "$args0" ;;
146 | (2) set -- "$args0" "$args1" ;;
147 | (3) set -- "$args0" "$args1" "$args2" ;;
148 | (4) set -- "$args0" "$args1" "$args2" "$args3" ;;
149 | (5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;;
150 | (6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;;
151 | (7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;;
152 | (8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;;
153 | (9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;;
154 | esac
155 | fi
156 |
157 | # Escape application args
158 | save () {
159 | for i do printf %s\\n "$i" | sed "s/'/'\\\\''/g;1s/^/'/;\$s/\$/' \\\\/" ; done
160 | echo " "
161 | }
162 | APP_ARGS=$(save "$@")
163 |
164 | # Collect all arguments for the java command, following the shell quoting and substitution rules
165 | eval set -- $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS "\"-Dorg.gradle.appname=$APP_BASE_NAME\"" -classpath "\"$CLASSPATH\"" org.gradle.wrapper.GradleWrapperMain "$APP_ARGS"
166 |
167 | # by default we should be in the correct project dir, but when run from Finder on Mac, the cwd is wrong
168 | if [ "$(uname)" = "Darwin" ] && [ "$HOME" = "$PWD" ]; then
169 | cd "$(dirname "$0")"
170 | fi
171 |
172 | exec "$JAVACMD" "$@"
173 |
--------------------------------------------------------------------------------
/android-pack-plugin/gradlew.bat:
--------------------------------------------------------------------------------
1 | @if "%DEBUG%" == "" @echo off
2 | @rem ##########################################################################
3 | @rem
4 | @rem Gradle startup script for Windows
5 | @rem
6 | @rem ##########################################################################
7 |
8 | @rem Set local scope for the variables with windows NT shell
9 | if "%OS%"=="Windows_NT" setlocal
10 |
11 | set DIRNAME=%~dp0
12 | if "%DIRNAME%" == "" set DIRNAME=.
13 | set APP_BASE_NAME=%~n0
14 | set APP_HOME=%DIRNAME%
15 |
16 | @rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
17 | set DEFAULT_JVM_OPTS=
18 |
19 | @rem Find java.exe
20 | if defined JAVA_HOME goto findJavaFromJavaHome
21 |
22 | set JAVA_EXE=java.exe
23 | %JAVA_EXE% -version >NUL 2>&1
24 | if "%ERRORLEVEL%" == "0" goto init
25 |
26 | echo.
27 | echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
28 | echo.
29 | echo Please set the JAVA_HOME variable in your environment to match the
30 | echo location of your Java installation.
31 |
32 | goto fail
33 |
34 | :findJavaFromJavaHome
35 | set JAVA_HOME=%JAVA_HOME:"=%
36 | set JAVA_EXE=%JAVA_HOME%/bin/java.exe
37 |
38 | if exist "%JAVA_EXE%" goto init
39 |
40 | echo.
41 | echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME%
42 | echo.
43 | echo Please set the JAVA_HOME variable in your environment to match the
44 | echo location of your Java installation.
45 |
46 | goto fail
47 |
48 | :init
49 | @rem Get command-line arguments, handling Windows variants
50 |
51 | if not "%OS%" == "Windows_NT" goto win9xME_args
52 |
53 | :win9xME_args
54 | @rem Slurp the command line arguments.
55 | set CMD_LINE_ARGS=
56 | set _SKIP=2
57 |
58 | :win9xME_args_slurp
59 | if "x%~1" == "x" goto execute
60 |
61 | set CMD_LINE_ARGS=%*
62 |
63 | :execute
64 | @rem Setup the command line
65 |
66 | set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar
67 |
68 | @rem Execute Gradle
69 | "%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %CMD_LINE_ARGS%
70 |
71 | :end
72 | @rem End local scope for the variables with windows NT shell
73 | if "%ERRORLEVEL%"=="0" goto mainEnd
74 |
75 | :fail
76 | rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of
77 | rem the _cmd.exe /c_ return code!
78 | if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1
79 | exit /b 1
80 |
81 | :mainEnd
82 | if "%OS%"=="Windows_NT" endlocal
83 |
84 | :omega
85 |
--------------------------------------------------------------------------------
/android-pack-plugin/local.properties:
--------------------------------------------------------------------------------
1 | ## This file must *NOT* be checked into Version Control Systems,
2 | # as it contains information specific to your local configuration.
3 | #
4 | # Location of the SDK. This is only used by Gradle.
5 | # For customization when using a Version Control System, please read the
6 | # header note.
7 | #Wed Mar 06 11:24:17 CST 2019
8 | sdk.dir=/Users/liuf/Library/Android/sdk
9 | #bintray.user=
10 | #bintray.apikey=
--------------------------------------------------------------------------------
/android-pack-plugin/packPlugin/build.gradle:
--------------------------------------------------------------------------------
1 | apply plugin: 'groovy'
2 | apply plugin: 'maven'
3 | apply plugin: 'maven-publish'
4 | apply plugin: 'com.jfrog.bintray'
5 |
6 | repositories {
7 | jcenter()
8 | google()
9 | mavenCentral()
10 | }
11 |
12 | dependencies {
13 | implementation localGroovy()
14 | implementation gradleApi()
15 | implementation 'commons-io:commons-io:2.4'
16 | implementation 'commons-codec:commons-codec:1.6'
17 | implementation 'org.apache.commons:commons-lang3:3.4'
18 | implementation 'com.android.tools.build:gradle:3.2.1'
19 | }
20 |
21 | group 'cn.zengcanxiang'
22 | def artifact = 'android-pack-plugin'
23 | version '1.0.1'
24 |
25 | publishing {
26 | publications {
27 | MyPublication(MavenPublication) {
28 | from components.java
29 | groupId group
30 | artifactId artifact
31 | version version
32 | }
33 | }
34 | }
35 |
36 | task sourcesJar(type: Jar) {
37 | from sourceSets.main.allSource
38 | classifier 'sources'
39 | }
40 |
41 | //task javadocJar(type: Jar) {
42 | // from javadoc
43 | // classifier 'javadoc'
44 | //}
45 |
46 | artifacts {
47 | // archives javadocJar
48 | archives sourcesJar
49 | }
50 |
51 | Properties properties = new Properties()
52 | properties.load(project.rootProject.file('local.properties').newDataInputStream())
53 |
54 | bintray {
55 | user = properties.getProperty("bintray.user")
56 | key = properties.getProperty("bintray.apikey")
57 | publications = ['MyPublication']
58 | configurations = ['archives']
59 | pkg {
60 | repo = 'maven'
61 | name = artifact
62 | userOrg = user
63 | licenses = ['Apache-2.0']
64 | vcsUrl = 'https://github.com/zengcanxiang/Android-pack-plugin.git'
65 | publicDownloadNumbers = true
66 | }
67 | }
68 |
69 |
70 | uploadArchives {
71 | repositories {
72 | mavenDeployer {
73 | repository(url: uri('../repo'))
74 | }
75 | }
76 | }
77 |
--------------------------------------------------------------------------------
/android-pack-plugin/packPlugin/src/main/groovy/cn/zengcanxiang/packplugin/PluginEntranceImpl.groovy:
--------------------------------------------------------------------------------
1 | package cn.zengcanxiang.packplugin
2 |
3 | import cn.zengcanxiang.packplugin.task.DownloadTask
4 | import cn.zengcanxiang.packplugin.task.FirmTask
5 | import cn.zengcanxiang.packplugin.task.MultiChannelTask
6 | import org.gradle.api.Plugin
7 | import org.gradle.api.Project
8 |
9 | class PluginEntranceImpl implements Plugin {
10 | @Override
11 | void apply(Project project) {
12 | project.extensions.create("androidPackPlugin", PluginExtension)
13 | def downloadTask = project.tasks.create("downTask", DownloadTask)
14 | def firmTask = project.tasks.create("firmTask", FirmTask)
15 | def multiChannelTask = project.tasks.create("multiChannelTask", MultiChannelTask)
16 |
17 | // 设置两个任务之间的依赖
18 | firmTask.dependsOn(downloadTask)
19 | multiChannelTask.dependsOn(firmTask)
20 | }
21 | }
22 |
--------------------------------------------------------------------------------
/android-pack-plugin/packPlugin/src/main/groovy/cn/zengcanxiang/packplugin/PluginExtension.groovy:
--------------------------------------------------------------------------------
1 | package cn.zengcanxiang.packplugin
2 |
3 | import com.android.build.gradle.BaseExtension
4 | import com.android.build.gradle.internal.dsl.SigningConfig
5 | import org.gradle.api.GradleException
6 | import org.gradle.api.Project
7 |
8 | class PluginExtension {
9 | static File apkFile
10 | static File channelOutputFolder
11 | Boolean isNeedFirm = true
12 | //输出总路径
13 | String outPath
14 | // 加固原文件
15 | String apkFilePath
16 | // 原文件mapping.txt
17 | String mappingPath
18 | //360加固账号
19 | String firmAccountName
20 | //360加固密码
21 | String firmAccountPwd
22 | // 渠道文件路径
23 | File channelConfigFile
24 | // Android SDK 目录
25 | File sdkDir
26 | // 指定的Android build-tools版本
27 | String buildToolsName
28 | //apk签名文件路径
29 | String apkJksPath
30 | //apk签名文件密码
31 | String apkJksStorePwd
32 | //apk签名文件别名
33 | String apkJksAlias
34 | //apk签名文件密码
35 | String apkJksPwd
36 |
37 | static PluginExtension getConfig(Project project) {
38 | def config = project.getExtensions().findByType(PluginExtension.class)
39 | if (config == null) {
40 | throw new GradleException("打包配置为空")
41 | }
42 | if (config.outPath == null || config.outPath.length() == 0) {
43 | config.outPath = project.buildDir
44 | }
45 | return config
46 | }
47 |
48 | def initFirm() {
49 | if (isNeedFirm && (firmAccountName == null || firmAccountPwd == null)) {
50 | throw new GradleException("360加固账号密码没有配置")
51 | }
52 | if (apkFilePath == null || apkFilePath.length() == 0 || !new File(apkFilePath).exists()) {
53 | throw new GradleException("apk文件不存在")
54 | }
55 | }
56 |
57 | def initSignConfig(Project project) {
58 | if (this.apkJksPath == null || this.apkJksAlias == null
59 | || this.apkJksStorePwd == null || this.apkJksPwd == null) {
60 | BaseExtension extension = project.extensions.getByName("android") as BaseExtension
61 | Collection signingConfigs = extension.getSigningConfigs()
62 | signingConfigs.forEach { signingConfig ->
63 | if (signingConfig.name == "release") {
64 | this.apkJksPath = signingConfig.storeFile.absolutePath
65 | this.apkJksAlias = signingConfig.keyAlias
66 | this.apkJksStorePwd = signingConfig.storePassword
67 | this.apkJksPwd = signingConfig.keyPassword
68 | }
69 | }
70 | if (this.apkJksPath == null || this.apkJksAlias == null
71 | || this.apkJksStorePwd == null || this.apkJksPwd == null) {
72 | throw new GradleException("签名配置错误(获取项目配置签名失败),至少需要配置签名和360加固账号相关数据\napkJksPath = $apkJksPath, apkJksAlias = $apkJksAlias, apkJksStorePwd = $apkJksStorePwd, apkJksPwd = $apkJksPwd")
73 | }
74 | }
75 | }
76 |
77 | def initSdkDir(Project project) {
78 | if (sdkDir == null || !sdkDir.exists()) {
79 | Properties properties = new Properties()
80 | InputStream inputStream = project.rootProject.file('local.properties').newDataInputStream()
81 | properties.load(inputStream)
82 | def sdkDirPath = properties.getProperty('sdk.dir')
83 | if (sdkDirPath != null && sdkDirPath.length() > 0) {
84 | sdkDir = new File(sdkDirPath)
85 | }
86 | if (!sdkDir.exists()) {
87 | //去读取环境变量
88 | properties = System.getProperties()
89 | sdkDirPath = properties.getProperty("ANDROID_HOME")
90 | if (sdkDirPath != null && sdkDirPath.length() > 0) {
91 | sdkDir = new File(sdkDirPath)
92 | }
93 | }
94 | if (!sdkDir.exists()) {
95 | throw new GradleException("获取AndroidSDK目录失败(请配置文件或者再local.properties添加sdk_dir或者配置ANDROID_HOME环境变量)")
96 | }
97 | }
98 | }
99 | }
100 |
--------------------------------------------------------------------------------
/android-pack-plugin/packPlugin/src/main/groovy/cn/zengcanxiang/packplugin/task/CopySourceTask.groovy:
--------------------------------------------------------------------------------
1 | package cn.zengcanxiang.packplugin.task
2 |
3 | import cn.zengcanxiang.packplugin.PluginExtension
4 | import com.android.build.gradle.BaseExtension
5 | import org.gradle.api.Action
6 | import org.gradle.api.Project
7 | import org.gradle.api.file.CopySpec
8 |
9 | class CopySourceTask {
10 | private PluginExtension config
11 | private Project project
12 |
13 | CopySourceTask(Project project) {
14 | this.project = project
15 | config = PluginExtension.getConfig(project)
16 | }
17 |
18 | def copySource() {
19 | println("开始复制文件")
20 | def extension = project.extensions.getByName("android") as BaseExtension
21 | def versionName = extension.defaultConfig.versionName
22 | def versionCode = extension.defaultConfig.versionCode
23 | File out = new File(PluginExtension.channelOutputFolder, "${versionName}_${versionCode}_source")
24 | if(config.apkFilePath != null){
25 | File sourceApk = new File(config.apkFilePath)
26 | if (sourceApk.exists()) {
27 | println("开始复制apk")
28 | copy(sourceApk, out)
29 | }
30 | }
31 | if(config.mappingPath != null){
32 | File sourceMapping = new File(config.mappingPath)
33 | if (sourceMapping.exists()) {
34 | println("开始复制mapping")
35 | copy(sourceMapping, out)
36 | }
37 | }
38 | }
39 |
40 | private def copy(File source, File out) {
41 | project.copy(new Action() {
42 | @Override
43 | void execute(CopySpec copySpec) {
44 | copySpec.from(source)
45 | .into(out)
46 | }
47 | })
48 | }
49 | }
50 |
--------------------------------------------------------------------------------
/android-pack-plugin/packPlugin/src/main/groovy/cn/zengcanxiang/packplugin/task/DownloadTask.groovy:
--------------------------------------------------------------------------------
1 | package cn.zengcanxiang.packplugin.task
2 |
3 | import cn.zengcanxiang.packplugin.PluginExtension
4 | import org.gradle.api.Action
5 | import org.gradle.api.DefaultTask
6 | import org.gradle.api.file.CopySpec
7 | import org.gradle.api.tasks.TaskAction
8 |
9 | class DownloadTask extends DefaultTask {
10 | static final String down_url_mac = "http://down.360safe.com/360Jiagu/360jiagubao_mac.zip"
11 |
12 | static final String down_url_linux = "http://down.360safe.com/360Jiagu/360jiagubao_linux_64.zip"
13 |
14 | static final String down_url_win = "http://down.360safe.com/360Jiagu/360jiagubao_windows_32.zip"
15 |
16 | String downUrl = down_url_mac
17 |
18 | // private def walle_cli_url = "https://github.com/Meituan-Dianping/walle/releases/download/v1.1.6/walle-cli-all.jar"
19 | //TODO 由于美团官方暂时没有提供最新的jar。所以下载一个第三方编译的
20 | private def walle_cli_url = "https://github.com/zengcanxiang/Android-pack-plugin/blob/master/walle_cli.jar"
21 |
22 | private File firmZipFile
23 |
24 | private File firmJarParentPath
25 |
26 | private final def firmJarPath = "jiagu/jiagu.jar"
27 |
28 | private PluginExtension config
29 |
30 | DownloadTask() {
31 | group = "android-pack"
32 | description = "下载必要的文件(包含360加固和walle-cli.jar)"
33 | config = PluginExtension.getConfig(project)
34 | }
35 |
36 | private def initConfig() {
37 | firmZipFile = new File(config.outPath, "360加固文件压缩包.zip")
38 | firmJarParentPath = new File(config.outPath, "360")
39 | def os = System.getProperty("os.name").toLowerCase()
40 | if (os.contains("linux")) {
41 | downUrl = down_url_linux
42 | } else if (os.contains("mac")) {
43 | downUrl = down_url_mac
44 | } else {
45 | downUrl = down_url_win
46 | }
47 | }
48 |
49 | @TaskAction
50 | def download() {
51 | initConfig()
52 | if (!isNeedDownload()) {
53 | println("检测到本地已存在360相关文件")
54 | } else {
55 | downLoadFile(downUrl, firmZipFile)
56 | unZip()
57 | }
58 | def walleFile = new File(config.outPath, "walle_cli.jar")
59 | if (!walleFile.exists()) {
60 | downLoadFile(walle_cli_url, walleFile)
61 | }
62 | }
63 |
64 | private def unZip() {
65 | println("开始解压文件")
66 | project.copy(new Action() {
67 | @Override
68 | void execute(CopySpec copySpec) {
69 | copySpec.from(project.zipTree(firmZipFile))
70 | .into(firmJarParentPath)
71 | println("解压文件结束")
72 | }
73 | })
74 | }
75 |
76 | private def downLoadFile(String downUrl, File saveFile) {
77 | println("下载文件:$downUrl")
78 | def connection = new URL(downUrl).openStream()
79 | def stream2 = new URL(downUrl).openConnection()
80 | def total = stream2.getContentLength()
81 | def len
82 | def hasRead = 0
83 | byte[] arr = new byte[1024 * 5]
84 | def out = new FileOutputStream(saveFile)
85 | def lastResult = 0
86 | while ((len = connection.read(arr)) != -1) {
87 | out.write(arr, 0, len)
88 | hasRead += len
89 | def decimal = hasRead / total * 100 + ""
90 |
91 | if (decimal != "100")
92 | decimal = decimal.substring(0, decimal.indexOf("."))
93 |
94 | if (lastResult == Integer.parseInt(decimal)) {
95 | lastResult++
96 | println("下载进度:" + decimal + "%")
97 | }
98 | }
99 | connection.close()
100 | out.close()
101 | println("下载完成")
102 | }
103 |
104 | private Boolean isNeedDownload() {
105 | def firmJar = new File(firmJarParentPath, firmJarPath)
106 | if (!firmJar.exists()) {
107 | if (!firmZipFile.exists()) {
108 | return true
109 | } else {
110 | println("检测到本地已存在下载的压缩包")
111 | unZip()
112 | }
113 | }
114 | return false
115 | }
116 |
117 | public File getFirmZipFile() {
118 | return firmZipFile
119 | }
120 |
121 | public File getFirmJarParentPath() {
122 | return firmJarParentPath
123 | }
124 |
125 | public String getDownUrl() {
126 | return downUrl
127 | }
128 | }
129 |
--------------------------------------------------------------------------------
/android-pack-plugin/packPlugin/src/main/groovy/cn/zengcanxiang/packplugin/task/FirmTask.groovy:
--------------------------------------------------------------------------------
1 | package cn.zengcanxiang.packplugin.task
2 |
3 | import cn.zengcanxiang.packplugin.PluginExtension
4 | import groovy.io.FileType
5 | import org.gradle.api.DefaultTask
6 | import org.gradle.api.GradleException
7 | import org.gradle.api.tasks.TaskAction
8 |
9 | class FirmTask extends DefaultTask {
10 | private PluginExtension config
11 |
12 | File jar
13 | File firmJarParentPath
14 | private def firmJarPath = "jiagu/jiagu.jar"
15 |
16 | FirmTask() {
17 | group = "android-pack"
18 | description = "执行360加固"
19 | config = PluginExtension.getConfig(project)
20 | }
21 |
22 | @TaskAction
23 | def firm() {
24 | firmJarParentPath = new File(config.outPath, "360")
25 | jar = new File(firmJarParentPath, firmJarPath)
26 | if (!config.isNeedFirm || !login()) {
27 | return
28 | }
29 | config.initFirm()
30 | clearFirmService()
31 | println("开始360加固")
32 | def firmResultPath = new File(new File(config.outPath, "firmResult"),
33 | new Date().format("yyyy_MM_dd_HH_mm_ss")
34 | )
35 | firmResultPath.mkdirs()
36 | def firmShell = "java -jar $jar.absolutePath -jiagu $config.apkFilePath $firmResultPath.absolutePath"
37 | def out = new StringBuilder(), err = new StringBuilder()
38 | // 10分钟的执行时间
39 | executeShell(firmShell, out, err, 1000 * 60 * 10)
40 | println("判断360加固是否完成")
41 | if (err.length() > 0) {
42 | println(err.toString())
43 | if (!err.contains("error=13, Permission denied")) {
44 | println("加固 失败")
45 | return
46 | }
47 | }
48 | if (out.length() <= 0 || !(out.contains("已加固") || out.contains("任务完成"))) {
49 | println("加固 验证成功条件不符合,可能存在失败情况")
50 | println(out.toString())
51 | }
52 | println("加固 完成")
53 | firmResultPath.eachFileMatch(FileType.FILES, ~/.*\.apk/) {
54 | PluginExtension.apkFile = it
55 | }
56 | }
57 |
58 | private Boolean login() {
59 | if (!jar.exists()) {
60 | def os = System.getProperty("os.name").toLowerCase()
61 | if (os.contains("linux")) {
62 | // 360加固linux 的文件夹里面的摆放和其他的不一样,需要处理
63 | firmJarParentPath.eachFile { child ->
64 | "mv ${new File(child, "jiagu").absolutePath} $child.parent".execute()
65 | }
66 | }
67 | }
68 | String loginShell = "java -jar $jar.absolutePath -login $config.firmAccountName $config.firmAccountPwd"
69 | def out = new StringBuilder(), err = new StringBuilder()
70 | executeShell(loginShell, out, err, 5000)
71 | if (out.length() <= 0 || !out.contains("login success")) {
72 | println(out.toString())
73 | println(err.toString())
74 | println(loginShell)
75 | throw new GradleException("加固 登录失败")
76 | }
77 | return true
78 | }
79 |
80 | private def clearFirmService() {
81 | println("加固 清除打包额外配置")
82 | def clearFirmServiceShell = "java -jar $jar.absolutePath -config -nocert"
83 | clearFirmServiceShell.execute()
84 | }
85 |
86 | static def executeShell(String shellStr,
87 | StringBuilder out,
88 | StringBuilder err,
89 | int millis) {
90 | def proc = shellStr.execute()
91 | proc.consumeProcessOutput(out, err)
92 | proc.waitForOrKill(millis)
93 | }
94 | }
95 |
--------------------------------------------------------------------------------
/android-pack-plugin/packPlugin/src/main/groovy/cn/zengcanxiang/packplugin/task/MultiChannelTask.groovy:
--------------------------------------------------------------------------------
1 | package cn.zengcanxiang.packplugin.task
2 |
3 | import cn.zengcanxiang.packplugin.PluginExtension
4 | import com.android.apksigner.core.ApkVerifier
5 | import com.android.apksigner.core.internal.util.ByteBufferDataSource
6 | import com.android.apksigner.core.util.DataSource
7 | import com.android.build.gradle.BaseExtension
8 | import groovy.io.FileType
9 | import org.apache.commons.io.IOUtils
10 | import org.gradle.api.DefaultTask
11 | import org.gradle.api.GradleException
12 | import org.gradle.api.tasks.TaskAction
13 |
14 | import java.nio.ByteBuffer
15 | import java.nio.channels.FileChannel
16 |
17 | class MultiChannelTask extends DefaultTask {
18 |
19 | File zipAlignFile
20 |
21 | File signFile
22 |
23 | PluginExtension config
24 |
25 | BaseExtension extension
26 |
27 | MultiChannelTask() {
28 | group = "android-pack"
29 | description = "注入多渠道"
30 | config = PluginExtension.getConfig(project)
31 | }
32 |
33 | @TaskAction
34 | def multiChannel() {
35 | println("多渠道注入任务开始")
36 | if (config.channelConfigFile == null || !config.channelConfigFile.exists()) {
37 | println("多渠道打包配置文件不存在,将不执行渠道注入任务")
38 | return
39 | }
40 |
41 | def androidExtensions = project.extensions.getByName("android")
42 | if( androidExtensions != null instanceof BaseExtension){
43 | extension = androidExtensions as BaseExtension
44 | }else{
45 | println("当前不在android工程内。无法获取项目版本相关信息和android签名工具路径")
46 | return
47 | }
48 |
49 | def apkFile = PluginExtension.apkFile
50 | if (apkFile == null) {
51 | apkFile = new File(config.apkFilePath)
52 | }
53 | if (apkFile == null || !apkFile.exists()) {
54 | throw new GradleException("多渠道原apk:${apkFile}, is not existed!")
55 | }
56 |
57 | Map nameVariantMap = [
58 | 'appName' : project.name,
59 | 'projectName' : project.rootProject.name,
60 | 'applicationId': extension.defaultConfig.applicationId,
61 | 'versionName' : extension.defaultConfig.versionName,
62 | 'versionCode' : extension.defaultConfig.versionCode.toString()
63 | ]
64 | println("对apk进行签名")
65 | def signApkPath = generateApkSinger(apkFile)
66 | if (config.channelConfigFile != null && config.channelConfigFile.exists()) {
67 | println("开始注入多渠道")
68 | File channelOutputFolderParent = new File(
69 | new File(config.outPath, "channelResult"),
70 | nameVariantMap["applicationId"]
71 | )
72 | channelOutputFolderParent.mkdirs()
73 | File channelOutputFolder = new File(
74 | channelOutputFolderParent, new Date().format("yyyy-MM-dd-HH-mm-s")
75 | )
76 | channelOutputFolder.mkdirs()
77 | PluginExtension.channelOutputFolder = channelOutputFolder
78 | generateChannelApkByConfigFile(config.channelConfigFile,
79 | signApkPath,
80 | channelOutputFolder,
81 | nameVariantMap
82 | )
83 | }
84 | }
85 |
86 | private def generateChannelApkByConfigFile(File configFile,
87 | String apkFile,
88 | File channelOutputFolder,
89 | Map nameVariantMap
90 | ) {
91 | def walleJarFile = new File(config.outPath, "walle_cli.jar")
92 | if (!walleJarFile.exists()) {
93 | println("请下载walle_cli.jar文件")
94 | return
95 | }
96 | def writeChannelShell = "java -jar $walleJarFile.absolutePath batch2 -f $configFile.absolutePath $apkFile $channelOutputFolder.absolutePath"
97 | def out = new StringBuilder(), err = new StringBuilder()
98 | println("注入渠道命令为:$writeChannelShell")
99 | FirmTask.executeShell(writeChannelShell, out, err, 1000 * 60 * 10)
100 | new CopySourceTask(project).copySource()
101 | }
102 |
103 | String generateApkSinger(File apkFile) {
104 | def apkPath = apkFile.absolutePath
105 |
106 | getBuildPath(extension.buildToolsVersion)
107 | config.initSignConfig(project)
108 | String zip_aligned_apk_path = apkPath.substring(0, apkPath.length() - 4) + "_zip.apk"
109 | String signed_apk_path = zip_aligned_apk_path.substring(0, zip_aligned_apk_path.length() - 4) + "_signer.apk"
110 | def out = new StringBuilder(), err = new StringBuilder()
111 | // APK zip对齐命令 xxx/zipalign -v 4 xx.apk xx_aligned.apk
112 | def zipAlignShell = "$zipAlignFile.absolutePath -v 4 $apkPath $zip_aligned_apk_path"
113 | //APK 签名命令
114 | def signedShell = "$signFile.absolutePath sign --ks $config.apkJksPath --ks-key-alias $config.apkJksAlias --ks-pass pass:$config.apkJksStorePwd --key-pass pass:$config.apkJksPwd --out $signed_apk_path $zip_aligned_apk_path"
115 | println("对齐命令为:$zipAlignShell")
116 | FirmTask.executeShell(zipAlignShell, out, err, 1000 * 60 * 10)
117 | if (err != null && err.length() > 0) {
118 | println("对齐错误:$zipAlignShell")
119 | println(err.toString())
120 | throw new GradleException(err.toString())
121 | }
122 | println("签名命令为:$signedShell")
123 | FirmTask.executeShell(signedShell, out, err, 1000 * 60 * 10)
124 | if (err != null && err.length() > 0) {
125 | println("签名错误:$signedShell")
126 | println(err.toString())
127 | throw new GradleException(err.toString())
128 | }
129 | checkV2Signature(project.file(signed_apk_path))
130 | return signed_apk_path
131 | }
132 |
133 | def getBuildPath(String buildVersion) {
134 | config.initSdkDir(project)
135 | def buildToolParent = new File(config.sdkDir, "build-tools")
136 | File apkBuild
137 | if (config.buildToolsName != null && config.buildToolsName.length() > 0) {
138 | apkBuild = new File(buildToolParent, config.buildToolsName)
139 | } else {
140 | apkBuild = new File(buildToolParent, buildVersion)
141 | }
142 | println("获取的sdk build-tools目录为:$apkBuild.absolutePath")
143 | if (apkBuild.exists()) {
144 | apkBuild.eachFile { childFile ->
145 | if (childFile.name.contains("zipalign")) {
146 | zipAlignFile = childFile
147 | }
148 | if (childFile.name.contains("apksigner")) {
149 | signFile = childFile
150 | }
151 | }
152 | }
153 | // 如果这两个有一个为空 则去遍历android_home/build-tools/目录
154 | if (zipAlignFile == null || signFile == null) {
155 | buildToolParent.eachFileRecurse(FileType.DIRECTORIES) { dir ->
156 | dir.eachFile { childFile ->
157 | if (childFile.name.contains("zipalign")) {
158 | zipAlignFile = childFile
159 | }
160 | if (childFile.name.contains("apksigner")) {
161 | signFile = childFile
162 | }
163 | }
164 | }
165 | if (zipAlignFile == null || signFile == null) {
166 | throw new GradleException("无法找到build_tools工具,请下载最新的build_tools工具")
167 | }
168 | }
169 | }
170 |
171 | private static def checkV2Signature(File apkFile) {
172 | println("检查apk v2签名空间")
173 | FileInputStream fIn = null
174 | FileChannel fChan = null
175 | try {
176 | fIn = new FileInputStream(apkFile)
177 | fChan = fIn.getChannel()
178 | long fSize = fChan.size()
179 | ByteBuffer byteBuffer = ByteBuffer.allocate((int) fSize)
180 | fChan.read(byteBuffer)
181 | byteBuffer.rewind()
182 | DataSource dataSource = new ByteBufferDataSource(byteBuffer)
183 | ApkVerifier apkVerifier = new ApkVerifier()
184 | ApkVerifier.Result result = apkVerifier.verify(dataSource, 0)
185 | if (!result.verified || !result.verifiedUsingV2Scheme) {
186 | throw new GradleException("${apkFile} has no v2 signature in Apk Signing Block!")
187 | }
188 | } catch (IOException ignore) {
189 | ignore.printStackTrace()
190 | } finally {
191 | IOUtils.closeQuietly(fChan)
192 | IOUtils.closeQuietly(fIn)
193 | }
194 | }
195 | }
196 |
--------------------------------------------------------------------------------
/android-pack-plugin/packPlugin/src/main/java/com/android/apksigner/core/ApkSignerEngine.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright (C) 2016 The Android Open Source Project
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS,
12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | * See the License for the specific language governing permissions and
14 | * limitations under the License.
15 | */
16 |
17 | package com.android.apksigner.core;
18 |
19 | import com.android.apksigner.core.util.DataSink;
20 | import com.android.apksigner.core.util.DataSource;
21 |
22 | import java.io.Closeable;
23 | import java.io.IOException;
24 | import java.security.InvalidKeyException;
25 | import java.security.SignatureException;
26 | import java.util.List;
27 |
28 | /**
29 | * APK signing logic which is independent of how input and output APKs are stored, parsed, and
30 | * generated.
31 | *
32 | *
Operating Model
33 | *
34 | * The abstract operating model is that there is an input APK which is being signed, thus producing
35 | * an output APK. In reality, there may be just an output APK being built from scratch, or the input APK and
36 | * the output APK may be the same file. Because this engine does not deal with reading and writing
37 | * files, it can handle all of these scenarios.
38 | *
39 | *
The engine is stateful and thus cannot be used for signing multiple APKs. However, once
40 | * the engine signed an APK, the engine can be used to re-sign the APK after it has been modified.
41 | * This may be more efficient than signing the APK using a new instance of the engine. See
42 | * Incremental Operation.
43 | *
44 | *
In the engine's operating model, a signed APK is produced as follows.
45 | *
46 | *
JAR entries to be signed are output,
47 | *
JAR archive is signed using JAR signing, thus adding the so-called v1 signature to the
48 | * output,
49 | *
JAR archive is signed using APK Signature Scheme v2, thus adding the so-called v2 signature
50 | * to the output.
51 | *
52 | *
53 | *
The input APK may contain JAR entries which, depending on the engine's configuration, may or
54 | * may not be output (e.g., existing signatures may need to be preserved or stripped) or which the
55 | * engine will overwrite as part of signing. The engine thus offers {@link #inputJarEntry(String)}
56 | * which tells the client whether the input JAR entry needs to be output. This avoids the need for
57 | * the client to hard-code the aspects of APK signing which determine which parts of input must be
58 | * ignored. Similarly, the engine offers {@link #inputApkSigningBlock(DataSource)} to help the
59 | * client avoid dealing with preserving or stripping APK Signature Scheme v2 signature of the input
60 | * APK.
61 | *
62 | *
To use the engine to sign an input APK (or a collection of JAR entries), follow these
63 | * steps:
64 | *
65 | *
Obtain a new instance of the engine -- engine instances are stateful and thus cannot be used
66 | * for signing multiple APKs.
67 | *
Locate the input APK's APK Signing Block and provide it to
68 | * {@link #inputApkSigningBlock(DataSource)}.
69 | *
For each JAR entry in the input APK, invoke {@link #inputJarEntry(String)} to determine
70 | * whether this entry should be output. The engine may request to inspect the entry.
71 | *
For each output JAR entry, invoke {@link #outputJarEntry(String)} which may request to
72 | * inspect the entry.
73 | *
Once all JAR entries have been output, invoke {@link #outputJarEntries()} which may request
74 | * that additional JAR entries are output. These entries comprise the output APK's JAR
75 | * signature.
76 | *
Locate the ZIP Central Directory and ZIP End of Central Directory sections in the output and
77 | * invoke {@link #outputZipSections(DataSource, DataSource, DataSource)} which may request that
78 | * an APK Signature Block is inserted before the ZIP Central Directory. The block contains the
79 | * output APK's APK Signature Scheme v2 signature.
80 | *
Invoke {@link #outputDone()} to signal that the APK was output in full. The engine will
81 | * confirm that the output APK is signed.
82 | *
Invoke {@link #close()} to signal that the engine will no longer be used. This lets the
83 | * engine free any resources it no longer needs.
84 | *
85 | *
86 | *
Some invocations of the engine may provide the client with a task to perform. The client is
87 | * expected to perform all requested tasks before proceeding to the next stage of signing. See
88 | * documentation of each method about the deadlines for performing the tasks requested by the
89 | * method.
90 | *
91 | *
Incremental Operation
92 | *
93 | * The engine supports incremental operation where a signed APK is produced, then modified and
94 | * re-signed. This may be useful for IDEs, where an app is frequently re-signed after small changes
95 | * by the developer. Re-signing may be more efficient than signing from scratch.
96 | *
97 | *
To use the engine in incremental mode, keep notifying the engine of changes to the APK through
98 | * {@link #inputApkSigningBlock(DataSource)}, {@link #inputJarEntry(String)},
99 | * {@link #inputJarEntryRemoved(String)}, {@link #outputJarEntry(String)},
100 | * and {@link #outputJarEntryRemoved(String)}, perform the tasks requested by the engine through
101 | * these methods, and, when a new signed APK is desired, run through steps 5 onwards to re-sign the
102 | * APK.
103 | *
104 | *
Output-only Operation
105 | *
106 | * The engine's abstract operating model consists of an input APK and an output APK. However, it is
107 | * possible to use the engine in output-only mode where the engine's {@code input...} methods are
108 | * not invoked. In this mode, the engine has less control over output because it cannot request that
109 | * some JAR entries are not output. Nevertheless, the engine will attempt to make the output APK
110 | * signed and will report an error if cannot do so.
111 | */
112 | public interface ApkSignerEngine extends Closeable {
113 |
114 | /**
115 | * Indicates to this engine that the input APK contains the provided APK Signing Block. The
116 | * block may contain signatures of the input APK, such as APK Signature Scheme v2 signatures.
117 | *
118 | * @param apkSigningBlock APK signing block of the input APK. The provided data source is
119 | * guaranteed to not be used by the engine after this method terminates.
120 | *
121 | * @throws IllegalStateException if this engine is closed
122 | */
123 | void inputApkSigningBlock(DataSource apkSigningBlock) throws IllegalStateException;
124 |
125 | /**
126 | * Indicates to this engine that the specified JAR entry was encountered in the input APK.
127 | *
128 | *
When an input entry is updated/changed, it's OK to not invoke
129 | * {@link #inputJarEntryRemoved(String)} before invoking this method.
130 | *
131 | * @return instructions about how to proceed with this entry
132 | *
133 | * @throws IllegalStateException if this engine is closed
134 | */
135 | InputJarEntryInstructions inputJarEntry(String entryName) throws IllegalStateException;
136 |
137 | /**
138 | * Indicates to this engine that the specified JAR entry was output.
139 | *
140 | *
It is unnecessary to invoke this method for entries added to output by this engine (e.g.,
141 | * requested by {@link #outputJarEntries()}) provided the entries were output with exactly the
142 | * data requested by the engine.
143 | *
144 | *
When an already output entry is updated/changed, it's OK to not invoke
145 | * {@link #outputJarEntryRemoved(String)} before invoking this method.
146 | *
147 | * @return request to inspect the entry or {@code null} if the engine does not need to inspect
148 | * the entry. The request must be fulfilled before {@link #outputJarEntries()} is
149 | * invoked.
150 | *
151 | * @throws IllegalStateException if this engine is closed
152 | */
153 | InspectJarEntryRequest outputJarEntry(String entryName) throws IllegalStateException;
154 |
155 | /**
156 | * Indicates to this engine that the specified JAR entry was removed from the input. It's safe
157 | * to invoke this for entries for which {@link #inputJarEntry(String)} hasn't been invoked.
158 | *
159 | * @return output policy of this JAR entry. The policy indicates how this input entry affects
160 | * the output APK. The client of this engine should use this information to determine
161 | * how the removal of this input APK's JAR entry affects the output APK.
162 | *
163 | * @throws IllegalStateException if this engine is closed
164 | */
165 | InputJarEntryInstructions.OutputPolicy inputJarEntryRemoved(String entryName)
166 | throws IllegalStateException;
167 |
168 | /**
169 | * Indicates to this engine that the specified JAR entry was removed from the output. It's safe
170 | * to invoke this for entries for which {@link #outputJarEntry(String)} hasn't been invoked.
171 | *
172 | * @throws IllegalStateException if this engine is closed
173 | */
174 | void outputJarEntryRemoved(String entryName) throws IllegalStateException;
175 |
176 | /**
177 | * Indicates to this engine that all JAR entries have been output.
178 | *
179 | *
180 | * @return request to add JAR signature to the output or {@code null} if there is no need to add
181 | * a JAR signature. The request will contain additional JAR entries to be output. The
182 | * request must be fulfilled before
183 | * {@link #outputZipSections(DataSource, DataSource, DataSource)} is invoked.
184 | *
185 | * @throws InvalidKeyException if a signature could not be generated because a signing key is
186 | * not suitable for generating the signature
187 | * @throws SignatureException if an error occurred while generating the JAR signature
188 | * @throws IllegalStateException if there are unfulfilled requests, such as to inspect some JAR
189 | * entries, or if the engine is closed
190 | */
191 | OutputJarSignatureRequest outputJarEntries() throws InvalidKeyException, SignatureException;
192 |
193 | /**
194 | * Indicates to this engine that the ZIP sections comprising the output APK have been output.
195 | *
196 | *
The provided data sources are guaranteed to not be used by the engine after this method
197 | * terminates.
198 | *
199 | * @param zipEntries the section of ZIP archive containing Local File Header records and data of
200 | * the ZIP entries. In a well-formed archive, this section starts at the start of the
201 | * archive and extends all the way to the ZIP Central Directory.
202 | * @param zipCentralDirectory ZIP Central Directory section
203 | * @param zipEocd ZIP End of Central Directory (EoCD) record
204 | *
205 | * @return request to add an APK Signing Block to the output or {@code null} if the output must
206 | * not contain an APK Signing Block. The request must be fulfilled before
207 | * {@link #outputDone()} is invoked.
208 | *
209 | * @throws IOException if an I/O error occurs while reading the provided ZIP sections
210 | * @throws InvalidKeyException if a signature could not be generated because a signing key is
211 | * not suitable for generating the signature
212 | * @throws SignatureException if an error occurred while generating the APK's signature
213 | * @throws IllegalStateException if there are unfulfilled requests, such as to inspect some JAR
214 | * entries or to output JAR signature, or if the engine is closed
215 | */
216 | OutputApkSigningBlockRequest outputZipSections(
217 | DataSource zipEntries,
218 | DataSource zipCentralDirectory,
219 | DataSource zipEocd) throws IOException, InvalidKeyException, SignatureException;
220 |
221 | /**
222 | * Indicates to this engine that the signed APK was output.
223 | *
224 | *
This does not change the output APK. The method helps the client confirm that the current
225 | * output is signed.
226 | *
227 | * @throws IllegalStateException if there are unfulfilled requests, such as to inspect some JAR
228 | * entries or to output signatures, or if the engine is closed
229 | */
230 | void outputDone() throws IllegalStateException;
231 |
232 | /**
233 | * Indicates to this engine that it will no longer be used. Invoking this on an already closed
234 | * engine is OK.
235 | *
236 | *
This does not change the output APK. For example, if the output APK is not yet fully
237 | * signed, it will remain so after this method terminates.
238 | */
239 | @Override
240 | void close();
241 |
242 | /**
243 | * Instructions about how to handle an input APK's JAR entry.
244 | *
245 | *
The instructions indicate whether to output the entry (see {@link #getOutputPolicy()}) and
246 | * may contain a request to inspect the entry (see {@link #getInspectJarEntryRequest()}), in
247 | * which case the request must be fulfilled before {@link ApkSignerEngine#outputJarEntries()} is
248 | * invoked.
249 | */
250 | public static class InputJarEntryInstructions {
251 | private final OutputPolicy mOutputPolicy;
252 | private final InspectJarEntryRequest mInspectJarEntryRequest;
253 |
254 | /**
255 | * Constructs a new {@code InputJarEntryInstructions} instance with the provided entry
256 | * output policy and without a request to inspect the entry.
257 | */
258 | public InputJarEntryInstructions(OutputPolicy outputPolicy) {
259 | this(outputPolicy, null);
260 | }
261 |
262 | /**
263 | * Constructs a new {@code InputJarEntryInstructions} instance with the provided entry
264 | * output mode and with the provided request to inspect the entry.
265 | *
266 | * @param inspectJarEntryRequest request to inspect the entry or {@code null} if there's no
267 | * need to inspect the entry.
268 | */
269 | public InputJarEntryInstructions(
270 | OutputPolicy outputPolicy,
271 | InspectJarEntryRequest inspectJarEntryRequest) {
272 | mOutputPolicy = outputPolicy;
273 | mInspectJarEntryRequest = inspectJarEntryRequest;
274 | }
275 |
276 | /**
277 | * Returns the output policy for this entry.
278 | */
279 | public OutputPolicy getOutputPolicy() {
280 | return mOutputPolicy;
281 | }
282 |
283 | /**
284 | * Returns the request to inspect the JAR entry or {@code null} if there is no need to
285 | * inspect the entry.
286 | */
287 | public InspectJarEntryRequest getInspectJarEntryRequest() {
288 | return mInspectJarEntryRequest;
289 | }
290 |
291 | /**
292 | * Output policy for an input APK's JAR entry.
293 | */
294 | public static enum OutputPolicy {
295 | /** Entry must not be output. */
296 | SKIP,
297 |
298 | /** Entry should be output. */
299 | OUTPUT,
300 |
301 | /** Entry will be output by the engine. The client can thus ignore this input entry. */
302 | OUTPUT_BY_ENGINE,
303 | }
304 | }
305 |
306 | /**
307 | * Request to inspect the specified JAR entry.
308 | *
309 | *
The entry's uncompressed data must be provided to the data sink returned by
310 | * {@link #getDataSink()}. Once the entry's data has been provided to the sink, {@link #done()}
311 | * must be invoked.
312 | */
313 | interface InspectJarEntryRequest {
314 |
315 | /**
316 | * Returns the data sink into which the entry's uncompressed data should be sent.
317 | */
318 | DataSink getDataSink();
319 |
320 | /**
321 | * Indicates that entry's data has been provided in full.
322 | */
323 | void done();
324 |
325 | /**
326 | * Returns the name of the JAR entry.
327 | */
328 | String getEntryName();
329 | }
330 |
331 | /**
332 | * Request to add JAR signature (aka v1 signature) to the output APK.
333 | *
334 | *
Entries listed in {@link #getAdditionalJarEntries()} must be added to the output APK after
335 | * which {@link #done()} must be invoked.
336 | */
337 | interface OutputJarSignatureRequest {
338 |
339 | /**
340 | * Returns JAR entries that must be added to the output APK.
341 | */
342 | List getAdditionalJarEntries();
343 |
344 | /**
345 | * Indicates that the JAR entries contained in this request were added to the output APK.
346 | */
347 | void done();
348 |
349 | /**
350 | * JAR entry.
351 | */
352 | public static class JarEntry {
353 | private final String mName;
354 | private final byte[] mData;
355 |
356 | /**
357 | * Constructs a new {@code JarEntry} with the provided name and data.
358 | *
359 | * @param data uncompressed data of the entry. Changes to this array will not be
360 | * reflected in {@link #getData()}.
361 | */
362 | public JarEntry(String name, byte[] data) {
363 | mName = name;
364 | mData = data.clone();
365 | }
366 |
367 | /**
368 | * Returns the name of this ZIP entry.
369 | */
370 | public String getName() {
371 | return mName;
372 | }
373 |
374 | /**
375 | * Returns the uncompressed data of this JAR entry.
376 | */
377 | public byte[] getData() {
378 | return mData.clone();
379 | }
380 | }
381 | }
382 |
383 | /**
384 | * Request to add the specified APK Signing Block to the output APK. APK Signature Scheme v2
385 | * signature(s) of the APK are contained in this block.
386 | *
387 | *
The APK Signing Block returned by {@link #getApkSigningBlock()} must be placed into the
388 | * output APK such that the block is immediately before the ZIP Central Directory, the offset of
389 | * ZIP Central Directory in the ZIP End of Central Directory record must be adjusted
390 | * accordingly, and then {@link #done()} must be invoked.
391 | *
392 | *
If the output contains an APK Signing Block, that block must be replaced by the block
393 | * contained in this request.
394 | */
395 | interface OutputApkSigningBlockRequest {
396 |
397 | /**
398 | * Returns the APK Signing Block.
399 | */
400 | byte[] getApkSigningBlock();
401 |
402 | /**
403 | * Indicates that the APK Signing Block was output as requested.
404 | */
405 | void done();
406 | }
407 | }
408 |
--------------------------------------------------------------------------------
/android-pack-plugin/packPlugin/src/main/java/com/android/apksigner/core/ApkVerifier.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright (C) 2016 The Android Open Source Project
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS,
12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | * See the License for the specific language governing permissions and
14 | * limitations under the License.
15 | */
16 |
17 | package com.android.apksigner.core;
18 |
19 | import com.android.apksigner.core.apk.ApkUtils;
20 | import com.android.apksigner.core.internal.apk.v2.ContentDigestAlgorithm;
21 | import com.android.apksigner.core.internal.apk.v2.SignatureAlgorithm;
22 | import com.android.apksigner.core.internal.apk.v2.V2SchemeVerifier;
23 | import com.android.apksigner.core.util.DataSource;
24 | import com.android.apksigner.core.zip.ZipFormatException;
25 |
26 | import java.io.IOException;
27 | import java.security.cert.X509Certificate;
28 | import java.util.ArrayList;
29 | import java.util.List;
30 |
31 | /**
32 | * APK signature verifier which mimics the behavior of the Android platform.
33 | *
34 | *
The verifier is designed to closely mimic the behavior of Android platforms. This is to enable
35 | * the verifier to be used for checking whether an APK's signatures will verify on Android.
36 | */
37 | public class ApkVerifier {
38 |
39 | /**
40 | * Verifies the APK's signatures and returns the result of verification. The APK can be
41 | * considered verified iff the result's {@link Result#isVerified()} returns {@code true}.
42 | * The verification result also includes errors, warnings, and information about signers.
43 | *
44 | * @param apk APK file contents
45 | * @param minSdkVersion API Level of the oldest Android platform on which the APK's signatures
46 | * may need to be verified
47 | *
48 | * @throws IOException if an I/O error is encountered while reading the APK
49 | * @throws ZipFormatException if the APK is malformed at ZIP format level
50 | */
51 | public Result verify(DataSource apk, int minSdkVersion) throws IOException, ZipFormatException {
52 | ApkUtils.ZipSections zipSections = ApkUtils.findZipSections(apk);
53 |
54 | // Attempt to verify the APK using APK Signature Scheme v2
55 | Result result = new Result();
56 | try {
57 | V2SchemeVerifier.Result v2Result = V2SchemeVerifier.verify(apk, zipSections);
58 | result.mergeFrom(v2Result);
59 | } catch (V2SchemeVerifier.SignatureNotFoundException ignored) {}
60 | if (result.containsErrors()) {
61 | return result;
62 | }
63 |
64 | // TODO: Verify JAR signature if necessary
65 | if (!result.isVerifiedUsingV2Scheme()) {
66 | return result;
67 | }
68 |
69 | // Verified
70 | result.setVerified();
71 | for (Result.V2SchemeSignerInfo signerInfo : result.getV2SchemeSigners()) {
72 | result.addSignerCertificate(signerInfo.getCertificate());
73 | }
74 |
75 | return result;
76 | }
77 |
78 | /**
79 | * Result of verifying an APKs signatures. The APK can be considered verified iff
80 | * {@link #isVerified()} returns {@code true}.
81 | */
82 | public static class Result {
83 | private final List mErrors = new ArrayList<>();
84 | private final List mWarnings = new ArrayList<>();
85 | private final List mSignerCerts = new ArrayList<>();
86 | private final List mV2SchemeSigners = new ArrayList<>();
87 |
88 | private boolean mVerified;
89 | private boolean mVerifiedUsingV2Scheme;
90 |
91 | /**
92 | * Returns {@code true} if the APK's signatures verified.
93 | */
94 | public boolean isVerified() {
95 | return mVerified;
96 | }
97 |
98 | private void setVerified() {
99 | mVerified = true;
100 | }
101 |
102 | /**
103 | * Returns {@code true} if the APK's APK Signature Scheme v2 signatures verified.
104 | */
105 | public boolean isVerifiedUsingV2Scheme() {
106 | return mVerifiedUsingV2Scheme;
107 | }
108 |
109 | /**
110 | * Returns the verified signers' certificates, one per signer.
111 | */
112 | public List getSignerCertificates() {
113 | return mSignerCerts;
114 | }
115 |
116 | private void addSignerCertificate(X509Certificate cert) {
117 | mSignerCerts.add(cert);
118 | }
119 |
120 | /**
121 | * Returns information about APK Signature Scheme v2 signers associated with the APK's
122 | * signature.
123 | */
124 | public List getV2SchemeSigners() {
125 | return mV2SchemeSigners;
126 | }
127 |
128 | /**
129 | * Returns errors encountered while verifying the APK's signatures.
130 | */
131 | public List getErrors() {
132 | return mErrors;
133 | }
134 |
135 | /**
136 | * Returns warnings encountered while verifying the APK's signatures.
137 | */
138 | public List getWarnings() {
139 | return mWarnings;
140 | }
141 |
142 | private void mergeFrom(V2SchemeVerifier.Result source) {
143 | mVerifiedUsingV2Scheme = source.verified;
144 | mErrors.addAll(source.getErrors());
145 | mWarnings.addAll(source.getWarnings());
146 | for (V2SchemeVerifier.Result.SignerInfo signer : source.signers) {
147 | mV2SchemeSigners.add(new V2SchemeSignerInfo(signer));
148 | }
149 | }
150 |
151 | /**
152 | * Returns {@code true} if an error was encountered while verifying the APK. Any error
153 | * prevents the APK from being considered verified.
154 | */
155 | public boolean containsErrors() {
156 | if (!mErrors.isEmpty()) {
157 | return true;
158 | }
159 | if (!mV2SchemeSigners.isEmpty()) {
160 | for (V2SchemeSignerInfo signer : mV2SchemeSigners) {
161 | if (signer.containsErrors()) {
162 | return true;
163 | }
164 | }
165 | }
166 |
167 | return false;
168 | }
169 |
170 | /**
171 | * Information about an APK Signature Scheme v2 signer associated with the APK's signature.
172 | */
173 | public static class V2SchemeSignerInfo {
174 | private final int mIndex;
175 | private final List mCerts;
176 |
177 | private final List mErrors;
178 | private final List mWarnings;
179 |
180 | private V2SchemeSignerInfo(V2SchemeVerifier.Result.SignerInfo result) {
181 | mIndex = result.index;
182 | mCerts = result.certs;
183 | mErrors = result.getErrors();
184 | mWarnings = result.getWarnings();
185 | }
186 |
187 | /**
188 | * Returns this signer's {@code 0}-based index in the list of signers contained in the
189 | * APK's APK Signature Scheme v2 signature.
190 | */
191 | public int getIndex() {
192 | return mIndex;
193 | }
194 |
195 | /**
196 | * Returns this signer's signing certificate or {@code null} if not available. The
197 | * certificate is guaranteed to be available if no errors were encountered during
198 | * verification (see {@link #containsErrors()}.
199 | *
200 | *
This certificate contains the signer's public key.
201 | */
202 | public X509Certificate getCertificate() {
203 | return mCerts.isEmpty() ? null : mCerts.get(0);
204 | }
205 |
206 | /**
207 | * Returns this signer's certificates. The first certificate is for the signer's public
208 | * key. An empty list may be returned if an error was encountered during verification
209 | * (see {@link #containsErrors()}).
210 | */
211 | public List getCertificates() {
212 | return mCerts;
213 | }
214 |
215 | public boolean containsErrors() {
216 | return !mErrors.isEmpty();
217 | }
218 |
219 | public List getErrors() {
220 | return mErrors;
221 | }
222 |
223 | public List getWarnings() {
224 | return mWarnings;
225 | }
226 | }
227 | }
228 |
229 | /**
230 | * Error or warning encountered while verifying an APK's signatures.
231 | */
232 | public static enum Issue {
233 |
234 | /**
235 | * Failed to parse the list of signers contained in the APK Signature Scheme v2 signature.
236 | */
237 | V2_SIG_MALFORMED_SIGNERS("Malformed list of signers"),
238 |
239 | /**
240 | * Failed to parse this signer's signer block contained in the APK Signature Scheme v2
241 | * signature.
242 | */
243 | V2_SIG_MALFORMED_SIGNER("Malformed signer block"),
244 |
245 | /**
246 | * Public key embedded in the APK Signature Scheme v2 signature of this signer could not be
247 | * parsed.
248 | *
249 | *
250 | *
Parameter 1: error details ({@code Throwable})
251 | *
252 | */
253 | V2_SIG_MALFORMED_PUBLIC_KEY("Malformed public key: %1$s"),
254 |
255 | /**
256 | * This APK Signature Scheme v2 signer's certificate could not be parsed.
257 | *
258 | *
259 | *
Parameter 1: index ({@code 0}-based) of the certificate in the signer's list of
260 | * certificates ({@code Integer})
261 | *
Parameter 2: sequence number ({@code 1}-based) of the certificate in the signer's
262 | * list of certificates ({@code Integer})
263 | *
Parameter 3: error details ({@code Throwable})
264 | *
265 | */
266 | V2_SIG_MALFORMED_CERTIFICATE("Malformed certificate #%2$d: %3$s"),
267 |
268 | /**
269 | * Failed to parse this signer's signature record contained in the APK Signature Scheme v2
270 | * signature.
271 | *
272 | *
273 | *
Parameter 1: record number (first record is {@code 1}) ({@code Integer})
274 | *
275 | */
276 | V2_SIG_MALFORMED_SIGNATURE("Malformed APK Signature Scheme v2 signature record #%1$d"),
277 |
278 | /**
279 | * Failed to parse this signer's digest record contained in the APK Signature Scheme v2
280 | * signature.
281 | *
282 | *
283 | *
Parameter 1: record number (first record is {@code 1}) ({@code Integer})
338 | */
339 | V2_SIG_DID_NOT_VERIFY("%1$s signature over signed-data did not verify"),
340 |
341 | /**
342 | * This APK Signature Scheme v2 signer offers no signatures.
343 | */
344 | V2_SIG_NO_SIGNATURES("No signatures"),
345 |
346 | /**
347 | * This APK Signature Scheme v2 signer offers signatures but none of them are supported.
348 | */
349 | V2_SIG_NO_SUPPORTED_SIGNATURES("No supported signatures"),
350 |
351 | /**
352 | * This APK Signature Scheme v2 signer offers no certificates.
353 | */
354 | V2_SIG_NO_CERTIFICATES("No certificates"),
355 |
356 | /**
357 | * This APK Signature Scheme v2 signer's public key listed in the signer's certificate does
358 | * not match the public key listed in the signatures record.
359 | *
360 | *
361 | *
Parameter 1: hex-encoded public key from certificate ({@code String})
362 | *
Parameter 2: hex-encoded public key from signatures record ({@code String})
363 | *
364 | */
365 | V2_SIG_PUBLIC_KEY_MISMATCH_BETWEEN_CERTIFICATE_AND_SIGNATURES_RECORD(
366 | "Public key mismatch between certificate and signature record: <%1$s> vs <%2$s>"),
367 |
368 | /**
369 | * This APK Signature Scheme v2 signer's signature algorithms listed in the signatures
370 | * record do not match the signature algorithms listed in the signatures record.
371 | *
372 | *
373 | *
Parameter 1: signature algorithms from signatures record ({@code List})
374 | *
Parameter 2: signature algorithms from digests record ({@code List})
375 | *
376 | */
377 | V2_SIG_SIG_ALG_MISMATCH_BETWEEN_SIGNATURES_AND_DIGESTS_RECORDS(
378 | "Signature algorithms mismatch between signatures and digests records"
379 | + ": %1$s vs %2$s"),
380 |
381 | /**
382 | * The APK's digest does not match the digest contained in the APK Signature Scheme v2
383 | * signature.
384 | *
385 | *