一、背景说明

HarmonyOS 创新技术沟通会近日重点介绍了星盾安全体系的升级方向,系统级安全能力的开放程度持续提高。应用侧的自研加密(如用 cryptoFramework 生成密钥再自行保存)始终存在密钥落盘被提取的风险。本文聚焦一个具体技术点:使用 Universal Keystore Kit(@kit.UniversalKeystoreKit,简称 HUKS)把密钥的生成、使用与销毁全部托管给系统安全环境,实现"密钥不出安全区"的数据加解密完整闭环,全部代码可直接编译运行(本文源码已在 AtomGit 仓库开源,见文末)。

二、技术原理

HUKS(Universal Keystore Kit,通用密钥库)是系统级密钥管理服务,密钥明文从生成起就在安全环境(TEE 或强访问控制的系统服务)内,应用全程只能拿到密钥句柄。核心概念:

  • keyAlias:密钥别名,业务内唯一索引,generateKeyItem 生成、deleteKeyItem 销毁;
  • HuksParamSet:属性集合,生成密钥时声明算法(HUKS_ALG_AES)、长度(HUKS_KEY_SIZE_256)、用途(HUKS_KEY_PURPOSE_ENCRYPT | DECRYPT)、填充与工作模式(PKCS7/CBC);
  • 三段式会话:initSession(拿到句柄)→ updateSession(分段输入数据)→ finishSession(完成并输出结果),每段都要传入与操作匹配的 HuksParamSet;
  • 密钥不可导出:不设置 EXPORTABLE 时,任何接口都无法把密钥明文读出,加解密只能在 HUKS 内完成。

与 cryptoFramework 的分工:cryptoFramework 适合数据加密(密钥可导出、应用自管);HUKS 适合密钥托管(设备绑定、密钥不出安全区)。数据流:

generateKeyItem(alias, 参数) → initSession(alias, 加密参数) → updateSession(明文) → finishSession(补齐填充) = 密文 → 存沙箱 → 解密时 initSession(解密参数) → updateSession(密文) → finishSession = 明文。

三、实现步骤

工程为 Stage 模型(API 12+),HUKS 基础加解密无需任何权限,module.json5 保持默认。

1. 密钥托管工具 HuksUtil.ets
import { huks } from '@kit.UniversalKeystoreKit';
import { util } from '@kit.ArkTS';
import { BusinessError } from '@kit.BasicServicesKit';

const KEY_ALIAS = 'app_master_key';

export class HuksUtil {
  private static encoder = util.TextEncoder.create('utf-8');
  private static decoder = util.TextDecoder.create('utf-8');

  // 生成密钥参数集:AES-256-CBC-PKCS7,用于加解密
  private static genKeyProperties(): huks.HuksParam[] {
    return [
      { tag: huks.HuksTag.HUKS_TAG_ALGORITHM, value: huks.HuksKeyAlg.HUKS_ALG_AES },
      { tag: huks.HuksTag.HUKS_TAG_KEY_SIZE, value: huks.HuksKeySize.HUKS_KEY_SIZE_256 },
      { tag: huks.HuksTag.HUKS_TAG_PURPOSE,
        value: huks.HuksKeyPurpose.HUKS_KEY_PURPOSE_ENCRYPT | huks.HuksKeyPurpose.HUKS_KEY_PURPOSE_DECRYPT },
      { tag: huks.HuksTag.HUKS_TAG_PADDING, value: huks.HuksKeyPadding.HUKS_PADDING_PKCS7 },
      { tag: huks.HuksTag.HUKS_TAG_CIPHER_MODE, value: huks.HuksCipherMode.HUKS_MODE_CBC }
    ];
  }

  // 密钥是否存在
  static async isKeyExist(): Promise<boolean> {
    return await huks.isKeyItemExist(KEY_ALIAS, {});
  }

  // 首次使用:在安全环境内生成密钥(明文不可导出)
  static async ensureKey(): Promise<void> {
    if (await HuksUtil.isKeyExist()) {
      return;
    }
    const options: huks.HuksOptions = { properties: HuksUtil.genKeyProperties() };
    await huks.generateKeyItem(KEY_ALIAS, options);
  }

