To protect code assets, source code obfuscation is originally enabled by default in DevEco Studio: For projects developed using API version 10 or later based on the stage model and built in release mode, parameter names and local variable names in source code are obfuscated by default.
Since DevEco Studio NEXT Developer Beta3 (5.0.3.600), source code obfuscation is disabled by default for new projects and modules. If source code obfuscation is enabled in the module-level build-profile.json5 file, the following recommended obfuscation options are enabled by default: -enable-property-obfuscation, -enable-toplevel-obfuscation, -enable-filename-obfuscation, and -enable-export-obfuscation. You can customize these and other obfuscation options in the obfuscation-rules.txt configuration file. For details, see ArkGuard Obfuscation Options.
You can configure source code obfuscation in the module-level build-profile.json5 file. The available fields are described as follows.
Field | Type | Mandatory | Description | |
|---|---|---|---|---|
ruleOptions | Object | No | Configuration of the code obfuscation rule. | |
enable | Boolean | Yes | Whether to enable source code obfuscation.
NOTE: Since DevEco Studio NEXT Developer Beta3 (5.0.3.600), the default value is changed from true to false. | |
files | String array | No | Relative paths of the obfuscation rule files. By default, the obfuscation-rules.txt file is used. The obfuscation rules configured in the file take effect only during the module's compilation process (including the dependent code). NOTE:
| |
consumerFiles | String/String array | No | Relative paths of the obfuscation rule files transferred to the integrator. This field is exclusive to HAR/HSP modules. Multiple files can be configured, and each file can have a custom name. NOTE:
| |
To protect code assets, code obfuscation is recommended. You can enable source code obfuscation in the module-level build-profile.json5 file.
"arkOptions": {
"obfuscation": {
"ruleOptions": {
"enable": true // Set this field to true to enable source code obfuscation.
}
}
} Since DevEco Studio NEXT Developer Beta3 (5.0.3.600), enabling obfuscation automatically enables the recommended obfuscation rules in the obfuscation-rules.txt file, including the -enable-property-obfuscation, -enable-toplevel-obfuscation, -enable-filename-obfuscation, and -enable-export-obfuscation options.
In release build mode, you are advised to enable obfuscation and correctly configure obfuscation rules. Failure to do so could lead to runtime issues.
After obfuscation is enabled, you can proceed to set up advanced obfuscation rules for more refined control over the obfuscation process.
{
"apiType": "stageMode",
"buildOptionSet": [
{
"name": "release",
"arkOptions": {
"obfuscation": {
"ruleOptions": {
"enable": true,
"files": [
"./obfuscation-rules.txt" // Obfuscation rule file.
]
}
}
}
},
],
} When multiple obfuscation rule files are specified, their rules are merged. For details about the merging and how the merged rules are applied, see Obfuscation Rule Merging Strategies.

To ensure seamless integration and functionality of the HAR or HSP module, configure retention options in the rule files for any content that you do not want the integrator to obfuscate, such as variables or functions exported from the HAR or HSP module.
{
"apiType": "stageMode",
"buildOptionSet": [
{
"name": "release",
"arkOptions": {
"obfuscation": {
"ruleOptions": {
"enable": true,
"files": [
"./obfuscation-rules.txt"
]
},
"consumerFiles": [ // Obfuscation rule in use when the module is depended on.
"./consumer-rules.txt"
]
}
}
},
],
} When multiple obfuscation rule files are specified, their rules are merged. For details about the merging and how the merged rules are applied, see Obfuscation Rule Merging Strategies.

When source code obfuscation is enabled, methods, properties, or paths in your code may be renamed. However, if the application runtime still references the original, unobfuscated names, functionality may fail. To resolve this, you must configure retention options for the affected fields. For specific scenarios and configuration guidelines, see Retention Options.
Given the numerous scenarios to troubleshoot and fields to configure, DevEco Studio provides the ObfuscationHelper tool. It scans source code by module and usage scenario to rapidly identify required retention options and trustlist fields, allowing developers to generate obfuscation rule files with a single click. For dynamically accessed names or properties (determined only at runtime), ObfuscationHelper identifies such scenarios. You must further verify and configure trustlists based on service requirements.

