編輯:關於 Android 程式設計
美團那篇《Android 資源混淆保護實踐》讀完,方向很清楚,但關鍵的那個函式並沒有公開——它把 getObfuscationName() 當成一個黑盒,實作留給讀者。本文就是想把這個黑盒拆開,寫出可以自己編譯驗證的版本。
以 Android 5.0 的系統原始碼為例,要改的是:
/frameworks/base/tools/aapt/Resource.cpp
改動集中在 makeFileResources() 這個函式裡。原始版本大致如下:
static status_t makeFileResources(Bundle* bundle, const sp<AaptAssets>& assets,
ResourceTable* table,
const sp<ResourceTypeSet>& set,
const char* resType) {
String8 type8(resType);
String16 type16(resType);
bool hasErrors = false;
ResourceDirIterator it(set, String8(resType));
ssize_t res;
while ((res = it.next()) == NO_ERROR) {
if (bundle->getVerbose()) {
printf(" (new resource id %s from %s)\n",
it.getBaseName().string(),
it.getFile()->getPrintableSource().string());
}
String16 baseName(it.getBaseName());
const char16_t* str = baseName.string();
const char16_t* const end = str + baseName.size();
while (str < end) {
if (!((*str >= 'a' && *str <= 'z')
|| (*str >= '0' && *str <= '9')
|| *str == '_' || *str == '.')) {
fprintf(stderr, "%s: Invalid file name: must contain only [a-z0-9_.]",
it.getPath().string());
hasErrors = true;
}
str++;
}
String8 resPath = it.getPath();
resPath.convertToResPath();
table->addEntry(SourcePos(it.getPath(), 0),
String16(assets->getPackage()),
type16, baseName, String16(resPath), NULL, &it.getParams());
assets->addResource(it.getLeafName(), resPath, it.getFile(), type8);
}
return hasErrors ? STATUST(UNKNOWN_ERROR) : NO_ERROR;
}
美團給出的差異只有幾行:多了一個 obfuscationPath,然後把原本傳入 resPath 的地方全部換掉。
String8 obfuscationName;
String8 obfuscationPath = getObfuscationName(resPath, obfuscationName);
table->addEntry(SourcePos(it.getPath(), 0),
String16(assets->getPackage()),
type16, baseName,
String16(obfuscationPath), // 原本: resPath
NULL, &it.getParams());
assets->addResource(it.getLeafName(),
obfuscationPath /*resPath*/,
it.getFile(), type8);
所以真正的功課就是把 getObfuscationName() 寫出來。
要自己拼出路徑,得先知道幾個方法的意義:
getBaseName():資源名稱,不含副檔名,例如 icon。
getLeafName():資源名稱,含副檔名,例如 icon.png。
getParams():限定符,例如 xxhdpi-v4。回傳的是物件,要轉字串得呼叫 toString(),且結果不含前綴的 -。
convertToResPath():把路徑中的反斜線換成正斜線,例如 res\drawable → res/drawable。這個方法屬於 String8。
resType:函式參數傳進來的資源類型,內部已用 String8 type8(resType) 轉好,直接用即可,例如 drawable。注意它同樣不含限定符。
預設打包時資源都在 res 目錄下。我們的目標是依一定規則把它們搬到 r 目錄,這樣反編譯工具看到的就只剩一團 r/xx/xx.png,無從對照原始結構。
先取限定符:
String8 params = it.getParams().toString();
限定符可能是空的,所以要分兩路處理。再準備一個用來存放新路徑的字串:
String8 obfuscationPath();
限定符為空時,直接拼接:
if (params.isEmpty()) {
obfuscationPath.append("r/"); // 目標目錄
obfuscationPath.append(type8); // 資源類型
obfuscationPath.append("/");
obfuscationPath.append(it.getLeafName()); // 含副檔名的檔名
}
限定符不為空時,中間插入 - 與限定符:
if (params.isEmpty()) {
// ...上面那段...
} else {
obfuscationPath.append("r/");
obfuscationPath.append(type8);
obfuscationPath.append("-");
obfuscationPath.append(params);
obfuscationPath.append("/");
obfuscationPath.append(it.getLeafName());
}
最後把打包時的 resPath 換成 obfuscationPath:
table->addEntry(SourcePos(it.getPath(), 0),
String16(assets->getPackage()),
type16, baseName, String16(obfuscationPath), NULL, &it.getParams());
assets->addResource(it.getLeafName(), obfuscationPath, it.getFile(), type8);
static status_t makeFileResources(Bundle* bundle, const sp<AaptAssets>& assets,
ResourceTable* table,
const sp<ResourceTypeSet>& set,
const char* resType) {
String8 type8(resType);
String16 type16(resType);
bool hasErrors = false;
ResourceDirIterator it(set, String8(resType));
ssize_t res;
while ((res = it.next()) == NO_ERROR) {
if (bundle->getVerbose()) {
printf(" (new resource id %s from %s)\n",
it.getBaseName().string(),
it.getFile()->getPrintableSource().string());
}
String16 baseName(it.getBaseName());
const char16_t* str = baseName.string();
const char16_t* const end = str + baseName.size();
while (str < end) {
if (!((*str >= 'a' && *str <= 'z')
|| (*str >= '0' && *str <= '9')
|| *str == '_' || *str == '.')) {
fprintf(stderr, "%s: Invalid file name: must contain only [a-z0-9_.]",
it.getPath().string());
hasErrors = true;
}
str++;
}
String8 resPath = it.getPath();
resPath.convertToResPath();
String8 params = it.getParams().toString();
String8 obfuscationPath();
if (params.isEmpty()) {
obfuscationPath.append("r/");
obfuscationPath.append(type8);
obfuscationPath.append("/");
obfuscationPath.append(it.getLeafName());
} else {
obfuscationPath.append("r/");
obfuscationPath.append(type8);
obfuscationPath.append("-");
obfuscationPath.append(params);
obfuscationPath.append("/");
obfuscationPath.append(it.getLeafName());
}
fprintf(stderr, " our Path:%s\n", obfuscationPath.string());
table->addEntry(SourcePos(it.getPath(), 0),
String16(assets->getPackage()),
type16, baseName, String16(obfuscationPath), NULL, &it.getParams());
assets->addResource(it.getLeafName(), obfuscationPath, it.getFile(), type8);
}
return hasErrors ? STATUST(UNKNOWN_ERROR) : NO_ERROR;
}
改完之後重新編譯出 aapt,用它取代原本的工具再打包一次。


