跪拜 Guibai
← Back to the summary

Decompilation Leaves Only Two Classes: A Self-Built Android Shell's Engineering Retrospective

After decompilation only 2 classes remain: a complete retrospective on self-developed DEX shell hardening

This is not a tutorial on "step-by-step how to write a hardening shell"; I won't post complete code.
This is an engineering retrospective: how a real componentized App, without introducing any commercial shell, encrypted all DEX, SO, and H5, withstood re-signing and tampering, while not breaking ARouter routing and multi-process.
After reading you'll get three things: an applicable architecture, 6 pitfalls I actually stepped in, and a compliance boundary for what to do and what not to do.

Cover: Android application security hardening concept Figure 0 · Conceptual illustration of business code protected by layers of encryption

One-sentence conclusion: Whole encryption + runtime restoration is more suitable for componentized engineering than open-source shells that do method-body stripping; the real difficulty has never been "encryption" itself, but ClassLoader replacement fallbacks, multi-process concurrent file writes, and caching compatibility with routing frameworks.


1. Why I wrote this: a question that must be answered

The requirement is straightforward: make static decompilation unable to see business code, while satisfying three hard constraints:

  1. Decrypt on demand at runtime, with no user perception;
  2. Resist re-signing and resource tampering;
  3. Don't break the existing componentized routing (ARouter) and multi-process architecture.

The third is the watershed. Many hardening schemes run fine on "Hello World", but crash on real engineering—routing won't jump, sub-processes won't start, a tab doesn't respond.

I'll first state the selection conclusion:

Compared with the open-source solution dpt-shell (method-body stripping). Its approach is harder, but tested on componentized + ARouter projects, it makes routing jumps fail (method-body stripping breaks route-table registration), and it only protects DEX, not encrypting SO. For such complex engineering, a self-developed "whole encryption + runtime cache prewriting" scheme is more controllable.

So the final route is: keep only a minimal shell in the APK, encrypt everything else into assets, and restore at runtime. Let's look at what the result looks like.


2. Look at the result first: what's in the hardened APK

Figure 1 Comparison of APK structure before and after hardening Figure 1 · APK structure before and after hardening: business assets go from "plaintext visible" to "encrypted payload"

After hardening, only these assets remain:

Asset Content Purpose
classes.dex Only shell classes (2) Application entry + AppComponentFactory
lib/<abi>/libshell.so Decryption / signature verification / anti-debug / hidden API bypass All native logic (stripped)
shell_payload.bin Full encryption of original classes*.dex Business DEX
so_payload.bin Full encryption of original lib/*.so Business SO
h5_payload.bin Encryption of *.html / *.htm H5 pages
arouter_routes.txt Route class names extracted at build time Input for route cache prewriting
integrity.sha256 SHA-256 manifest for each entry Integrity check

Encryption itself uses stream XOR, the key does not reside in the DEX, decryption is in native:

/* Simplified symmetric stream transform: position-dependent XOR to avoid whole-block repeated byte patterns */
cipher[i] = plain[i] ^ key[i % keylen] ^ ((i * 31) & 0xFF);

This encryption is not strong—it solves the problem of "static decompilation cannot directly see business code", not fighting an experienced reverse engineer. I'll honestly state the strength boundary in Section 7.


3. Startup chain: 7 steps to restore

Figure 2 Shell startup sequence Figure 2 · Shell startup sequence: 7 steps from attachBaseContext to the real business Application

The entire startup chain is a serial pipeline; any step that fails kills the process directly, and never continues in a "half-restored" state:

  1. attachBaseContext — the shell Application takes over the entry, earlier than any business code;
  2. Signature verification — native compares the certificate SHA-256, mismatch → SIGKILL;
  3. Integrity verification — compares each entry against the SHA-256 manifest, mismatch → SIGKILL;
  4. DEX / SO / H5 restoration — native decrypts to the app private directory (protected by FileLock);
  5. ClassLoader replacement — three reflection paths + self-check + official channel + safety net;
  6. Route cache prewriting — pre-writes the ARouter cache to prevent it from scanning an empty DEX;
  7. Reflective creation of the real Application — proxy lifecycle, business code officially starts.

Among these, steps 5 and 6 are the technical core of the scheme; I'll break them out separately below.


4. Six key decisions (including the pitfalls I stepped in)

Decision 1: Whole encryption, not method-body stripping

Method-body stripping (emptying every method body in the DEX and backfilling at runtime) sounds "harsher", but its cost is: it breaks runtime reflection and annotation scanning of frameworks. ARouter scans all DEX on first initialization to collect the route table; after method bodies are stripped, the registration logic fails, and the result is routing won't jump and pages won't open.

Whole encryption, instead, "restores the original DEX untouched", making it completely transparent to upper-layer frameworks. That is the fundamental reason I abandoned dpt-shell and chose self-development.