Historical records can be associated since DevEco Studio 6.0.0 Beta1.



On the Recommended Trustlist configuration page, view identified retention options and trustlist fields from the scan results, then generate an obfuscation rule file with one click.
Module name ----Obfuscation options --------Scanning task: number of recommended trustlist fields found in the scanning task
Select a scanning task. The recommended retention options and trustlist fields are displayed in the following tree structure in the lower part of the page.
Retention options ----Core code --------Trustlist field --> File where the field is located: code line



If Merge trustlists is selected, and you click OK or Configure Supplemental Trustlist, the merged trustlist file Hm-merge-recommend-keep-list.txt is generated in the project root directory. This file merges the Hm-recommend-keep-list.txt files of entry modules and the Hm-recommend-consumer-keep-list.txt files of all modules.
For example, the recommended trustlist file is generated in the following modules:


On the Supplemental Trustlist page, view the scanned core code and further check the core code, identify trustlist fields, and configure the fields in the target file.
Module name ----Obfuscation options --------Scanning task: number of core code statements to be checked
Select a scanning task. The code to be checked is displayed in the lower part of the page. Click the core code to go to the file and code line where the code is located.

If an item is marked as Yes, it does not need to be checked again when the module and scenario are scanned again with the check record associated.


If Merge trustlists is selected, and you click OK, the merged trustlist file Hm-merge-manual-keep-list.txt is generated in the project root directory. This file merges the Hm-manual-keep-list.txt files of entry modules and the Hm-manual-consumer-keep-list.txt files of all modules.
For example, the supplemental trustlist file is generated in the following modules:


After you generate a recommended trustlist or supplemental trustlist, a historical record is generated, which can be used for further check.
On the home screen of ObfuscationHelper, click History at the bottom to view all historical records.

