鸿蒙 APP 开发:安全加固与组件化架构
鸿蒙 APP 开发涉及安全加固与组件化架构的关键技术。文章详细阐述了数据加密、代码混淆及权限控制的实现方案,利用 AES 算法保护敏感信息存储与传输。同时介绍了组件化架构的设计思路,涵盖模块化组件拆分、通用 UI 组件封装以及组件间的通信机制。通过具体代码示例演示了如何在 HarmonyOS 项目中集成安全策略并优化项目结构,提升应用的可维护性与安全性。

鸿蒙 APP 开发涉及安全加固与组件化架构的关键技术。文章详细阐述了数据加密、代码混淆及权限控制的实现方案,利用 AES 算法保护敏感信息存储与传输。同时介绍了组件化架构的设计思路,涵盖模块化组件拆分、通用 UI 组件封装以及组件间的通信机制。通过具体代码示例演示了如何在 HarmonyOS 项目中集成安全策略并优化项目结构,提升应用的可维护性与安全性。

本文介绍鸿蒙 APP 开发中的安全加固与组件化架构技术,旨在实现数据加密、代码混淆、权限控制等安全功能,并构建模块化与通用组件以提升应用的可维护性与复用性。
核心目标:
安全加固是指对应用进行安全防护,防止恶意攻击、篡改或破解。主要包括:
采用分层架构设计:
基于项目架构实现以下功能:
文件路径:entry/src/main/ets/utils/EncryptionUtil.ets
import crypto from '@ohos.crypto';
export class EncryptionUtil {
private static instance: EncryptionUtil | null = null;
private key: Uint8Array = new Uint8Array([1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16]);
private iv: Uint8Array = new Uint8Array([1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16]);
static getInstance(): EncryptionUtil {
if (!EncryptionUtil.instance) {
EncryptionUtil.instance = new EncryptionUtil();
}
return EncryptionUtil.instance;
}
async aesEncrypt(data: string): Promise<string> {
const cipher = crypto.createCipher('aes-128-cbc', this.key, this.iv);
const encryptedData = cipher.update(data, 'utf8', 'base64') + cipher.final('base64');
return encryptedData;
}
async aesDecrypt(encryptedData: string): Promise<string> {
const decipher = crypto.createDecipher('aes-128-cbc', this.key, this.iv);
const decryptedData = decipher.update(encryptedData, 'base64', 'utf8') + decipher.final('utf8');
return decryptedData;
}
async md5Encrypt(data: string): Promise<string> {
const md5 = crypto.createHash('md5');
md5.update(data);
const encryptedData = md5.digest('hex');
return encryptedData;
}
async sha256Encrypt(data: string): Promise<string> {
const sha256 = crypto.createHash('sha256');
sha256.update(data);
const encryptedData = sha256.digest('hex');
return encryptedData;
}
}
文件路径:entry/src/main/ets/services/UserService.ets
import { EncryptionUtil } from '../utils/EncryptionUtil';
export class UserService {
async register(username: string, password: string): Promise<boolean> {
const encryptedPassword = await EncryptionUtil.getInstance().aesEncrypt(password);
const user = { id: Date.now(), username, password: encryptedPassword };
await this.saveUser(user);
return true;
}
async login(username: string, password: string): Promise<boolean> {
const user = await this.getUserByUsername(username);
if (!user) return false;
const decryptedPassword = await EncryptionUtil.getInstance().aesDecrypt(user.password);
if (decryptedPassword !== password) return false;
AppStorage.SetOrCreate('isLoggedIn', true);
AppStorage.SetOrCreate('currentUser', user);
return true;
}
async getCurrentUser(): Promise<UserModel | null> {
const isLoggedIn = AppStorage.Get('isLoggedIn');
if (!isLoggedIn) return null;
return AppStorage.Get('currentUser');
}
async logout(): Promise<void> {
AppStorage.SetOrCreate('isLoggedIn', false);
AppStorage.SetOrCreate('currentUser', null);
}
}
在 build-profile.json5 中添加配置:
{
"app": {
"signingConfigs": [],
"products": [
{
"name": "default",
"signingConfig": "default",
"compatibleSdkVersion": "3.2.100(5)",
"runtimeOS": "HarmonyOS",
"compilerOptions": {
"obfuscation": true
}
}
]
}
}
文件路径:entry/src/main/ets/utils/PermissionUtil.ets
import abilityAccessCtrl from '@ohos.abilityAccessCtrl';
import { UIAbilityContext } from '@ohos.abilityAccessCtrl';
export class PermissionUtil {
private static instance: PermissionUtil | null = null;
private atManager: abilityAccessCtrl.AtManager | null = null;
static getInstance(): PermissionUtil {
if (!PermissionUtil.instance) {
PermissionUtil.instance = new PermissionUtil();
}
return PermissionUtil.instance;
}
async init(context: UIAbilityContext): Promise<void> {
if (!this.atManager) {
this.atManager = abilityAccessCtrl.createAtManager(context);
}
}
async checkPermission(permission: string): Promise<boolean> {
if (!this.atManager) return false;
const result = await this.atManager.checkPermission(permission);
return result === abilityAccessCtrl.GrantStatus.PERMISSION_GRANTED;
}
async requestPermission(permission: string): Promise<boolean> {
if (!this.atManager) return false;
const result = await this.atManager.requestPermissions([permission]);
return result[0].grantStatus === abilityAccessCtrl.GrantStatus.PERMISSION_GRANTED;
}
async getAllPermissions(): Promise<Array<string>> {
if (!this.atManager) return [];
const result = await this.atManager.getPermissions();
return result;
}
}
文件路径:entry/src/main/ets/entryability/EntryAbility.ets
import { PermissionUtil } from '../utils/PermissionUtil';
export default class EntryAbility extends UIAbility {
onWindowStageCreate(windowStage: window.WindowStage): void {
PermissionUtil.getInstance().init(this.context);
this.checkAndRequestPermissions();
windowStage.loadContent('pages/Index', (err, data) => {
if (err.code) {
hilog.error(0x0000, 'EntryAbility', 'Failed to load content. Cause: %{public}s', JSON.stringify(err) ?? '');
return;
}
hilog.info(0x0000, 'EntryAbility', 'Succeeded in loading content. Data: %{public}s', JSON.stringify(data) ?? '');
});
}
async checkAndRequestPermissions(): Promise<void> {
const permissions = [
'ohos.permission.DISTRIBUTED_DATASYNC',
'ohos.permission.DISTRIBUTED_COMMUNICATION',
'ohos.permission.GET_NETWORK_INFO',
'ohos.permission.READ_EXTERNAL_STORAGE',
'ohos.permission.WRITE_EXTERNAL_STORAGE'
];
for (const permission of permissions) {
const isGranted = await PermissionUtil.getInstance().checkPermission(permission);
if (!isGranted) {
const result = await PermissionUtil.getInstance().requestPermission(permission);
if (!result) {
hilog.error(0x0000, 'EntryAbility', 'Failed to request permission: %{public}s', permission);
}
}
}
}
}
在 entry/src/main/ets 下创建目录:
modules:存放模块化组件;components:存放通用组件;utils:存放工具类。文件路径:entry/src/main/ets/modules/UserModule/UserModule.ets
import { UserService } from '../services/UserService';
import { LoginPage } from '../pages/LoginPage';
import { RegisterPage } from '../pages/RegisterPage';
export class UserModule {
static LoginPage(): any { return LoginPage; }
static RegisterPage(): any { return RegisterPage; }
static UserService(): any { return UserService; }
}
文件路径:entry/src/main/ets/modules/ProductModule/ProductModule.ets
import { ProductService } from '../services/ProductService';
import { ProductListPage } from '../pages/ProductListPage';
import { ProductDetailPage } from '../pages/ProductDetailPage';
export class ProductModule {
static ProductListPage(): any { return ProductListPage; }
static ProductDetailPage(): any { return ProductDetailPage; }
static ProductService(): any { return ProductService; }
}
文件路径:entry/src/main/ets/modules/CartModule/CartModule.ets
import { CartService } from '../services/CartService';
import { CartPage } from '../pages/CartPage';
export class CartModule {
static CartPage(): any { return CartPage; }
static CartService(): any { return CartService; }
}
文件路径:entry/src/main/ets/components/ButtonComponent.ets
@Component
export struct ButtonComponent {
@Prop text: string = '';
@Prop onClick: () => void = () => {};
@Prop disabled: boolean = false;
build() {
Button(this.text)
.width('100%')
.height(48)
.fontSize(16)
.fontWeight(FontWeight.Bold)
.backgroundColor(this.disabled ? '#CCCCCC' : '#007DFF')
.onClick(this.onClick)
.enabled(!this.disabled);
}
}
文件路径:entry/src/main/ets/components/InputComponent.ets
@Component
export struct InputComponent {
@Prop placeholder: string = '';
@Prop value: string = '';
@Prop onChange: (value: string) => void = () => {};
@Prop type: InputType = InputType.Normal;
build() {
TextInput({ text: this.value, placeholder: this.placeholder })
.width('100%')
.height(48)
.fontSize(16)
.backgroundColor('#F5F5F5')
.borderRadius(8)
.padding({ left: 16, right: 16 })
.type(this.type)
.onChange(this.onChange);
}
}
文件路径:entry/src/main/ets/components/ListComponent.ets
@Component
export struct ListComponent {
@Prop data: Array<any> = [];
@Prop renderItem: (item: any, index: number) => void = () => {};
@Prop onItemClick: (item: any, index: number) => void = () => {};
build() {
List({ space: 16 }) {
ForEach(this.data, (item: any, index: number) => {
ListItem() {
this.renderItem(item, index);
}
.width('100%')
.height('auto')
.onClick(() => {
this.onItemClick(item, index);
});
}, (item: any) => item.id);
}
.width('100%')
.height('100%')
.padding(16);
}
}
文件路径:entry/src/main/ets/pages/ProductDetailPage.ets
import { ListComponent } from '../components/ListComponent';
import { CartModule } from '../modules/CartModule/CartModule';
@Entry
@Component
struct ProductDetailPage {
@State product: ProductModel = {
id: 1,
name: 'iPhone 15',
description: '最新款 iPhone',
price: 5999,
imageUrl: 'https://example.com/iphone15.jpg',
category: '手机',
stock: 100
};
@State cartItems: Array<CartItemModel> = [];
build() {
Column({ space: 16 }) {
Image(this.product.imageUrl)
.width('100%')
.height(200)
.objectFit(ImageFit.Cover)
.borderRadius(12);
Text(this.product.name).fontSize(20).fontWeight(FontWeight.Bold).textColor('#000000');
Text(this.product.description).fontSize(16).textColor('#666666');
Text(`¥${this.product.price}`).fontSize(24).fontWeight(FontWeight.Bold).textColor('#FF0000');
ListComponent({
data: this.cartItems,
renderItem: (item: CartItemModel, index: number) => {
Row({ space: 16 }) {
Image(item.imageUrl).width(60).height(60).objectFit(ImageFit.Contain);
Column({ space: 8 }) {
Text(item.name).fontSize(14).fontWeight(FontWeight.Bold).textColor('#000000');
Text(`¥${item.price}`).fontSize(16).fontWeight(FontWeight.Bold).textColor('#FF0000');
}.layoutWeight(1);
Text(`${item.count}`).fontSize(14).textColor('#000000');
}
.width('100%')
.height('auto')
.padding(16)
.backgroundColor('#FFFFFF')
.borderRadius(12);
},
onItemClick: (item: CartItemModel, index: number) => {
CartModule.CartService().deleteCartItem(item.id);
}
});
ButtonComponent({
text: '添加到购物车',
onClick: async () => {
await CartModule.CartService().addToCart(this.product.id, 1);
this.cartItems = await CartModule.CartService().getCartItems();
},
disabled: false
});
}
.width('100%')
.height('100%')
.padding(16)
.backgroundColor('#F5F5F5');
}
aboutToAppear() {
this.getCartItems();
}
async getCartItems(): Promise<void> {
this.cartItems = await CartModule.CartService().getCartItems();
}
}
在 entry/src/main/module.json5 中确认权限与能力配置。
本文完成了鸿蒙 APP 安全加固与组件化架构的核心技术实践:
通过上述方案,开发者可构建更安全、可维护且可扩展的鸿蒙应用。

微信公众号「极客日志」,在微信中扫描左侧二维码关注。展示文案:极客日志 zeeklog
将字符串编码和解码为其 Base64 格式表示形式即可。 在线工具,Base64 字符串编码/解码在线工具,online
将字符串、文件或图像转换为其 Base64 表示形式。 在线工具,Base64 文件转换器在线工具,online
将 Markdown(GFM)转为 HTML 片段,浏览器内 marked 解析;与 HTML转Markdown 互为补充。 在线工具,Markdown转HTML在线工具,online
将 HTML 片段转为 GitHub Flavored Markdown,支持标题、列表、链接、代码块与表格等;浏览器内处理,可链接预填。 在线工具,HTML转Markdown在线工具,online
通过删除不必要的空白来缩小和压缩JSON。 在线工具,JSON 压缩在线工具,online
将JSON字符串修饰为友好的可读格式。 在线工具,JSON美化和格式化在线工具,online