Pitfall note: When choosing, don't only look at "protection strength"; look at whether your project depends on frameworks that scan DEX at runtime (routing, pluginization, hotfix all count). If yes, don't touch method-body stripping.

Decision 2: ClassLoader replacement needs three layers of fallback

Figure 3 ClassLoader multi-path replacement and three-layer fallback Figure 3 · ClassLoader multi-path replacement: three reflection paths + self-check + official channel + safety net

Android has different ClassLoader mount points across versions, so a single reflection path will inevitably fail on some devices. My approach is to prepare three paths simultaneously + self-check + two layers of fallback:

// Path 1: ContextImpl.mPackageInfo -> LoadedApk.mClassLoader
// Path 2: ActivityThread.mPackages -> LoadedApk.mClassLoader
// Path 3: ContextImpl.mClassLoader
private boolean swapClassLoader(Context ctx, ClassLoader newCl) {
    for (String path : SWAP_PATHS) {
        if (trySwapByPath(ctx, newCl, path)) {
            return verifyClassLoader(ctx, newCl);   // Must self-check after swapping
        }
    }
    return false;
}

verifyClassLoader actually loads a class that only exists in the real DEX, confirming the new ClassLoader is indeed active—"reflection didn't throw an exception" does not equal "replacement succeeded", a point many people overlook.

Then it adds two more layers of insurance:

// Official channel: the sanctioned replacement point on Android 7.0+
@Override
public ClassLoader instantiateClassLoader(ClassLoader cl, ApplicationInfo info) {
    return realCl(cl);   // Return the real ClassLoader after restoration
}

Why this is a key decision: The shell's first principle is "must not prevent the app from starting". The three-layer fallback downgrades a "hardening failure" from a "crash" to "degrading to plaintext execution", a very worthwhile trade-off.

Decision 3: Multi-process concurrent restoration must be locked

Figure 4 Multi-process concurrent restoration Figure 4 · Multi-process concurrent restoration: FileLock + marker + atomic rename

This App has multiple processes (main process + two sub-processes), and each process executes the shell code independently. If three processes write the decrypted result to the same file at the same time, what happens?

Pitfall note: Such bugs manifest as SIGBUS / SIGSEGV random crashes, with no business stack in the logs, extremely hard to diagnose—because the root cause is "two processes truncating the same DEX file concurrently".

The solution is the classic three-piece set:

FileLock lock = channel.lock();          // 1. Cross-process mutual exclusion
 try {
    if (marker.exists()) return;          // 2. If already done, reuse it
    writeToTmp(decryptedBytes);           // 3a. Write to temp file first
    Files.move(tmp, target, ATOMIC_MOVE); // 3b. Atomic rename
    marker.createNewFile();               // 3c. Mark as done
} finally {
    lock.release();
}

".tmp → atomic rename" ensures any process at any moment sees either a complete file or its absence, never a half-written DEX.

Decision 4: Anti-re-sign and anti-tampering must be "early, hard, and complete"

Here's a pitfall that's easy to step into:

Pitfall 5: The integrity manifest must be generated before the APK is finalized. Initially I generated it after packaging and stuffed it in, and as a result any "modify APK after packaging" operation (channel package writing, re-signing) would fail the check. Also, the manifest must skip META-INF (signatures modify it) and AndroidManifest.xml (unpacking tools recompile it).

Decision 5: ARouter cache prewriting—the most hidden pitfall

Figure 5 ARouter cache prewriting Figure 5 · ARouter cache prewriting principle: from "empty scan writes dead cache" to "build-time extraction + runtime prewrite"

This pitfall deserves a separate section because its symptom and root cause are completely in different places.

Symptom: After hardening, the "My" tab doesn't respond, and all route jumps fail.

First reaction: Is the DEX not restored? No, the logs show restoration is normal.

Actual root cause: ARouter scans all DEX inside the APK on first initialization to collect the route table. After hardening, the APK only contains the shell DEX (2 classes), so the scan result is empty; ARouter writes the "empty set" into its cache and marks itself "initialized"—even after the real DEX is restored, it never scans again. One empty scan permanently writes the route table as empty.

Solution: Extract route class names at build time, and at runtime, before ARouter initializes, actively write the cache:

private void prewarmArouterCache(Context ctx) {
    // 1. Write route group data (content from the build-time extracted arouter_routes.txt)
    SharedPreferences sp = ctx.getSharedPreferences(SP_NAME, MODE);
    sp.edit().putString(KEY_ROUTE_MAP, routeMapFromAssets).apply();
    // 2. Mark "version seen", so it takes the cache branch and no longer scans empty DEX
    sp.edit().putBoolean(KEY_VERSION_SEEN, true).apply();
    // 3. Reflectively force-disable the obfuscated debug switch class/field (fill in per target project's actual obfuscation)
    forceDisableDebugSwitch();
}