  // 构造 CBC 模式会话参数:IV 固定 16 字节(生产环境建议每次随机并随密文保存)
  private static genSessionProperties(iv: Uint8Array): huks.HuksParam[] {
    return [
      { tag: huks.HuksTag.HUKS_TAG_ALGORITHM, value: huks.HuksKeyAlg.HUKS_ALG_AES },
      { tag: huks.HuksTag.HUKS_TAG_KEY_SIZE, value: huks.HuksKeySize.HUKS_KEY_SIZE_256 },
      { tag: huks.HuksTag.HUKS_TAG_PADDING, value: huks.HuksKeyPadding.HUKS_PADDING_PKCS7 },
      { tag: huks.HuksTag.HUKS_TAG_CIPHER_MODE, value: huks.HuksCipherMode.HUKS_MODE_CBC },
      { tag: huks.HuksTag.HUKS_TAG_NONCE, value: iv }
    ];
  }

  // 加密:三段式 init → update → finish,返回密文字节
  static async encrypt(plain: string, iv: Uint8Array): Promise<Uint8Array> {
    await HuksUtil.ensureKey();
    const options: huks.HuksOptions = { properties: HuksUtil.genSessionProperties(iv) };
    const session = await huks.initSession(KEY_ALIAS, options);
    const updateResult = await huks.updateSession(session.handle, options,
      { inData: HuksUtil.encoder.encodeInto(plain) });
    const finalResult = await huks.finishSession(session.handle, options);
    return HuksUtil.concat(updateResult.outData ?? new Uint8Array(0),
      finalResult.outData ?? new Uint8Array(0));
  }

  // 解密:密文经同样三段式还原为明文
  static async decrypt(cipher: Uint8Array, iv: Uint8Array): Promise<string> {
    const options: huks.HuksOptions = { properties: HuksUtil.genSessionProperties(iv) };
    const session = await huks.initSession(KEY_ALIAS, options);
    const updateResult = await huks.updateSession(session.handle, options,
      { inData: cipher });
    await huks.finishSession(session.handle, options);
    const out = updateResult.outData ?? new Uint8Array(0);
    return HuksUtil.decoder.decodeToString(out);
  }

  // 销毁密钥(销毁后原密文将永久无法解密)
  static async destroyKey(): Promise<void> {
    await huks.deleteKeyItem(KEY_ALIAS, {});
  }

  private static concat(a: Uint8Array, b: Uint8Array): Uint8Array {
    const out = new Uint8Array(a.length + b.length);
    out.set(a, 0);
    out.set(b, a.length);
    return out;
  }
}
2. UI 调用示例 Index.ets
import { BusinessError } from '@kit.BasicServicesKit';
import { util } from '@kit.ArkTS';
import { HuksUtil } from '../model/HuksUtil';

@Entry
@Component
struct Index {
  @State log: string = '就绪';
  private iv: Uint8Array = new Uint8Array(16).fill(1); // 演示用固定 IV
  private cipherText: Uint8Array | null = null;

  private append(text: string): void {
    this.log = `${this.log}\n${text}`;
  }

  build() {
    Column({ space: 12 }) {
      Text('HUKS 密钥托管加解密').fontSize(16).fontWeight(FontWeight.Bold)

      Button('加密').onClick(async () => {
        try {
          this.cipherText = await HuksUtil.encrypt('hello huks', this.iv);
          this.append(`加密成功,密文长度 ${this.cipherText.length}`);
        } catch (err) {
          this.append(`加密失败 code=${(err as BusinessError).code}`);
        }
      })

      Button('解密').onClick(async () => {
        try {
          if (this.cipherText === null) {
            this.append('请先加密');
            return;
          }
          const plain = await HuksUtil.decrypt(this.cipherText, this.iv);
          this.append(`解密成功:${plain}`);
        } catch (err) {
          this.append(`解密失败 code=${(err as BusinessError).code}`);
        }
      })

      Button('销毁密钥').onClick(async () => {
        try {
          await HuksUtil.destroyKey();
          this.append('密钥已销毁,旧密文永久无法解密');
        } catch (err) {
          this.append(`销毁失败 code=${(err as BusinessError).code}`);
        }
      })

      Text(this.log)
        .fontSize(13)
        .width('90%')
        .height(200)
        .backgroundColor('#F2F3F5')
        .padding(10)
        .borderRadius(8)
    }
    .width('100%')
    .height('100%')
    .justifyContent(FlexAlign.Center)
  }
}
四、应用场景示例

