本文原创发布在华为开发者社区

介绍

本示例展示了密钥管理,包括:密钥生成/销毁、密钥导入、密钥证明、密钥协商、密钥派生相关功能。以及秘钥使用,包括:加解密、签名/验签、访问控制相关功能。

实现通用密钥管理功能源码链接

效果预览

请添加链接描述

使用说明

点击对应模式按钮即可展示结果。

实现思路

  1. 模拟加密场景,首先获取密钥别名、待加密的数据与加密算法参数配置,后调用initSession获取handle,调用finishSession获取加密后的密文。

    export async function encryptData(data2Encrypt:string) {
      let encryptProperties = getAesGcmEncryptProperties();
      let options: huks.HuksOptions = {
     properties: encryptProperties,
     inData: stringToUint8Array(data2Encrypt)
      }
      await huks.initSession(keyAlias, options)
     .then((data) => {
       handle = data.handle;
     }).catch((error: Error) => {
       hilog.error(0xd000,'promise: init EncryptDataGcm failed, %{public}s',JSON.stringify(error))
     })
      await huks.finishSession(handle, options)
     .then((data) => {
       cipherData = data.outData as Uint8Array;
     }).catch((error: Error) => {
       hilog.error(0xd000,'promise: encrypt data failed, %{public}s',JSON.stringify(error))
     })
    }
  2. 模拟解密场景,首先获取密钥别名、待解密的密文和解密算法参数配置,后调用initSession获取handle,调用finishSession获取解密后的数据。

    export async function decryptDataImpl() {
      let result:string = '';
      let decryptOptions = getAesGcmDecryptProperties(cipherData)
      let options: huks.HuksOptions = {
     properties: decryptOptions,
     inData: cipherData.slice(0, cipherData.length-16)
      }
      await huks.initSession(keyAlias, options)
     .then((data) => {
       handle = data.handle;
     }).catch((error: Error) => {
       hilog.error(0xd000,'promise: init DecryptDataGcm failed, %{public}s',JSON.stringify(error))
     })
      await huks.finishSession(handle, options)
     .then((data) => {
       result =  uint8ArrayToString(data.outData as Uint8Array);
     }).catch((error: Error) => {
       hilog.error(0xd000,'promise: decrypt data failed, %{public}s',JSON.stringify(error))
     })
      return result;
    }

鸿蒙场景化代码
1 声望0 粉丝