蓝色天空.知识 · 实践 · 创造
我的收藏
在线代码实验室

运行合成 APK ZIP 条目分类、二进制 AXML(0x0003) 与 DEX(035) 头解析及 ProGuard/R8 混淆映射实测

PYTHONWindows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。explore-tutorial-decompile-apk-get-code-resources.py
explore-tutorial-decompile-apk-get-code-resources.py161 行
"""Offline deterministic verifier for Android CH14 (tutorial-decompile-apk-get-code-resources)."""
from __future__ import annotations

import json
import struct
import tempfile
import zipfile
from pathlib import Path


def build_synthetic_apk(apk_path: Path) -> None:
    png_bytes = b"\x89PNG\r\n\x1a\n" + b"\x00\x00\x00\rIHDR" + b"\x00" * 16
    # Android binary XML (AXML) header: type=0x0003, header_size=0x0008, file_size=24
    axml_bytes = struct.pack("<HHI", 0x0003, 0x0008, 24) + b"\x01\x00\x1c\x00" + b"\x00" * 12
    # DEX header magic + version 035 + checksum placeholder + file_size
    dex_bytes = b"dex\n035\x00" + b"\x00" * 24 + struct.pack("<I", 112) + b"\x00" * 76
    arsc_bytes = struct.pack("<HHI", 0x0002, 0x000C, 16) + b"\x00" * 8
    with zipfile.ZipFile(apk_path, "w", compression=zipfile.ZIP_DEFLATED) as zf:
        zf.writestr("res/drawable/ic_logo.png", png_bytes)
        zf.writestr("AndroidManifest.xml", axml_bytes)
        zf.writestr("classes.dex", dex_bytes)
        zf.writestr("resources.arsc", arsc_bytes)


def case_apk_zip_classification() -> dict:
    with tempfile.TemporaryDirectory() as tmp:
        apk = Path(tmp) / "sample.apk"
        build_synthetic_apk(apk)
        with zipfile.ZipFile(apk, "r") as zf:
            png_readable = zf.read("res/drawable/ic_logo.png").startswith(b"\x89PNG\r\n\x1a\n")
            manifest_raw = zf.read("AndroidManifest.xml")
            manifest_is_plain_xml = manifest_raw.lstrip().startswith(b"<")
            dex_present = "classes.dex" in zf.namelist()
            entry_count = len(zf.namelist())
    actual = {
        "zip_entry_count": entry_count,
        "bitmap_directly_readable": png_readable,
        "compiled_manifest_plain_text": manifest_is_plain_xml,
        "contains_classes_dex": dex_present,
    }
    expected = {
        "zip_entry_count": 4,
        "bitmap_directly_readable": True,
        "compiled_manifest_plain_text": False,
        "contains_classes_dex": True,
    }
    return {
        "name": "apk_zip_unpack_and_entry_classification",
        "summary": "验证直接将 APK 改后缀解压可读 PNG 位图,但二进制 XML 不可直读且字节码封存于 classes.dex",
        "expected": expected,
        "actual": actual,
        "passed": actual == expected,
    }


def case_axml_and_dex_headers() -> dict:
    with tempfile.TemporaryDirectory() as tmp:
        apk = Path(tmp) / "sample.apk"
        build_synthetic_apk(apk)
        with zipfile.ZipFile(apk, "r") as zf:
            axml = zf.read("AndroidManifest.xml")
            dex = zf.read("classes.dex")
        res_type, hdr_size, axml_size = struct.unpack("<HHI", axml[:8])
        dex_magic = dex[:8].decode("ascii", errors="replace")
        dex_file_size = struct.unpack("<I", dex[32:36])[0]
    actual = {
        "axml_type_hex": f"0x{res_type:04x}",
        "axml_header_size": hdr_size,
        "axml_size_matches": axml_size == len(axml),
        "dex_magic": dex_magic.replace("\n", "\\n").replace("\x00", "\\0"),
        "dex_size_matches": dex_file_size == len(dex),
    }
    expected = {
        "axml_type_hex": "0x0003",
        "axml_header_size": 8,
        "axml_size_matches": True,
        "dex_magic": "dex\\n035\\0",
        "dex_size_matches": True,
    }
    return {
        "name": "axml_and_dex_header_inspector",
        "summary": "解析离线模拟 APK 的二进制 AXML(0x0003)与 DEX(dex\\n035\\0)文件头结构",
        "expected": expected,
        "actual": actual,
        "passed": actual == expected,
    }