to go to the corresponding trustlist configuration page.The following describes the scanning tasks performed by ObfuscationHelper.
Property obfuscation
Properties in object types converted via JSON/ArkTSUtils.ASON must be retained.
// JSON.parse
class JSONTest {
prop1: string = ""
prop2: number = 0
}
// Example JSON file (test.json)
/*
{
"prop1": "value",
"prop2": 10
}
*/
const jsonData = buffer.from(this.context.resourceManager.getRawFileContentSync("test.json")).toString();
let demo: JSONTest = JSON.parse(jsonData) // Add JSONTest to keep-property-name.
let demo = JSON.parse(jsonData) as JSONTest // Add JSONTest to keep-property-name.
let demo = JSON.parse(jsonData) as ESObject as JSONTest // Add JSONTest to keep-property-name.
let demo: ESObject = JSON.parse(jsonData) // Add dynamically typed objects (including ESObject, Object, and object) to the supplemental trustlist, which requires adding all keys in jsonData (such as prop1 and prop2) to keep-property-name.
// ArkTSUtils.ASON.parse
let demo: JSONTest = ArkTSUtils.ASON.parse(jsonData) // Add JSONTest to keep-property-name.
let demo = ArkTSUtils.ASON.parse(jsonData) as JSONTest // Add JSONTest to keep-property-name.
let demo = ArkTSUtils.ASON.parse(jsonData) as ESObject as ESObject as JSONTest // Add JSONTest to keep-property-name.
let demo: ESObject = ArkTSUtils.ASON.parse(jsonData) // Add dynamically typed objects (including ESObject, Object, and object) to the supplemental trustlist, which requires adding all keys in jsonData (such as prop1 and prop2) to keep-property-name.
// JSON.stringify
let type = new JSONTest()
let str = JSON.stringify(type) //Add JSON.stringify to the supplemental trustlist, which requires adding all properties in JSONTest to keep-property-name.
// ArkTSUtils.ASON.stringify
let type = new JSONTest()
let str = ArkTSUtils.ASON.stringify(type) // Add ArkTSUtils.ASON.stringify to the supplemental trustlist, which requires adding all properties in JSONTest to keep-property-name. Properties accessed through bracket notation ([]), and properties in Object.defineProperty, Object.defineProperties, and Object.getOwnPropertyDescriptor APIs must be retained.
// For properties accessed via bracket notation like obj['name'], if name is a variable, add to the supplemental trustlist, which requires adding the corresponding content to -keep-property-name.
Object.defineProperty(obj, 'y', {}) // If y is a variable, add to the supplemental trustlist, which requires adding the corresponding content to -keep-property-name.
Object.defineProperties(obj, { // Add properties prop1 and prop2 to -keep-property-name in the recommended trustlist.
prop1: {
value: 'Hello',
writable: true,
enumerable: true,
configurable: true
},
prop2: {
value: 'Hello',
writable: true,
enumerable: true,
configurable: true
}
});
Object.getOwnPropertyDescriptor(obj, 'bbb'); // If bbb is a variable, add to the supplemental trustlist, which requires adding the corresponding content to -keep-property-name.
obj.s=0; let key='s'; obj[key] // If key is a variable, add to the supplemental trustlist, which requires adding the corresponding content s to keep-property-name. You need to check the ArkTS property strings related to the C++ APIs and manually add them to the trustlist. For details about the involved C++ APIs, see Setting ArkTS Object Properties Using Node-API.
//index.ets
func() {
let obj: NapiTestClassObj = { napiTestClassObjData: 0, napiTestClassObjMessage: "hello world" };
let result: ESObject = testNapi.setProperty(obj, "napiTestClassObjMessage", "100"); // Manual check based on the napi_set_property API reveals that the napiTestClassObjMessage property has been modified, which must be added to -keep-property-name in the trustlist.
if (obj.napiTestClassObjMessage === "100") {
console.log("setProperty success");
return true;
}
return false;
}
//napi_init.cpp
static napi_value SetProperty(napi_env env, napi_callback_info info) {
size_t argc = 3;
napi_value args[3];
napi_status status = napi_get_cb_info(env, info, &argc, args, nullptr, nullptr);
if (status != napi_ok) {
napi_throw_error(env, nullptr, "Node-API napi_get_cb_info fail");
}
status = napi_set_property(env, args[0], args[1], args[2]); // Detected critical API: napi_set_property
if (status != napi_ok) {
napi_throw_error(env, nullptr, "Node-API napi_set_property fail");
return nullptr;
}
return args[0];
} Properties in the database key-value pair type (ValuesBucket) must be retained.
const valueBucket: ValuesBucket = {
'ID1': ID1, // Add ID1, NAME1, AGE1, and SALARY1 to -keep-property-name.
'NAME1': name,
'AGE1': age,
'SALARY1': salary
}; Member variables, methods, and parameters decorated with custom decorators need to be checked to see if they should be added to the trustlist.
function logClass(target: any) {
console.log('Class created:', target); // MyClass is not obfuscated. Therefore, the class name decorated with @logClass does not need to be added to the trustlist.
return target;
}
export function logMethod(target: any, methodName: string, descriptor: PropertyDescriptor) {
const originalMethod = descriptor.value;
descriptor.value = function (...args: any[]) {
if(methodName === 'myMethod'){ // methodName is obfuscated. The comparison with yMethod does not meet the expectation. Therefore, the method name myMethod decorated with @logMethod needs to be added to the trustlist.
console.log('Calling myMethod')
}
console.log(`The ${methodName} method is about to be called with arguments:`, args);
const result = originalMethod.apply(this, args);
console.log(`Method ${methodName} call completed. Result:`, result);
return result;
};
return descriptor;
}
function logProperty(target: any, propertyName: string) {
let value;
const getter = function () {
console.log(`Obtaining the ${propertyName} property`); // propertyName is obfuscated, which does not affect the running result. You do not need to add it to the trustlist.
return value;
};
const setter = function (newValue: any) {
console.log(`Setting the ${propertyName} property to ${newValue}`);
value = newValue;
};
Object.defineProperty(target, propertyName, {
get: getter,
set: setter,
enumerable: true,
configurable: true
});
return;
}
@logClass
class MyClass { // Name of the class decorated with a custom decorator. Check whether MyClass should be added to the trustlist.
@logProperty
myProperty: number; // Name of the property decorated with a custom decorator. Check whether myProperty should be added to the trustlist.
constructor() {
this.myProperty = 10;
}
@abcd
@logMethod
myMethod(arg1: number, arg2: number) { // Name of the method decorated with a custom decorator. Check whether myMethod should be added to the trustlist.
return arg1 + arg2;
}
} Properties of record-type objects must be preserved. This scenario is supported starting from DevEco Studio 6.0.1 Beta1.
// Supported scenario
export function hello() {
const person: Record<string, Object> = {
ddName: 'zhangsan', // Properties ddName, ggAge, and isWfStudent of the record-type object 'person' are preserved via -keep-property-name.
ggAge: 25,
isWfStudent: true
}
person.wwArea = '112'; // The wwArea property, added via dot notation, is preserved via -keep-property-name.
return person;
}
// Unsupported scenarios
// 1. Scanning is not supported for the sssd property added via dot notation on a record-type object obtained by calling this function; the property will not be preserved and will be obfuscated.
let ret = hello();
ret.sssd = '1111';
// 2. Scanning is not supported for properties a123 and b123 of the implicit record-type object 'parameters'; these properties will not be preserved and will be obfuscated.
export function sendPost3() {
const want: Want = {
action: 'ohos.want.action.viewData',
entities: ['entity.system.browsable'],
uri: '123',
parameters: {
a123: 1,
b123: 2
}
};
} Top-level scope name obfuscation
Names exported from namespaces and nested namespaces must be retained.
export namespace namespace1 {
export class namespace1Class1 { // Add namespace1Class1 to -keep-global-name in the recommended trustlist.
}
export namespace namespace1_1 { // Add namespace1_1 to -keep-global-name in the recommended trustlist.
export let namespace1Property1_1: string = '111'; // Add namespace1Property1_1 to -keep-global-name in the recommended trustlist.
export function namespace1Func1_1() { // Add namespace1Func1_1 to -keep-global-name in the recommended trustlist.
console.log('namespace1Func1_1 execute success');
}
export class namespaceClass1_1{ // Add namespaceClass1_1 to -keep-global-name in the recommended trustlist.
func(){
console.log(""namespaceClass1_1 success"")
}
}
}
} API names, property names, and class names that are dynamically imported must be retained. This feature is supported since DevEco Studio 6.0.0 Beta2.
// After module import, add the used class name TestClass to keep-global-name in the recommended trustlist.
try {
let test = (await import('../model/TestClass')).TestClass
console.warn(TAG, 'test = ', test);
// console.warn(TAG, 'test TestClass = ', test.);
console.warn(TAG, 'test staticGlsAdd = ', test.staticGlsAdd(5, 6));
} catch (e) {
console.warn(TAG, `error = ${e}`);
}
// After module import, add the used method name componentClass to keep-global-name in the recommended trustlist.
let util = await import('harlibrary/src/main/ets/utils/Util');
try {
console.warn(TAG, 'util = ', util);
console.warn(TAG, 'call util function = ', await util.componentClass());
} catch (e) {
console.warn(TAG, `error = ${e}`);
}
// After module import, add the name of the warn method called after default to keep-global-name in the recommended trustlist.
import('hsplibrary/src/main/ets/utils/Logger').then(logger => {
try {
console.warn(TAG, 'import Logger success.');
logger.default.warn('this is logger warn')
} catch (e) {
console.warn(TAG, `error = ${e}`);
}
})
// Encapsulate dynamic import into a method. If the exported class instance is a variable, add it to the supplemental trustlist. After the check, add the variable value to keep-global-name.
public static importFile<T>(modulePath: string, resultClassName: string) {
return import(modulePath).then((ns: ESObject) => {
let res: T = new ns[resultClassName](); // Add this line to the supplemental trustlist. After the check, add TestClass corresponding to resultClassName to keep-global-name.
return res;
}).catch((err: Error) => {
console.warn('chisj debug: importFile error = ', err);
return undefined;
});
}
// Index.ets
let modulePath = '../model/TestClass';
let className = 'TestClass';
ImportUtil.importFile<ESObject>(modulePath, className).then((ns:ESObject) => {
try {
console.warn(TAG, 'import importFile success')
console.warn(TAG, 'ns = ', ns)
console.warn(TAG, 'calcAdd = ', ns?.calcAdd(1, 2));
} catch (e) {
console.warn(TAG, `error = ${e}`);
}
})
// Encapsulate dynamic import into a method, and add the Calc method called by the exported module myModule to the recommended trustlist.
// ImportUtil.ts
export function dynamicImport<T>(modulePath: string): Promise<T> {
return import(modulePath).then(module => {
// Some modules may have default exports; additional processing is needed here.
return module.default || module as T;
});
}
// Index.ets
const myModule = await dynamicImport<typeof import('harlibrary')>('harlibrary');
console.warn(TAG, '1 calc = ', myModule.Calc(1, 2)) File name obfuscation
The path names corresponding to the sources field in the build-profile.json5 file of the module must be retained.
// Module-level build-profile.json5
{
"apiType": "stageMode",
"buildOption": {
"arkOptions": {"runtimeOnly": {"sources": ["./aaa/bbb", "./ccc/dddd"]}} // Add ./aaa/bbb and ./ccc/dddd to keep-file-name.
},
"buildOptionSet": [
{
"name": "release",
"arkOptions": {
"runtimeOnly": {"sources": ["./e/f", "./g/h"]}, // Add ./e/f and ./g/h to keep-file-name.
"obfuscation": {
"ruleOptions": {
"enable": true,
"files": [
"./obfuscation-rules.txt"
]
}
}
},
},
],
} The path names corresponding to the pageSourceFile field in the resources/base/profile/route_map.json file of the module must be retained.
// resources/base/profile/route_map.json file of the module
{
"routerMap": [
{
"name": "PageOne",
"pageSourceFile": "src/main/ets/pages/directory/PageOne.ets", // Add src/main/ets/pages/directory/PageOne.ets to keep-file-name.
"buildFunction": "PageOneBuilder",
"data": {
"description" : "this is PageOne"
}
}
]
} Imported/exported name obfuscation
The APIs imported from .so libraries and their properties accessed in dot notation must be retained. In versions earlier than DevEco Studio 6.1.1 Release, only the methods exported from src/main/cpp/lib{Module name}/Index.d.ts can be scanned.
import testNapi from "xxxx.so" // Add testNapi to keep-global-name.
import {testNapi} from "xxxx.so" // Add testNapi to keep-global-name.
import {testNapi as napi} from "xxxx.so" // Add testNapi to keep-global-name.
testNapi.add() // Add add to -keep-property-name. // Exported constant
export const LOCAL_NUM = 100 // Add LOCAL_NUM to keep-global-name.
// Exported method
export function harFun() { // Add harFun to keep-global-name.
}
// Names of the exported class and its properties (including the parent class and its properties). If a property is also a class, that class must be retained in the same manner.
class FatherClass {
prop4: string = "bbb"
}
class SubClass {
prop3: string = "bbb"
}
export class HSPClass extends FatherClass{ // Add the class name HSPClass to -keep-global-name.
prop1: string = "aaa"
prop2: SubClass = new SubClass() // Add prop1, prop2, prop3, and prop4 to -keep-property-name.
}
// Exported namespace, including its methods, constants, classes (with the retention method the same as above), and sub-namespaces.
export namespace NmSpace {
export const NUM_NAME_SPACE = 100 // Add the NUM_NAME_SPACE constant to -keep-global-name.
export class classNameSpace { // Add the class name classNameSpace to -keep-global-name.
prop: string = "bbb" // Add the class property prop to -keep-property-name.
}
export function funNameSpace() { // Add the funNameSpace method to -keep-global-name.
}
}
// Add the relative path of the entry file, for example, ./index.ets, to the keep option.
// Add the entry file name, for example, index.ets, to the keep-file-name option. The APIs imported from HSP files and their properties accessed in dot notation must be retained.
import MyClass1 from "xxxx" // Add MyClass1 to keep-global-name.
import {MyClass2} from "xxxx" // Add MyClass2 to keep-global-name.
import {MyClass3 as MyClass} from "xxxx" // Add MyClass3 to keep-global-name.
MyClass1.add() // Add add to keep-property-name. For details, see APIs exposed by HSP.
A HAR will be scanned only when HAP->HSP->HAR and HAP->HAR simultaneously, where -> indicates a dependency relationship.