本地敏感数据(如用户笔记)落盘前加密——密钥托管在 HUKS,文件即使被拉取也无法解密:

import { HuksUtil } from '../model/HuksUtil';

// 写入:加密后再落盘
const cipher = await HuksUtil.encrypt(noteText, this.iv);
fs.writeSync(file.fd, cipher);

// 读取:从文件读出密文再经 HUKS 解密
const cipherData = fs.readSync(file.fd, new ArrayBuffer(fileStat.size));
const plain = await HuksUtil.decrypt(new Uint8Array(cipherData), this.iv);
五、技术要点
1. 密钥不可导出是核心优势

generateKeyItem 生成的密钥默认不可导出(无 EXPORTABLE 属性),应用崩溃、root、备份提取都拿不到密钥明文;需要跨设备迁移时改用 HUKS 的加密导入导出能力,而非明文导出。

2. IV 管理与三段式顺序
  • CBC 模式的 IV 为 16 字节,加密与解密必须使用同一 IV;生产环境应每次加密随机生成 IV 并与密文一起保存(IV 不是秘密,重复使用才危险);
  • 三段式的参数集每次都要传入(含 IV),漏传 HUKS_TAG_NONCE 会直接报参数错误。
3. 错误处理
try {
  await HuksUtil.encrypt('demo', this.iv);
} catch (err) {
  const e = err as BusinessError;
  if (e.code === 12000002) {
    console.error('密钥别名不存在,先 generateKeyItem');
  } else if (e.code === 12000012) {
    console.error('密钥文件损坏');
  } else {
    console.error(`huks error code=${e.code}, msg=${e.message}`);
  }
}
4. 使用限制
  • updateSession 的单次输入长度有上限,超长数据需分段多次调用后 finishSession(空数据用 new Uint8Array(0));
  • 与 Device Security Kit / 远程证明等高级能力配合时需按业务场景申请对应权限;
  • HUKS 密钥默认与应用绑定,卸载应用后密钥即销毁,依赖 HUKS 加密的文件也随之失效。
六、扩展建议
  1. 用户认证门禁:密钥属性设置 HUKS_TAG_USER_AUTH_TYPE(指纹/人脸/锁屏密码),解密前自动拉起系统认证,实现"认证后才能解密";
  2. 签名验签:把算法换成 HUKS_ALG_RSA/ECC、用途换成 SIGN/VERIFY,可实现设备指纹与数据完整性校验;
  3. 与 Asset Store Kit 组合:ASSET 存"短敏感数据密文",HUKS 存"加密它们的密钥",两层配合覆盖绝大多数本地安全场景:
// 密钥由 HUKS 托管,业务数据密文可交给 ASSET 或沙箱文件
attr.set(asset.Tag.SECRET, cipherBytes); // ASSET 只存结果
结语

本文用 HUKS 完成了密钥从生成、三段式加解密到销毁托管的完整实现,核心代码约 140 行,均已开源到文末 AtomGit 仓库。理解"密钥不出安全区"模型与三段式会话后,应用内的本地敏感数据就有了硬件级安全水位,且无需自行保管任何密钥。

代码仓库

本文完整工程已在 AtomGit 开源:https://atomgit.com/NJPJI_Yang/hm-article-20261125-huks-atomgit

仓库包含可直接用 DevEco Studio 打开编译的完整鸿蒙 Stage 工程(AppScope 应用配置、entry 模块、hvigor 构建脚本齐全),以及与 CSDN 发布内容一致的 article.md 全文。

Logo

作为“人工智能6S店”的官方数字引擎,为AI开发者与企业提供一个覆盖软硬件全栈、一站式门户。

更多推荐