如果 apk 裡的資源已經從 res/ 變成 r/,說明改動生效了。
搬到 r 目錄只是第一步,目錄名稱還是 drawable、layout 這些一看就懂的英文。真正的混淆要模仿 Java 類別混淆的思維:把 anim 映射成 a、color 映射成 b,以此類推;目錄下的檔案也依序改名。a 到 z 不夠用就換成 aa 到 zz,甚至 aaa 到 zzz。
關鍵就在這個「原名 → 混淆名」的對照函式,而它必須是雙射的——因為 resources.arsc 裡存的是資源 ID 與名稱的對應關係,打包時改名,執行期靠 ID 查找,兩邊對得上就不會出問題。實作上通常會準備一份靜態的字元序列產生器,搭配一個 map 記錄映射關係,並把這份對照表另外存檔,方便線上排查時反查。
這部分實作難度並不高,只是瑣碎。有興趣的可以照上面的骨架自己補完——記得改動 AAPT 屬於侵入式修改,每次 Android 版本升級都要重新對齊一次原始碼差異,這點在維護成本上要事先想清楚。
Android IntentService 使用與源碼解析:Roterated 後台任務的最佳解
為什麼需要 IntentService Service 是 Android 四大組件之一,地位舉足輕重。當你的應用需要下載檔案、播放音樂這類長期在後台進行、又沒有使用者介
Android 面試必考:橫豎屏切換時 Activity 生命周期的完整變化
橫豎屏切換的 lifecycle 變化是面試高頻題,但很多人背了答案卻說不清原理。最靠譜的辦法是自己跑一遍日誌。以下用一個把所有生命周期方法都打了 log 的 Activ
Android 登入客戶端實戰:驗證碼抓取、網頁資料解析與 HttpWatch 抓包
大家好,我是 M1ko。在這個處處都要連網的時代,一個完全沒有網路能力的 App 很難有長但它的生命週期,所以 Android 網路程式設計是每個開發者的必修課。我本身是
深入理解 ButterKnife 源碼並掌握原理(三):Java 文件的生成
前兩篇我們分析到處理器的 findAndParseTargets 方法,它會把使用注解的類的 TypeElement 與解析後的 BindingClass 組裝成一個集合