Pitfall 6: The obfuscated debug switch class/field names must be filled according to the target project's actual situation; copying my placeholder will definitely fail—which is also why it cannot become a "zero-configuration" generic step.

Decision 6: Two details in native compilation

These two pitfalls are small but fatal, both the type that "compiles fine, crashes at runtime":

# Pitfall A: Must link log and pthread, otherwise dlopen reports missing symbols and JNI methods are missing
LOCAL_LDLIBS := -llog -pthread

# Pitfall B: strip can only remove local symbols; must keep the Java_* exports in .dynsym
llvm-strip --strip-unneeded libshell.so   # Don't use strip --strip-all

Using --strip-all will strip the dynamic symbols that JNI auto-registration depends on, resulting in a runtime error of No implementation found for ....

There's also a non-technical pitfall:

Signature certificate consistency: The hardened package must be re-signed with the original release keystore, otherwise the signature check will kill the process; changing the signature must also update the config and the fingerprint in native. Don't ask how I know—the first time I packaged with a debug signature, the startup was killed by my own check.


5. Verification: let adversarial testing speak

Figure 6 Adversarial verification matrix Figure 6 · Adversarial verification matrix: five attack types and measured protection results, red=attack blocked, green=protection works

Attack method Protection mechanism Measured result
Re-sign and install with a different certificate Native signature verification (certificate SHA-256) Process SIGKILLed, startup fails
Modify icon / resources / DEX integrity.sha256 entry manifest Process SIGKILLed, startup fails
Frida / injection / debugger TracerPid + maps + port detection Hit means process killed
Static decompilation Only 2 shell classes remain, SO / H5 fully encrypted Cannot see business code or plaintext SO
3 processes × 3 cold starts Real-device regression (Android 10 / 16) 0 crashes, routing and tabs normal

Besides functional regression, I also ran three cold-start stability tests, covering two mainstream vendor devices (Android 10 and Android 16). I want to specially record a high-version compatibility detail:

hiddenapi: symbols unavailable on this Android (using reflection path)

On Android 16, the native symbols for hidden APIs are unavailable, and this line of warning is printed. This is a harmless degradation—the reflection fallback path takes effect, ClassLoader replacement succeeds (self-check verified = true), and all three processes are normal. Don't treat it as a crash precursor and try to "fix" it.


6. About security checks: which are real, which are false positives

When dealing with third-party security checks, I divide "high-risk items" into two categories:

The first is genuine gaps, worth seriously solving:

The second is false positives from the feature library, and they need honest communication:

Compliance red line: I did not forge 360 / Legu or other commercial vendor shell markers to fool the scanner. Doing so carries trademark and unfair-competition risk and doesn't match the authenticity of the evaluation. For a self-developed shell, honestly state the encryption scope—real protection speaks with real data, not with brand labels.


7. Capability boundaries (must be clearly stated)

This is a landing-grade shell, not absolute security. I'll list what it can and cannot do:

Can do Cannot do / needs evaluation
Static decompilation cannot see business code Decrypted DEX / SO written in app private directory, root can dump
Resist re-sign and resource tampering Key is in native, theoretically extractable by reversing the so
Anti-debug / anti-injection (raise the cost) Hidden API reflection may be further restricted on new systems, needs version-by-version regression
Componentized / multi-process compatibility Does not include VMP, no hardening, strong anti-debug, or other commercial-grade strength

When should you switch to commercial hardening: If your threat model includes "facing professional reverse engineers", you should directly evaluate legitimate commercial hardening products. The positioning of a self-developed landing-grade shell is "raising the threshold from 'can use apktool' to 'requires dynamic debugging'"—it solves most automated disassembly and script-kiddie scenarios.


Conclusion

Returning to the opening: the value of this scheme is not in the word "encryption", but in the respect for real engineering behind the six engineering decisions—routing frameworks must be compatible, multi-process must be locked, failed replacement must have a fallback, detection false positives must be honestly communicated, and capability boundaries must be honestly marked.

If this post helps you avoid one pitfall, give it a bookmark. If you want to start directly, the tool has a download entry in Section 8. My next piece plans to write "The hidden API degradation path of hardened packages on Android 16", explaining the mechanism behind that line of warning in detail.

Comments

Top 1 of 2 from juejin.cn, machine-translated. The original thread is authoritative.

细语棉柔

Can REA crack it?

王二蛋与他的张大花

Good question. REA is a scout, not a lockpicker—officially it doesn't do automated unpacking; after packing, it only sees the 2 shell classes. Frida dynamic instrumentation gets blocked by anti-injection detection. Dumping under root is theoretically still possible; that's the boundary of this practical shell, as made clear in section 7. It can stop automated dismantling, but against professional reverse engineering you'd still need commercial hardening.