0%

Android-随机包名

本文代码主要来源 Magisk, 主要代码语言为 kotlin.

原理

修改 AndroidManifest.xml 的 package (包名) 和 android:label (应用名) 来修改 app 包名.

代码

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
private suspend fun patchAndHide(
activity: Activity,
label: String,
onFailure: Runnable,
path: String
): Boolean {
// val stub = File(activity.cacheDir, "stub.apk")
val stub = File(path) //拿到自身app的apk文件

// Generate a new random package name and signature
val repack = File(activity.cacheDir, "patched.apk")

val pkg = genPackageName() //随机生成包名

if (!patch(activity, stub, FileOutputStream(repack), pkg, label)) //修改AndroidManifest.xml文件
return false

// Install
val cmd = "pm install ${repack.absolutePath}"
return if(Shell.su(cmd).exec().isSuccess){ //pm install安装新的apk
UiThreadHandler.run { Toast.makeText(activity, "随机包名安装成功,应用名:${label}", Toast.LENGTH_LONG).show() }
true
}else{
UiThreadHandler.run { Toast.makeText(activity, "随机包名安装失败", Toast.LENGTH_LONG).show() }
false
}
}
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
fun patch(
context: Context,
apk: File, out: OutputStream,
pkg: String, label: CharSequence
): Boolean {
val info = context.packageManager.getPackageArchiveInfo(apk.path, 0) ?: return false
val name = info.applicationInfo.nonLocalizedLabel.toString()
try {
JarMap.open(apk, true).use { jar ->
val je = jar.getJarEntry(ANDROID_MANIFEST)
val xml = AXML(jar.getRawData(je))//打开原apk的AndroidManifest.xml文件

if (!xml.findAndPatch(APPLICATION_ID to pkg, name to label.toString())) //替换掉原包名和应用名.
return false

// Write apk changes
jar.getOutputStream(je).use { it.write(xml.bytes) }
val keys = Keygen(context)
SignApk.sign(keys.cert, keys.key, jar, out)//apk签名
return true
}
} catch (e: Exception) {
Timber.e(e)
return false
}
}

核心代码就这么点,是不是很简单?

最后

Magisk 的代码里会默认替换所有匹配的包名,所以启动的 Activity 包名不要和 package 名一致。本项目 (kotlin) 源码见 Github:
https://github.com/PShocker/HideAPK

JAVA 版本可以参考小五的代码:
https://github.com/xw103/DeepApp/tree/master/hide

测试用例:
https://github.com/PShocker/HideAPK/releases/download/1.0/app-release.apk