使用的核心API通用密钥库开发步骤:①确定密钥别名②初始化密钥属性集③将密钥别名与密钥参数集作为参数传入,生成密钥④初始化密钥会话huks.initSession()⑤结束密钥会话huks.finishSession()核心代码解释封装加密参数生成指定别名密钥加密步骤解密步骤核心代码如下:function GetAesEncryptProperties() { let properties: Array<huks.HuksParam> = new Array(); let index = 0; properties[index++] = { tag: huks.HuksTag.HUKS_TAG_ALGORITHM, value: huks.HuksKeyAlg.HUKS_ALG_AES }; //指定算法 properties[index++] = { tag: huks.HuksTag.HUKS_TAG_KEY_SIZE, value: huks.HuksKeySize.HUKS_AES_KEY_SIZE_128 }; //指定密钥长度 properties[index++] = { tag: huks.HuksTag.HUKS_TAG_PURPOSE, value: huks.HuksKeyPurpose.HUKS_KEY_PURPOSE_ENCRYPT } //指定密钥用途 properties[index++] = { tag: huks.HuksTag.HUKS_TAG_PADDING, value: huks.HuksKeyPadding.HUKS_PADDING_PKCS7 } //指定密钥填充格式 properties[index++] = { tag: huks.HuksTag.HUKS_TAG_BLOCK_MODE, value: huks.HuksCipherMode.HUKS_MODE_CBC }//指定密码格式 properties[index++] = { tag: huks.HuksTag.HUKS_TAG_IV, value: StringToUint8Array(IV) }//偏移量 return properties; } export async function GenerateAesKey(aesKeyAlias:string) { let genProperties = GetAesGenerateProperties(); let options: huks.HuksOptions = { properties: genProperties } await huks.generateKeyItem(aesKeyAlias, options) .then((data) => { console.info(`callback: generate AES Key success, data = ${JSON.stringify(data)}`); AlertDialog.show({message: '密钥生成成功:'+aesKeyAlias }); }).catch((error: BusinessError)=>{ console.error(`callback: generate AES Key failed`); AlertDialog.show({message: '密钥生成失败:'+aesKeyAlias}); }) }let handle:number; let cipherData:Uint8Array; export async function EncryptData(aesKeyAlias:string,plainText:string) { //plainText需小于100k let encryptProperties = GetAesEncryptProperties(); let options: huks.HuksOptions = { properties: encryptProperties, inData: StringToUint8Array(plainText) } await huks.initSession(aesKeyAlias, options) .then((data) => { handle = data.handle; }).catch((error: BusinessError)=>{ AlertDialog.show({message: '错误码:'+error.code+`加密初始化失败`}); }) await huks.finishSession(handle, options) .then((data) => { cipherData = data.outData as Uint8Array; AlertDialog.show({message: '加密成功:密文是:'+Uint8ArrayToString(data.outData as Uint8Array)}); }).catch((error: BusinessError)=>{ AlertDialog.show({message: '错误码:'+error.code+`最终加密失败`}); }) return cipherData; }export async function DecryptData(aesKeyAlias:string,cipherData:Uint8Array) { let decryptOptions = GetAesDecryptProperties() let options: huks.HuksOptions = { properties: decryptOptions, inData: cipherData } let a = await huks.initSession(aesKeyAlias, options); handle = a.handle try { let b = await huks.finishSession(handle, options) AlertDialog.show({ message: Uint8ArrayToString(b.outData as Uint8Array) }); } catch (err) { AlertDialog.show({ message: err.message }); } }适配的版本信息· IDE:DevEco Studio 4.0.3.601· SDK:HarmoneyOS 4.0.10.11
使用的核心API
开发步骤:
①确定密钥别名
②初始化密钥属性集
③将密钥别名与密钥参数集作为参数传入,生成密钥
④初始化密钥会话huks.initSession()
⑤结束密钥会话huks.finishSession()
核心代码解释
核心代码如下:
适配的版本信息
· IDE:DevEco Studio 4.0.3.601
· SDK:HarmoneyOS 4.0.10.11