def case_decompile_toolchain_pipeline() -> dict:
    classic_steps = [
        {"tool": "apktool", "cmd": "apktool d sample.apk", "input": ".apk", "output": "decoded_xml_and_res_and_smali"},
        {"tool": "dex2jar", "cmd": "d2j-dex2jar classes.dex", "input": "classes.dex", "output": "classes-dex2jar.jar"},
        {"tool": "jd-gui", "cmd": "jd-gui classes-dex2jar.jar", "input": "classes-dex2jar.jar", "output": "decompiled_java_view"},
    ]
    modern_tools = ["jadx-gui", "Android Studio APK Analyzer (apkanalyzer)"]
    chained_ok = classic_steps[1]["output"] == classic_steps[2]["input"]
    actual = {
        "classic_tool_names": [s["tool"] for s in classic_steps],
        "dex2jar_feeds_jdgui": chained_ok,
        "modern_alternatives": modern_tools,
    }
    expected = {
        "classic_tool_names": ["apktool", "dex2jar", "jd-gui"],
        "dex2jar_feeds_jdgui": True,
        "modern_alternatives": ["jadx-gui", "Android Studio APK Analyzer (apkanalyzer)"],
    }
    return {
        "name": "reverse_engineering_toolchain_pipeline",
        "summary": "核对 apktool + dex2jar + jd-gui 经典三件套输入输出衔接及现代 jadx/APK Analyzer 演进",
        "expected": expected,
        "actual": actual,
        "passed": actual == expected,
    }


def case_proguard_r8_obfuscation() -> dict:
    keep_classes = {"com.example.app.MainActivity"}
    symbols = [
        "com.example.app.MainActivity",
        "com.example.app.NewsRepository",
        "com.example.app.TokenSigner",
    ]
    obf_names = iter(["a.a", "a.b", "a.c"])
    mapping = {}
    for sym in symbols:
        mapping[sym] = sym if sym in keep_classes else next(obf_names)
    actual = {
        "manifest_activity_kept": mapping["com.example.app.MainActivity"] == "com.example.app.MainActivity",
        "internal_classes_obfuscated": [mapping["com.example.app.NewsRepository"], mapping["com.example.app.TokenSigner"]],
        "mapping_reversible_with_table": len(set(mapping.values())) == len(symbols),
    }
    expected = {
        "manifest_activity_kept": True,
        "internal_classes_obfuscated": ["a.a", "a.b"],
        "mapping_reversible_with_table": True,
    }
    return {
        "name": "proguard_r8_obfuscation_mapping_check",
        "summary": "模拟 ProGuard/R8 代码混淆映射:保留 Manifest 入口 Activity 并缩短内部业务类符号",
        "expected": expected,
        "actual": actual,
        "passed": actual == expected,
    }


def main() -> None:
    payload = {
        "version": "CPython 3.12.14 offline Android XML/layout/manifest verifier (Android SDK/emulator absent)",
        "cases": [
            case_apk_zip_classification(),
            case_axml_and_dex_headers(),
            case_decompile_toolchain_pipeline(),
            case_proguard_r8_obfuscation(),
        ],
    }
    print(json.dumps(payload, ensure_ascii=False, indent=2))


if __name__ == "__main__":
    main()
本例需在 Windows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。 中运行,请复制源码、保存文件或下载工程包后在本地执行验证。
运行说明与环境独立工程

运行环境:Windows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。

入口文件:projects/android-tutorial-decompile-apk-get-code-resources-lab/explore-tutorial-decompile-apk-get-code-resources.py

本地运行步骤快速上手
  1. 点击上方“保存源码”保存为 explore-tutorial-decompile-apk-get-code-resources.py,或下载右侧课程工程包。
  2. 确认本地已准备 Windows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。。
  3. 按对应章节命令执行,结合正文核对实际输出。
附件与关联工程包下载

下载课程关联工程包:Android

课程关联工程包(登记关联156章) · 含当前章节或实例 · mbskycom202612a1829.zip

下载课程关联工程包:Android

课程关联工程包(登记关联1章) · 含当前章节或实例 · mbskycom202612a1866.zip
SITE SEARCH

搜索教程、工具与资讯

热门搜索

JavaScriptJSON格式化正则表达式AI 编程AI 翻译AI导航专题标签
Esc 关闭

欢迎登录蓝色天空网

使用会员账号,继续你的学习