diff --git a/zh-cn/application-dev/reference/apis/js-apis-huks.md b/zh-cn/application-dev/reference/apis/js-apis-huks.md
index 7421c7fb92e6ac8a4c26b808c18516c975886579..6e5a68a050a6095fbe08600ad2065957bf715343 100755
--- a/zh-cn/application-dev/reference/apis/js-apis-huks.md
+++ b/zh-cn/application-dev/reference/apis/js-apis-huks.md
@@ -12,7 +12,7 @@ HUKS所管理的密钥可以由应用导入或者由应用调用HUKS接口生成
```js
import huks from '@ohos.security.huks'
```
-## HuksErrorCode
+## HuksErrorCode(deprecated)
表示错误码的枚举。
@@ -95,6 +95,113 @@ import huks from '@ohos.security.huks'
| HUKS_ERROR_INTERNAL_ERROR | -999 |表示内部错误。|
| HUKS_ERROR_UNKNOWN_ERROR | -1000 |表示未知错误。|
+## HuksExceptionErrCode9+
+
+表示错误码的枚举以及对应的错误信息, 错误码表示错误类型,错误信息展示错误详情。
+
+**系统能力**:SystemCapability.Security.Huks
+
+| 类型 | 名称 | 说明 | 错误码 |
+| ------------------------- | ---------------------------------------------- | --------------------------- | -------- |
+| 权限 | HUKS_ERR_CODE_PERMISSION_FAIL | 权限错误导致失败。 | 201 |
+| 参数 | HUKS_ERR_CODE_ILLEGAL_ARGUMENT | 参数错误导致失败。 | 401 |
+| 不支持的API | HUKS_ERR_CODE_NOT_SUPPORTED_API | 不支持的API。 | 801 |
+| 不支持的功能/特性 | HUKS_ERR_CODE_FEATURE_NOT_SUPPORTED | 不支持的功能/特性。 | 12000001 |
+| 缺少密钥算法参数 | HUKS_ERR_CODE_MISSING_CRYPTO_ALG_ARGUMENT | 缺少密钥算法参数。 | 12000002 |
+| 无效密钥算法参数 | HUKS_ERR_CODE_INVALID_CRYPTO_ALG_ARGUMENT | 无效密钥算法参数。 | 12000003 |
+| 文件 | HUKS_ERR_CODE_FILE_OPERATION_FAIL | 文件操作失败。 | 12000004 |
+| 通信 | HUKS_ERR_CODE_COMMUNICATION_FAIL | 通信失败。 | 12000005 |
+| 算法库操作失败 | HUKS_ERR_CODE_CRYPTO_FAIL | 算法库操作失败。 | 12000006 |
+| 密钥访问失败-密钥访问失效 | HUKS_ERR_CODE_KEY_AUTH_PERMANENTLY_INVALIDATED | 密钥访问失败-密钥访问失效。 | 12000007 |
+| 密钥访问失败-密钥认证失败 | HUKS_ERR_CODE_KEY_AUTH_VERIFY_FAILED | 密钥访问失败-密钥认证失败。 | 12000008 |
+| 密钥访问失败-密钥访问超时 | HUKS_ERR_CODE_KEY_AUTH_TIME_OUT | 密钥访问失败-密钥访问超时。 | 12000009 |
+| 密钥操作会话数已达上限 | HUKS_ERR_CODE_SESSION_LIMIT | 密钥操作会话数已达上限。 | 12000010 |
+| 目标对象不存在 | HUKS_ERR_CODE_ITEM_NOT_EXIST | 目标对象不存在。 | 12000011 |
+| 外部错误 | HUKS_ERR_CODE_EXTERNAL_ERROR | 外部错误。 | 12000012 |
+| 缺失所需凭据 | HUKS_ERR_CODE_CREDENTIAL_NOT_EXIST | 缺失所需凭据。 | 12000013 |
+| 内存不足 | HUKS_ERR_CODE_INSUFFICIENT_MEMORY | 内存不足。 | 12000014 |
+| 调用其他系统服务失败 | HUKS_ERR_CODE_CALL_SERVICE_FAILED | 调用其他系统服务失败。 | 12000015 |
+
+错误信息:
+
+| 类型 | 错误码 | ERROR MESSAGE | 错误信息 |
+| ------------------------- | -------- | ------------------------------------------------------------ | ----------------------------------------- |
+| 权限 | 201 | Check permission failed. User should request permission first. | 表示没有许可。 |
+| 参数 | 401 | Argument is invalid. User should make sure using the correct value. | 表示无效的参数。 |
+| 参数 | 401 | Input data is not sufficient. | 表示数据不足。 |
+| 参数 | 401 | The buffer is too small. | 表示缓冲区太小。 |
+| 参数 | 401 | Parameter is null. User should make sure using the correct value. | 表示空指针。 |
+| 参数 | 401 | Public key is invalid. | 表示无效的公钥。 |
+| 参数 | 401 | Key info is invalid. | 表示无效的密钥信息。 |
+| 参数 | 401 | Queried param does not exist. | 表示参数不存在。 |
+| 参数 | 401 | Root key material already exists. | 表示存在新的根密钥材料。 |
+| 参数 | 401 | The format of wrapped key data is invalid. | 表示导入加密密钥时,密钥格式错误。 |
+| 参数 | 401 | Check get auth type failed. User should add auth type in paramset. | 表示获取身份验证类型失败。 |
+| 参数 | 401 | Check get challenge type failed. User should add challenge type in paramset. | 表示获取挑战值类型失败。 |
+| 参数 | 401 | Check get access type failed. User should add access type in paramset. | 表示获取访问类型失败。 |
+| 参数 | 401 | Check get auth token failed. User should add auth token in paramset. | 表示获取身份验证令牌失败。 |
+| 参数 | 401 | Time out param is invalid. User should make sure using the correct value. | 表示超时参数无效 |
+| 参数 | 401 | Auth type param is invalid. User should make sure using the correct value. | 表示身份验证类型参数无效。 |
+| 参数 | 401 | Challenge type param is invalid. User should make sure using the correct value. | 表示挑战值类型参数无效。 |
+| 参数 | 401 | Access type param is invalid. User should make sure using the correct value. | 表示访问类型参数无效。 |
+| 参数 | 401 | Auth token param is invalid. User should make sure using the correct value. | 表示身份验证令牌参数无效。 |
+| 参数 | 401 | Secure sign type param is invalid. User should make sure using the correct value. | 表示安全符号类型参数无效。 |
+| 不支持的API | 801 | This api is not supported in current device. | 不支持的API。 |
+| 不支持的功能/特性 | 12000001 | Feature is not support. Please make sure using the correct combination of params. | 功能特性不支持,请输入正确的参数组合。 |
+| 不支持的功能/特性 | 12000001 | This user auth type is not supported in current device. | 表示不支持当前用户认证类型的访问控制。 |
+| 缺少密钥算法参数 | 12000002 | Check get algorithm failed. User should add algorithm in paramset. | 表示检查获取 ALG 失败。 |
+| 缺少密钥算法参数 | 12000002 | Check get key size failed. User should add key size in paramset. | 表示检查获取密钥大小失败。 |
+| 缺少密钥算法参数 | 12000002 | Check get padding failed. User should add padding in paramset. | 表示检查获取填充失败。 |
+| 缺少密钥算法参数 | 12000002 | Check get purpose failed. User should add purpose in paramset. | 表示检查获取目的失败。 |
+| 缺少密钥算法参数 | 12000002 | Check get digest failed. User should add digest in paramset. | 表示检查获取摘要失败。 |
+| 缺少密钥算法参数 | 12000002 | Check get mode failed. User should add mode in paramset. | 表示检查获取模式失败。 |
+| 缺少密钥算法参数 | 12000002 | Check get nonce failed. User should add nonce in paramset. | 表示检查获取随机数失败。 |
+| 缺少密钥算法参数 | 12000002 | Check get aad failed. User should add AAD in paramset. | 表示检查获取 AAD 失败。 |
+| 缺少密钥算法参数 | 12000002 | Check get iv failed. User should add iv in paramset. | 表示检查 GET IV 失败。 |
+| 缺少密钥算法参数 | 12000002 | Check get aead failed. User should add aead in paramset. | 表示检查获取 AE 标记失败。 |
+| 缺少密钥算法参数 | 12000002 | Check get salt failed. User should add salt in paramset. | 表示检查获取SALT失败。 |
+| 缺少密钥算法参数 | 12000002 | Check get iteration failed. User should add iteration in paramset. | 表示检查获取迭代失败。 |
+| 无效密钥算法参数 | 12000003 | Algorithm param is invalid. User should make sure using the correct value. | 表示无效的算法。 |
+| 无效密钥算法参数 | 12000003 | Key size param is invalid. User should make sure using the correct value. | 表示无效的密钥大小。 |
+| 无效密钥算法参数 | 12000003 | Padding param is invalid. User should make sure using the correct value. | 表示无效的填充。 |
+| 无效密钥算法参数 | 12000003 | Purpose param is invalid. User should make sure using the correct value. | 表示无效的目的。 |
+| 无效密钥算法参数 | 12000003 | Mode param is invalid. User should make sure using the correct value. | 表示无效模式。 |
+| 无效密钥算法参数 | 12000003 | Digest param is invalid. User should make sure using the correct value. | 表示无效的摘要。 |
+| 无效密钥算法参数 | 12000003 | Signture size param is invalid. User should make sure using the correct value. | 表示签名大小无效。 |
+| 无效密钥算法参数 | 12000003 | IV param is invalid. User should make sure using the correct value. | 表示无效的 IV。 |
+| 无效密钥算法参数 | 12000003 | AAD param is invalid. User should make sure using the correct value. | 表示无效的 AAD。 |
+| 无效密钥算法参数 | 12000003 | Nonce param is invalid. User should make sure using the correct value. | 表示无效的随机数。 |
+| 无效密钥算法参数 | 12000003 | AE param is invalid. User should make sure using the correct value. | 表示无效的 AE 标签。 |
+| 无效密钥算法参数 | 12000003 | Salt param is invalid. User should make sure using the correct value. | 表示无效SALT。 |
+| 无效密钥算法参数 | 12000003 | Iteration param is invalid. User should make sure using the correct value. | 表示无效的迭代。 |
+| 无效密钥算法参数 | 12000003 | Purpose param is invalid. User should make sure using the correct value. | 表示导入加密密钥时,密钥用途错误。 |
+| 文件 | 12000004 | Storage space is insufficient. | 表示存储故障。 |
+| 文件 | 12000004 | The value of file size is unexpected. | 表示文件大小失败。 |
+| 文件 | 12000004 | Read file failed. | 表示读取文件失败。 |
+| 文件 | 12000004 | Write file failed. | 表示写文件失败。 |
+| 文件 | 12000004 | Remove file failed. | 表示删除文件失败。 |
+| 文件 | 12000004 | Open file failed. | 表示打开文件失败。 |
+| 文件 | 12000004 | Close file failed. | 表示关闭文件失败。 |
+| 文件 | 12000004 | Make directory failed. | 表示创建目录失败。 |
+| 文件 | 12000004 | Read key from file failed, for key fi哦呜le is invalid. | 表示无效的密钥文件。 |
+| 通信 | 12000005 | Get message from IPC failed. | 表示IPC 信息失败。 |
+| 通信 | 12000005 | IPC communication time out. | 表示通讯超时。 |
+| 通信 | 12000005 | IPC init failed. | 表示IPC 初始化失败。 |
+| 通信 | 12000005 | IPC async call failed. | IPC异步调用失败。 |
+| 算法库操作失败 | 12000006 | Errors occured in crypto engine. | 表示CRYPTO ENGINE错误。 |
+| 密钥访问失败-密钥访问失效 | 12000007 | This credential is already invalidated permanently. | 密钥访问失败-密钥访问失效 |
+| 密钥访问失败-密钥认证失败 | 12000008 | Verify authtoken failed. | 密钥访问失败-密钥认证失败 |
+| 密钥访问失败-密钥访问超时 | 12000009 | This authtoken is already timeout. | 密钥访问失败-密钥访问超时 |
+| 密钥操作会话数已达上限 | 12000010 | The number of sessions has reached limit. | 密钥操作会话数已达上限。 |
+| 目标对象不存在 | 12000011 | Queried entity does not exist. | 表示不存在。 |
+| 外部错误 | 12000012 | General error. | 一般错误。 |
+| 外部错误 | 12000012 | System error. | 系统错误。 |
+| 外部错误 | 12000012 | System external error. | 表示系统外部错误。 |
+| 缺失所需凭据 | 12000013 | Queried credential does not exist. | 查询的凭据不存在。 |
+| 内存不足 | 12000014 | Memory is insufficient. | 表示内存不足。 |
+| 内存不足 | 12000014 | Malloc failed. | 表示MALLOC 失败。 |
+| 调用其他系统服务失败 | 12000015 | Calling useriam to get sec info failed. | 访问useriam获取当前用户安全属性信息失败。 |
+| 调用其他系统服务失败 | 12000015 | Calling useriam to get auth info failed. | 访问useriam获取当前用户认证信息失败。 |
## HuksKeyPurpose
@@ -448,12 +555,14 @@ import huks from '@ohos.security.huks'
| HUKS_TAG_ASYMMETRIC_PUBLIC_KEY_DATA | HuksTagType.HUKS_TAG_TYPE_BYTES \| 20002 | 预留。 |
| HUKS_TAG_ASYMMETRIC_PRIVATE_KEY_DATA | HuksTagType.HUKS_TAG_TYPE_BYTES \| 20003 | 预留。 |
-## huks.generateKey
+## huks.generateKey(deprecated)
generateKey(keyAlias: string, options: HuksOptions, callback: AsyncCallback\) : void
生成密钥,使用Callback回调异步返回结果。
+> **说明:** 从API Version 9开始废弃,建议使用[huks.generateKeyItem9+](#huksgeneratekeyitem9)替代。
+
**系统能力**:SystemCapability.Security.Huks
**参数:**
@@ -498,12 +607,14 @@ var options = {
huks.generateKey(keyAlias, options, function (err, data){});
```
-## huks.generateKey
+## huks.generateKey(deprecated)
generateKey(keyAlias: string, options: HuksOptions) : Promise\
生成密钥,使用Promise方式异步返回结果。
+> **说明:** 从API Version 9开始废弃,建议使用[huks.generateKeyItem9+](#huksgeneratekeyitem9-1)替代。
+
**系统能力**:SystemCapability.Security.Huks
**参数:**
@@ -549,12 +660,125 @@ var options = {
var result = huks.generateKey(keyAlias, options);
```
-## huks.deleteKey
+## huks.generateKeyItem9+
+
+generateKeyItem(keyAlias: string, options: HuksOptions, callback: AsyncCallback\) : void
+
+生成密钥,使用Callback回调异步返回结果。
+
+**系统能力**:SystemCapability.Security.Huks
+
+**参数:**
+
+| 参数名 | 类型 | 必填 | 说明 |
+| -------- | --------------------------- | ---- | --------------------------------------------- |
+| keyAlias | string | 是 | 别名。 |
+| options | [HuksOptions](#huksoptions) | 是 | 用于存放生成key所需TAG。 |
+| callback | AsyncCallback\ | 是 | 不返回err值时表示接口使用成功,其他时为错误。 |
+
+**示例:**
+
+```js
+/* 以生成ECC256密钥为例 */
+var keyAlias = 'keyAlias';
+var properties = new Array();
+properties[0] = {
+ tag: huks.HuksTag.HUKS_TAG_ALGORITHM,
+ value: huks.HuksKeyAlg.HUKS_ALG_ECC
+};
+properties[1] = {
+ tag: huks.HuksTag.HUKS_TAG_KEY_SIZE,
+ value: huks.HuksKeySize.HUKS_ECC_KEY_SIZE_256
+};
+properties[2] = {
+ tag: huks.HuksTag.HUKS_TAG_PURPOSE,
+ value:
+ huks.HuksKeyPurpose.HUKS_KEY_PURPOSE_SIGN |
+ huks.HuksKeyPurpose.HUKS_KEY_PURPOSE_VERIFY
+};
+properties[3] = {
+ tag: huks.HuksTag.HUKS_TAG_DIGEST,
+ value: huks.HuksKeyDigest.HUKS_DIGEST_SHA256
+};
+var options = {
+ properties: properties
+};
+try {
+ huks.generateKeyItem(keyAlias, options, function (error, data) {
+ if (error) {
+ console.error(`callback: generateKeyItem failed, code: ${error.code}, msg: ${error.message}`);
+ } else {
+ console.info(`callback: generateKeyItem key success`);
+ }
+ });
+} catch (error) {
+ console.error(`callback: generateKeyItem input arg invalid, code: ${error.code}, msg: ${error.message}`);
+}
+```
+
+## huks.generateKeyItem9+
+
+generateKeyItem(keyAlias: string, options: HuksOptions) : Promise\
+
+生成密钥,使用Promise方式异步返回结果。
+
+**系统能力**:SystemCapability.Security.Huks
+
+**参数:**
+
+| 参数名 | 类型 | 必填 | 说明 |
+| -------- | --------------------------- | ---- | ------------------------ |
+| keyAlias | string | 是 | 密钥别名。 |
+| options | [HuksOptions](#huksoptions) | 是 | 用于存放生成key所需TAG。 |
+
+**示例:**
+
+```js
+/* 以生成ECC256密钥为例 */
+var keyAlias = 'keyAlias';
+var properties = new Array();
+properties[0] = {
+ tag: huks.HuksTag.HUKS_TAG_ALGORITHM,
+ value: huks.HuksKeyAlg.HUKS_ALG_ECC
+};
+properties[1] = {
+ tag: huks.HuksTag.HUKS_TAG_KEY_SIZE,
+ value: huks.HuksKeySize.HUKS_ECC_KEY_SIZE_256
+};
+properties[2] = {
+ tag: huks.HuksTag.HUKS_TAG_PURPOSE,
+ value:
+ huks.HuksKeyPurpose.HUKS_KEY_PURPOSE_SIGN |
+ huks.HuksKeyPurpose.HUKS_KEY_PURPOSE_VERIFY
+};
+properties[3] = {
+ tag: huks.HuksTag.HUKS_TAG_DIGEST,
+ value: huks.HuksKeyDigest.HUKS_DIGEST_SHA256
+};
+var options = {
+ properties: properties
+};
+try {
+ huks.generateKeyItem(keyAlias, options)
+ .then((data) => {
+ console.info(`promise: generateKeyItem success`);
+ })
+ .catch(error => {
+ console.error(`promise: generateKeyItem failed, code: ${error.code}, msg: ${error.message}`);
+ });
+} catch (error) {
+ console.error(`promise: generateKeyItem input arg invalid, code: ${error.code}, msg: ${error.message}`);
+}
+```
+
+## huks.deleteKey(deprecated)
deleteKey(keyAlias: string, options: HuksOptions, callback: AsyncCallback\) : void
删除密钥,使用Callback回调异步返回结果。
+> **说明:** 从API Version 9开始废弃,建议使用[huks.deleteKeyItem9+](#huksdeletekeyitem9)替代。
+
**系统能力**:SystemCapability.Security.Huks
**参数:**
@@ -576,12 +800,14 @@ var emptyOptions = {
huks.deleteKey(keyAlias, emptyOptions, function (err, data) {});
```
-## huks.deleteKey
+## huks.deleteKey(deprecated)
deleteKey(keyAlias: string, options: HuksOptions) : Promise\
删除密钥,使用Promise方式异步返回结果。
+> **说明:** 从API Version 9开始废弃,建议使用[huks.deleteKeyItem9+](#huksdeletekeyitem9-1)替代。
+
**系统能力**:SystemCapability.Security.Huks
**参数:**
@@ -608,6 +834,79 @@ var emptyOptions = {
var result = huks.deleteKey(keyAlias, emptyOptions);
```
+## huks.deleteKeyItem9+
+
+deleteKeyItem(keyAlias: string, options: HuksOptions, callback: AsyncCallback\) : void
+
+删除密钥,使用Callback回调异步返回结果。
+
+**系统能力**:SystemCapability.Security.Huks
+
+**参数:**
+
+| 参数名 | 类型 | 必填 | 说明 |
+| -------- | --------------------------- | ---- | --------------------------------------------- |
+| keyAlias | string | 是 | 密钥别名,应为生成key时传入的别名。 |
+| options | [HuksOptions](#huksoptions) | 是 | 空对象(此处传空即可)。 |
+| callback | AsyncCallback\ | 是 | 不返回err值时表示接口使用成功,其他时为错误。 |
+
+**示例:**
+
+```js
+/* 此处options选择emptyOptions传空 */
+var keyAlias = 'keyAlias';
+var emptyOptions = {
+ properties: []
+};
+try {
+ huks.deleteKeyItem(keyAlias, emptyOptions, function (error, data) {
+ if (error) {
+ console.error(`callback: deleteKeyItem failed, code: ${error.code}, msg: ${error.message}`);
+ } else {
+ console.info(`callback: deleteKeyItem key success`);
+ }
+ });
+} catch (error) {
+ console.error(`callback: deleteKeyItem input arg invalid, code: ${error.code}, msg: ${error.message}`);
+}
+```
+
+## huks.deleteKeyItem9+
+
+deleteKeyItem(keyAlias: string, options: HuksOptions) : Promise\
+
+删除密钥,使用Promise方式异步返回结果。
+
+**系统能力**:SystemCapability.Security.Huks
+
+**参数:**
+
+| 参数名 | 类型 | 必填 | 说明 |
+| -------- | --------------------------- | ---- | ----------------------------------- |
+| keyAlias | string | 是 | 密钥别名,应为生成key时传入的别名。 |
+| options | [HuksOptions](#huksoptions) | 是 | 空对象(此处传空即可)。 |
+
+**示例:**
+
+```js
+/* 此处options选择emptyOptions传空 */
+var keyAlias = 'keyAlias';
+var emptyOptions = {
+ properties: []
+};
+try {
+ huks.deleteKeyItem(keyAlias, emptyOptions)
+ .then ((data) => {
+ console.info(`promise: deleteKeyItem key success`);
+ })
+ .catch(error => {
+ console.error(`promise: deleteKeyItem failed, code: ${error.code}, msg: ${error.message}`);
+ });
+} catch (error) {
+ console.error(`promise: deleteKeyItem input arg invalid, code: ${error.code}, msg: ${error.message}`);
+}
+```
+
## huks.getSdkVersion
getSdkVersion(options: HuksOptions) : string
@@ -638,12 +937,14 @@ var emptyOptions = {
var result = huks.getSdkVersion(emptyOptions);
```
-## huks.importKey
+## huks.importKey(deprecated)
importKey(keyAlias: string, options: HuksOptions, callback: AsyncCallback\) : void
导入明文密钥,使用Callback方式回调异步返回结果 。
+> **说明:** 从API Version 9开始废弃,建议使用[huks.importKeyItem9+](#huksimportkeyitem9)替代。
+
**系统能力**:SystemCapability.Security.Huks
**参数:**
@@ -696,12 +997,14 @@ var options = {
huks.importKey(keyAlias, options, function (err, data){});
```
-## huks.importKey
+## huks.importKey(deprecated)
importKey(keyAlias: string, options: HuksOptions) : Promise\
导入明文密钥,使用Promise方式异步返回结果。
+> **说明:** 从API Version 9开始废弃,建议使用[huks.importKeyItem9+](#huksimportkeyitem9-1)替代。
+
**系统能力**:SystemCapability.Security.Huks
**参数:**
@@ -761,242 +1064,395 @@ var huksoptions = {
var result = huks.importKey(keyAlias, huksoptions);
```
-## huks.attestkey9+
+## huks.importKeyItem9+
-attestKey(keyAlias: string, options: HuksOptions, callback: AsyncCallback\) : void
+importKeyItem(keyAlias: string, options: HuksOptions, callback: AsyncCallback\) : void
-获取密钥证书,使用Callback方式回调异步返回结果 。
+导入明文密钥,使用Callback方式回调异步返回结果 。
**系统能力**:SystemCapability.Security.Huks
**参数:**
-| 参数名 | 类型 | 必填 | 说明 |
-| ---------------- | ----------------------------------------- | ---- | -------------------------------------------------- |
-| keyAlias | string | 是 | 密钥别名,存放待获取证书密钥的别名。 |
-| options | [HuksOptions](#huksoptions) | 是 | 用于获取证书时指定所需参数与数据。 |
-| callback | AsyncCallback\<[HuksResult](#huksresult)> | 是 | 返回HUKS_SUCCESS时表示接口使用成功,其他时为错误。 |
+| 参数名 | 类型 | 必填 | 说明 |
+| -------- | --------------------------- | ---- | --------------------------------------------- |
+| keyAlias | string | 是 | 密钥别名。 |
+| options | [HuksOptions](#huksoptions) | 是 | 用于导入时所需TAG和需要导入的密钥。 |
+| callback | AsyncCallback\ | 是 | 不返回err值时表示接口使用成功,其他时为错误。 |
**示例:**
```js
-let securityLevel = stringToUint8Array('sec_level');
-let challenge = stringToUint8Array('challenge_data');
-let versionInfo = stringToUint8Array('version_info');
-let keyAliasString = "key attest";
-
-function stringToUint8Array(str) {
- var arr = [];
- for (var i = 0, j = str.length; i < j; ++i) {
- arr.push(str.charCodeAt(i));
- }
- var tmpUint8Array = new Uint8Array(arr);
- return tmpUint8Array;
-}
-
-function printLog(...data) {
- console.error(data.toString());
-}
-
-async function generateKey(alias) {
- let properties = new Array();
- properties[0] = {
+/* 以导入AES256密钥为例 */
+var plainTextSize32 = makeRandomArr(32);
+function makeRandomArr(size) {
+ var arr = new Uint8Array(size);
+ for (var i = 0; i < size; i++) {
+ arr[i] = Math.floor(Math.random() * 10);
+ }
+ return arr;
+};
+var keyAlias = 'keyAlias';
+var properties = new Array();
+properties[0] = {
tag: huks.HuksTag.HUKS_TAG_ALGORITHM,
- value: huks.HuksKeyAlg.HUKS_ALG_RSA
- };
- properties[1] = {
- tag: huks.HuksTag.HUKS_TAG_KEY_STORAGE_FLAG,
- value: huks.HuksKeyStorageType.HUKS_STORAGE_PERSISTENT
- };
- properties[2] = {
+ value: huks.HuksKeyAlg.HUKS_ALG_AES
+};
+properties[1] = {
tag: huks.HuksTag.HUKS_TAG_KEY_SIZE,
- value: huks.HuksKeySize.HUKS_RSA_KEY_SIZE_2048
- };
- properties[3] = {
+ value: huks.HuksKeySize.HUKS_AES_KEY_SIZE_256
+};
+properties[2] = {
tag: huks.HuksTag.HUKS_TAG_PURPOSE,
- value: huks.HuksKeyPurpose.HUKS_KEY_PURPOSE_VERIFY
- };
- properties[4] = {
- tag: huks.HuksTag.HUKS_TAG_DIGEST,
- value: huks.HuksKeyDigest.HUKS_DIGEST_SHA256
- };
- properties[5] = {
+ value:
+ huks.HuksKeyPurpose.HUKS_KEY_PURPOSE_ENCRYPT | huks.HuksKeyPurpose.HUKS_KEY_PURPOSE_DECRYPT
+};
+properties[3] = {
tag: huks.HuksTag.HUKS_TAG_PADDING,
- value: huks.HuksKeyPadding.HUKS_PADDING_PSS
- };
- properties[6] = {
- tag: huks.HuksTag.HUKS_TAG_KEY_GENERATE_TYPE,
- value: huks.HuksKeyGenerateType.HUKS_KEY_GENERATE_TYPE_DEFAULT
- };
- properties[7] = {
+ value:huks.HuksKeyPadding.HUKS_PADDING_PKCS7
+};
+properties[4] = {
tag: huks.HuksTag.HUKS_TAG_BLOCK_MODE,
value: huks.HuksCipherMode.HUKS_MODE_ECB
- };
- let options = {
- properties: properties
- };
-
- await huks.generateKey(alias, options).then(async (data) => {
- console.error(`generateKey data ${JSON.stringify(data)}`);
- }).catch((err) => {
- console.error(`generateKey err: " + ${JSON.stringify(err)}`);
- });;
-}
-
-async function attestKey() {
- let aliasString = keyAliasString;
- let aliasUint8 = stringToUint8Array(aliasString);
- let properties = new Array();
- properties[0] = {
- tag: huks.HuksTag.HUKS_TAG_ATTESTATION_ID_SEC_LEVEL_INFO,
- value: securityLevel
- };
- properties[1] = {
- tag: huks.HuksTag.HUKS_TAG_ATTESTATION_CHALLENGE,
- value: challenge
- };
- properties[2] = {
- tag: huks.HuksTag.HUKS_TAG_ATTESTATION_ID_VERSION_INFO,
- value: versionInfo
- };
- properties[3] = {
- tag: huks.HuksTag.HUKS_TAG_ATTESTATION_ID_ALIAS,
- value: aliasUint8
- };
- let options = {
- properties: properties
- };
- await generateKey(aliasString);
- huks.attestKey(aliasString, options, function (err, data) {
- printLog(`key attest result : ${JSON.stringify(data)}`);
- });
+};
+var options = {
+ properties: properties,
+ inData: plainTextSize32
+};
+try {
+ huks.importKeyItem(keyAlias, options, function (error, data) {
+ if (error) {
+ console.error(`callback: importKeyItem failed, code: ${error.code}, msg: ${error.message}`);
+ } else {
+ console.info(`callback: importKeyItem success`);
+ }
+ });
+} catch (error) {
+ console.error(`callback: importKeyItem input arg invalid, code: ${error.code}, msg: ${error.message}`);
}
```
-## huks.attestkey9+
+## huks.importKeyItem9+
-attestKey(keyAlias: string, options: HuksOptions) : Promise\
+importKeyItem(keyAlias: string, options: HuksOptions) : Promise\
-获取密钥证书,使用Promise方式异步返回结果 。
+导入明文密钥,使用Promise方式异步返回结果。
**系统能力**:SystemCapability.Security.Huks
**参数:**
-| 参数名 | 类型 | 必填 | 说明 |
-| ---------------- | ----------------------------------------- | ---- | -------------------------------------------------- |
-| keyAlias | string | 是 | 密钥别名,存放待获取证书密钥的别名。 |
-| options | [HuksOptions](#huksoptions) | 是 | 用于获取证书时指定所需参数与数据。 |
-
-**返回值:**
-
-| 类型 | 说明 |
-| ----------------------------------- | -------------------------------------------------- |
-| Promise\<[HuksResult](#huksresult)> | 返回HUKS_SUCCESS时表示接口使用成功,其他时为错误。 |
+| 参数名 | 类型 | 必填 | 说明 |
+| -------- | --------------------------- | ---- | ----------------------------------- |
+| keyAlias | string | 是 | 密钥别名。 |
+| options | [HuksOptions](#huksoptions) | 是 | 用于导入时所需TAG和需要导入的密钥。 |
**示例:**
```js
-let securityLevel = stringToUint8Array('sec_level');
-let challenge = stringToUint8Array('challenge_data');
-let versionInfo = stringToUint8Array('version_info');
-let keyAliasString = "key attest";
-
-function stringToUint8Array(str) {
- var arr = [];
- for (var i = 0, j = str.length; i < j; ++i) {
- arr.push(str.charCodeAt(i));
- }
- var tmpUint8Array = new Uint8Array(arr);
- return tmpUint8Array;
-}
+/* 以导入AES128为例 */
+var plainTextSize32 = makeRandomArr(32);
-function printLog(...data) {
- console.error(data.toString());
-}
+function makeRandomArr(size) {
+ var arr = new Uint8Array(size);
+ for (var i = 0; i < size; i++) {
+ arr[i] = Math.floor(Math.random() * 10);
+ }
+ return arr;
+};
-async function generateKey(alias) {
- let properties = new Array();
- properties[0] = {
+/*第一步:生成密钥*/
+var keyAlias = 'keyAlias';
+var properties = new Array();
+properties[0] = {
tag: huks.HuksTag.HUKS_TAG_ALGORITHM,
- value: huks.HuksKeyAlg.HUKS_ALG_RSA
- };
- properties[1] = {
- tag: huks.HuksTag.HUKS_TAG_KEY_STORAGE_FLAG,
- value: huks.HuksKeyStorageType.HUKS_STORAGE_PERSISTENT
- };
- properties[2] = {
- tag: huks.HuksTag.HUKS_TAG_KEY_SIZE,
- value: huks.HuksKeySize.HUKS_RSA_KEY_SIZE_2048
- };
- properties[3] = {
+ value: huks.HuksKeyAlg.HUKS_ALG_AES
+};
+properties[1] = {
+ tag: huks.HuksTag.HUKS_TAG_KEY_SIZE,
+ value: huks.HuksKeySize.HUKS_AES_KEY_SIZE_128
+};
+properties[2] = {
tag: huks.HuksTag.HUKS_TAG_PURPOSE,
- value: huks.HuksKeyPurpose.HUKS_KEY_PURPOSE_VERIFY
- };
- properties[4] = {
- tag: huks.HuksTag.HUKS_TAG_DIGEST,
- value: huks.HuksKeyDigest.HUKS_DIGEST_SHA256
- };
- properties[5] = {
+ value: huks.HuksKeyPurpose.HUKS_KEY_PURPOSE_ENCRYPT | huks.HuksKeyPurpose.HUKS_KEY_PURPOSE_DECRYPT
+};
+properties[3] = {
tag: huks.HuksTag.HUKS_TAG_PADDING,
- value: huks.HuksKeyPadding.HUKS_PADDING_PSS
- };
- properties[6] = {
- tag: huks.HuksTag.HUKS_TAG_KEY_GENERATE_TYPE,
- value: huks.HuksKeyGenerateType.HUKS_KEY_GENERATE_TYPE_DEFAULT
- };
- properties[7] = {
+ value:huks.HuksKeyPadding.HUKS_PADDING_PKCS7
+};
+properties[4] = {
tag: huks.HuksTag.HUKS_TAG_BLOCK_MODE,
value: huks.HuksCipherMode.HUKS_MODE_ECB
- };
- let options = {
- properties: properties
- };
+};
+var huksoptions = {
+ properties: properties,
+ inData: plainTextSize32
+};
+try {
+ huks.importKeyItem(keyAlias, huksoptions)
+ .then ((data) => {
+ console.info(`promise: importKeyItem success`);
+ })
+ .catch(error => {
+ console.error(`promise: importKeyItem failed, code: ${error.code}, msg: ${error.message}`);
+ });
+} catch (error) {
+ console.error(`promise: importKeyItem input arg invalid, code: ${error.code}, msg: ${error.message}`);
+}
+```
- await huks.generateKey(alias, options).then(async (data) => {
- console.error(`generateKey data ${JSON.stringify(data)}`);
- }).catch((err) => {
- console.error(`generateKey err: " + ${JSON.stringify(err)}`);
- });;
+## huks.attestKeyItem9+
+
+attestKeyItem(keyAlias: string, options: HuksOptions, callback: AsyncCallback\) : void
+
+获取密钥证书,使用Callback方式回调异步返回结果 。
+
+**系统能力**:SystemCapability.Security.Huks
+
+**参数:**
+
+| 参数名 | 类型 | 必填 | 说明 |
+| -------- | ---------------------------------------------------- | ---- | --------------------------------------------- |
+| keyAlias | string | 是 | 密钥别名,存放待获取证书密钥的别名。 |
+| options | [HuksOptions](#huksoptions) | 是 | 用于获取证书时指定所需参数与数据。 |
+| callback | AsyncCallback<[HuksReturnResult](#huksreturnresult)> | 是 | 不返回err值时表示接口使用成功,其他时为错误。 |
+
+**示例:**
+
+```js
+let securityLevel = stringToUint8Array('sec_level');
+let challenge = stringToUint8Array('challenge_data');
+let versionInfo = stringToUint8Array('version_info');
+let keyAliasString = "key attest";
+
+function stringToUint8Array(str) {
+ var arr = [];
+ for (var i = 0, j = str.length; i < j; ++i) {
+ arr.push(str.charCodeAt(i));
+ }
+ var tmpUint8Array = new Uint8Array(arr);
+ return tmpUint8Array;
+}
+
+async function generateKey(alias) {
+ let properties = new Array();
+ properties[0] = {
+ tag: huks.HuksTag.HUKS_TAG_ALGORITHM,
+ value: huks.HuksKeyAlg.HUKS_ALG_RSA
+ };
+ properties[1] = {
+ tag: huks.HuksTag.HUKS_TAG_KEY_STORAGE_FLAG,
+ value: huks.HuksKeyStorageType.HUKS_STORAGE_PERSISTENT
+ };
+ properties[2] = {
+ tag: huks.HuksTag.HUKS_TAG_KEY_SIZE,
+ value: huks.HuksKeySize.HUKS_RSA_KEY_SIZE_2048
+ };
+ properties[3] = {
+ tag: huks.HuksTag.HUKS_TAG_PURPOSE,
+ value: huks.HuksKeyPurpose.HUKS_KEY_PURPOSE_VERIFY
+ };
+ properties[4] = {
+ tag: huks.HuksTag.HUKS_TAG_DIGEST,
+ value: huks.HuksKeyDigest.HUKS_DIGEST_SHA256
+ };
+ properties[5] = {
+ tag: huks.HuksTag.HUKS_TAG_PADDING,
+ value: huks.HuksKeyPadding.HUKS_PADDING_PSS
+ };
+ properties[6] = {
+ tag: huks.HuksTag.HUKS_TAG_KEY_GENERATE_TYPE,
+ value: huks.HuksKeyGenerateType.HUKS_KEY_GENERATE_TYPE_DEFAULT
+ };
+ properties[7] = {
+ tag: huks.HuksTag.HUKS_TAG_BLOCK_MODE,
+ value: huks.HuksCipherMode.HUKS_MODE_ECB
+ };
+ let options = {
+ properties: properties
+ };
+
+ try {
+ huks.generateKeyItem(alias, options, function (error, data) {
+ if (error) {
+ console.error(`callback: generateKeyItem failed, code: ${error.code}, msg: ${error.message}`);
+ } else {
+ console.info(`callback: generateKeyItem success`);
+ }
+ });
+ } catch (error) {
+ console.error(`callback: generateKeyItem input arg invalid, code: ${error.code}, msg: ${error.message}`);
+ }
}
async function attestKey() {
- let aliasString = keyAliasString;
- let aliasUint8 = stringToUint8Array(aliasString);
- let properties = new Array();
- properties[0] = {
- tag: huks.HuksTag.HUKS_TAG_ATTESTATION_ID_SEC_LEVEL_INFO,
- value: securityLevel
- };
- properties[1] = {
- tag: huks.HuksTag.HUKS_TAG_ATTESTATION_CHALLENGE,
- value: challenge
- };
- properties[2] = {
- tag: huks.HuksTag.HUKS_TAG_ATTESTATION_ID_VERSION_INFO,
- value: versionInfo
- };
- properties[3] = {
- tag: huks.HuksTag.HUKS_TAG_ATTESTATION_ID_ALIAS,
- value: aliasUint8
- };
- let options = {
- properties: properties
- };
- await generateKey(aliasString);
- huks.attestKey(aliasString, options)
- .then((data) => {
- console.log(`test attestKey data: ${JSON.stringify(data)}`);
- })
- .catch((err) => {
- console.log('test attestKey information: ' + JSON.stringify(err));
- });
+ let aliasString = keyAliasString;
+ let aliasUint8 = stringToUint8Array(aliasString);
+ let properties = new Array();
+ properties[0] = {
+ tag: huks.HuksTag.HUKS_TAG_ATTESTATION_ID_SEC_LEVEL_INFO,
+ value: securityLevel
+ };
+ properties[1] = {
+ tag: huks.HuksTag.HUKS_TAG_ATTESTATION_CHALLENGE,
+ value: challenge
+ };
+ properties[2] = {
+ tag: huks.HuksTag.HUKS_TAG_ATTESTATION_ID_VERSION_INFO,
+ value: versionInfo
+ };
+ properties[3] = {
+ tag: huks.HuksTag.HUKS_TAG_ATTESTATION_ID_ALIAS,
+ value: aliasUint8
+ };
+ let options = {
+ properties: properties
+ };
+ await generateKey(aliasString);
+ try {
+ huks.attestKeyItem(aliasString, options, function (error, data) {
+ if (error) {
+ console.error(`callback: attestKeyItem failed, code: ${error.code}, msg: ${error.message}`);
+ } else {
+ console.info(`callback: attestKeyItem success`);
+ }
+ });
+ } catch (error) {
+ console.error(`callback: attestKeyItem input arg invalid, code: ${error.code}, msg: ${error.message}`);
+ }
}
```
-## huks.importWrappedKey9+
+## huks.attestKeyItem9+
-importWrappedKey(keyAlias: string, wrappingKeyAlias: string, options: HuksOptions, callback: AsyncCallback\) : void
+attestKeyItem(keyAlias: string, options: HuksOptions) : Promise\
+
+获取密钥证书,使用Promise方式异步返回结果 。
+
+**系统能力**:SystemCapability.Security.Huks
+
+**参数:**
+
+| 参数名 | 类型 | 必填 | 说明 |
+| -------- | --------------------------- | ---- | ------------------------------------ |
+| keyAlias | string | 是 | 密钥别名,存放待获取证书密钥的别名。 |
+| options | [HuksOptions](#huksoptions) | 是 | 用于获取证书时指定所需参数与数据。 |
+
+**返回值:**
+
+| 类型 | 说明 |
+| ---------------------------------------------- | --------------------------------------------- |
+| Promise<[HuksReturnResult](#huksreturnresult)> | 不返回err值时表示接口使用成功,其他时为错误。 |
+
+**示例:**
+
+```js
+let securityLevel = stringToUint8Array('sec_level');
+let challenge = stringToUint8Array('challenge_data');
+let versionInfo = stringToUint8Array('version_info');
+let keyAliasString = "key attest";
+
+function stringToUint8Array(str) {
+ var arr = [];
+ for (var i = 0, j = str.length; i < j; ++i) {
+ arr.push(str.charCodeAt(i));
+ }
+ var tmpUint8Array = new Uint8Array(arr);
+ return tmpUint8Array;
+}
+
+async function generateKey(alias) {
+ let properties = new Array();
+ properties[0] = {
+ tag: huks.HuksTag.HUKS_TAG_ALGORITHM,
+ value: huks.HuksKeyAlg.HUKS_ALG_RSA
+ };
+ properties[1] = {
+ tag: huks.HuksTag.HUKS_TAG_KEY_STORAGE_FLAG,
+ value: huks.HuksKeyStorageType.HUKS_STORAGE_PERSISTENT
+ };
+ properties[2] = {
+ tag: huks.HuksTag.HUKS_TAG_KEY_SIZE,
+ value: huks.HuksKeySize.HUKS_RSA_KEY_SIZE_2048
+ };
+ properties[3] = {
+ tag: huks.HuksTag.HUKS_TAG_PURPOSE,
+ value: huks.HuksKeyPurpose.HUKS_KEY_PURPOSE_VERIFY
+ };
+ properties[4] = {
+ tag: huks.HuksTag.HUKS_TAG_DIGEST,
+ value: huks.HuksKeyDigest.HUKS_DIGEST_SHA256
+ };
+ properties[5] = {
+ tag: huks.HuksTag.HUKS_TAG_PADDING,
+ value: huks.HuksKeyPadding.HUKS_PADDING_PSS
+ };
+ properties[6] = {
+ tag: huks.HuksTag.HUKS_TAG_KEY_GENERATE_TYPE,
+ value: huks.HuksKeyGenerateType.HUKS_KEY_GENERATE_TYPE_DEFAULT
+ };
+ properties[7] = {
+ tag: huks.HuksTag.HUKS_TAG_BLOCK_MODE,
+ value: huks.HuksCipherMode.HUKS_MODE_ECB
+ };
+ let options = {
+ properties: properties
+ };
+
+ try {
+ await huks.generateKeyItem(alias, options)
+ .then((data) => {
+ console.info(`promise: generateKeyItem success`);
+ })
+ .catch(error => {
+ console.error(`promise: generateKeyItem failed, code: ${error.code}, msg: ${error.message}`);
+ });
+ } catch (error) {
+ console.error(`promise: generateKeyItem input arg invalid, code: ${error.code}, msg: ${error.message}`);
+ }
+}
+
+async function attestKey() {
+ let aliasString = keyAliasString;
+ let aliasUint8 = stringToUint8Array(aliasString);
+ let properties = new Array();
+ properties[0] = {
+ tag: huks.HuksTag.HUKS_TAG_ATTESTATION_ID_SEC_LEVEL_INFO,
+ value: securityLevel
+ };
+ properties[1] = {
+ tag: huks.HuksTag.HUKS_TAG_ATTESTATION_CHALLENGE,
+ value: challenge
+ };
+ properties[2] = {
+ tag: huks.HuksTag.HUKS_TAG_ATTESTATION_ID_VERSION_INFO,
+ value: versionInfo
+ };
+ properties[3] = {
+ tag: huks.HuksTag.HUKS_TAG_ATTESTATION_ID_ALIAS,
+ value: aliasUint8
+ };
+ let options = {
+ properties: properties
+ };
+ await generateKey(aliasString);
+ try {
+ await huks.attestKeyItem(aliasString, options)
+ .then ((data) => {
+ console.info(`promise: attestKeyItem success`);
+ })
+ .catch(error => {
+ console.error(`promise: attestKeyItem failed, code: ${error.code}, msg: ${error.message}`);
+ });
+ } catch (error) {
+ console.error(`promise: attestKeyItem input arg invalid, code: ${error.code}, msg: ${error.message}`);
+ }
+}
+```
+
+## huks.importWrappedKeyItem9+
+
+importWrappedKeyItem(keyAlias: string, wrappingKeyAlias: string, options: HuksOptions, callback: AsyncCallback\) : void
导入加密密钥,使用Callback方式回调异步返回结果 。
@@ -1004,98 +1460,118 @@ importWrappedKey(keyAlias: string, wrappingKeyAlias: string, options: HuksOption
**参数:**
-| 参数名 | 类型 | 必填 | 说明 |
-| ---------------- | ----------------------------------------- | ---- | -------------------------------------------------- |
-| keyAlias | string | 是 | 密钥别名,存放待导入密钥的别名。 |
-| wrappingKeyAlias | string | 是 | 密钥别名,对应密钥用于解密加密的密钥数据。 |
-| options | [HuksOptions](#huksoptions) | 是 | 用于导入时所需TAG和需要导入的加密的密钥数据。 |
-| callback | AsyncCallback\<[HuksResult](#huksresult)> | 是 | 返回HUKS_SUCCESS时表示接口使用成功,其他时为错误。 |
+| 参数名 | 类型 | 必填 | 说明 |
+| ---------------- | --------------------------- | ---- | --------------------------------------------- |
+| keyAlias | string | 是 | 密钥别名,存放待导入密钥的别名。 |
+| wrappingKeyAlias | string | 是 | 密钥别名,对应密钥用于解密加密的密钥数据。 |
+| options | [HuksOptions](#huksoptions) | 是 | 用于导入时所需TAG和需要导入的加密的密钥数据。 |
+| callback | AsyncCallback\ | 是 | 不返回err值时表示接口使用成功,其他时为错误。 |
**示例:**
```js
+import huks from '@ohos.security.huks';
+
var exportWrappingKey;
var alias1 = "importAlias";
var alias2 = "wrappingKeyAlias";
async function TestGenFunc(alias, options) {
- await genKey(alias, options)
- .then((data) => {
- console.log(`test genKey data: ${JSON.stringify(data)}`);
- })
- .catch((err) => {
- console.log('test genKey err information: ' + JSON.stringify(err));
- });
+ try {
+ await genKey(alias, options)
+ .then((data) => {
+ console.info(`callback: generateKeyItem success`);
+ })
+ .catch(error => {
+ console.error(`callback: generateKeyItem failed, code: ${error.code}, msg: ${error.message}`);
+ });
+ } catch (error) {
+ console.error(`callback: generateKeyItem input arg invalid, code: ${error.code}, msg: ${error.message}`);
+ }
}
function genKey(alias, options) {
- return new Promise((resolve, reject) => {
- huks.generateKey(alias, options, function (err, data) {
- console.log(`test genKey data: ${JSON.stringify(data)}`);
- if (err.code !== 0) {
- console.log('test genKey err information: ' + JSON.stringify(err));
- reject(err);
- } else {
- resolve(data);
- }
+ return new Promise((resolve, reject) => {
+ try {
+ huks.generateKeyItem(alias, options, function (error, data) {
+ if (error) {
+ reject(error);
+ } else {
+ resolve(data);
+ }
+ });
+ } catch (error) {
+ throw(error);
+ }
});
- });
}
async function TestExportFunc(alias, options) {
- await exportKey(alias, options)
- .then((data) => {
- console.log(`test exportKey data: ${JSON.stringify(data)}`);
- })
- .catch((err) => {
- console.log('test exportKey err information: ' + JSON.stringify(err));
- });
+ try {
+ await exportKey(alias, options)
+ .then ((data) => {
+ console.info(`callback: exportKeyItem success, data = ${JSON.stringify(data)}`);
+ exportWrappingKey = data.outData;
+ })
+ .catch(error => {
+ console.error(`callback: exportKeyItem failed, code: ${error.code}, msg: ${error.message}`);
+ });
+ } catch (error) {
+ console.error(`callback: exportKeyItem input arg invalid, code: ${error.code}, msg: ${error.message}`);
+ }
}
-function exportKey(alias, options) {
- return new Promise((resolve, reject) => {
- huks.exportKey(alias, options, function (err, data) {
- console.log(`test exportKey data: ${JSON.stringify(data)}`);
- if (err.code !== 0) {
- console.log('test exportKey err information: ' + JSON.stringify(err));
- reject(err);
- } else {
- exportWrappingKey = data.outData;
- resolve(data);
- }
+function exportKey(alias, options) : Promise {
+ return new Promise((resolve, reject) => {
+ try {
+ huks.exportKeyItem(alias, options, function (error, data) {
+ if (error) {
+ reject(error);
+ } else {
+ resolve(data);
+ }
+ });
+ } catch (error) {
+ throw(error);
+ }
});
- });
}
async function TestImportWrappedFunc(alias, wrappingAlias, options) {
- await importWrappedKey(alias, wrappingAlias, options)
- .then((data) => {
- console.log(`TestImportWrappedFunc data: ${JSON.stringify(data)}`);
- })
- .catch((err) => {
- console.log('test importWrappedKey err information: ' + JSON.stringify(err));
- });
+ try {
+ await importWrappedKey(alias, wrappingAlias, options)
+ .then ((data) => {
+ console.info(`callback: importWrappedKeyItem success`);
+ })
+ .catch(error => {
+ console.error(`callback: importWrappedKeyItem failed, code: ${error.code}, msg: ${error.message}`);
+ });
+ } catch (error) {
+ console.error(`callback: importWrappedKeyItem input arg invalid, code: ${error.code}, msg: ${error.message}`);
+ }
}
function importWrappedKey(alias, wrappingAlias, options) {
- return new Promise((resolve, reject) => {
- huks.importWrappedKey(alias, wrappingAlias, options, function (err, data) {
- console.log(`importWrappedKey data: ${JSON.stringify(data)}`);
- if (err.code !== 0) {
- console.log('importWrappedKey err information: ' + JSON.stringify(err));
- reject(err);
- } else {
- resolve(data);
- }
+ return new Promise((resolve, reject) => {
+ try {
+ huks.importWrappedKeyItem(alias, wrappingAlias, options, function (error, data) {
+ if (error) {
+ reject(error);
+ } else {
+ resolve(data);
+ }
+ });
+ } catch (error) {
+ throw(error);
+ }
});
- });
}
async function TestImportWrappedKeyFunc(
- alias,
- wrappingAlias,
- genOptions,
- importOptions
+ alias,
+ wrappingAlias,
+ genOptions,
+ importOptions
) {
await TestGenFunc(wrappingAlias, genOptions);
await TestExportFunc(wrappingAlias, genOptions);
@@ -1119,72 +1595,80 @@ async function TestImportWrappedKeyFunc(
}
function makeGenerateOptions() {
- var properties = new Array();
- properties[0] = {
- tag: huks.HuksTag.HUKS_TAG_ALGORITHM,
- value: huks.HuksKeyAlg.HUKS_ALG_ECC
- };
- properties[1] = {
- tag: huks.HuksTag.HUKS_TAG_KEY_SIZE,
- value: huks.HuksKeySize.HUKS_ECC_KEY_SIZE_256
- };
- properties[2] = {
- tag: huks.HuksTag.HUKS_TAG_PURPOSE,
- value: huks.HuksKeyPurpose.HUKS_KEY_PURPOSE_UNWRAP
- };
- properties[3] = {
- tag: huks.HuksTag.HUKS_TAG_DIGEST,
- value: huks.HuksKeyDigest.HUKS_DIGEST_SHA256
- };
- var options = {
- properties: properties
- };
- return options;
+ var properties = new Array();
+ properties[0] = {
+ tag: huks.HuksTag.HUKS_TAG_ALGORITHM,
+ value: huks.HuksKeyAlg.HUKS_ALG_ECC
+ };
+ properties[1] = {
+ tag: huks.HuksTag.HUKS_TAG_KEY_SIZE,
+ value: huks.HuksKeySize.HUKS_ECC_KEY_SIZE_256
+ };
+ properties[2] = {
+ tag: huks.HuksTag.HUKS_TAG_PURPOSE,
+ value: huks.HuksKeyPurpose.HUKS_KEY_PURPOSE_UNWRAP
+ };
+ properties[3] = {
+ tag: huks.HuksTag.HUKS_TAG_DIGEST,
+ value: huks.HuksKeyDigest.HUKS_DIGEST_SHA256
+ };
+ properties[4] = {
+ tag: huks.HuksTag.HUKS_TAG_IMPORT_KEY_TYPE,
+ value: huks.HuksImportKeyType.HUKS_KEY_TYPE_KEY_PAIR,
+ };
+ var options = {
+ properties: properties
+ };
+ return options;
};
function makeImportOptions() {
- var properties = new Array();
- properties[0] = {
- tag: huks.HuksTag.HUKS_TAG_ALGORITHM,
- value: huks.HuksKeyAlg.HUKS_ALG_AES
- };
- properties[1] = {
- tag: huks.HuksTag.HUKS_TAG_KEY_SIZE,
- value: huks.HuksKeySize.HUKS_AES_KEY_SIZE_256
- };
- properties[2] = {
- tag: huks.HuksTag.HUKS_TAG_PURPOSE,
- value: huks.HuksKeyPurpose.HUKS_KEY_PURPOSE_ENCRYPT | huks.HuksKeyPurpose.HUKS_KEY_PURPOSE_DECRYPT
- };
- properties[3] = {
- tag: huks.HuksTag.HUKS_TAG_BLOCK_MODE,
- value: huks.HuksCipherMode.HUKS_MODE_CBC
- };
- properties[4] = {
- tag: huks.HuksTag.HUKS_TAG_UNWRAP_ALGORITHM_SUITE,
- value: huks.HuksUnwrapSuite.HUKS_UNWRAP_SUITE_ECDH_AES_256_GCM_NOPADDING
- };
- var options = {
- properties: properties
- };
- return options;
+ var properties = new Array();
+ properties[0] = {
+ tag: huks.HuksTag.HUKS_TAG_ALGORITHM,
+ value: huks.HuksKeyAlg.HUKS_ALG_AES
+ };
+ properties[1] = {
+ tag: huks.HuksTag.HUKS_TAG_KEY_SIZE,
+ value: huks.HuksKeySize.HUKS_AES_KEY_SIZE_256
+ };
+ properties[2] = {
+ tag: huks.HuksTag.HUKS_TAG_PURPOSE,
+ value: huks.HuksKeyPurpose.HUKS_KEY_PURPOSE_ENCRYPT | huks.HuksKeyPurpose.HUKS_KEY_PURPOSE_DECRYPT
+ };
+ properties[3] = {
+ tag: huks.HuksTag.HUKS_TAG_BLOCK_MODE,
+ value: huks.HuksCipherMode.HUKS_MODE_CBC
+ };
+ properties[4] = {
+ tag: huks.HuksTag.HUKS_TAG_PADDING,
+ value: huks.HuksKeyPadding.HUKS_PADDING_NONE
+ };
+ properties[5] = {
+ tag: huks.HuksTag.HUKS_TAG_UNWRAP_ALGORITHM_SUITE,
+ value: huks.HuksUnwrapSuite.HUKS_UNWRAP_SUITE_ECDH_AES_256_GCM_NOPADDING
+ };
+ var options = {
+ properties: properties
+ };
+ return options;
};
function huksImportWrappedKey() {
- var genOptions = makeGenerateOptions();
- var importOptions = makeImportOptions();
- TestImportWrappedKeyFunc(
- alias1,
- alias2,
- genOptions,
- importOptions
- );
+ var genOptions = makeGenerateOptions();
+ var importOptions = makeImportOptions();
+ TestImportWrappedKeyFunc(
+ alias1,
+ alias2,
+ genOptions,
+ importOptions
+ );
}
```
-## huks.importWrappedKey9+
+## huks.importWrappedKeyItem9+
-importWrappedKey(keyAlias: string, wrappingKeyAlias: string, options: HuksOptions) : Promise\
+importWrappedKeyItem(keyAlias: string, wrappingKeyAlias: string, options: HuksOptions) : Promise\
导入加密密钥,使用Promise方式异步返回结果。
@@ -1198,32 +1682,33 @@ importWrappedKey(keyAlias: string, wrappingKeyAlias: string, options: HuksOption
| wrappingKeyAlias | string | 是 | 密钥别名,对应密钥用于解密加密的密钥数据。 |
| options | [HuksOptions](#huksoptions) | 是 | 用于导入时所需TAG和需要导入的加密的密钥数据。 |
-**返回值:**
-
-| 类型 | 说明 |
-| ----------------------------------- | -------------------------------------------------- |
-| Promise\<[HuksResult](#huksresult)> | 返回HUKS_SUCCESS时表示接口使用成功,其他时为错误。 |
-
**示例:**
```js
/* 处理流程与callback类似,主要差异点为如下函数: */
async function TestImportWrappedFunc(alias, wrappingAlias, options) {
- var result = await huks.importWrappedKey(alias, wrappingAlias, options);
- if (result.errorCode === 0) {
- console.log('test importWrappedKey success');
- } else {
- console.log('test importWrappedKey fail');
- }
+ try {
+ await huks.importWrappedKeyItem(alias, wrappingAlias, options)
+ .then ((data) => {
+ console.info(`promise: importWrappedKeyItem success`);
+ })
+ .catch(error => {
+ console.error(`promise: importWrappedKeyItem failed, code: ${error.code}, msg: ${error.message}`);
+ });
+ } catch (error) {
+ console.error(`promise: importWrappedKeyItem input arg invalid, code: ${error.code}, msg: ${error.message}`);
+ }
}
```
-## huks.exportKey
+## huks.exportKey(deprecated)
exportKey(keyAlias: string, options: HuksOptions, callback: AsyncCallback\) : void
导出密钥,使用Callback方式回调异步返回的结果。
+> **说明:** 从API Version 9开始废弃,建议使用[huks.exportKeyItem9+](#huksexportkeyitem9)替代。
+
**系统能力**:SystemCapability.Security.Huks
**参数:**
@@ -1245,12 +1730,14 @@ var emptyOptions = {
huks.exportKey(keyAlias, emptyOptions, function (err, data){});
```
-## huks.exportKey
+## huks.exportKey(deprecated)
exportKey(keyAlias: string, options: HuksOptions) : Promise\
导出密钥,使用Promise方式回调异步返回的结果。
+> **说明:** 从API Version 9开始废弃,建议使用[huks.exportKeyItem9+](#huksexportkeyitem9-1))替代。
+
**系统能力**:SystemCapability.Security.Huks
**参数:**
@@ -1277,12 +1764,93 @@ var emptyOptions = {
var result = huks.exportKey(keyAlias, emptyOptions);
```
-## huks.getKeyProperties
+## huks.exportKeyItem9+
+
+exportKeyItem(keyAlias: string, options: HuksOptions, callback: AsyncCallback\) : void
+
+导出密钥,使用Callback方式回调异步返回的结果。
+
+**系统能力**:SystemCapability.Security.Huks
+
+**参数:**
+
+| 参数名 | 类型 | 必填 | 说明 |
+| -------- | ---------------------------------------------------- | ---- | ------------------------------------------------------------ |
+| keyAlias | string | 是 | 密钥别名,应与所用密钥生成时使用的别名相同。 |
+| options | [HuksOptions](#huksoptions) | 是 | 空对象(此处传空即可)。 |
+| callback | AsyncCallback<[HuksReturnResult](#huksreturnresult)> | 是 | 返回HUKS_SUCCESS时表示接口使用成功,其他时为错误。outData:返回从密钥中导出的公钥。 |
+
+**示例:**
+
+```js
+/* 此处options选择emptyOptions来传空 */
+var keyAlias = 'keyAlias';
+var emptyOptions = {
+ properties: []
+};
+try {
+ huks.exportKeyItem(keyAlias, emptyOptions, function (error, data) {
+ if (error) {
+ console.error(`callback: exportKeyItem failed, code: ${error.code}, msg: ${error.message}`);
+ } else {
+ console.info(`callback: exportKeyItem success, data = ${JSON.stringify(data)}`);
+ }
+ });
+} catch (error) {
+ console.error(`callback: exportKeyItem input arg invalid, code: ${error.code}, msg: ${error.message}`);
+}
+```
+
+## huks.exportKeyItem9+
+
+exportKeyItem(keyAlias: string, options: HuksOptions) : Promise\
+
+导出密钥,使用Promise方式回调异步返回的结果。
+
+**系统能力**:SystemCapability.Security.Huks
+
+**参数:**
+
+| 参数名 | 类型 | 必填 | 说明 |
+| -------- | --------------------------- | ---- | -------------------------------------------- |
+| keyAlias | string | 是 | 密钥别名,应与所用密钥生成时使用的别名相同。 |
+| options | [HuksOptions](#huksoptions) | 是 | 空对象(此处传空即可)。 |
+
+**返回值:**
+
+| 类型 | 说明 |
+| ---------------------------------------------- | ------------------------------------------------------------ |
+| Promise<[HuksReturnResult](#huksreturnresult)> | 不返回err值时表示接口使用成功,其他时为错误。outData:返回从密钥中导出的公钥。 |
+
+**示例:**
+
+```js
+/* 此处options选择emptyOptions来传空 */
+var keyAlias = 'keyAlias';
+var emptyOptions = {
+ properties: []
+};
+try {
+ huks.exportKeyItem(keyAlias, emptyOptions)
+ .then ((data) => {
+ console.info(`promise: exportKeyItem success, data = ${JSON.stringify(data)}`);
+ })
+ .catch(error => {
+ console.error(`promise: exportKeyItem failed, code: ${error.code}, msg: ${error.message}`);
+ });
+} catch (error) {
+ console.error(`promise: exportKeyItem input arg invalid, code: ${error.code}, msg: ${error.message}`);
+}
+```
+
+## huks.getKeyProperties(deprecated)
getKeyProperties(keyAlias: string, options: HuksOptions, callback: AsyncCallback\) : void
获取密钥属性,使用Callback回调异步返回结果。
+> **说明:** 从API Version 9开始废弃,建议使用[huks.getKeyItemProperties9+](#huksgetkeyitemproperties9)替代。
+
**系统能力**:SystemCapability.Security.Huks
**参数:**
@@ -1304,12 +1872,14 @@ var emptyOptions = {
huks.getKeyProperties(keyAlias, emptyOptions, function (err, data){});
```
-## huks.getKeyProperties
+## huks.getKeyProperties(deprecated)
getKeyProperties(keyAlias: string, options: HuksOptions) : Promise\
获取密钥属性,使用Promise回调异步返回结果。
+> **说明:** 从API Version 9开始废弃,建议使用[huks.getKeyItemProperties9+](#huksgetkeyitemproperties9-1)替代。
+
**系统能力**:SystemCapability.Security.Huks
**参数:**
@@ -1336,7 +1906,86 @@ var emptyOptions = {
var result = huks.getKeyProperties(keyAlias, emptyOptions);
```
-## huks.isKeyExist
+## huks.getKeyItemProperties9+
+
+getKeyItemProperties(keyAlias: string, options: HuksOptions, callback: AsyncCallback\) : void
+
+获取密钥属性,使用Callback回调异步返回结果。
+
+**系统能力**:SystemCapability.Security.Huks
+
+**参数:**
+
+| 参数名 | 类型 | 必填 | 说明 |
+| -------- | ---------------------------------------------------- | ---- | ------------------------------------------------------------ |
+| keyAlias | string | 是 | 密钥别名,应与所用密钥生成时使用的别名相同。 |
+| options | [HuksOptions](#huksoptions) | 是 | 空对象(此处传空即可)。 |
+| callback | AsyncCallback<[HuksReturnResult](#huksreturnresult)> | 是 | errorCode:返回HUKS_SUCCESS时表示接口使用成功,其他时为错误。 |
+
+**示例:**
+
+```js
+/* 此处options选择emptyOptions来传空 */
+var keyAlias = 'keyAlias';
+var emptyOptions = {
+ properties: []
+};
+try {
+ huks.getKeyItemProperties(keyAlias, emptyOptions, function (error, data) {
+ if (error) {
+ console.error(`callback: getKeyItemProperties failed, code: ${error.code}, msg: ${error.message}`);
+ } else {
+ console.info(`callback: getKeyItemProperties success, data = ${JSON.stringify(data)}`);
+ }
+ });
+} catch (error) {
+ console.error(`callback: getKeyItemProperties input arg invalid, code: ${error.code}, msg: ${error.message}`);
+}
+```
+
+## huks.getKeyItemProperties9+
+
+getKeyItemProperties(keyAlias: string, options: HuksOptions) : Promise\
+
+获取密钥属性,使用Promise回调异步返回结果。
+
+**系统能力**:SystemCapability.Security.Huks
+
+**参数:**
+
+| 参数名 | 类型 | 必填 | 说明 |
+| -------- | --------------------------- | ---- | -------------------------------------------- |
+| keyAlias | string | 是 | 密钥别名,应与所用密钥生成时使用的别名相同。 |
+| options | [HuksOptions](#huksoptions) | 是 | 空对象(此处传空即可)。 |
+
+**返回值:**
+
+| 类型 | 说明 |
+| ----------------------------------------------- | ------------------------------------------------------------ |
+| Promise\<[HuksReturnResult](#huksreturnresult)> | 不返回err值时表示接口使用成功,其他时为错误。properties:返回值为生成密钥时所需参数。 |
+
+**示例:**
+
+```js
+/* 此处options选择emptyOptions来传空 */
+var keyAlias = 'keyAlias';
+var emptyOptions = {
+ properties: []
+};
+try {
+ huks.getKeyItemProperties(keyAlias, emptyOptions)
+ .then ((data) => {
+ console.info(`promise: getKeyItemProperties success, data = ${JSON.stringify(data)}`);
+ })
+ .catch(error => {
+ console.error(`promise: getKeyItemProperties failed, code: ${error.code}, msg: ${error.message}`);
+ });
+} catch (error) {
+ console.error(`promise: getKeyItemProperties input arg invalid, code: ${error.code}, msg: ${error.message}`);
+}
+```
+
+## huks.isKeyExist(deprecated)
isKeyExist(keyAlias: string, options: HuksOptions, callback: AsyncCallback\) : void
@@ -1363,7 +2012,7 @@ var emptyOptions = {
huks.isKeyExist(keyAlias, emptyOptions, function (err, data){});
```
-## huks.isKeyExist
+## huks.isKeyExist(deprecated)
isKeyExist(keyAlias: string, options: HuksOptions) : Promise\
@@ -1395,15 +2044,94 @@ var emptyOptions = {
var result = huks.isKeyExist(keyAlias, emptyOptions);
```
+## huks.isKeyItemExist9+
+
+isKeyItemExist(keyAlias: string, options: HuksOptions, callback: AsyncCallback\) : void
+
+判断密钥是否存在,使用Callback回调异步返回结果 。
+
+**系统能力**:SystemCapability.Security.Huks
+
+**参数:**
+
+| 参数名 | 类型 | 必填 | 说明 |
+| -------- | --------------------------- | ---- | --------------------------------------- |
+| keyAlias | string | 是 | 所需查找的密钥的别名。 |
+| options | [HuksOptions](#huksoptions) | 是 | 空对象(此处传空即可)。 |
+| callback | AsyncCallback\ | 是 | FALSE代表密钥不存在,TRUE代表密钥存在。 |
+
+**示例:**
+
+```js
+/* 此处options选择emptyOptions来传空 */
+var keyAlias = 'keyAlias';
+var emptyOptions = {
+ properties: []
+};
+try {
+ huks.isKeyItemExist(keyAlias, emptyOptions, function (error, data) {
+ if (error) {
+ console.info(`callback: isKeyItemExist success, data = ${JSON.stringify(data)}`);
+ } else {
+ console.error(`callback: isKeyItemExist failed, code: ${error.code}, msg: ${error.message}`);
+ }
+ });
+} catch (error) {
+ console.error(`promise: isKeyItemExist input arg invalid, code: ${error.code}, msg: ${error.message}`);
+}
+```
+
+## huks.isKeyItemExist9+
+isKeyItemExist(keyAlias: string, options: HuksOptions) : Promise\
-## huks.init
+判断密钥是否存在,使用Promise回调异步返回结果 。
+
+**系统能力**:SystemCapability.Security.Huks
+
+**参数:**
+
+| 参数名 | 类型 | 必填 | 说明 |
+| -------- | --------------------------- | ---- | ------------------------ |
+| keyAlias | string | 是 | 所需查找的密钥的别名。 |
+| options | [HuksOptions](#huksoptions) | 是 | 空对象(此处传空即可)。 |
+
+**返回值:**
+
+| 类型 | 说明 |
+| ----------------- | --------------------------------------- |
+| Promise\ | FALSE代表密钥不存在,TRUE代表密钥存在。 |
+
+**示例:**
+
+```js
+/* 此处options选择emptyOptions来传空 */
+var keyAlias = 'keyAlias';
+var emptyOptions = {
+ properties: []
+};
+try {
+ huks.isKeyItemExist(keyAlias, emptyOptions)
+ .then ((data) => {
+ console.info(`promise: isKeyItemExist success, data = ${JSON.stringify(data)}`);
+ })
+ .catch(error => {
+ console.error(`promise: isKeyItemExist failed, code: ${error.code}, msg: ${error.message}`);
+ });
+} catch (error) {
+ console.error(`promise: isKeyItemExist input arg invalid, code: ${error.code}, msg: ${error.message}`);
+}
+```
+
+## huks.init(deprecated)
init(keyAlias: string, options: HuksOptions, callback: AsyncCallback\) : void
init操作密钥接口,使用Callback回调异步返回结果 。
-**系统能力**:SystemCapability.Security.Huks
+> **说明:** 从API Version 9开始废弃,建议使用[huks.initSession9+](#huksinitsession9-1)替代。
+
+系统能力**:SystemCapability.Security.Huks
**参数:**
@@ -1414,13 +2142,15 @@ init操作密钥接口,使用Callback回调异步返回结果 。
| callback | AsyncCallback\<[HuksHandle](#hukshandle)> | 是 | 将Init操作操作返回的handle添加到密钥管理系统的回调。 |
-## huks.init
+## huks.init(deprecated)
init(keyAlias: string, options: HuksOptions) : Promise\
init操作密钥接口,使用Promise方式异步返回结果。
-**系统能力**:SystemCapability.Security.Huks
+> **说明:** 从API Version 9开始废弃,建议使用[huks.initSession9+](#huksinitsession9-1)替代。
+
+系统能力**:SystemCapability.Security.Huks
**参数:**
@@ -1430,14 +2160,62 @@ init操作密钥接口,使用Promise方式异步返回结果。
| options | [HuksOptions](#huksoptions) | 是 | Init参数集合。 |
| promise | Promise\<[HuksHandle](#hukshandle)> | 是 | 将Init操作返回的handle添加到密钥管理系统的回调。 |
+## huks.initSession9+
+
+initSession(keyAlias: string, options: HuksOptions, callback: AsyncCallback\) : void
+
+initSession操作密钥接口,使用Callback回调异步返回结果 。
+
+系统能力**:SystemCapability.Security.Huks
+
+**参数:**
+
+| 参数名 | 类型 | 必填 | 说明 |
+| -------- | ------------------------------------------------------- | ---- | ---------------------------------------------------- |
+| keyAlias | string | 是 | Init操作密钥的别名。 |
+| options | [HuksOptions](#huksoptions) | 是 | Init操作的参数集合。 |
+| callback | AsyncCallback\<[HuksSessionHandle](#hukssessionhandle)> | 是 | 将Init操作操作返回的handle添加到密钥管理系统的回调。 |
+
+
+## huks.initSession9+
+
+initSession(keyAlias: string, options: HuksOptions) : Promise\
+
+initSession操作密钥接口,使用Promise方式异步返回结果。
+
+系统能力**:SystemCapability.Security.Huks
+
+**参数:**
+
+| 参数名 | 类型 | 必填 | 说明 |
+| -------- | ------------------------------------------------- | ---- | ------------------------------------------------ |
+| keyAlias | string | 是 | Init操作密钥的别名。 |
+| options | [HuksOptions](#huksoptions) | 是 | Init参数集合。 |
+| promise | Promise\<[HuksSessionHandle](#hukssessionhandle)> | 是 | 将Init操作返回的handle添加到密钥管理系统的回调。 |
+
+## huks.update(deprecated)
+
+update(handle: number, options: HuksOptions, callback: AsyncCallback\) : void
+
+update操作密钥接口,使用Callback回调异步返回结果 。
+
+**系统能力**:SystemCapability.Security.Huks
+
+**参数:**
+
+| 参数名 | 类型 | 必填 | 说明 |
+| -------- | ----------------------------------------- | ---- | -------------------------------------------- |
+| handle | number | 是 | Update操作的handle。 |
+| options | [HuksOptions](#huksoptions) | 是 | Update的参数集合。 |
+| callback | AsyncCallback\<[HuksResult](#huksresult)> | 是 | 将Update操作的结果添加到密钥管理系统的回调。 |
## huks.update(deprecated)
-update(handle: number, token?: Uint8Array, options: HuksOptions, callback: AsyncCallback\) : void
+update(handle: number, options: HuksOptions, token: Uint8Array, callback: AsyncCallback\) : void
update操作密钥接口,使用Callback回调异步返回结果 。
-> **说明:** 从API Version 9开始废弃,建议使用[huks.update9+](#huksupdate9-1)替代。
+> **说明:** 从API Version 9开始废弃,建议使用[huks.updateSession9+](#huksupdatesession9)替代。
**系统能力**: SystemCapability.Security.Huks
@@ -1452,11 +2230,11 @@ update操作密钥接口,使用Callback回调异步返回结果 。
## huks.update(deprecated)
-update(handle: number, token?: Uint8Array, options: HuksOptions) : Promise\
+update(handle: number, options: HuksOptions, token?: Uint8Array) : Promise\
update操作密钥接口,使用Promise方式异步返回结果。
-> **说明:** 从API Version 9开始废弃,建议使用[huks.update9+](#huksupdate9)替代。
+> **说明:** 从API Version 9开始废弃,建议使用[huks.updateSession9+](#huksupdatesession9-1)替代。
**系统能力**: SystemCapability.Security.Huks
@@ -1469,63 +2247,65 @@ update操作密钥接口,使用Promise方式异步返回结果。
| options | [HuksOptions](#huksoptions) | 是 | Update操作的参数集合。 |
| promise | Promise\<[HuksResult](#huksresult)> | 是 | 将Update操作的结果添加到密钥管理系统的回调。 |
-## huks.update9+
+## huks.updateSession9+
-update(handle: number, options: HuksOptions, callback: AsyncCallback\) : void
+updateSession(handle: number, options: HuksOptions, callback: AsyncCallback\) : void
-update操作密钥接口,使用Callback回调异步返回结果 。
+updateSession操作密钥接口,使用Callback回调异步返回结果 。
**系统能力**:SystemCapability.Security.Huks
**参数:**
-| 参数名 | 类型 | 必填 | 说明 |
-| -------- | ----------------------------------------- | ---- | -------------------------------------------- |
-| handle | number | 是 | Update操作的handle。 |
-| options | [HuksOptions](#huksoptions) | 是 | Update的参数集合。 |
-| callback | AsyncCallback\<[HuksResult](#huksresult)> | 是 | 将Update操作的结果添加到密钥管理系统的回调。 |
+| 参数名 | 类型 | 必填 | 说明 |
+| -------- | ---------------------------------------------------- | ---- | -------------------------------------------- |
+| handle | number | 是 | Update操作的handle。 |
+| options | [HuksOptions](#huksoptions) | 是 | Update的参数集合。 |
+| callback | AsyncCallback<[HuksReturnResult](#huksreturnresult)> | 是 | 将Update操作的结果添加到密钥管理系统的回调。 |
-## huks.update9+
+## huks.updateSession9+
-update(handle: number, options: HuksOptions, token: Uint8Array, callback: AsyncCallback\) : void
+updateSession(handle: number, options: HuksOptions, token: Uint8Array, callback: AsyncCallback\) : void
-update操作密钥接口,使用Callback回调异步返回结果 。
+updateSession操作密钥接口,使用Callback回调异步返回结果 。
**系统能力**:SystemCapability.Security.Huks
**参数:**
-| 参数名 | 类型 | 必填 | 说明 |
-| -------- | ----------------------------------------- | ---- | -------------------------------------------- |
-| handle | number | 是 | Update操作的handle。 |
-| options | [HuksOptions](#huksoptions) | 是 | Update操作的参数集合。 |
-| token | Uint8Array | 是 | Update操作的token。 |
-| callback | AsyncCallback\<[HuksResult](#huksresult)> | 是 | 将Update操作的结果添加到密钥管理系统的回调。 |
+| 参数名 | 类型 | 必填 | 说明 |
+| -------- | ---------------------------------------------------- | ---- | -------------------------------------------- |
+| handle | number | 是 | Update操作的handle。 |
+| options | [HuksOptions](#huksoptions) | 是 | Update操作的参数集合。 |
+| token | Uint8Array | 是 | Update操作的token。 |
+| callback | AsyncCallback<[HuksReturnResult](#huksreturnresult)> | 是 | 将Update操作的结果添加到密钥管理系统的回调。 |
-## huks.update9+
+## huks.updateSession9+
-update(handle: number, options: HuksOptions, token?: Uint8Array) : Promise\
+updateSession(handle: number, options: HuksOptions, token?: Uint8Array) : Promise\
-update操作密钥接口,使用Promise方式异步返回结果。
+uupdateSession操作密钥接口,使用Promise方式异步返回结果。
**系统能力**:SystemCapability.Security.Huks
**参数:**
-| 参数名 | 类型 | 必填 | 说明 |
-| ------- | ----------------------------------- | ---- | -------------------------------------------- |
-| handle | number | 是 | Update操作的handle。 |
-| options | [HuksOptions](#huksoptions) | 是 | Update操作的参数集合。 |
-| token | Uint8Array | 否 | Update操作的token。 |
-| promise | Promise\<[HuksResult](#huksresult)> | 是 | 将Update操作的结果添加到密钥管理系统的回调。 |
+| 参数名 | 类型 | 必填 | 说明 |
+| ------- | ---------------------------------------------- | ---- | -------------------------------------------- |
+| handle | number | 是 | Update操作的handle。 |
+| options | [HuksOptions](#huksoptions) | 是 | Update操作的参数集合。 |
+| token | Uint8Array | 否 | Update操作的token。 |
+| promise | Promise<[HuksReturnResult](#huksreturnresult)> | 是 | 将Update操作的结果添加到密钥管理系统的回调。 |
-## huks.finish
+## huks.finish(deprecated)
finish(handle: number, options: HuksOptions, callback: AsyncCallback\) : void
finish操作密钥接口,使用Callback回调异步返回结果 。
+> **说明:** 从API Version 9开始废弃,建议使用[huks.finishSession9+](#huksfinishsession9)替代。
+
**系统能力**:SystemCapability.Security.Huks
**参数:**
@@ -1537,12 +2317,14 @@ finish操作密钥接口,使用Callback回调异步返回结果 。
| callback | AsyncCallback\<[HuksResult](#huksresult)> | 是 | 将Finish操作的结果添加到密钥管理系统的回调。 |
-## huks.finish
+## huks.finish(deprecated)
finish(handle: number, options: HuksOptions) : Promise\
finish操作密钥接口,使用Promise方式异步返回结果。
+> **说明:** 从API Version 9开始废弃,建议使用[huks.updateSession9+](#huksfinishsession9-1)替代。
+
**系统能力**:SystemCapability.Security.Huks
**参数:**
@@ -1553,47 +2335,66 @@ finish操作密钥接口,使用Promise方式异步返回结果。
| options | [HuksOptions](#huksoptions) | 是 | Finish操作的参数集合。 |
| promise | Promise\<[HuksResult](#huksresult)> | 是 | promise实例,用于获取异步返回结果。 |
-## huks.finish9+
+## huks.finishSession9+
-finish(handle: number, options: HuksOptions, token: Uint8Array, callback: AsyncCallback\) : void
+finishSession(handle: number, options: HuksOptions, callback: AsyncCallback\) : void
-finish操作密钥接口,使用Callback回调异步返回结果 。
+finishSession操作密钥接口,使用Callback回调异步返回结果 。
**系统能力**:SystemCapability.Security.Huks
**参数:**
-| 参数名 | 类型 | 必填 | 说明 |
-| -------- | ----------------------------------------- | ---- | -------------------------------------------- |
-| handle | number | 是 | Finish操作的handle。 |
-| options | [HuksOptions](#huksoptions) | 是 | Finish的参数集合。 |
-| token | Uint8Array | 是 | Finish操作的token。 |
-| callback | AsyncCallback\<[HuksResult](#huksresult)> | 是 | 将Finish操作的结果添加到密钥管理系统的回调。 |
+| 参数名 | 类型 | 必填 | 说明 |
+| -------- | ---------------------------------------------------- | ---- | -------------------------------------------- |
+| handle | number | 是 | Finish操作的handle。 |
+| options | [HuksOptions](#huksoptions) | 是 | Finish的参数集合。 |
+| token | Uint8Array | 是 | Finish操作的token。 |
+| callback | AsyncCallback<[HuksReturnResult](#huksreturnresult)> | 是 | 将Finish操作的结果添加到密钥管理系统的回调。 |
+## huks.finishSession9+
-## huks.finish9+
+finishSession(handle: number, options: HuksOptions, token: Uint8Array, callback: AsyncCallback\) : void
-finish(handle: number, options: HuksOptions, token?: Uint8Array) : Promise\
+finishSession操作密钥接口,使用Callback回调异步返回结果 。
-finish操作密钥接口,使用Promise方式异步返回结果。
+**系统能力**:SystemCapability.Security.Huks
+
+**参数:**
+
+| 参数名 | 类型 | 必填 | 说明 |
+| -------- | ----------------------------------------------------- | ---- | -------------------------------------------- |
+| handle | number | 是 | Finish操作的handle。 |
+| options | [HuksOptions](#huksoptions) | 是 | Finish的参数集合。 |
+| token | Uint8Array | 是 | Finish操作的token。 |
+| callback | AsyncCallback\<[HuksReturnResult](#huksreturnresult)> | 是 | 将Finish操作的结果添加到密钥管理系统的回调。 |
+
+
+## huks.finishSession9+
+
+finishSession(handle: number, options: HuksOptions, token?: Uint8Array) : Promise\
+
+finishSession操作密钥接口,使用Promise方式异步返回结果。
**系统能力**:SystemCapability.Security.Huks
**参数:**
-| 参数名 | 类型 | 必填 | 说明 |
-| ------- | ----------------------------------- | ---- | ----------------------------------- |
-| handle | number | 是 | Finish操作的handle。 |
-| options | [HuksOptions](#huksoptions) | 是 | Finish操作的参数集合。 |
-| token | Uint8Array | 否 | Finish操作的token。 |
-| promise | Promise\<[HuksResult](#huksresult)> | 是 | promise实例,用于获取异步返回结果。 |
+| 参数名 | 类型 | 必填 | 说明 |
+| ------- | ----------------------------------------------- | ---- | ----------------------------------- |
+| handle | number | 是 | Finish操作的handle。 |
+| options | [HuksOptions](#huksoptions) | 是 | Finish操作的参数集合。 |
+| token | Uint8Array | 否 | Finish操作的token。 |
+| promise | Promise\<[HuksReturnResult](#huksreturnresult)> | 是 | promise实例,用于获取异步返回结果。 |
-## huks.abort
+## huks.abort(deprecated)
abort(handle: number, options: HuksOptions, callback: AsyncCallback\) : void
abort操作密钥接口,使用Callback回调异步返回结果 。
+> **说明:** 从API Version 9开始废弃,建议使用[huks.abortSession9+](#huksabortsession9)替代。
+
**系统能力**:SystemCapability.Security.Huks
**参数:**
@@ -1612,19 +2413,6 @@ abort操作密钥接口,使用Callback回调异步返回结果 。
*
* 以下以RSA1024密钥的callback操作使用为例
*/
-import router from '@system.router';
-import huks from '@ohos.security.huks';
-
-async function routePage() {
- let options = {
- uri: 'pages/second'
- }
- try {
- await router.push(options)
- } catch (err) {
- console.error(`fail callback, code: ${err.code}, msg: ${err.msg}`)
- }
-}
var keyalias = "HuksDemoRSA";
var properties = new Array();
var options = {
@@ -1708,112 +2496,16 @@ async function huksAbort() {
});
console.log(resultMessage);
}
-
-@Entry
-@Component
-struct Index {
- build() {
- Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) {
- Text('Hello World')
- .fontSize(50)
- .fontWeight(FontWeight.Bold)
- Button() {
- Text('Tocallback')
- .fontSize(25)
- .fontWeight(FontWeight.Bold)
- }.type(ButtonType.Capsule)
- .margin({
- top: 20
- })
- .width('50%')
- .height('10%')
- .backgroundColor('#0D9FFB')
- .onClick(() => {
- routePage()
- })
- Button() {
- Text('generateKey')
- .fontSize(25)
- .fontWeight(FontWeight.Bold)
- }.type(ButtonType.Capsule)
- .margin({
- top: 20
- })
- .width('50%')
- .height('10%')
- .backgroundColor('#0D9FFB')
- .onClick(() => {
- generateKey()
- })
- Button() {
- Text('Init')
- .fontSize(25)
- .fontWeight(FontWeight.Bold)
- }.type(ButtonType.Capsule)
- .margin({
- top: 20
- })
- .width('50%')
- .height('10%')
- .backgroundColor('#0D9FFB')
- .onClick(() => {
- huksInit()
- })
- Button() {
- Text('Update')
- .fontSize(25)
- .fontWeight(FontWeight.Bold)
- }.type(ButtonType.Capsule)
- .margin({
- top: 20
- })
- .width('50%')
- .height('10%')
- .backgroundColor('#0D9FFB')
- .onClick(() => {
- huksUpdate()
- })
- Button() {
- Text('Finish')
- .fontSize(25)
- .fontWeight(FontWeight.Bold)
- }.type(ButtonType.Capsule)
- .margin({
- top: 20
- })
- .width('50%')
- .height('10%')
- .backgroundColor('#0D9FFB')
- .onClick(() => {
- huksFinish()
- })
- Button() {
- Text('Abort')
- .fontSize(25)
- .fontWeight(FontWeight.Bold)
- }.type(ButtonType.Capsule)
- .margin({
- top: 20
- })
- .width('50%')
- .height('10%')
- .backgroundColor('#0D9FFB')
- .onClick(() => {
- huksAbort()
- })
- }
- .width('100%')
- .height('100%')
- }
-}
```
-## huks.abort
+## huks.abort(deprecated)
abort(handle: number, options: HuksOptions) : Promise\;
abort操作密钥接口,使用Promise方式异步返回结果。
+> **说明:** 从API Version 9开始废弃,建议使用[huks.abortSession9+](#huksabortsession9-1)替代。
+
**系统能力**:SystemCapability.Security.Huks
**参数:**
@@ -1832,20 +2524,6 @@ abort操作密钥接口,使用Promise方式异步返回结果。
*
* 以下以RSA1024密钥的promise操作使用为例
*/
-import router from '@system.router';
-import huks from '@ohos.security.huks';
-
-async function routePage() {
- let options = {
- uri: 'pages/second'
- }
- try {
- await router.push(options)
- } catch (err) {
- console.error(`fail callback, code: ${err.code}, msg: ${err.msg}`)
- }
-}
-
var keyalias = "HuksDemoRSA";
var properties = new Array();
var options = {
@@ -1935,102 +2613,295 @@ function huksAbort() {
});
});
}
-@Entry
-@Component
-struct Index {
- build() {
- Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) {
- Text('Hello World')
- .fontSize(50)
- .fontWeight(FontWeight.Bold)
- Button() {
- Text('to Promise')
- .fontSize(20)
- .fontWeight(FontWeight.Bold)
- }.type(ButtonType.Capsule)
- .margin({
- top: 20
- })
- .width('50%')
- .height('10%')
- .backgroundColor('#0D9FFB')
- .onClick(() => {
- router.back()
- })
- Button() {
- Text('generateKey')
- .fontSize(25)
- .fontWeight(FontWeight.Bold)
- }.type(ButtonType.Capsule)
- .margin({
- top: 20
- })
- .width('50%')
- .height('10%')
- .backgroundColor('#0D9FFB')
- .onClick(() => {
- generateKey()
- })
- Button() {
- Text('Init')
- .fontSize(25)
- .fontWeight(FontWeight.Bold)
- }.type(ButtonType.Capsule)
- .margin({
- top: 20
- })
- .width('50%')
- .height('10%')
- .backgroundColor('#0D9FFB')
- .onClick(() => {
- huksInit()
- })
- Button() {
- Text('Update')
- .fontSize(25)
- .fontWeight(FontWeight.Bold)
- }.type(ButtonType.Capsule)
- .margin({
- top: 20
- })
- .width('50%')
- .height('10%')
- .backgroundColor('#0D9FFB')
- .onClick(() => {
- huksUpdate()
- })
- Button() {
- Text('Finish')
- .fontSize(25)
- .fontWeight(FontWeight.Bold)
- }.type(ButtonType.Capsule)
- .margin({
- top: 20
- })
- .width('50%')
- .height('10%')
- .backgroundColor('#0D9FFB')
- .onClick(() => {
- huksFinish()
- })
- Button() {
- Text('Abort')
- .fontSize(25)
- .fontWeight(FontWeight.Bold)
- }.type(ButtonType.Capsule)
- .margin({
- top: 20
- })
- .width('50%')
- .height('10%')
- .backgroundColor('#0D9FFB')
- .onClick(() => {
- huksAbort()
- })
+```
+
+## huks.abortSession9+
+
+abortSession(handle: number, options: HuksOptions, callback: AsyncCallback\) : void
+
+abort操作密钥接口,使用Callback回调异步返回结果 。
+
+**系统能力**:SystemCapability.Security.Huks
+
+**参数:**
+
+| 参数名 | 类型 | 必填 | 说明 |
+| -------- | --------------------------- | ---- | ------------------------------------------- |
+| handle | number | 是 | Abort操作的handle。 |
+| options | [HuksOptions](#huksoptions) | 是 | Abort操作的参数集合。 |
+| callback | AsyncCallback\ | 是 | 将Abort操作的结果添加到密钥管理系统的回调。 |
+
+**示例:**
+
+```js
+/* huks.initSession, huks.updateSession, huks.finishSession为三段式接口,需要一起使用,当
+ * huks.initSession和huks.updateSession
+ * 以及huks.finishSession操作中的任一阶段发生错误时,
+ * 都需要调用huks.abortSession来终止密钥的使用。
+ *
+ * 以下以RSA1024密钥的callback功能使用为例
+ */
+function stringToUint8Array(str) {
+ var arr = [];
+ for (var i = 0, j = str.length; i < j; ++i) {
+ arr.push(str.charCodeAt(i));
+ }
+ var tmpUint8Array = new Uint8Array(arr);
+ return tmpUint8Array;
+}
+
+var keyAlias = "HuksDemoRSA";
+var properties = new Array();
+var options = {
+ properties: properties,
+ inData: new Uint8Array(0)
+};
+var handle;
+async function generateKey() {
+ properties[0] = {
+ tag: huks.HuksTag.HUKS_TAG_ALGORITHM,
+ value: huks.HuksKeyAlg.HUKS_ALG_RSA
+ };
+ properties[1] = {
+ tag: huks.HuksTag.HUKS_TAG_KEY_SIZE,
+ value: huks.HuksKeySize.HUKS_RSA_KEY_SIZE_1024
+ };
+ properties[2] = {
+ tag: huks.HuksTag.HUKS_TAG_PURPOSE,
+ value: huks.HuksKeyPurpose.HUKS_KEY_PURPOSE_ENCRYPT
+ };
+ properties[3] = {
+ tag: huks.HuksTag.HUKS_TAG_PADDING,
+ value: huks.HuksKeyPadding.HUKS_PADDING_PKCS1_V1_5
+ };
+ properties[4] = {
+ tag: huks.HuksTag.HUKS_TAG_DIGEST,
+ value: huks.HuksKeyDigest.HUKS_DIGEST_SHA256
+ };
+ properties[5] = {
+ tag: huks.HuksTag.HUKS_TAG_BLOCK_MODE,
+ value: huks.HuksCipherMode.HUKS_MODE_ECB,
+ }
+
+ try {
+ await huks.generateKeyItem(keyAlias, options, function (error, data) {
+ if (error) {
+ console.error(`callback: generateKeyItem failed, code: ${error.code}, msg: ${error.message}`);
+ } else {
+ console.info(`callback: generateKeyItem success`);
+ }
+ });
+ } catch (error) {
+ console.error(`callback: generateKeyItem input arg invalid, code: ${error.code}, msg: ${error.message}`);
+ }
+}
+
+async function huksInit() {
+ console.log('enter huksInit');
+ try {
+ huks.initSession(keyAlias, options, function (error, data) {
+ if (error) {
+ console.error(`callback: initSession failed, code: ${error.code}, msg: ${error.message}`);
+ } else {
+ console.info(`callback: initSession success, data = ${JSON.stringify(data)}`);
+ handle = data.handle;
+ }
+ });
+ } catch (error) {
+ console.error(`callback: initSession input arg invalid, code: ${error.code}, msg: ${error.message}`);
+ }
+}
+
+async function huksUpdate() {
+ console.log('enter huksUpdate');
+ options.inData = stringToUint8Array("huksHmacTest");
+ try {
+ huks.updateSession(handle, options, function (error, data) {
+ if (error) {
+ console.error(`callback: updateSession failed, code: ${error.code}, msg: ${error.message}`);
+ } else {
+ console.info(`callback: updateSession success, data = ${JSON.stringify(data)}`);
+ }
+ });
+ } catch (error) {
+ console.error(`callback: updateSession input arg invalid, code: ${error.code}, msg: ${error.message}`);
+ }
+}
+
+async function huksFinish() {
+ console.log('enter huksFinish');
+ options.inData = new Uint8Array(0);
+ try {
+ huks.finishSession(handle, options, function (error, data) {
+ if (error) {
+ console.error(`callback: finishSession failed, code: ${error.code}, msg: ${error.message}`);
+ } else {
+ console.info(`callback: finishSession success, data = ${JSON.stringify(data)}`);
+ }
+ });
+ } catch (error) {
+ console.error(`callback: finishSession input arg invalid, code: ${error.code}, msg: ${error.message}`);
+ }
+}
+
+async function huksAbort() {
+ console.log('enter huksAbort');
+ try {
+ huks.abortSession(handle, options, function (error, data) {
+ if (error) {
+ console.error(`callback: abortSession failed, code: ${error.code}, msg: ${error.message}`);
+ } else {
+ console.info(`callback: abortSession success`);
+ }
+ });
+ } catch (error) {
+ console.error(`callback: abortSession input arg invalid, code: ${error.code}, msg: ${error.message}`);
+ }
+}
+```
+
+## huks.abortSession9+
+
+abortSession(handle: number, options: HuksOptions) : Promise\;
+
+abort操作密钥接口,使用Promise方式异步返回结果。
+
+**系统能力**:SystemCapability.Security.Huks
+
+**参数:**
+
+| 参数名 | 类型 | 必填 | 说明 |
+| ------- | --------------------------- | ---- | ------------------------------------------- |
+| handle | number | 是 | Abort操作的handle。 |
+| options | [HuksOptions](#huksoptions) | 是 | Abort操作的参数集合。 |
+| promise | Promise\ | 是 | 将Abort操作的结果添加到密钥管理系统的回调。 |
+
+**示例:**
+
+```js
+/* huks.initSession, huks.updateSession, huks.finishSession为三段式接口,需要一起使用,当
+ * huks.initSession和huks.updateSession
+ * 以及huks.finishSession操作中的任一阶段发生错误时,
+ * 都需要调用huks.abortSession来终止密钥的使用。
+ *
+ * 以下以RSA1024密钥的callback功能使用为例
+ */
+function stringToUint8Array(str) {
+ var arr = [];
+ for (var i = 0, j = str.length; i < j; ++i) {
+ arr.push(str.charCodeAt(i));
+ }
+ var tmpUint8Array = new Uint8Array(arr);
+ return tmpUint8Array;
+}
+
+var keyAlias = "HuksDemoRSA";
+var properties = new Array();
+var options = {
+ properties: properties,
+ inData: new Uint8Array(0)
+};
+var handle;
+async function generateKey() {
+ properties[0] = {
+ tag: huks.HuksTag.HUKS_TAG_ALGORITHM,
+ value: huks.HuksKeyAlg.HUKS_ALG_RSA
+ };
+ properties[1] = {
+ tag: huks.HuksTag.HUKS_TAG_KEY_SIZE,
+ value: huks.HuksKeySize.HUKS_RSA_KEY_SIZE_1024
+ };
+ properties[2] = {
+ tag: huks.HuksTag.HUKS_TAG_PURPOSE,
+ value: huks.HuksKeyPurpose.HUKS_KEY_PURPOSE_ENCRYPT
+ };
+ properties[3] = {
+ tag: huks.HuksTag.HUKS_TAG_PADDING,
+ value: huks.HuksKeyPadding.HUKS_PADDING_PKCS1_V1_5
+ };
+ properties[4] = {
+ tag: huks.HuksTag.HUKS_TAG_DIGEST,
+ value: huks.HuksKeyDigest.HUKS_DIGEST_SHA256
+ };
+ properties[5] = {
+ tag: huks.HuksTag.HUKS_TAG_BLOCK_MODE,
+ value: huks.HuksCipherMode.HUKS_MODE_ECB,
+ }
+
+ try {
+ await huks.generateKeyItem(keyAlias, options)
+ .then((data) => {
+ console.info(`promise: generateKeyItem success`);
+ })
+ .catch(error => {
+ console.error(`promise: generateKeyItem failed, code: ${error.code}, msg: ${error.message}`);
+ });
+ } catch (error) {
+ console.error(`promise: generateKeyItem input arg invalid, code: ${error.code}, msg: ${error.message}`);
+ }
+}
+
+async function huksInit() {
+ console.log('enter huksInit');
+ try {
+ await huks.initSession(keyAlias, options)
+ .then ((data) => {
+ console.info(`promise: initSession success, data = ${JSON.stringify(data)}`);
+ handle = data.handle;
+ })
+ .catch(error => {
+ console.error(`promise: initSession key failed, code: ${error.code}, msg: ${error.message}`);
+ });
+ } catch (error) {
+ console.error(`promise: initSession input arg invalid, code: ${error.code}, msg: ${error.message}`);
+ }
+}
+
+async function huksUpdate() {
+ console.log('enter huksUpdate');
+ options.inData = stringToUint8Array("huksHmacTest");
+ try {
+ await huks.updateSession(handle, options)
+ .then ((data) => {
+ console.info(`promise: updateSession success, data = ${JSON.stringify(data)}`);
+ })
+ .catch(error => {
+ console.error(`promise: updateSession failed, code: ${error.code}, msg: ${error.message}`);
+ });
+ } catch (error) {
+ console.error(`promise: updateSession input arg invalid, code: ${error.code}, msg: ${error.message}`);
+ }
+}
+
+async function huksFinish() {
+ console.log('enter huksFinish');
+ options.inData = new Uint8Array(0);
+ try {
+ await huks.finishSession(handle, options)
+ .then ((data) => {
+ console.info(`promise: finishSession success, data = ${JSON.stringify(data)}`);
+ })
+ .catch(error => {
+ console.error(`promise: finishSession failed, code: ${error.code}, msg: ${error.message}`);
+ });
+ } catch (error) {
+ console.error(`promise: finishSession input arg invalid, code: ${error.code}, msg: ${error.message}`);
+ }
+}
+
+async function huksAbort() {
+ console.log('enter huksAbort');
+ try {
+ await huks.abortSession(keyAlias, options)
+ .then ((data) => {
+ console.info(`promise: abortSession success`);
+ })
+ .catch(error => {
+ console.error(`promise: abortSession failed, code: ${error.code}, msg: ${error.message}`);
+ });
+ } catch (error) {
+ console.error(`promise: abortSession input arg invalid, code: ${error.code}, msg: ${error.message}`);
}
- .width('100%')
- .height('100%')
- }
}
```
@@ -2056,7 +2927,7 @@ struct Index {
| properties | Array\<[HuksParam](#huksparam)> | 否 | 属性,用于存HuksParam的数组。 |
| inData | Uint8Array | 否 | 输入数据。 |
-## HuksHandle
+## HuksHandle(deprecated)
huks Handle结构体。
@@ -2068,8 +2939,18 @@ huks Handle结构体。
| handle | number | 是 | 表示handle值。 |
| token | Uint8Array | 否 | 表示[init](#huksinit)操作之后获取到的challenge信息。 |
+## HuksSessionHandle9+
-## HuksResult
+huks Handle结构体。
+
+**系统能力**:SystemCapability.Security.Huks
+
+| 参数名 | 类型 | 必填 | 说明 |
+| --------- | ---------- | ---- | ---------------------------------------------------- |
+| handle | number | 是 | 表示handle值。 |
+| challenge | Uint8Array | 否 | 表示[init](#huksinit)操作之后获取到的challenge信息。 |
+
+## HuksResult(deprecated)
调用接口返回的result。
@@ -2084,3 +2965,16 @@ huks Handle结构体。
| properties | Array\<[HuksParam](#huksparam)> | 否 | 表示属性信息。 |
| certChains | Array\ | 否 | 表示证书链数据。 |
+## HuksReturnResult9+
+
+调用接口返回的result。
+
+**系统能力**:SystemCapability.Security.Huks
+
+
+
+| 参数名 | 类型 | 必填 | 说明 |
+| ---------- | ------------------------------- | ---- | ---------------- |
+| outData | Uint8Array | 否 | 表示输出数据。 |
+| properties | Array\<[HuksParam](#huksparam)> | 否 | 表示属性信息。 |
+| certChains | Array\ | 否 | 表示证书链数据。 |
\ No newline at end of file
diff --git a/zh-cn/application-dev/security/huks-guidelines.md b/zh-cn/application-dev/security/huks-guidelines.md
index 3e8c29679158e3dbb7b5b0299be645bfe7fee706..ad21dacc614d44fe52b4829ebe8cdef4d5e7ff6d 100644
--- a/zh-cn/application-dev/security/huks-guidelines.md
+++ b/zh-cn/application-dev/security/huks-guidelines.md
@@ -1,134 +1,18 @@
# HUKS开发指导
-## 场景介绍
-
- HUKS(OpenHarmony Universal KeyStore,OpenHarmony通用密钥库系统)向应用提供密钥库能力,包括密钥管理及密钥的密码学操作等功能。HUKS所管理的密钥可以由应用导入或者由应用调用HUKS接口生成。
-
-## 基于JS的开发指导
-
-1. 引入HUKS模块
-
- ```js
- import huks from '@ohos.security.huks'
- ```
-
-2. 使用generateKey接口生成密钥。
-
- keyAlias为生成的密钥别名,options为生成密钥时使用到的参数,需根据具体需要到的算法设定options中的参数。
-
- generateKey接口会返回密钥的生成是否成功。
-
- ```js
- var alias = 'testAlias';
- var properties = new Array();
- properties[0] = {
- tag: huks.HuksTag.HUKS_TAG_ALGORITHM,
- value: huks.HuksKeyAlg.HUKS_ALG_ECC
- };
- properties[1] = {
- tag: huks.HuksTag.HUKS_TAG_KEY_SIZE,
- value: huks.HuksKeySize.HUKS_ECC_KEY_SIZE_224
- };
- properties[2] = {
- tag: huks.HuksTag.HUKS_TAG_PURPOSE,
- value: huks.HuksKeyPurpose.HUKS_KEY_PURPOSE_AGREE
- };
- properties[3] = {
- tag: huks.HuksTag.HUKS_TAG_DIGEST,
- value: huks.HuksKeyDigest.HUKS_DIGEST_NONE
- };
- var options = {
- properties: properties
- }
- var resultA = huks.generateKey(alias, options);
- ```
-
-3. 使用Init接口进行init操作。
-
- Alias为初始化密钥的别名,options为初始化密钥用的参数集合,需根据具体需要到的算法设定options中的参数。
-
- init接口会返回init操作是否成功。
-
- ```js
- var alias = 'test001'
- var properties = new Array();
- properties[0] = {
- tag: huks.HuksTag.HUKS_TAG_ALGORITHM,
- value: huks.HuksKeyAlg.HUKS_ALG_DH
- };
- properties[1] = {
- tag: huks.HuksTag.HUKS_TAG_PURPOSE,
- value: huks.HuksKeyPurpose.HUKS_KEY_PURPOSE_AGREE
- };
- properties[2] = {
- tag: huks.HuksTag.HUKS_TAG_KEY_SIZE,
- value: huks.HuksKeySize.HUKS_DH_KEY_SIZE_4096
- };
- var options = {
- properties: properties
- };
- huks.init(alias, options, function(err, data) {
- if (err.code !== 0) {
- console.log("test init err information: " + JSON.stringify(err));
- } else {
- console.log(`test init data: ${JSON.stringify(data)}`);
- }
- })
- ```
-
-4. 使用Update接口进行update操作。
-
- handle为更新密钥的session id,options为更新密钥用的参数集合,需根据具体需要到的算法设定options中的参数。
-
- update接口会返回update操作是否成功。
-
- ```js
- var properties = new Array();
- properties[0] = {
- tag: huks.HuksTag.HUKS_TAG_ALGORITHM,
- value: huks.HuksKeyAlg.HUKS_ALG_DH
- };
- properties[1] = {
- tag: huks.HuksTag.HUKS_TAG_PURPOSE,
- value: huks.HuksKeyPurpose.HUKS_KEY_PURPOSE_AGREE
- };
- properties[2] = {
- tag: huks.HuksTag.HUKS_TAG_KEY_SIZE,
- value: huks.HuksKeySize.HUKS_DH_KEY_SIZE_4096
- };
- var options = {
- properties: properties
- };
- var result = huks.update(handle, options)
- ```
-
-5. 使用Finish接口进行finish操作。
-
- handle为 结束密钥的session id,options为结束密钥用的参数集合,需根据具体需要到的算法设定options中的参数。
-
- finish接口会返回finish操作是否成功。
-
- ```js
- var properties = new Array();
- properties[0] = {
- tag: huks.HuksTag.HUKS_TAG_ALGORITHM,
- value: huks.HuksKeyAlg.HUKS_ALG_DH
- };
- properties[1] = {
- tag: huks.HuksTag.HUKS_TAG_PURPOSE,
- value: huks.HuksKeyPurpose.HUKS_KEY_PURPOSE_AGREE
- };
- properties[2] = {
- tag: huks.HuksTag.HUKS_TAG_KEY_SIZE,
- value: huks.HuksKeySize.HUKS_DH_KEY_SIZE_4096
- };
- var options = {
- properties: properties
- };
- var result = huks.finish(handle, options)
- ```
-
-## 基于TS的开发指导
+HUKS(OpenHarmony Universal KeyStore,OpenHarmony通用密钥库系统)向应用提供密钥库能力,包括密钥管理及密钥的密码学操作等功能。HUKS所管理的密钥可以由应用导入或者由应用调用HUKS接口生成。
+
+> **说明**
+>
+> 本开发指导基于API version 9,仅适用于eTS语言开发
+
+### **前提条件**
+
+在使用HUKS的接口开发前,需要引入HUKS模块
+
+```ts
+import huks from '@ohos.security.huks'
+```
### 密钥导入导出
@@ -168,98 +52,252 @@ RSA512, RSA768, RSA1024, RSA2048, RSA3072, RSA4096, ECC224, ECC256, ECC384, ECC5
**示例:**
```ts
-/* 以生成RSA512密钥为例 */
+/* 以导出RSA512密钥及导入ECC256密钥为例 */
+import huks from '@ohos.security.huks';
+
+function StringToUint8Array(str) {
+ var arr = [];
+ for (var i = 0, j = str.length; i < j; ++i) {
+ arr.push(str.charCodeAt(i));
+ }
+ return new Uint8Array(arr);
+}
+
+async function publicGenKeyFunc(keyAlias:string, huksOptions:huks.HuksOptions) {
+ console.info(`enter callback generateKeyItem`);
+ try {
+ await generateKeyItem(keyAlias, huksOptions)
+ .then((data) => {
+ console.info(`callback: generateKeyItem success, data = ${JSON.stringify(data)}`);
+ })
+ .catch(error => {
+ console.error(`callback: generateKeyItem failed, code: ${error.code}, msg: ${error.message}`);
+ });
+ } catch (error) {
+ console.error(`callback: generateKeyItem input arg invalid, code: ${error.code}, msg: ${error.message}`);
+ }
+}
+
+function generateKeyItem(keyAlias:string, huksOptions:huks.HuksOptions) {
+ return new Promise((resolve, reject) => {
+ try {
+ huks.generateKeyItem(keyAlias, huksOptions, function (error, data) {
+ if (error) {
+ reject(error);
+ } else {
+ resolve(data);
+ }
+ });
+ } catch (error) {
+ throw(error);
+ }
+ });
+}
+
+async function publicExportKeyFunc(keyAlias:string, huksOptions:huks.HuksOptions) {
+ console.info(`enter callback export`);
+ try {
+ await exportKeyItem(keyAlias, huksOptions)
+ .then ((data) => {
+ console.info(`callback: exportKeyItem success, data = ${JSON.stringify(data)}`);
+ if (data.outData !== null) {
+ exportKey = data.outData;
+ }
+ })
+ .catch(error => {
+ console.error(`callback: exportKeyItem failed, code: ${error.code}, msg: ${error.message}`);
+ });
+ } catch (error) {
+ console.error(`callback: exportKeyItem input arg invalid, code: ${error.code}, msg: ${error.message}`);
+ }
+}
+
+function exportKeyItem(keyAlias:string, huksOptions:huks.HuksOptions) : Promise {
+ return new Promise((resolve, reject) => {
+ try {
+ huks.exportKeyItem(keyAlias, huksOptions, function (error, data) {
+ if (error) {
+ reject(error);
+ } else {
+ resolve(data);
+ }
+ });
+ } catch (error) {
+ throw(error);
+ }
+ });
+}
+
+async function publicImportKeyFunc(keyAlias:string, huksOptions:huks.HuksOptions) {
+ console.info(`enter promise importKeyItem`);
+ try {
+ await importKeyItem(keyAlias, huksOptions)
+ .then ((data) => {
+ console.info(`callback: importKeyItem success, data = ${JSON.stringify(data)}`);
+ })
+ .catch(error => {
+ console.error(`callback: importKeyItem failed, code: ${error.code}, msg: ${error.message}`);
+ });
+ } catch (error) {
+ console.error(`callback: importKeyItem input arg invalid, code: ${error.code}, msg: ${error.message}`);
+ }
+}
+
+function importKeyItem(keyAlias:string, huksOptions:huks.HuksOptions) {
+ return new Promise((resolve, reject) => {
+ try {
+ huks.importKeyItem(keyAlias, huksOptions, function (error, data) {
+ if (error) {
+ reject(error);
+ } else {
+ resolve(data);
+ }
+ });
+ } catch (error) {
+ throw(error);
+ }
+ });
+}
+
+async function publicDeleteKeyFunc(keyAlias:string, huksOptions:huks.HuksOptions) {
+ console.info(`enter callback deleteKeyItem`);
+ try {
+ await deleteKeyItem(keyAlias, huksOptions)
+ .then ((data) => {
+ console.info(`callback: deleteKeyItem key success, data = ${JSON.stringify(data)}`);
+ })
+ .catch(error => {
+ console.error(`callback: deleteKeyItem failed, code: ${error.code}, msg: ${error.message}`);
+ });
+ } catch (error) {
+ console.error(`callback: deleteKeyItem input arg invalid, code: ${error.code}, msg: ${error.message}`);
+ }
+}
+
+function deleteKeyItem(keyAlias:string, huksOptions:huks.HuksOptions) {
+ return new Promise((resolve, reject) => {
+ try {
+ huks.deleteKeyItem(keyAlias, huksOptions, function (error, data) {
+ if (error) {
+ reject(error);
+ } else {
+ resolve(data);
+ }
+ });
+ } catch (error) {
+ throw(error);
+ }
+ });
+}
+
var srcKeyAlias = 'hukRsaKeyAlias';
var srcKeyAliasSecond = 'huksRsaKeyAliasSecond';
var exportKey;
+var inputEccPair = new Uint8Array([
+ 0x02, 0x00, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x20, 0x00, 0x00, 0x00, 0x20, 0x00, 0x00, 0x00,
+ 0x20, 0x00, 0x00, 0x00, 0xa5, 0xb8, 0xa3, 0x78, 0x1d, 0x6d, 0x76, 0xe0, 0xb3, 0xf5, 0x6f, 0x43,
+ 0x9d, 0xcf, 0x60, 0xf6, 0x0b, 0x3f, 0x64, 0x45, 0xa8, 0x3f, 0x1a, 0x96, 0xf1, 0xa1, 0xa4, 0x5d,
+ 0x3e, 0x2c, 0x3f, 0x13, 0xd7, 0x81, 0xf7, 0x2a, 0xb5, 0x8d, 0x19, 0x3d, 0x9b, 0x96, 0xc7, 0x6a,
+ 0x10, 0xf0, 0xaa, 0xbc, 0x91, 0x6f, 0x4d, 0xa7, 0x09, 0xb3, 0x57, 0x88, 0x19, 0x6f, 0x00, 0x4b,
+ 0xad, 0xee, 0x34, 0x35, 0xfb, 0x8b, 0x9f, 0x12, 0xa0, 0x83, 0x19, 0xbe, 0x6a, 0x6f, 0x63, 0x2a,
+ 0x7c, 0x86, 0xba, 0xca, 0x64, 0x0b, 0x88, 0x96, 0xe2, 0xfa, 0x77, 0xbc, 0x71, 0xe3, 0x0f, 0x0f,
+ 0x9e, 0x3c, 0xe5, 0xf9]);
async function testImportExport() {
/* 集成生成密钥参数集 */
- var properties = new Array();
- properties[0] = {
+ var exportProperties = new Array();
+ exportProperties[0] = {
tag: huks.HuksTag.HUKS_TAG_ALGORITHM,
value: huks.HuksKeyAlg.HUKS_ALG_RSA,
}
- properties[1] = {
+ exportProperties[1] = {
tag: huks.HuksTag.HUKS_TAG_PURPOSE,
value:
huks.HuksKeyPurpose.HUKS_KEY_PURPOSE_ENCRYPT |
huks.HuksKeyPurpose.HUKS_KEY_PURPOSE_DECRYPT,
}
- properties[2] = {
+ exportProperties[2] = {
tag: huks.HuksTag.HUKS_TAG_KEY_SIZE,
value: huks.HuksKeySize.HUKS_RSA_KEY_SIZE_512,
}
- properties[3] = {
+ exportProperties[3] = {
tag: huks.HuksTag.HUKS_TAG_BLOCK_MODE,
value: huks.HuksCipherMode.HUKS_MODE_ECB,
}
- properties[4] = {
+ exportProperties[4] = {
tag: huks.HuksTag.HUKS_TAG_PADDING,
value: huks.HuksKeyPadding.HUKS_PADDING_PKCS1_V1_5,
}
- properties[5] = {
+ exportProperties[5] = {
tag: huks.HuksTag.HUKS_TAG_DIGEST,
value: huks.HuksKeyDigest.HUKS_DIGEST_SHA256,
}
var huksOptions = {
- properties: properties,
+ properties: exportProperties,
inData: new Uint8Array(new Array())
}
/* 生成密钥 */
- await huks.generateKey(srcKeyAlias, huksOptions).then((data) => {
- console.info(`test generateKey data: ${JSON.stringify(data)}`);
- }).catch((err) => {
- console.info('test generateKey err information: ' + JSON.stringify(err));
- });
+ await publicGenKeyFunc(srcKeyAlias, huksOptions);
/* 导出密钥 */
- await huks.exportKey(srcKeyAlias, huksOptions).then((data) => {
- console.info(`test ExportKey data: ${JSON.stringify(data)}`);
- exportKey = data.outData;
- }).catch((err) => {
- console.info('test ImportKey err information: ' + JSON.stringify(err));
- });
+ await publicExportKeyFunc(srcKeyAlias, huksOptions);
/* 集成导入密钥参数集 */
- var propertiesEncrypt = new Array();
- propertiesEncrypt[0] = {
+ var importProperties = new Array();
+ importProperties[0] = {
tag: huks.HuksTag.HUKS_TAG_ALGORITHM,
- value: huks.HuksKeyAlg.HUKS_ALG_RSA,
- }
- propertiesEncrypt[1] = {
+ value: huks.HuksKeyAlg.HUKS_ALG_ECC
+ };
+ importProperties[1] = {
tag: huks.HuksTag.HUKS_TAG_KEY_SIZE,
- value: huks.HuksKeySize.HUKS_RSA_KEY_SIZE_512,
- }
- propertiesEncrypt[2] = {
- tag: huks.HuksTag.HUKS_TAG_PADDING,
- value: huks.HuksKeyPadding.HUKS_PADDING_PKCS1_V1_5,
- }
- propertiesEncrypt[3] = {
- tag: huks.HuksTag.HUKS_TAG_BLOCK_MODE,
- value: huks.HuksCipherMode.HUKS_MODE_ECB,
- }
- propertiesEncrypt[4] = {
- tag: huks.HuksTag.HUKS_TAG_DIGEST,
- value: huks.HuksKeyDigest.HUKS_DIGEST_SHA256,
- }
- propertiesEncrypt[5] = {
+ value: huks.HuksKeySize.HUKS_ECC_KEY_SIZE_256
+ };
+ importProperties[2] = {
tag: huks.HuksTag.HUKS_TAG_PURPOSE,
- value: huks.HuksKeyPurpose.HUKS_KEY_PURPOSE_ENCRYPT,
- }
- var encryptOptions = {
- properties: propertiesEncrypt,
- inData: new Uint8Array(new Array())
- }
+ value: huks.HuksKeyPurpose.HUKS_KEY_PURPOSE_UNWRAP
+ };
+ importProperties[3] = {
+ tag: huks.HuksTag.HUKS_TAG_DIGEST,
+ value: huks.HuksKeyDigest.HUKS_DIGEST_SHA256
+ };
+ importProperties[4] = {
+ tag: huks.HuksTag.HUKS_TAG_IMPORT_KEY_TYPE,
+ value: huks.HuksImportKeyType.HUKS_KEY_TYPE_KEY_PAIR,
+ };
+ var importOptions = {
+ properties: importProperties,
+ inData: inputEccPair
+ };
/* 导入密钥 */
- encryptOptions.inData = exportKey;
- await huks.importKey(srcKeyAliasSecond, encryptOptions).then((data) => {
- console.info(`test ImportKey data: ${JSON.stringify(data)}`);
- }).catch((err) => {
- console.info('test ImportKey err information: ' + JSON.stringify(err));
- });
+ await publicImportKeyFunc(srcKeyAliasSecond, importOptions);
+
+ await publicDeleteKeyFunc(srcKeyAlias, huksOptions);
+ await publicDeleteKeyFunc(srcKeyAliasSecond, importOptions);
+}
+
+@Entry
+@Component
+struct Index {
+ build() {
+ Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) {
+ Button() {
+ Text('testImportExport')
+ .fontSize(30)
+ .fontWeight(FontWeight.Bold)
+ }.type(ButtonType.Capsule)
+ .margin({
+ top: 20
+ })
+ .backgroundColor('#0D9FFB')
+ .onClick(()=>{
+ testImportExport();
+ })
+ }
+ .width('100%')
+ .height('100%')
+ }
}
```
@@ -299,87 +337,211 @@ AES128, AES192, AES256, RSA512, RSA768, RSA1024, RSA2048, RSA3072, RSA4096, Hmac
**示例:**
```ts
-var inputEccPair = new Uint8Array([
- 0x02, 0x00, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x20, 0x00, 0x00,
- 0x00, 0x20, 0x00, 0x00, 0x00, 0x20, 0x00, 0x00, 0x00, 0xa5, 0xb8,
- 0xa3, 0x78, 0x1d, 0x6d, 0x76, 0xe0, 0xb3, 0xf5, 0x6f, 0x43, 0x9d,
- 0xcf, 0x60, 0xf6, 0x0b, 0x3f, 0x64, 0x45, 0xa8, 0x3f, 0x1a, 0x96,
- 0xf1, 0xa1, 0xa4, 0x5d, 0x3e, 0x2c, 0x3f, 0x13, 0xd7, 0x81, 0xf7,
- 0x2a, 0xb5, 0x8d, 0x19, 0x3d, 0x9b, 0x96, 0xc7, 0x6a, 0x10, 0xf0,
- 0xaa, 0xbc, 0x91, 0x6f, 0x4d, 0xa7, 0x09, 0xb3, 0x57, 0x88, 0x19,
- 0x6f, 0x00, 0x4b, 0xad, 0xee, 0x34, 0x35, 0xfb, 0x8b, 0x9f, 0x12,
- 0xa0, 0x83, 0x19, 0xbe, 0x6a, 0x6f, 0x63, 0x2a, 0x7c, 0x86, 0xba,
- 0xca, 0x64, 0x0b, 0x88, 0x96, 0xe2, 0xfa, 0x77, 0xbc, 0x71, 0xe3,
- 0x0f, 0x0f, 0x9e, 0x3c, 0xe5, 0xf9]);
-
-var exportWrappingKey;
-var importAlias = "importAlias";
-var wrapAlias = "wrappingKeyAlias";
+import huks from '@ohos.security.huks';
+
+async function publicExportKeyFunc(keyAlias:string, huksOptions:huks.HuksOptions) {
+ console.info(`enter callback export`);
+ try {
+ await exportKeyItem(keyAlias, huksOptions)
+ .then ((data) => {
+ console.info(`callback: exportKeyItem success, data = ${JSON.stringify(data)}`);
+ if (data.outData !== null) {
+ exportKey = data.outData;
+ }
+ })
+ .catch(error => {
+ console.error(`callback: exportKeyItem failed, code: ${error.code}, msg: ${error.message}`);
+ });
+ } catch (error) {
+ console.error(`callback: exportKeyItem input arg invalid, code: ${error.code}, msg: ${error.message}`);
+ }
+}
-async function TestGenFunc(alias, options) {
- await genKey(alias, options).then((data) => {
- console.log(`test genKey data: ${JSON.stringify(data)}`);
- })
- .catch((err) => {
- console.log('test genKey err information: ' + JSON.stringify(err));
+function exportKeyItem(keyAlias:string, huksOptions:huks.HuksOptions) : Promise {
+ return new Promise((resolve, reject) => {
+ try {
+ huks.exportKeyItem(keyAlias, huksOptions, function (error, data) {
+ if (error) {
+ reject(error);
+ } else {
+ resolve(data);
+ }
+ });
+ } catch (error) {
+ throw(error);
+ }
});
}
-function genKey(alias, options) {
+async function publicImportKeyFunc(keyAlias:string, huksOptions:huks.HuksOptions) {
+ console.info(`enter promise importKeyItem`);
+ try {
+ await importKeyItem(keyAlias, huksOptions)
+ .then ((data) => {
+ console.info(`callback: importKeyItem success, data = ${JSON.stringify(data)}`);
+ })
+ .catch(error => {
+ console.error(`callback: importKeyItem failed, code: ${error.code}, msg: ${error.message}`);
+ });
+ } catch (error) {
+ console.error(`callback: importKeyItem input arg invalid, code: ${error.code}, msg: ${error.message}`);
+ }
+}
+
+function importKeyItem(keyAlias:string, huksOptions:huks.HuksOptions) {
return new Promise((resolve, reject) => {
- huks.importKey(alias, options, function (err, data) {
- console.log(`test genKey data: ${JSON.stringify(data)}`);
- if (err.code !== 0) {
- console.log('test genKey err information: ' + JSON.stringify(err));
- reject(err);
- } else {
- resolve(data);
- }
- });
+ try {
+ huks.importKeyItem(keyAlias, huksOptions, function (error, data) {
+ if (error) {
+ reject(error);
+ } else {
+ resolve(data);
+ }
+ });
+ } catch (error) {
+ throw(error);
+ }
});
}
-async function TestExportFunc(alias, options) {
- await exportKey(alias, options).then((data) => {
- console.log(`test exportKey data: ${JSON.stringify(data)}`);
- })
- .catch((err) => {
- console.log('test exportKey err information: ' + JSON.stringify(err));
- });
+async function publicImportWrappedKey(keyAlias:string, wrappingKeyAlias:string, huksOptions:huks.HuksOptions) {
+ console.info(`enter callback importWrappedKeyItem`);
+ try {
+ await importWrappedKeyItem(keyAlias, wrappingKeyAlias, huksOptions)
+ .then ((data) => {
+ console.info(`callback: importWrappedKeyItem success, data = ${JSON.stringify(data)}`);
+ })
+ .catch(error => {
+ console.error(`callback: importWrappedKeyItem failed, code: ${error.code}, msg: ${error.message}`);
+ });
+ } catch (error) {
+ console.error(`callback: importWrappedKeyItem input arg invalid, code: ${error.code}, msg: ${error.message}`);
+ }
}
-function exportKey(alias, options) {
+function importWrappedKeyItem(keyAlias:string, wrappingKeyAlias:string, huksOptions:huks.HuksOptions) {
return new Promise((resolve, reject) => {
- huks.exportKey(alias, options, function (err, data) {
- console.log(`test exportKey data: ${JSON.stringify(data)}`);
- if (err.code !== 0) {
- console.log('test exportKey err information: ' + JSON.stringify(err));
- reject(err);
- } else {
- exportWrappingKey = data.outData;
- resolve(data);
- }
- });
+ try {
+ huks.importWrappedKeyItem(keyAlias, wrappingKeyAlias, huksOptions, function (error, data) {
+ if (error) {
+ reject(error);
+ } else {
+ resolve(data);
+ }
+ });
+ } catch (error) {
+ throw(error);
+ }
});
}
-async function TestImportWrappedFunc(alias, wrappingAlias, options) {
- var result = await huks.importWrappedKey(alias, wrappingAlias, options);
- if (result.errorCode === 0) {
- console.error('test importWrappedKey success');
- } else {
- console.error('test importWrappedKey fail');
+async function publicDeleteKeyFunc(keyAlias:string, huksOptions:huks.HuksOptions) {
+ console.info(`enter callback deleteKeyItem`);
+ try {
+ await deleteKeyItem(keyAlias, huksOptions)
+ .then ((data) => {
+ console.info(`callback: deleteKeyItem key success, data = ${JSON.stringify(data)}`);
+ })
+ .catch(error => {
+ console.error(`callback: deleteKeyItem failed, code: ${error.code}, msg: ${error.message}`);
+ });
+ } catch (error) {
+ console.error(`callback: deleteKeyItem input arg invalid, code: ${error.code}, msg: ${error.message}`);
}
}
-async function TestImportWrappedKeyFunc(
- importAlias,
- wrappingAlias,
- genOptions,
- importOptions
-) {
- await TestGenFunc(wrappingAlias, genOptions);
- await TestExportFunc(wrappingAlias, genOptions);
+function deleteKeyItem(keyAlias:string, huksOptions:huks.HuksOptions) {
+ return new Promise((resolve, reject) => {
+ try {
+ huks.deleteKeyItem(keyAlias, huksOptions, function (error, data) {
+ if (error) {
+ reject(error);
+ } else {
+ resolve(data);
+ }
+ });
+ } catch (error) {
+ throw(error);
+ }
+ });
+}
+
+var importAlias = "importAlias";
+var wrapAlias = "wrappingKeyAlias";
+var exportKey;
+
+var inputEccPair = new Uint8Array([
+ 0x02, 0x00, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x20, 0x00, 0x00, 0x00, 0x20, 0x00, 0x00, 0x00,
+ 0x20, 0x00, 0x00, 0x00, 0xa5, 0xb8, 0xa3, 0x78, 0x1d, 0x6d, 0x76, 0xe0, 0xb3, 0xf5, 0x6f, 0x43,
+ 0x9d, 0xcf, 0x60, 0xf6, 0x0b, 0x3f, 0x64, 0x45, 0xa8, 0x3f, 0x1a, 0x96, 0xf1, 0xa1, 0xa4, 0x5d,
+ 0x3e, 0x2c, 0x3f, 0x13, 0xd7, 0x81, 0xf7, 0x2a, 0xb5, 0x8d, 0x19, 0x3d, 0x9b, 0x96, 0xc7, 0x6a,
+ 0x10, 0xf0, 0xaa, 0xbc, 0x91, 0x6f, 0x4d, 0xa7, 0x09, 0xb3, 0x57, 0x88, 0x19, 0x6f, 0x00, 0x4b,
+ 0xad, 0xee, 0x34, 0x35, 0xfb, 0x8b, 0x9f, 0x12, 0xa0, 0x83, 0x19, 0xbe, 0x6a, 0x6f, 0x63, 0x2a,
+ 0x7c, 0x86, 0xba, 0xca, 0x64, 0x0b, 0x88, 0x96, 0xe2, 0xfa, 0x77, 0xbc, 0x71, 0xe3, 0x0f, 0x0f,
+ 0x9e, 0x3c, 0xe5, 0xf9]);
+
+var properties = new Array();
+properties[0] = {
+ tag: huks.HuksTag.HUKS_TAG_ALGORITHM,
+ value: huks.HuksKeyAlg.HUKS_ALG_ECC
+};
+properties[1] = {
+ tag: huks.HuksTag.HUKS_TAG_KEY_SIZE,
+ value: huks.HuksKeySize.HUKS_ECC_KEY_SIZE_256
+};
+properties[2] = {
+ tag: huks.HuksTag.HUKS_TAG_PURPOSE,
+ value: huks.HuksKeyPurpose.HUKS_KEY_PURPOSE_UNWRAP
+};
+properties[3] = {
+ tag: huks.HuksTag.HUKS_TAG_DIGEST,
+ value: huks.HuksKeyDigest.HUKS_DIGEST_SHA256
+};
+properties[4] = {
+ tag: huks.HuksTag.HUKS_TAG_IMPORT_KEY_TYPE,
+ value: huks.HuksImportKeyType.HUKS_KEY_TYPE_KEY_PAIR,
+};
+var huksOptions = {
+ properties: properties,
+ inData: inputEccPair
+};
+
+var importProperties = new Array();
+importProperties[0] = {
+ tag: huks.HuksTag.HUKS_TAG_ALGORITHM,
+ value: huks.HuksKeyAlg.HUKS_ALG_AES
+};
+importProperties[1] = {
+ tag: huks.HuksTag.HUKS_TAG_KEY_SIZE,
+ value: huks.HuksKeySize.HUKS_AES_KEY_SIZE_256
+};
+importProperties[2] = {
+ tag: huks.HuksTag.HUKS_TAG_PURPOSE,
+ value: huks.HuksKeyPurpose.HUKS_KEY_PURPOSE_ENCRYPT | huks.HuksKeyPurpose.HUKS_KEY_PURPOSE_DECRYPT
+};
+importProperties[3] = {
+ tag: huks.HuksTag.HUKS_TAG_BLOCK_MODE,
+ value: huks.HuksCipherMode.HUKS_MODE_CBC
+};
+importProperties[4] = {
+ tag: huks.HuksTag.HUKS_TAG_PADDING,
+ value: huks.HuksKeyPadding.HUKS_PADDING_NONE
+};
+importProperties[5] = {
+ tag: huks.HuksTag.HUKS_TAG_UNWRAP_ALGORITHM_SUITE,
+ value: huks.HuksUnwrapSuite.HUKS_UNWRAP_SUITE_ECDH_AES_256_GCM_NOPADDING
+};
+var importOptions = {
+ properties: importProperties,
+ inData: new Uint8Array(new Array())
+};
+
+async function importWrappedKeyItemTest() {
+
+ console.info(`enter ImportWrapKey test`);
+ await publicImportKeyFunc(wrapAlias, huksOptions);
+
+ await publicExportKeyFunc(wrapAlias, huksOptions);
/* 以下操作不需要调用HUKS接口,此处不给出具体实现。
* 假设待导入的密钥为keyA
@@ -395,110 +557,55 @@ async function TestImportWrappedKeyFunc(
* keyA长度占用的内存长度(4字节) + keyA的长度 + keyA_enc的长度(4字节) + keyA_enc的数据
*/
var inputKey = new Uint8Array([
- 0x5b, 0x00, 0x00, 0x00, 0x30, 0x59, 0x30, 0x13, 0x06, 0x07, 0x2a,
- 0x86, 0x48, 0xce, 0x3d, 0x02, 0x01, 0x06, 0x08, 0x2a, 0x86, 0x48,
- 0xce, 0x3d, 0x03, 0x01, 0x07, 0x03, 0x42, 0x00, 0x04, 0xc0, 0xfe,
- 0x1c, 0x67, 0xde, 0x86, 0x0e, 0xfb, 0xaf, 0xb5, 0x85, 0x52, 0xb4,
- 0x0e, 0x1f, 0x6c, 0x6c, 0xaa, 0xc5, 0xd9, 0xd2, 0x4d, 0xb0, 0x8a,
- 0x72, 0x24, 0xa1, 0x99, 0xaf, 0xfc, 0x3e, 0x55, 0x5a, 0xac, 0x99,
- 0x3d, 0xe8, 0x34, 0x72, 0xb9, 0x47, 0x9c, 0xa6, 0xd8, 0xfb, 0x00,
- 0xa0, 0x1f, 0x9f, 0x7a, 0x41, 0xe5, 0x44, 0x3e, 0xb2, 0x76, 0x08,
- 0xa2, 0xbd, 0xe9, 0x41, 0xd5, 0x2b, 0x9e, 0x10, 0x00, 0x00, 0x00,
- 0xbf, 0xf9, 0x69, 0x41, 0xf5, 0x49, 0x85, 0x31, 0x35, 0x14, 0x69,
- 0x12, 0x57, 0x9c, 0xc8, 0xb7, 0x10, 0x00, 0x00, 0x00, 0x2d, 0xb7,
- 0xf1, 0x5a, 0x0f, 0xb8, 0x20, 0xc5, 0x90, 0xe5, 0xca, 0x45, 0x84,
- 0x5c, 0x08, 0x08, 0x10, 0x00, 0x00, 0x00, 0x43, 0x25, 0x1b, 0x2f,
- 0x5b, 0x86, 0xd8, 0x87, 0x04, 0x4d, 0x38, 0xc2, 0x65, 0xcc, 0x9e,
- 0xb7, 0x20, 0x00, 0x00, 0x00, 0xf4, 0xe8, 0x93, 0x28, 0x0c, 0xfa,
- 0x4e, 0x11, 0x6b, 0xe8, 0xbd, 0xa8, 0xe9, 0x3f, 0xa7, 0x8f, 0x2f,
- 0xe3, 0xb3, 0xbf, 0xaf, 0xce, 0xe5, 0x06, 0x2d, 0xe6, 0x45, 0x5d,
- 0x19, 0x26, 0x09, 0xe7, 0x10, 0x00, 0x00, 0x00, 0xf4, 0x1e, 0x7b,
- 0x01, 0x7a, 0x84, 0x36, 0xa4, 0xa8, 0x1c, 0x0d, 0x3d, 0xde, 0x57,
- 0x66, 0x73, 0x10, 0x00, 0x00, 0x00, 0xe3, 0xff, 0x29, 0x97, 0xad,
- 0xb3, 0x4a, 0x2c, 0x50, 0x08, 0xb5, 0x68, 0xe1, 0x90, 0x5a, 0xdc,
- 0x10, 0x00, 0x00, 0x00, 0x26, 0xae, 0xdc, 0x4e, 0xa5, 0x6e, 0xb1,
- 0x38, 0x14, 0x24, 0x47, 0x1c, 0x41, 0x89, 0x63, 0x11, 0x04, 0x00,
- 0x00, 0x00, 0x20, 0x00, 0x00, 0x00, 0x20, 0x00, 0x00, 0x00, 0x0b,
- 0xcb, 0xa9, 0xa8, 0x5f, 0x5a, 0x9d, 0xbf, 0xa1, 0xfc, 0x72, 0x74,
- 0x87, 0x79, 0xf2, 0xf4, 0x22, 0x0c, 0x8a, 0x4d, 0xd8, 0x7e, 0x10,
- 0xc8, 0x44, 0x17, 0x95, 0xab, 0x3b, 0xd2, 0x8f, 0x0a]);
+ 0x5b, 0x00, 0x00, 0x00, 0x30, 0x59, 0x30, 0x13, 0x06, 0x07, 0x2a, 0x86, 0x48, 0xce, 0x3d, 0x02,
+ 0x01, 0x06, 0x08, 0x2a, 0x86, 0x48, 0xce, 0x3d, 0x03, 0x01, 0x07, 0x03, 0x42, 0x00, 0x04, 0xc0,
+ 0xfe, 0x1c, 0x67, 0xde, 0x86, 0x0e, 0xfb, 0xaf, 0xb5, 0x85, 0x52, 0xb4, 0x0e, 0x1f, 0x6c, 0x6c,
+ 0xaa, 0xc5, 0xd9, 0xd2, 0x4d, 0xb0, 0x8a, 0x72, 0x24, 0xa1, 0x99, 0xaf, 0xfc, 0x3e, 0x55, 0x5a,
+ 0xac, 0x99, 0x3d, 0xe8, 0x34, 0x72, 0xb9, 0x47, 0x9c, 0xa6, 0xd8, 0xfb, 0x00, 0xa0, 0x1f, 0x9f,
+ 0x7a, 0x41, 0xe5, 0x44, 0x3e, 0xb2, 0x76, 0x08, 0xa2, 0xbd, 0xe9, 0x41, 0xd5, 0x2b, 0x9e, 0x10,
+ 0x00, 0x00, 0x00, 0xbf, 0xf9, 0x69, 0x41, 0xf5, 0x49, 0x85, 0x31, 0x35, 0x14, 0x69, 0x12, 0x57,
+ 0x9c, 0xc8, 0xb7, 0x10, 0x00, 0x00, 0x00, 0x2d, 0xb7, 0xf1, 0x5a, 0x0f, 0xb8, 0x20, 0xc5, 0x90,
+ 0xe5, 0xca, 0x45, 0x84, 0x5c, 0x08, 0x08, 0x10, 0x00, 0x00, 0x00, 0x43, 0x25, 0x1b, 0x2f, 0x5b,
+ 0x86, 0xd8, 0x87, 0x04, 0x4d, 0x38, 0xc2, 0x65, 0xcc, 0x9e, 0xb7, 0x20, 0x00, 0x00, 0x00, 0xf4,
+ 0xe8, 0x93, 0x28, 0x0c, 0xfa, 0x4e, 0x11, 0x6b, 0xe8, 0xbd, 0xa8, 0xe9, 0x3f, 0xa7, 0x8f, 0x2f,
+ 0xe3, 0xb3, 0xbf, 0xaf, 0xce, 0xe5, 0x06, 0x2d, 0xe6, 0x45, 0x5d, 0x19, 0x26, 0x09, 0xe7, 0x10,
+ 0x00, 0x00, 0x00, 0xf4, 0x1e, 0x7b, 0x01, 0x7a, 0x84, 0x36, 0xa4, 0xa8, 0x1c, 0x0d, 0x3d, 0xde,
+ 0x57, 0x66, 0x73, 0x10, 0x00, 0x00, 0x00, 0xe3, 0xff, 0x29, 0x97, 0xad, 0xb3, 0x4a, 0x2c, 0x50,
+ 0x08, 0xb5, 0x68, 0xe1, 0x90, 0x5a, 0xdc, 0x10, 0x00, 0x00, 0x00, 0x26, 0xae, 0xdc, 0x4e, 0xa5,
+ 0x6e, 0xb1, 0x38, 0x14, 0x24, 0x47, 0x1c, 0x41, 0x89, 0x63, 0x11, 0x04, 0x00, 0x00, 0x00, 0x20,
+ 0x00, 0x00, 0x00, 0x20, 0x00, 0x00, 0x00, 0x0b, 0xcb, 0xa9, 0xa8, 0x5f, 0x5a, 0x9d, 0xbf, 0xa1,
+ 0xfc, 0x72, 0x74, 0x87, 0x79, 0xf2, 0xf4, 0x22, 0x0c, 0x8a, 0x4d, 0xd8, 0x7e, 0x10, 0xc8, 0x44,
+ 0x17, 0x95, 0xab, 0x3b, 0xd2, 0x8f, 0x0a
+ ]);
importOptions.inData = inputKey;
- await TestImportWrappedFunc(importAlias, wrappingAlias, importOptions);
-}
+ await publicImportWrappedKey(importAlias, wrapAlias, importOptions);
-function makePubKeyOptions() {
- var properties = new Array();
- properties[0] = {
- tag: huks.HuksTag.HUKS_TAG_ALGORITHM,
- value: huks.HuksKeyAlg.HUKS_ALG_ECC
- };
- properties[1] = {
- tag: huks.HuksTag.HUKS_TAG_KEY_SIZE,
- value: huks.HuksKeySize.HUKS_ECC_KEY_SIZE_256
- };
- properties[2] = {
- tag: huks.HuksTag.HUKS_TAG_PURPOSE,
- value: huks.HuksKeyPurpose.HUKS_KEY_PURPOSE_UNWRAP
- };
- properties[3] = {
- tag: huks.HuksTag.HUKS_TAG_DIGEST,
- value: huks.HuksKeyDigest.HUKS_DIGEST_SHA256
- };
- properties[4] = {
- tag: huks.HuksTag.HUKS_TAG_IMPORT_KEY_TYPE,
- value: huks.HuksImportKeyType.HUKS_KEY_TYPE_KEY_PAIR,
- };
- var options = {
- properties: properties,
- inData: inputEccPair
- };
- return options;
+ await publicDeleteKeyFunc(wrapAlias, huksOptions);
+ await publicDeleteKeyFunc(importAlias, importOptions);
}
-function makeImportOptions() {
- var properties = new Array();
- properties[0] = {
- tag: huks.HuksTag.HUKS_TAG_ALGORITHM,
- value: huks.HuksKeyAlg.HUKS_ALG_AES
- };
- properties[1] = {
- tag: huks.HuksTag.HUKS_TAG_KEY_SIZE,
- value: huks.HuksKeySize.HUKS_AES_KEY_SIZE_256
- };
- properties[2] = {
- tag: huks.HuksTag.HUKS_TAG_PURPOSE,
- value:
- huks.HuksKeyPurpose.HUKS_KEY_PURPOSE_ENCRYPT |
- huks.HuksKeyPurpose.HUKS_KEY_PURPOSE_DECRYPT
- };
- properties[3] = {
- tag: huks.HuksTag.HUKS_TAG_BLOCK_MODE,
- value: huks.HuksCipherMode.HUKS_MODE_CBC
- };
- properties[4] = {
- tag: huks.HuksTag.HUKS_TAG_PADDING,
- value: huks.HuksKeyPadding.HUKS_PADDING_NONE
- };
- properties[5] = {
- tag: huks.HuksTag.HUKS_TAG_UNWRAP_ALGORITHM_SUITE,
- value: huks.HuksUnwrapSuite.HUKS_UNWRAP_SUITE_ECDH_AES_256_GCM_NOPADDING
- };
- var options = {
- properties: properties
- };
- return options;
-}
-
-function huksImportWrappedKey() {
- var genOptions = makePubKeyOptions();
- var importOptions = makeImportOptions();
- TestImportWrappedKeyFunc(
- importAlias,
- wrapAlias,
- genOptions,
- importOptions
- );
+@Entry
+@Component
+struct Index {
+ build() {
+ Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) {
+ Button() {
+ Text('importWrappedKeyItemTest')
+ .fontSize(30)
+ .fontWeight(FontWeight.Bold)
+ }.type(ButtonType.Capsule)
+ .margin({
+ top: 20
+ })
+ .backgroundColor('#0D9FFB')
+ .onClick(()=>{
+ importWrappedKeyItemTest();
+ })
+ }
+ .width('100%')
+ .height('100%')
+ }
}
```
@@ -553,14 +660,17 @@ function huksImportWrappedKey() {
*
* 以下以SM4 128密钥的Promise操作使用为例
*/
-function sm4CipherStringToUint8Array(str) {
+import huks from '@ohos.security.huks';
+
+function StringToUint8Array(str) {
var arr = [];
for (var i = 0, j = str.length; i < j; ++i) {
arr.push(str.charCodeAt(i));
}
return new Uint8Array(arr);
}
-function sm4CipherUint8ArrayToString(fileData) {
+
+function Uint8ArrayToString(fileData) {
var dataString = '';
for (var i = 0; i < fileData.length; i++) {
dataString += String.fromCharCode(fileData[i]);
@@ -568,14 +678,157 @@ function sm4CipherUint8ArrayToString(fileData) {
return dataString;
}
-var handle;
+async function publicGenKeyFunc(keyAlias:string, huksOptions:huks.HuksOptions) {
+ console.info(`enter callback generateKeyItem`);
+ try {
+ await generateKeyItem(keyAlias, huksOptions)
+ .then((data) => {
+ console.info(`callback: generateKeyItem success, data = ${JSON.stringify(data)}`);
+ })
+ .catch(error => {
+ console.error(`callback: generateKeyItem failed, code: ${error.code}, msg: ${error.message}`);
+ });
+ } catch (error) {
+ console.error(`callback: generateKeyItem input arg invalid, code: ${error.code}, msg: ${error.message}`);
+ }
+}
+
+function generateKeyItem(keyAlias:string, huksOptions:huks.HuksOptions) {
+ return new Promise((resolve, reject) => {
+ try {
+ huks.generateKeyItem(keyAlias, huksOptions, function (error, data) {
+ if (error) {
+ reject(error);
+ } else {
+ resolve(data);
+ }
+ });
+ } catch (error) {
+ throw(error);
+ }
+ });
+}
+
+async function publicInitFunc(keyAlias:string, huksOptions:huks.HuksOptions) {
+ console.info(`enter promise doInit`);
+ try {
+ await huks.initSession(keyAlias, huksOptions)
+ .then ((data) => {
+ console.info(`promise: doInit success, data = ${JSON.stringify(data)}`);
+ handle = data.handle;
+ })
+ .catch(error => {
+ console.error(`promise: doInit key failed, code: ${error.code}, msg: ${error.message}`);
+ });
+ } catch (error) {
+ console.error(`promise: doInit input arg invalid, code: ${error.code}, msg: ${error.message}`);
+ }
+}
+
+async function publicUpdateFunc(handle:number, huksOptions:huks.HuksOptions) {
+ console.info(`enter callback doUpdate`);
+ try {
+ await updateSession(handle, huksOptions)
+ .then ((data) => {
+ console.info(`callback: doUpdate success, data = ${JSON.stringify(data)}`);
+ updateResult = Array.from(data.outData);
+ })
+ .catch(error => {
+ console.error(`callback: doUpdate failed, code: ${error.code}, msg: ${error.message}`);
+ });
+ } catch (error) {
+ console.error(`callback: doUpdate input arg invalid, code: ${error.code}, msg: ${error.message}`);
+ }
+}
+
+function updateSession(handle:number, huksOptions:huks.HuksOptions) : Promise {
+ return new Promise((resolve, reject) => {
+ try {
+ huks.updateSession(handle, huksOptions, function (error, data) {
+ if (error) {
+ reject(error);
+ } else {
+ resolve(data);
+ }
+ });
+ } catch (error) {
+ throw(error);
+ }
+ });
+}
+
+async function publicFinishFunc(handle:number, huksOptions:huks.HuksOptions) {
+ console.info(`enter callback doFinish`);
+ try {
+ await finishSession(handle, huksOptions)
+ .then ((data) => {
+ finishOutData = Uint8ArrayToString(new Uint8Array(updateResult));
+ console.info(`callback: doFinish success, data = ${JSON.stringify(data)}`);
+ })
+ .catch(error => {
+ console.error(`callback: doFinish failed, code: ${error.code}, msg: ${error.message}`);
+ });
+ } catch (error) {
+ console.error(`callback: doFinish input arg invalid, code: ${error.code}, msg: ${error.message}`);
+ }
+}
+
+function finishSession(handle:number, huksOptions:huks.HuksOptions) : Promise {
+ return new Promise((resolve, reject) => {
+ try {
+ huks.finishSession(handle, huksOptions, function (error, data) {
+ if (error) {
+ reject(error);
+ } else {
+ resolve(data);
+ }
+ });
+ } catch (error) {
+ throw(error);
+ }
+ });
+}
+
+async function publicDeleteKeyFunc(keyAlias:string, huksOptions:huks.HuksOptions) {
+ console.info(`enter callback deleteKeyItem`);
+ try {
+ await deleteKeyItem(keyAlias, huksOptions)
+ .then ((data) => {
+ console.info(`callback: deleteKeyItem key success, data = ${JSON.stringify(data)}`);
+ })
+ .catch(error => {
+ console.error(`callback: deleteKeyItem failed, code: ${error.code}, msg: ${error.message}`);
+ });
+ } catch (error) {
+ console.error(`callback: deleteKeyItem input arg invalid, code: ${error.code}, msg: ${error.message}`);
+ }
+}
+
+function deleteKeyItem(keyAlias:string, huksOptions:huks.HuksOptions) {
+ return new Promise((resolve, reject) => {
+ try {
+ huks.deleteKeyItem(keyAlias, huksOptions, function (error, data) {
+ if (error) {
+ reject(error);
+ } else {
+ resolve(data);
+ }
+ });
+ } catch (error) {
+ throw(error);
+ }
+ });
+}
+
var IV = '0000000000000000';
var cipherInData = 'Hks_SM4_Cipher_Test_101010101010101010110_string';
var srcKeyAlias = 'huksCipherSm4SrcKeyAlias';
var encryptUpdateResult = new Array();
-var decryptUpdateResult = new Array();
+var handle;
+var updateResult = new Array();
+var finishOutData;
-async function testCipher() {
+async function testSm4Cipher() {
/* 集成生成密钥参数集 & 加密参数集 */
var properties = new Array();
properties[0] = {
@@ -628,7 +881,7 @@ async function testCipher() {
}
propertiesEncrypt[5] = {
tag: huks.HuksTag.HUKS_TAG_IV,
- value: sm4CipherStringToUint8Array(IV),
+ value: StringToUint8Array(IV),
}
var encryptOptions = {
properties: propertiesEncrypt,
@@ -636,38 +889,22 @@ async function testCipher() {
}
/* 生成密钥 */
- await huks.generateKey(srcKeyAlias, huksOptions).then((data) => {
- console.info(`test generateKey data: ${JSON.stringify(data)}`);
- }).catch((err) => {
- console.info('test generateKey err information: ' + JSON.stringify(err));
- });
+ await publicGenKeyFunc(srcKeyAlias, huksOptions);
/* 进行密钥加密操作 */
- await huks.init(srcKeyAlias, encryptOptions).then((data) => {
- console.info(`test init data: ${JSON.stringify(data)}`);
- handle = data.handle;
- }).catch((err) => {
- console.info('test init err information: ' + JSON.stringify(err));
- });
- encryptOptions.inData = sm4CipherStringToUint8Array(cipherInData);
- await huks.update(handle, encryptOptions).then(async (data) => {
- console.info(`test update data ${JSON.stringify(data)}`);
- encryptUpdateResult = Array.from(data.outData);
- }).catch((err) => {
- console.info('test update err information: ' + err);
- });
+ await publicInitFunc(srcKeyAlias, encryptOptions);
+
+ encryptOptions.inData = StringToUint8Array(cipherInData);
+ await publicUpdateFunc(handle, encryptOptions);
+ encryptUpdateResult = updateResult;
+
encryptOptions.inData = new Uint8Array(new Array());
- await huks.finish(handle, encryptOptions).then((data) => {
- console.info(`test finish data: ${JSON.stringify(data)}`);
- var finishData = sm4CipherUint8ArrayToString(new Uint8Array(encryptUpdateResult));
- if (finishData === cipherInData) {
- console.info('test finish encrypt err ');
- } else {
- console.info('test finish encrypt success');
- }
- }).catch((err) => {
- console.info('test finish err information: ' + JSON.stringify(err));
- });
+ await publicFinishFunc(handle, encryptOptions);
+ if (finishOutData === cipherInData) {
+ console.info('test finish encrypt err ');
+ } else {
+ console.info('test finish encrypt success');
+ }
/* 修改加密参数集为解密参数集 */
propertiesEncrypt.splice(1, 1, {
@@ -680,37 +917,43 @@ async function testCipher() {
}
/* 进行解密操作 */
- await huks.init(srcKeyAlias, decryptOptions).then((data) => {
- console.info(`test init data: ${JSON.stringify(data)}`);
- handle = data.handle;
- }).catch((err) => {
- console.info('test init err information: ' + JSON.stringify(err));
- });
+ await publicInitFunc(srcKeyAlias, decryptOptions);
+
decryptOptions.inData = new Uint8Array(encryptUpdateResult);
- await huks.update(handle, decryptOptions).then(async (data) => {
- console.info(`test update data ${JSON.stringify(data)}`);
- decryptUpdateResult = Array.from(data.outData);
- }).catch((err) => {
- console.info('test update err information: ' + err);
- });
+ await publicUpdateFunc(handle, decryptOptions);
+
decryptOptions.inData = new Uint8Array(new Array());
- await huks.finish(handle, decryptOptions).then((data) => {
- console.info(`test finish data: ${JSON.stringify(data)}`);
- var finishData = sm4CipherUint8ArrayToString(new Uint8Array(decryptUpdateResult));
- if (finishData === cipherInData) {
- console.info('test finish decrypt success ');
- } else {
- console.info('test finish decrypt err');
- }
- }).catch((err) => {
- console.info('test finish err information: ' + JSON.stringify(err));
- });
+ await publicFinishFunc(handle, decryptOptions);
+ if (finishOutData === cipherInData) {
+ console.info('test finish decrypt success ');
+ } else {
+ console.info('test finish decrypt err');
+ }
- await huks.deleteKey(srcKeyAlias, huksOptions).then((data) => {
- console.info(`test deleteKey data: ${JSON.stringify(data)}`);
- }).catch((err) => {
- console.info('test deleteKey err information: ' + JSON.stringify(err));
- });
+ await publicDeleteKeyFunc(srcKeyAlias, huksOptions);
+}
+
+@Entry
+@Component
+struct Index {
+ build() {
+ Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) {
+ Button() {
+ Text('testSm4Cipher')
+ .fontSize(30)
+ .fontWeight(FontWeight.Bold)
+ }.type(ButtonType.Capsule)
+ .margin({
+ top: 20
+ })
+ .backgroundColor('#0D9FFB')
+ .onClick(()=>{
+ testSm4Cipher();
+ })
+ }
+ .width('100%')
+ .height('100%')
+ }
}
```
@@ -721,14 +964,17 @@ async function testCipher() {
*
* 以下以AES128 GCM密钥的Promise操作使用为例
*/
-function aesCipherStringToUint8Array(str) {
+import huks from '@ohos.security.huks';
+
+function StringToUint8Array(str) {
var arr = [];
for (var i = 0, j = str.length; i < j; ++i) {
arr.push(str.charCodeAt(i));
}
return new Uint8Array(arr);
}
-function aesCipherUint8ArrayToString(fileData) {
+
+function Uint8ArrayToString(fileData) {
var dataString = '';
for (var i = 0; i < fileData.length; i++) {
dataString += String.fromCharCode(fileData[i]);
@@ -736,15 +982,160 @@ function aesCipherUint8ArrayToString(fileData) {
return dataString;
}
-async function aesCipher() {
- var handle;
- var AAD = '0000000000000000';
- var NONCE = '000000000000';
- var AEAD = '0000000000000000';
- var cipherInData = 'Hks_AES_Cipher_Test_00000000000000000000000000000000000000000000000000000_string';
- var srcKeyAlias = 'huksCipherAesSrcKeyAlias';
- var encryptUpdateResult = new Array();
- var decryptUpdateResult = new Array();
+async function publicGenKeyFunc(keyAlias:string, huksOptions:huks.HuksOptions) {
+ console.info(`enter callback generateKeyItem`);
+ try {
+ await generateKeyItem(keyAlias, huksOptions)
+ .then((data) => {
+ console.info(`callback: generateKeyItem success, data = ${JSON.stringify(data)}`);
+ })
+ .catch(error => {
+ console.error(`callback: generateKeyItem failed, code: ${error.code}, msg: ${error.message}`);
+ });
+ } catch (error) {
+ console.error(`callback: generateKeyItem input arg invalid, code: ${error.code}, msg: ${error.message}`);
+ }
+}
+
+function generateKeyItem(keyAlias:string, huksOptions:huks.HuksOptions) {
+ return new Promise((resolve, reject) => {
+ try {
+ huks.generateKeyItem(keyAlias, huksOptions, function (error, data) {
+ if (error) {
+ reject(error);
+ } else {
+ resolve(data);
+ }
+ });
+ } catch (error) {
+ throw(error);
+ }
+ });
+}
+
+async function publicInitFunc(keyAlias:string, huksOptions:huks.HuksOptions) {
+ console.info(`enter promise doInit`);
+ try {
+ await huks.initSession(keyAlias, huksOptions)
+ .then ((data) => {
+ console.info(`promise: doInit success, data = ${JSON.stringify(data)}`);
+ handle = data.handle;
+ })
+ .catch(error => {
+ console.error(`promise: doInit key failed, code: ${error.code}, msg: ${error.message}`);
+ });
+ } catch (error) {
+ console.error(`promise: doInit input arg invalid, code: ${error.code}, msg: ${error.message}`);
+ }
+}
+
+async function publicUpdateFunc(handle:number, huksOptions:huks.HuksOptions) {
+ console.info(`enter callback doUpdate`);
+ try {
+ await updateSession(handle, huksOptions)
+ .then ((data) => {
+ console.info(`callback: doUpdate success, data = ${JSON.stringify(data)}`);
+ updateResult = Array.from(data.outData);
+ })
+ .catch(error => {
+ console.error(`callback: doUpdate failed, code: ${error.code}, msg: ${error.message}`);
+ });
+ } catch (error) {
+ console.error(`callback: doUpdate input arg invalid, code: ${error.code}, msg: ${error.message}`);
+ }
+}
+
+function updateSession(handle:number, huksOptions:huks.HuksOptions) : Promise {
+ return new Promise((resolve, reject) => {
+ try {
+ huks.updateSession(handle, huksOptions, function (error, data) {
+ if (error) {
+ reject(error);
+ } else {
+ resolve(data);
+ }
+ });
+ } catch (error) {
+ throw(error);
+ }
+ });
+}
+
+async function publicFinishFunc(handle:number, huksOptions:huks.HuksOptions) {
+ console.info(`enter callback doFinish`);
+ try {
+ await finishSession(handle, huksOptions)
+ .then ((data) => {
+ updateResult = updateResult.concat(Array.from(data.outData));
+ console.info(`callback: doFinish success, data = ${JSON.stringify(data)}`);
+ })
+ .catch(error => {
+ console.error(`callback: doFinish failed, code: ${error.code}, msg: ${error.message}`);
+ });
+ } catch (error) {
+ console.error(`callback: doFinish input arg invalid, code: ${error.code}, msg: ${error.message}`);
+ }
+}
+
+function finishSession(handle:number, huksOptions:huks.HuksOptions) : Promise {
+ return new Promise((resolve, reject) => {
+ try {
+ huks.finishSession(handle, huksOptions, function (error, data) {
+ if (error) {
+ reject(error);
+ } else {
+ resolve(data);
+ }
+ });
+ } catch (error) {
+ throw(error);
+ }
+ });
+}
+
+async function publicDeleteKeyFunc(keyAlias:string, huksOptions:huks.HuksOptions) {
+ console.info(`enter callback deleteKeyItem`);
+ try {
+ await deleteKeyItem(keyAlias, huksOptions)
+ .then ((data) => {
+ console.info(`callback: deleteKeyItem key success, data = ${JSON.stringify(data)}`);
+ })
+ .catch(error => {
+ console.error(`callback: deleteKeyItem failed, code: ${error.code}, msg: ${error.message}`);
+ });
+ } catch (error) {
+ console.error(`callback: deleteKeyItem input arg invalid, code: ${error.code}, msg: ${error.message}`);
+ }
+}
+
+function deleteKeyItem(keyAlias:string, huksOptions:huks.HuksOptions) {
+ return new Promise((resolve, reject) => {
+ try {
+ huks.deleteKeyItem(keyAlias, huksOptions, function (error, data) {
+ if (error) {
+ reject(error);
+ } else {
+ resolve(data);
+ }
+ });
+ } catch (error) {
+ throw(error);
+ }
+ });
+}
+
+var AAD = '0000000000000000';
+var NONCE = '000000000000';
+var AEAD = '0000000000000000';
+var cipherInData = 'Hks_AES_Cipher_Test_00000000000000000000000000000000000000000000000000000_string';
+var srcKeyAlias = 'huksCipherSm4SrcKeyAlias';
+var updateResult = new Array();
+var encryptUpdateResult = new Array();
+var decryptUpdateResult = new Array();
+var handle;
+var finishOutData;
+
+async function testAesCipher() {
/* 集成生成密钥参数集 & 加密参数集 */
var properties = new Array();
properties[0] = {
@@ -769,7 +1160,7 @@ async function aesCipher() {
tag: huks.HuksTag.HUKS_TAG_PADDING,
value: huks.HuksKeyPadding.HUKS_PADDING_NONE,
}
- var HuksOptions = {
+ var huksOptions = {
properties: properties,
inData: new Uint8Array(new Array())
}
@@ -801,15 +1192,15 @@ async function aesCipher() {
}
propertiesEncrypt[6] = {
tag: huks.HuksTag.HUKS_TAG_ASSOCIATED_DATA,
- value: aesCipherStringToUint8Array(AAD),
+ value: StringToUint8Array(AAD),
}
propertiesEncrypt[7] = {
tag: huks.HuksTag.HUKS_TAG_NONCE,
- value: aesCipherStringToUint8Array(NONCE),
+ value: StringToUint8Array(NONCE),
}
propertiesEncrypt[8] = {
tag: huks.HuksTag.HUKS_TAG_AE_TAG,
- value: aesCipherStringToUint8Array(AEAD),
+ value: StringToUint8Array(AEAD),
}
var encryptOptions = {
properties: propertiesEncrypt,
@@ -817,39 +1208,24 @@ async function aesCipher() {
}
/* 生成密钥 */
- await huks.generateKey(srcKeyAlias, HuksOptions).then((data) => {
- console.info(`test generateKey data: ${JSON.stringify(data)}`);
- }).catch((err) => {
- console.info('test generateKey err information: ' + JSON.stringify(err));
- });
+ await publicGenKeyFunc(srcKeyAlias, huksOptions);
/* 进行密钥加密操作 */
- await huks.init(srcKeyAlias, encryptOptions).then((data) => {
- console.info(`test init data: ${JSON.stringify(data)}`);
- handle = data.handle;
- }).catch((err) => {
- console.info('test init err information: ' + JSON.stringify(err));
- });
- encryptOptions.inData = aesCipherStringToUint8Array(cipherInData.slice(0,64));
- await huks.update(handle, encryptOptions).then(async (data) => {
- console.info(`test update data ${JSON.stringify(data)}`);
- encryptUpdateResult = Array.from(data.outData);
- }).catch((err) => {
- console.info('test update err information: ' + err);
- });
- encryptOptions.inData = aesCipherStringToUint8Array(cipherInData.slice(64,80));
- await huks.finish(handle, encryptOptions).then((data) => {
- console.info(`test finish data: ${JSON.stringify(data)}`);
- encryptUpdateResult = encryptUpdateResult.concat(Array.from(data.outData));
- var finishData = aesCipherUint8ArrayToString(new Uint8Array(encryptUpdateResult));
- if (finishData === cipherInData) {
- console.info('test finish encrypt err ');
- } else {
- console.info('test finish encrypt success');
- }
- }).catch((err) => {
- console.info('test finish err information: ' + JSON.stringify(err));
- });
+ await publicInitFunc(srcKeyAlias, encryptOptions);
+
+ encryptOptions.inData = StringToUint8Array(cipherInData.slice(0,64));
+ await publicUpdateFunc(handle, encryptOptions);
+ encryptUpdateResult = updateResult;
+
+ encryptOptions.inData = StringToUint8Array(cipherInData.slice(64,80));
+ await publicFinishFunc(handle, encryptOptions);
+ encryptUpdateResult = updateResult;
+ finishOutData = Uint8ArrayToString(new Uint8Array(encryptUpdateResult));
+ if (finishOutData === cipherInData) {
+ console.info('test finish encrypt err ');
+ } else {
+ console.info('test finish encrypt success');
+ }
/* 修改加密参数集为解密参数集 */
propertiesEncrypt.splice(1, 1, {
@@ -866,38 +1242,46 @@ async function aesCipher() {
}
/* 进行解密操作 */
- await huks.init(srcKeyAlias, decryptOptions).then((data) => {
- console.info(`test init data: ${JSON.stringify(data)}`);
- handle = data.handle;
- }).catch((err) => {
- console.info('test init err information: ' + JSON.stringify(err));
- });
+ await publicInitFunc(srcKeyAlias, decryptOptions);
+
decryptOptions.inData = new Uint8Array(encryptUpdateResult.slice(0,64));
- await huks.update(handle, decryptOptions).then(async (data) => {
- console.info(`test update data ${JSON.stringify(data)}`);
- decryptUpdateResult = Array.from(data.outData);
- }).catch((err) => {
- console.info('test update err information: ' + err);
- });
+ await publicUpdateFunc(handle, decryptOptions);
+ decryptUpdateResult = updateResult;
+
decryptOptions.inData = new Uint8Array(encryptUpdateResult.slice(64,encryptUpdateResult.length));
- await huks.finish(handle, decryptOptions).then((data) => {
- console.info(`test finish data: ${JSON.stringify(data)}`);
- decryptUpdateResult = decryptUpdateResult.concat(Array.from(data.outData));
- var finishData = aesCipherUint8ArrayToString(new Uint8Array(decryptUpdateResult));
- if (finishData === cipherInData) {
- console.info('test finish decrypt success ');
- } else {
- console.info('test finish decrypt err');
- }
- }).catch((err) => {
- console.info('test finish err information: ' + JSON.stringify(err));
- });
+ await publicFinishFunc(handle, decryptOptions);
+ decryptUpdateResult = updateResult;
+ finishOutData = Uint8ArrayToString(new Uint8Array(decryptUpdateResult));
+ if (finishOutData === cipherInData) {
+ console.info('test finish decrypt success ');
+ } else {
+ console.info('test finish decrypt err');
+ }
- await huks.deleteKey(srcKeyAlias, HuksOptions).then((data) => {
- console.info(`test deleteKey data: ${JSON.stringify(data)}`);
- }).catch((err) => {
- console.info('test deleteKey err information: ' + JSON.stringify(err));
- });
+ await publicDeleteKeyFunc(srcKeyAlias, huksOptions);
+}
+
+@Entry
+@Component
+struct Index {
+ build() {
+ Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) {
+ Button() {
+ Text('testAesCipher')
+ .fontSize(30)
+ .fontWeight(FontWeight.Bold)
+ }.type(ButtonType.Capsule)
+ .margin({
+ top: 20
+ })
+ .backgroundColor('#0D9FFB')
+ .onClick(()=>{
+ testAesCipher();
+ })
+ }
+ .width('100%')
+ .height('100%')
+ }
}
```
@@ -938,13 +1322,13 @@ Update过程只将inData发送到Core中记录在ctx中,不进行Hash计算,
在使用示例前,需要先了解几个预先定义的变量:
-| 参数名 | 类型 | 必填 | 说明 |
-| -------------------- | ----------- | ---- | ------------------------ |
-| srcRsaKeyAliasSign | string | 是 | 生成密钥别名。 |
-| srcRsaKeyAliasVerify | string | 是 | 导入密钥别名。 |
-| rsaSignOptions | HuksOptions | 是 | 用于存放生成key所需TAG。 |
-| rsaSignOptionsSecond | HuksOptions | 是 | 用于存放签名key所需TAG。 |
-| rsaVerifyOptions | HuksOptions | 是 | 用于存放验签key所需TAG。 |
+| 参数名 | 类型 | 必填 | 说明 |
+| ----------------- | ----------- | ---- | ------------------------ |
+| generateKeyAlias | string | 是 | 生成密钥别名。 |
+| importKeyAlias | string | 是 | 导入密钥别名。 |
+| genrateKeyOptions | HuksOptions | 是 | 用于存放生成key所需TAG。 |
+| signOptions | HuksOptions | 是 | 用于存放签名key所需TAG。 |
+| verifyOptions | HuksOptions | 是 | 用于存放验签key所需TAG。 |
关于接口的具体信息,可在[API参考文档](../reference/apis/js-apis-huks.md)中查看。
@@ -953,9 +1337,11 @@ Update过程只将inData发送到Core中记录在ctx中,不进行Hash计算,
```ts
/* Sign/Verify操作支持RSA、ECC、SM2、ED25519、DSA类型的密钥。
*
- * 以下以RSA512密钥的Promise操作使用为例
+ * 以下以SM2密钥的Callback操作使用为例
*/
-function rsaSignVerifyStringToUint8Array(str) {
+import huks from '@ohos.security.huks';
+
+function StringToUint8Array(str) {
var arr = [];
for (var i = 0, j = str.length; i < j; ++i) {
arr.push(str.charCodeAt(i));
@@ -963,168 +1349,367 @@ function rsaSignVerifyStringToUint8Array(str) {
return new Uint8Array(arr);
}
-var rsaSignHandle;
-var rsaSignVerifyInData = 'signVerifyInData';
-var srcRsaKeyAliasSign = 'huksSignVerifySrcKeyAliasSign';
-var srcRsaKeyAliasVerify = 'huksSignVerifySrcKeyAliasVerify';
-var finishRsaSignData;
-var rsaExportSignKey;
-
-async function testSignVerify() {
- /* 集成生成密钥参数集 & 签名参数集 & 验签参数集 */
- var rsaSignProperties = new Array();
- rsaSignProperties[0] = {
- tag: huks.HuksTag.HUKS_TAG_ALGORITHM,
- value: huks.HuksKeyAlg.HUKS_ALG_RSA,
- }
- rsaSignProperties[1] = {
- tag: huks.HuksTag.HUKS_TAG_PURPOSE,
- value: huks.HuksKeyPurpose.HUKS_KEY_PURPOSE_SIGN,
- }
- rsaSignProperties[2] = {
- tag: huks.HuksTag.HUKS_TAG_KEY_SIZE,
- value: huks.HuksKeySize.HUKS_RSA_KEY_SIZE_512,
- }
- rsaSignProperties[3] = {
- tag: huks.HuksTag.HUKS_TAG_DIGEST,
- value: huks.HuksKeyDigest.HUKS_DIGEST_MD5,
- }
- rsaSignProperties[4] = {
- tag: huks.HuksTag.HUKS_TAG_PADDING,
- value: huks.HuksKeyPadding.HUKS_PADDING_PKCS1_V1_5,
- }
- var rsaSignOptions = {
- properties: rsaSignProperties,
- inData: new Uint8Array(new Array())
+async function publicGenKeyFunc(keyAlias:string, huksOptions:huks.HuksOptions) {
+ console.info(`enter callback generateKeyItem`);
+ try {
+ await generateKeyItem(keyAlias, huksOptions)
+ .then((data) => {
+ console.info(`callback: generateKeyItem success, data = ${JSON.stringify(data)}`);
+ })
+ .catch(error => {
+ console.error(`callback: generateKeyItem failed, code: ${error.code}, msg: ${error.message}`);
+ });
+ } catch (error) {
+ console.error(`callback: generateKeyItem input arg invalid, code: ${error.code}, msg: ${error.message}`);
}
+}
- var rsaPropertiesSign = new Array();
- rsaPropertiesSign[0] = {
- tag: huks.HuksTag.HUKS_TAG_ALGORITHM,
- value: huks.HuksKeyAlg.HUKS_ALG_RSA,
- }
- rsaPropertiesSign[1] = {
- tag: huks.HuksTag.HUKS_TAG_PURPOSE,
- value:
- huks.HuksKeyPurpose.HUKS_KEY_PURPOSE_SIGN
- }
- rsaPropertiesSign[2] = {
- tag: huks.HuksTag.HUKS_TAG_DIGEST,
- value: huks.HuksKeyDigest.HUKS_DIGEST_MD5,
- }
- rsaPropertiesSign[3] = {
- tag: huks.HuksTag.HUKS_TAG_KEY_SIZE,
- value: huks.HuksKeySize.HUKS_RSA_KEY_SIZE_512,
- }
- rsaPropertiesSign[4] = {
- tag: huks.HuksTag.HUKS_TAG_PADDING,
- value: huks.HuksKeyPadding.HUKS_PADDING_PKCS1_V1_5,
- }
- var rsaSignOptionsSecond = {
- properties: rsaPropertiesSign,
- inData: new Uint8Array(new Array())
- }
+function generateKeyItem(keyAlias:string, huksOptions:huks.HuksOptions) {
+ return new Promise((resolve, reject) => {
+ try {
+ huks.generateKeyItem(keyAlias, huksOptions, function (error, data) {
+ if (error) {
+ reject(error);
+ } else {
+ resolve(data);
+ }
+ });
+ } catch (error) {
+ throw(error);
+ }
+ });
+}
- var rsaPropertiesVerify = new Array();
- rsaPropertiesVerify[0] = {
- tag: huks.HuksTag.HUKS_TAG_ALGORITHM,
- value: huks.HuksKeyAlg.HUKS_ALG_RSA,
- }
- rsaPropertiesVerify[1] = {
- tag: huks.HuksTag.HUKS_TAG_PURPOSE,
- value: huks.HuksKeyPurpose.HUKS_KEY_PURPOSE_VERIFY
- }
- rsaPropertiesVerify[2] = {
- tag: huks.HuksTag.HUKS_TAG_DIGEST,
- value: huks.HuksKeyDigest.HUKS_DIGEST_MD5,
- }
- rsaPropertiesVerify[3] = {
- tag: huks.HuksTag.HUKS_TAG_KEY_SIZE,
- value: huks.HuksKeySize.HUKS_RSA_KEY_SIZE_512,
- }
- rsaPropertiesVerify[4] = {
- tag: huks.HuksTag.HUKS_TAG_PADDING,
- value: huks.HuksKeyPadding.HUKS_PADDING_PKCS1_V1_5,
- }
- var rsaVerifyOptions = {
- properties: rsaPropertiesVerify,
- inData: new Uint8Array(new Array())
+async function publicInitFunc(keyAlias:string, huksOptions:huks.HuksOptions) {
+ console.info(`enter callback doInit`);
+ try {
+ await initSession(keyAlias, huksOptions)
+ .then ((data) => {
+ console.info(`callback1: doInit success, data = ${JSON.stringify(data)}`);
+ handle = data.handle;
+ })
+ .catch((error) => {
+ console.error(`callback1: doInit failed, code: ${error.code}, msg: ${error.message}`);
+ });
+ } catch (error) {
+ console.error(`callback: doInit input arg invalid, code: ${error.code}, msg: ${error.message}`);
}
+}
- /* 生成密钥 */
- await huks.generateKey(srcRsaKeyAliasSign, rsaSignOptions).then((data) => {
- console.info(`test generateKey data: ${JSON.stringify(data)}`);
- }).catch((err) => {
- console.info('test generateKey err information: ' + JSON.stringify(err));
+function initSession(keyAlias:string, huksOptions:huks.HuksOptions) : Promise {
+ return new Promise((resolve, reject) => {
+ try {
+ huks.initSession(keyAlias, huksOptions, function (error, data) {
+ if (error) {
+ reject(error);
+ } else {
+ resolve(data);
+ }
+ });
+ } catch (error) {
+ throw(error);
+ }
});
+}
- /* 对密钥进行签名操作 */
- await huks.init(srcRsaKeyAliasSign, rsaSignOptionsSecond).then((data) => {
- console.info(`test init data: ${JSON.stringify(data)}`);
- rsaSignHandle = data.handle;
- }).catch((err) => {
- console.info('test init err information: ' + JSON.stringify(err));
- });
- rsaSignOptionsSecond.inData = rsaSignVerifyStringToUint8Array(rsaSignVerifyInData)
- await huks.update(rsaSignHandle, rsaSignOptionsSecond).then(async (data) => {
- console.info(`test update data ${JSON.stringify(data)}`);
- }).catch((err) => {
- console.info('test update err information: ' + err);
- });
- rsaSignOptionsSecond.inData = new Uint8Array(new Array());
- await huks.finish(rsaSignHandle, rsaSignOptionsSecond).then((data) => {
- console.info(`test finish data: ${JSON.stringify(data)}`);
- finishRsaSignData = data.outData;
- }).catch((err) => {
- console.info('test finish err information: ' + JSON.stringify(err));
- });
+async function publicUpdateFunc(handle:number, huksOptions:huks.HuksOptions) {
+ console.info(`enter callback doUpdate`);
+ try {
+ await updateSession(handle, huksOptions)
+ .then ((data) => {
+ console.info(`callback: doUpdate success, data = ${JSON.stringify(data)}`);
+ })
+ .catch(error => {
+ console.error(`callback: doUpdate failed, code: ${error.code}, msg: ${error.message}`);
+ });
+ } catch (error) {
+ console.error(`callback: doUpdate input arg invalid, code: ${error.code}, msg: ${error.message}`);
+ }
+}
- /* 通过导出导入模拟获取一段密钥数据 */
- await huks.exportKey(srcRsaKeyAliasSign, rsaSignOptions).then((data) => {
- console.info(`test exportKey data: ${JSON.stringify(data)}`);
- rsaExportSignKey = data.outData;
- }).catch((err) => {
- console.info('test exportKey err information: ' + JSON.stringify(err));
- });
- rsaVerifyOptions.inData = rsaExportSignKey;
- await huks.importKey(srcRsaKeyAliasVerify, rsaVerifyOptions).then((data) => {
- console.info(`test ImportKey data: ${JSON.stringify(data)}`);
- }).catch((err) => {
- console.info('test exportKey err information: ' + JSON.stringify(err));
+function updateSession(handle:number, huksOptions:huks.HuksOptions) : Promise {
+ return new Promise((resolve, reject) => {
+ try {
+ huks.updateSession(handle, huksOptions, function (error, data) {
+ if (error) {
+ reject(error);
+ } else {
+ resolve(data);
+ }
+ });
+ } catch (error) {
+ throw(error);
+ }
});
+}
- /* 对密钥进行验签 */
- await huks.init(srcRsaKeyAliasVerify, rsaVerifyOptions).then((data) => {
- console.info(`test init data: ${JSON.stringify(data)}`);
- rsaSignHandle = data.handle;
- }).catch((err) => {
- console.info('test init err information: ' + JSON.stringify(err));
- });
- rsaVerifyOptions.inData = rsaSignVerifyStringToUint8Array(rsaSignVerifyInData);
- await huks.update(rsaSignHandle, rsaVerifyOptions).then(async (data) => {
- console.info(`test update data ${JSON.stringify(data)}`);
- }).catch((err) => {
- console.info('test update err information: ' + err);
+async function publicFinishFunc(handle:number, huksOptions:huks.HuksOptions) {
+ console.info(`enter callback doFinish`);
+ try {
+ await finishSession(handle, huksOptions)
+ .then ((data) => {
+ finishOutData = data.outData;;
+ console.info(`callback: doFinish success, data = ${JSON.stringify(data)}`);
+ })
+ .catch(error => {
+ console.error(`callback: doFinish failed, code: ${error.code}, msg: ${error.message}`);
+ });
+ } catch (error) {
+ console.error(`callback: doFinish input arg invalid, code: ${error.code}, msg: ${error.message}`);
+ }
+}
+
+function finishSession(handle:number, huksOptions:huks.HuksOptions) : Promise {
+ return new Promise((resolve, reject) => {
+ try {
+ huks.finishSession(handle, huksOptions, function (error, data) {
+ if (error) {
+ reject(error);
+ } else {
+ resolve(data);
+ }
+ });
+ } catch (error) {
+ throw(error);
+ }
});
- rsaVerifyOptions.inData = finishRsaSignData;
- await huks.finish(rsaSignHandle, rsaVerifyOptions).then((data) => {
- console.info(`test finish data: ${JSON.stringify(data)}`);
- }).catch((err) => {
- console.info('test finish err information: ' + JSON.stringify(err));
+}
+
+async function publicExportKeyFunc(keyAlias:string, huksOptions:huks.HuksOptions) {
+ console.info(`enter callback export`);
+ try {
+ await exportKeyItem(keyAlias, huksOptions)
+ .then ((data) => {
+ console.info(`callback: exportKeyItem success, data = ${JSON.stringify(data)}`);
+ exportKey = data.outData;
+ })
+ .catch(error => {
+ console.error(`callback: exportKeyItem failed, code: ${error.code}, msg: ${error.message}`);
+ });
+ } catch (error) {
+ console.error(`callback: exportKeyItem input arg invalid, code: ${error.code}, msg: ${error.message}`);
+ }
+}
+
+function exportKeyItem(keyAlias:string, huksOptions:huks.HuksOptions) : Promise {
+ return new Promise((resolve, reject) => {
+ try {
+ huks.exportKeyItem(keyAlias, huksOptions, function (error, data) {
+ if (error) {
+ reject(error);
+ } else {
+ resolve(data);
+ }
+ });
+ } catch (error) {
+ throw(error);
+ }
});
+}
+
+async function publicImportKeyFunc(keyAlias:string, huksOptions:huks.HuksOptions) {
+ console.info(`enter promise importKeyItem`);
+ try {
+ await importKeyItem(keyAlias, huksOptions)
+ .then ((data) => {
+ console.info(`callback: importKeyItem success, data = ${JSON.stringify(data)}`);
+ })
+ .catch(error => {
+ console.error(`callback: importKeyItem failed, code: ${error.code}, msg: ${error.message}`);
+ });
+ } catch (error) {
+ console.error(`callback: importKeyItem input arg invalid, code: ${error.code}, msg: ${error.message}`);
+ }
+}
- await huks.deleteKey(srcRsaKeyAliasVerify, rsaVerifyOptions).then((data) => {
- console.info(`test deleteKey data: ${JSON.stringify(data)}`);
- }).catch((err) => {
- console.info('test deleteKey err information: ' + JSON.stringify(err));
+function importKeyItem(keyAlias:string, huksOptions:huks.HuksOptions) {
+ return new Promise((resolve, reject) => {
+ try {
+ huks.importKeyItem(keyAlias, huksOptions, function (error, data) {
+ if (error) {
+ reject(error);
+ } else {
+ resolve(data);
+ }
+ });
+ } catch (error) {
+ throw(error);
+ }
});
+}
+
+async function publicDeleteKeyFunc(keyAlias:string, huksOptions:huks.HuksOptions) {
+ console.info(`enter callback deleteKeyItem`);
+ try {
+ await deleteKeyItem(keyAlias, huksOptions)
+ .then ((data) => {
+ console.info(`callback: deleteKeyItem key success, data = ${JSON.stringify(data)}`);
+ })
+ .catch(error => {
+ console.error(`callback: deleteKeyItem failed, code: ${error.code}, msg: ${error.message}`);
+ });
+ } catch (error) {
+ console.error(`callback: deleteKeyItem input arg invalid, code: ${error.code}, msg: ${error.message}`);
+ }
+}
- await huks.deleteKey(srcRsaKeyAliasSign, rsaSignOptions).then((data) => {
- console.info(`test deleteKey data: ${JSON.stringify(data)}`);
- }).catch((err) => {
- console.info('test deleteKey err information: ' + JSON.stringify(err));
+function deleteKeyItem(keyAlias:string, huksOptions:huks.HuksOptions) {
+ return new Promise((resolve, reject) => {
+ try {
+ huks.deleteKeyItem(keyAlias, huksOptions, function (error, data) {
+ if (error) {
+ reject(error);
+ } else {
+ resolve(data);
+ }
+ });
+ } catch (error) {
+ throw(error);
+ }
});
}
+
+var signVerifyInData = 'signVerifyInDataForTest';
+var generateKeyAlias = 'generateKeyAliasForTest';
+var importKeyAlias = 'importKeyAliasForTest';
+var handle;
+var exportKey;
+var finishOutData;
+
+/* 集成生成密钥参数集 */
+var generateKeyProperties = new Array();
+generateKeyProperties[0] = {
+ tag: huks.HuksTag.HUKS_TAG_ALGORITHM,
+ value: huks.HuksKeyAlg.HUKS_ALG_SM2,
+}
+generateKeyProperties[1] = {
+ tag: huks.HuksTag.HUKS_TAG_PURPOSE,
+ value:
+ huks.HuksKeyPurpose.HUKS_KEY_PURPOSE_SIGN |
+ huks.HuksKeyPurpose.HUKS_KEY_PURPOSE_VERIFY,
+}
+generateKeyProperties[2] = {
+ tag: huks.HuksTag.HUKS_TAG_KEY_SIZE,
+ value: huks.HuksKeySize.HUKS_SM2_KEY_SIZE_256,
+}
+generateKeyProperties[3] = {
+ tag: huks.HuksTag.HUKS_TAG_DIGEST,
+ value: huks.HuksKeyDigest.HUKS_DIGEST_SM3,
+}
+var genrateKeyOptions = {
+ properties: generateKeyProperties,
+ inData: new Uint8Array(new Array())
+}
+
+/* 集成签名参数集 */
+var signProperties = new Array();
+signProperties[0] = {
+ tag: huks.HuksTag.HUKS_TAG_ALGORITHM,
+ value: huks.HuksKeyAlg.HUKS_ALG_SM2,
+}
+signProperties[1] = {
+ tag: huks.HuksTag.HUKS_TAG_PURPOSE,
+ value:
+ huks.HuksKeyPurpose.HUKS_KEY_PURPOSE_SIGN
+}
+signProperties[2] = {
+ tag: huks.HuksTag.HUKS_TAG_DIGEST,
+ value: huks.HuksKeyDigest.HUKS_DIGEST_SM3,
+}
+signProperties[3] = {
+ tag: huks.HuksTag.HUKS_TAG_KEY_SIZE,
+ value: huks.HuksKeySize.HUKS_SM2_KEY_SIZE_256,
+}
+var signOptions = {
+ properties: signProperties,
+ inData: new Uint8Array(new Array())
+}
+
+/* 集成验签参数集 */
+var verifyProperties = new Array();
+verifyProperties[0] = {
+ tag: huks.HuksTag.HUKS_TAG_ALGORITHM,
+ value: huks.HuksKeyAlg.HUKS_ALG_SM2,
+}
+verifyProperties[1] = {
+ tag: huks.HuksTag.HUKS_TAG_PURPOSE,
+ value: huks.HuksKeyPurpose.HUKS_KEY_PURPOSE_VERIFY
+}
+verifyProperties[2] = {
+ tag: huks.HuksTag.HUKS_TAG_DIGEST,
+ value: huks.HuksKeyDigest.HUKS_DIGEST_SM3,
+}
+verifyProperties[3] = {
+ tag: huks.HuksTag.HUKS_TAG_KEY_SIZE,
+ value: huks.HuksKeySize.HUKS_SM2_KEY_SIZE_256,
+}
+var verifyOptions = {
+ properties: verifyProperties,
+ inData: new Uint8Array(new Array())
+}
+
+async function testSm2SignVerify() {
+ /* 生成密钥 */
+ await publicGenKeyFunc(generateKeyAlias, genrateKeyOptions);
+
+ /* 签名 */
+ var signHandle;
+ var signFinishOutData;
+ await publicInitFunc(generateKeyAlias, signOptions);
+
+ signHandle = handle;
+ signOptions.inData = StringToUint8Array(signVerifyInData)
+ await publicUpdateFunc(signHandle, signOptions);
+
+ signOptions.inData = new Uint8Array(new Array());
+ await publicFinishFunc(signHandle, signOptions);
+ signFinishOutData = finishOutData;
+
+ /* 导出密钥 */
+ await publicExportKeyFunc(generateKeyAlias, genrateKeyOptions);
+
+ /* 导入密钥 */
+ verifyOptions.inData = exportKey;
+ await publicImportKeyFunc(importKeyAlias, verifyOptions);
+
+ /* 验证签名 */
+ var verifyHandle;
+ await publicInitFunc(importKeyAlias, verifyOptions);
+
+ verifyHandle = handle;
+
+ verifyOptions.inData = StringToUint8Array(signVerifyInData)
+ await publicUpdateFunc(verifyHandle, verifyOptions);
+
+ verifyOptions.inData = signFinishOutData;
+ await publicFinishFunc(verifyHandle, verifyOptions);
+
+ await publicDeleteKeyFunc(generateKeyAlias, genrateKeyOptions);
+ await publicDeleteKeyFunc(importKeyAlias, genrateKeyOptions);
+}
+
+@Entry
+@Component
+struct Index {
+ build() {
+ Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) {
+ Button() {
+ Text('testSm2SignVerify')
+ .fontSize(30)
+ .fontWeight(FontWeight.Bold)
+ }.type(ButtonType.Capsule)
+ .margin({
+ top: 20
+ })
+ .backgroundColor('#0D9FFB')
+ .onClick(()=>{
+ testSm2SignVerify();
+ })
+ }
+ .width('100%')
+ .height('100%')
+ }
+}
```
### 密钥协商
@@ -1185,7 +1770,9 @@ HksFinish对paramSet中参数的要求:
*
* 以下以X25519 256 TEMP密钥的Promise操作使用为例
*/
-function AgreeStringToUint8Array(str) {
+import huks from '@ohos.security.huks';
+
+function StringToUint8Array(str) {
var arr = [];
for (var i = 0, j = str.length; i < j; ++i) {
arr.push(str.charCodeAt(i));
@@ -1193,9 +1780,199 @@ function AgreeStringToUint8Array(str) {
return new Uint8Array(arr);
}
+async function publicGenKeyFunc(keyAlias:string, huksOptions:huks.HuksOptions) {
+ console.info(`enter callback generateKeyItem`);
+ try {
+ await generateKeyItem(keyAlias, huksOptions)
+ .then((data) => {
+ console.info(`callback: generateKeyItem success, data = ${JSON.stringify(data)}`);
+ })
+ .catch(error => {
+ console.error(`callback: generateKeyItem failed, code: ${error.code}, msg: ${error.message}`);
+ });
+ } catch (error) {
+ console.error(`callback: generateKeyItem input arg invalid, code: ${error.code}, msg: ${error.message}`);
+ }
+}
+
+function generateKeyItem(keyAlias:string, huksOptions:huks.HuksOptions) {
+ return new Promise((resolve, reject) => {
+ try {
+ huks.generateKeyItem(keyAlias, huksOptions, function (error, data) {
+ if (error) {
+ reject(error);
+ } else {
+ resolve(data);
+ }
+ });
+ } catch (error) {
+ throw(error);
+ }
+ });
+}
+
+async function publicInitFunc(keyAlias:string, huksOptions:huks.HuksOptions) {
+ console.info(`enter callback doInit`);
+ try {
+ await initSession(keyAlias, huksOptions)
+ .then ((data) => {
+ console.info(`callback1: doInit success, data = ${JSON.stringify(data)}`);
+ handle = data.handle;
+ })
+ .catch((error) => {
+ console.error(`callback1: doInit failed, code: ${error.code}, msg: ${error.message}`);
+ });
+ } catch (error) {
+ console.error(`callback: doInit input arg invalid, code: ${error.code}, msg: ${error.message}`);
+ }
+}
+
+function initSession(keyAlias:string, huksOptions:huks.HuksOptions) : Promise {
+ return new Promise((resolve, reject) => {
+ try {
+ huks.initSession(keyAlias, huksOptions, function (error, data) {
+ if (error) {
+ reject(error);
+ } else {
+ resolve(data);
+ }
+ });
+ } catch (error) {
+ throw(error);
+ }
+ });
+}
+
+async function publicUpdateFunc(handle:number, huksOptions:huks.HuksOptions) {
+ console.info(`enter callback doUpdate`);
+ try {
+ await updateSession(handle, huksOptions)
+ .then ((data) => {
+ console.info(`callback: doUpdate success, data = ${JSON.stringify(data)}`);
+ })
+ .catch(error => {
+ console.error(`callback: doUpdate failed, code: ${error.code}, msg: ${error.message}`);
+ });
+ } catch (error) {
+ console.error(`callback: doUpdate input arg invalid, code: ${error.code}, msg: ${error.message}`);
+ }
+}
+
+function updateSession(handle:number, huksOptions:huks.HuksOptions) : Promise {
+ return new Promise((resolve, reject) => {
+ try {
+ huks.updateSession(handle, huksOptions, function (error, data) {
+ if (error) {
+ reject(error);
+ } else {
+ resolve(data);
+ }
+ });
+ } catch (error) {
+ throw(error);
+ }
+ });
+}
+
+async function publicFinishFunc(handle:number, huksOptions:huks.HuksOptions) {
+ console.info(`enter callback doFinish`);
+ try {
+ await finishSession(handle, huksOptions)
+ .then ((data) => {
+ console.info(`callback: doFinish success, data = ${JSON.stringify(data)}`);
+ })
+ .catch(error => {
+ console.error(`callback: doFinish failed, code: ${error.code}, msg: ${error.message}`);
+ });
+ } catch (error) {
+ console.error(`callback: doFinish input arg invalid, code: ${error.code}, msg: ${error.message}`);
+ }
+}
+
+function finishSession(handle:number, huksOptions:huks.HuksOptions) : Promise {
+ return new Promise((resolve, reject) => {
+ try {
+ huks.finishSession(handle, huksOptions, function (error, data) {
+ if (error) {
+ reject(error);
+ } else {
+ resolve(data);
+ }
+ });
+ } catch (error) {
+ throw(error);
+ }
+ });
+}
+
+async function publicExportKeyFunc(keyAlias:string, huksOptions:huks.HuksOptions) {
+ console.info(`enter callback export`);
+ try {
+ await exportKeyItem(keyAlias, huksOptions)
+ .then ((data) => {
+ console.info(`callback: exportKeyItem success, data = ${JSON.stringify(data)}`);
+ exportKey = data.outData;
+ })
+ .catch(error => {
+ console.error(`callback: exportKeyItem failed, code: ${error.code}, msg: ${error.message}`);
+ });
+ } catch (error) {
+ console.error(`callback: exportKeyItem input arg invalid, code: ${error.code}, msg: ${error.message}`);
+ }
+}
+
+function exportKeyItem(keyAlias:string, huksOptions:huks.HuksOptions) : Promise {
+ return new Promise((resolve, reject) => {
+ try {
+ huks.exportKeyItem(keyAlias, huksOptions, function (error, data) {
+ if (error) {
+ reject(error);
+ } else {
+ resolve(data);
+ }
+ });
+ } catch (error) {
+ throw(error);
+ }
+ });
+}
+
+async function publicDeleteKeyFunc(keyAlias:string, huksOptions:huks.HuksOptions) {
+ console.info(`enter callback deleteKeyItem`);
+ try {
+ await deleteKeyItem(keyAlias, huksOptions)
+ .then ((data) => {
+ console.info(`callback: deleteKeyItem key success, data = ${JSON.stringify(data)}`);
+ })
+ .catch(error => {
+ console.error(`callback: deleteKeyItem failed, code: ${error.code}, msg: ${error.message}`);
+ });
+ } catch (error) {
+ console.error(`callback: deleteKeyItem input arg invalid, code: ${error.code}, msg: ${error.message}`);
+ }
+}
+
+function deleteKeyItem(keyAlias:string, huksOptions:huks.HuksOptions) {
+ return new Promise((resolve, reject) => {
+ try {
+ huks.deleteKeyItem(keyAlias, huksOptions, function (error, data) {
+ if (error) {
+ reject(error);
+ } else {
+ resolve(data);
+ }
+ });
+ } catch (error) {
+ throw(error);
+ }
+ });
+}
+
var srcKeyAliasFirst = "AgreeX25519KeyFirstAlias";
var srcKeyAliasSecond = "AgreeX25519KeySecondAlias";
var agreeX25519InData = 'AgreeX25519TestIndata';
+var handle;
+var exportKey;
var exportKeyFrist;
var exportKeySecond;
@@ -1232,28 +2009,13 @@ async function testAgree() {
}
/* 1.生成两个密钥并导出 */
- await huks.generateKey(srcKeyAliasFirst, HuksOptions).then((data) => {
- console.info('test generateKey data = ' + JSON.stringify(data));
- }).catch((err) => {
- console.info(`test generateKey err: " + ${JSON.stringify(err)}`);
- });
- await huks.generateKey(srcKeyAliasSecond, HuksOptions).then((data) => {
- console.info('test generateKey data = ' + JSON.stringify(data));
- }).catch((err) => {
- console.info(`test generateKey err: " + ${JSON.stringify(err)}`);
- });
- await huks.exportKey(srcKeyAliasFirst, HuksOptions).then((data) => {
- console.info('test exportKey data = ' + JSON.stringify(data));
- exportKeyFrist = data.outData;
- }).catch((err) => {
- console.info(`test exportKey err: " + ${JSON.stringify(err)}`);
- });
- await huks.exportKey(srcKeyAliasSecond, HuksOptions).then((data) => {
- console.info('test exportKey data = ' + JSON.stringify(data));
- exportKeySecond = data.outData;
- }).catch((err) => {
- console.info(`test exportKey err: " + ${JSON.stringify(err)}`);
- });
+ await publicGenKeyFunc(srcKeyAliasFirst, HuksOptions);
+ await publicGenKeyFunc(srcKeyAliasSecond, HuksOptions);
+
+ await publicExportKeyFunc(srcKeyAliasFirst, HuksOptions);
+ exportKeyFrist = exportKey;
+ await publicExportKeyFunc(srcKeyAliasFirst, HuksOptions);
+ exportKeySecond = exportKey;
/* 集成第一个协商参数集 */
var finishProperties = new Array();
@@ -1285,7 +2047,7 @@ async function testAgree() {
}
finishProperties[6] = {
tag: huks.HuksTag.HUKS_TAG_KEY_ALIAS,
- value: AgreeStringToUint8Array(srcKeyAliasFirst+ 'final'),
+ value: StringToUint8Array(srcKeyAliasFirst+ 'final'),
}
finishProperties[7] = {
tag: huks.HuksTag.HUKS_TAG_PADDING,
@@ -1297,67 +2059,57 @@ async function testAgree() {
}
var finishOptionsFrist = {
properties: finishProperties,
- inData: AgreeStringToUint8Array(agreeX25519InData)
+ inData: StringToUint8Array(agreeX25519InData)
}
-
+
/* 对第一个密钥进行协商 */
- await huks.init(srcKeyAliasFirst, HuksOptions).then((data) => {
- console.info(`test init data: ${JSON.stringify(data)}`);
- handle = data.handle;
- }).catch((err) => {
- console.info(`test init err: " + ${JSON.stringify(err)}`);
- });
+ await publicInitFunc(srcKeyAliasFirst, HuksOptions);
HuksOptions.inData = exportKeySecond;
- await huks.update(handle, HuksOptions).then((data) => {
- console.info(`test update data: ${JSON.stringify(data)}`);
- }).catch((err) => {
- console.info(`test update err: " + ${JSON.stringify(err)}`);
- });
- await huks.finish(handle, finishOptionsFrist).then((data) => {
- console.info(`test finish data: ${JSON.stringify(data)}`);
- }).catch((err) => {
- console.info('test finish err information: ' + JSON.stringify(err));
- });
+ await publicUpdateFunc(handle, HuksOptions);
+ await publicFinishFunc(handle, finishOptionsFrist);
/* 集成第二个协商参数集 */
var finishOptionsSecond = {
properties: finishProperties,
- inData: AgreeStringToUint8Array(agreeX25519InData)
+ inData: StringToUint8Array(agreeX25519InData)
}
finishOptionsSecond.properties.splice(6, 1, {
tag: huks.HuksTag.HUKS_TAG_KEY_ALIAS,
- value: AgreeStringToUint8Array(srcKeyAliasSecond + 'final'),
+ value: StringToUint8Array(srcKeyAliasSecond + 'final'),
})
-
+
/* 对第二个密钥进行协商 */
- await huks.init(srcKeyAliasSecond, HuksOptions).then((data) => {
- console.info(`test init data: ${JSON.stringify(data)}`);
- handle = data.handle;
- }).catch((err) => {
- console.info(`test init err: " + ${JSON.stringify(err)}`);
- });
+ await publicInitFunc(srcKeyAliasSecond, HuksOptions);
HuksOptions.inData = exportKeyFrist;
- await huks.update(handle, HuksOptions).then((data) => {
- console.info(`test update data: ${JSON.stringify(data)}`);
- }).catch((err) => {
- console.info(`test update err: " + ${JSON.stringify(err)}`);
- });
- await huks.finish(handle, finishOptionsSecond).then((data) => {
- console.info(`test finish data: ${JSON.stringify(data)}`);
- }).catch((err) => {
- console.info('test finish err information: ' + JSON.stringify(err));
- });
+ await publicUpdateFunc(handle, HuksOptions);
+ await publicFinishFunc(handle, finishOptionsSecond);
- await huks.deleteKey(srcKeyAliasFirst, huksOptions).then((data) => {
- console.info(`test deleteKey data: ${JSON.stringify(data)}`);
- }).catch((err) => {
- console.info('test deleteKey err information: ' + JSON.stringify(err));
- });
- await huks.deleteKey(srcKeyAliasSecond, huksOptions).then((data) => {
- console.info(`test deleteKey data: ${JSON.stringify(data)}`);
- }).catch((err) => {
- console.info('test deleteKey err information: ' + JSON.stringify(err));
- });
+
+ await publicDeleteKeyFunc(srcKeyAliasFirst, HuksOptions);
+ await publicDeleteKeyFunc(srcKeyAliasSecond, HuksOptions);
+}
+
+@Entry
+@Component
+struct Index {
+ build() {
+ Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) {
+ Button() {
+ Text('testAgree')
+ .fontSize(30)
+ .fontWeight(FontWeight.Bold)
+ }.type(ButtonType.Capsule)
+ .margin({
+ top: 20
+ })
+ .backgroundColor('#0D9FFB')
+ .onClick(()=>{
+ testAgree();
+ })
+ }
+ .width('100%')
+ .height('100%')
+ }
}
```
@@ -1416,7 +2168,9 @@ HksFinish对paramSet中参数的要求:
*
* 以下以HKDF256密钥的Promise操作使用为例
*/
-function hkdfStringToUint8Array(str) {
+import huks from '@ohos.security.huks';
+
+function StringToUint8Array(str) {
var arr = [];
for (var i = 0, j = str.length; i < j; ++i) {
arr.push(str.charCodeAt(i));
@@ -1424,6 +2178,146 @@ function hkdfStringToUint8Array(str) {
return new Uint8Array(arr);
}
+async function publicGenKeyFunc(keyAlias:string, huksOptions:huks.HuksOptions) {
+ console.info(`enter callback generateKeyItem`);
+ try {
+ await generateKeyItem(keyAlias, huksOptions)
+ .then((data) => {
+ console.info(`callback: generateKeyItem success, data = ${JSON.stringify(data)}`);
+ })
+ .catch(error => {
+ console.error(`callback: generateKeyItem failed, code: ${error.code}, msg: ${error.message}`);
+ });
+ } catch (error) {
+ console.error(`callback: generateKeyItem input arg invalid, code: ${error.code}, msg: ${error.message}`);
+ }
+}
+
+function generateKeyItem(keyAlias:string, huksOptions:huks.HuksOptions) {
+ return new Promise((resolve, reject) => {
+ try {
+ huks.generateKeyItem(keyAlias, huksOptions, function (error, data) {
+ if (error) {
+ reject(error);
+ } else {
+ resolve(data);
+ }
+ });
+ } catch (error) {
+ throw(error);
+ }
+ });
+}
+
+async function publicInitFunc(keyAlias:string, huksOptions:huks.HuksOptions) {
+ console.info(`enter promise doInit`);
+ try {
+ await huks.initSession(keyAlias, huksOptions)
+ .then ((data) => {
+ console.info(`promise: doInit success, data = ${JSON.stringify(data)}`);
+ handle = data.handle;
+ })
+ .catch(error => {
+ console.error(`promise: doInit key failed, code: ${error.code}, msg: ${error.message}`);
+ });
+ } catch (error) {
+ console.error(`promise: doInit input arg invalid, code: ${error.code}, msg: ${error.message}`);
+ }
+}
+
+async function publicUpdateFunc(handle:number, huksOptions:huks.HuksOptions) {
+ console.info(`enter callback doUpdate`);
+ try {
+ await updateSession(handle, huksOptions)
+ .then ((data) => {
+ console.info(`callback: doUpdate success, data = ${JSON.stringify(data)}`);
+ })
+ .catch(error => {
+ console.error(`callback: doUpdate failed, code: ${error.code}, msg: ${error.message}`);
+ });
+ } catch (error) {
+ console.error(`callback: doUpdate input arg invalid, code: ${error.code}, msg: ${error.message}`);
+ }
+}
+
+function updateSession(handle:number, huksOptions:huks.HuksOptions) : Promise {
+ return new Promise((resolve, reject) => {
+ try {
+ huks.updateSession(handle, huksOptions, function (error, data) {
+ if (error) {
+ reject(error);
+ } else {
+ resolve(data);
+ }
+ });
+ } catch (error) {
+ throw(error);
+ }
+ });
+}
+
+async function publicFinishFunc(handle:number, huksOptions:huks.HuksOptions) {
+ console.info(`enter callback doFinish`);
+ try {
+ await finishSession(handle, huksOptions)
+ .then ((data) => {
+ console.info(`callback: doFinish success, data = ${JSON.stringify(data)}`);
+ })
+ .catch(error => {
+ console.error(`callback: doFinish failed, code: ${error.code}, msg: ${error.message}`);
+ });
+ } catch (error) {
+ console.error(`callback: doFinish input arg invalid, code: ${error.code}, msg: ${error.message}`);
+ }
+}
+
+function finishSession(handle:number, huksOptions:huks.HuksOptions) : Promise {
+ return new Promise((resolve, reject) => {
+ try {
+ huks.finishSession(handle, huksOptions, function (error, data) {
+ if (error) {
+ reject(error);
+ } else {
+ resolve(data);
+ }
+ });
+ } catch (error) {
+ throw(error);
+ }
+ });
+}
+
+async function publicDeleteKeyFunc(keyAlias:string, huksOptions:huks.HuksOptions) {
+ console.info(`enter callback deleteKeyItem`);
+ try {
+ await deleteKeyItem(keyAlias, huksOptions)
+ .then ((data) => {
+ console.info(`callback: deleteKeyItem key success, data = ${JSON.stringify(data)}`);
+ })
+ .catch(error => {
+ console.error(`callback: deleteKeyItem failed, code: ${error.code}, msg: ${error.message}`);
+ });
+ } catch (error) {
+ console.error(`callback: deleteKeyItem input arg invalid, code: ${error.code}, msg: ${error.message}`);
+ }
+}
+
+function deleteKeyItem(keyAlias:string, huksOptions:huks.HuksOptions) {
+ return new Promise((resolve, reject) => {
+ try {
+ huks.deleteKeyItem(keyAlias, huksOptions, function (error, data) {
+ if (error) {
+ reject(error);
+ } else {
+ resolve(data);
+ }
+ });
+ } catch (error) {
+ throw(error);
+ }
+ });
+}
+
var deriveHkdfInData = "deriveHkdfTestIndata";
var srcKeyAlias = "deriveHkdfKeyAlias";
var handle;
@@ -1454,11 +2348,7 @@ async function testDerive() {
}
/* 生成密钥 */
- await huks.generateKey(srcKeyAlias, huksOptions).then((data) => {
- console.info('test generateKey data = ' + JSON.stringify(data));
- }).catch((err) => {
- console.info(`test init err: " + ${JSON.stringify(err)}`);
- });
+ await publicGenKeyFunc(srcKeyAlias, huksOptions);
/* 调整init时的参数集 */
huksOptions.properties.splice(0, 1, {
@@ -1499,7 +2389,7 @@ async function testDerive() {
}
finishProperties[6] = {
tag: huks.HuksTag.HUKS_TAG_KEY_ALIAS,
- value: hkdfStringToUint8Array(srcKeyAlias),
+ value: StringToUint8Array(srcKeyAlias),
}
finishProperties[7] = {
tag: huks.HuksTag.HUKS_TAG_PADDING,
@@ -1515,23 +2405,11 @@ async function testDerive() {
}
/* 进行派生操作 */
- await huks.init(srcKeyAlias, huksOptions).then((data) => {
- console.log(`test init data: ${JSON.stringify(data)}`);
- handle = data.handle;
- }).catch((err) => {
- console.log(`test init err: " + ${JSON.stringify(err)}`);
- });
- huksOptions.inData = hkdfStringToUint8Array(deriveHkdfInData);
- await huks.update(handle, huksOptions).then((data) => {
- console.log(`test update data: ${JSON.stringify(data)}`);
- }).catch((err) => {
- console.log(`test update err: " + ${JSON.stringify(err)}`);
- });
- await huks.finish(handle, finishOptions).then((data) => {
- console.log(`test finish data: ${JSON.stringify(data)}`);
- }).catch((err) => {
- console.log('test finish err information: ' + JSON.stringify(err));
- });
+ await publicInitFunc(srcKeyAlias, huksOptions);
+
+ huksOptions.inData = StringToUint8Array(deriveHkdfInData);
+ await publicUpdateFunc(handle, huksOptions);
+ await publicFinishFunc(handle, finishOptions);
huksOptions.properties.splice(0, 1, {
tag: huks.HuksTag.HUKS_TAG_ALGORITHM,
@@ -1542,11 +2420,30 @@ async function testDerive() {
value: huks.HuksKeySize.HUKS_AES_KEY_SIZE_128,
});
- await huks.deleteKey(srcKeyAlias, huksOptions).then((data) => {
- console.log(`test deleteKey data: ${JSON.stringify(data)}`);
- }).catch((err) => {
- console.log('test deleteKey err information: ' + JSON.stringify(err));
- });
+ await publicDeleteKeyFunc(srcKeyAlias, huksOptions);
+}
+
+@Entry
+@Component
+struct Index {
+ build() {
+ Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) {
+ Button() {
+ Text('testDerive')
+ .fontSize(30)
+ .fontWeight(FontWeight.Bold)
+ }.type(ButtonType.Capsule)
+ .margin({
+ top: 20
+ })
+ .backgroundColor('#0D9FFB')
+ .onClick(()=>{
+ testDerive();
+ })
+ }
+ .width('100%')
+ .height('100%')
+ }
}
```
@@ -1588,7 +2485,9 @@ HksInit对paramSet中参数的要求,其他三段式接口对paramSet无要求
*
* 以下以SM3 256密钥的Promise操作使用为例
*/
-function macStringToUint8Array(str) {
+import huks from '@ohos.security.huks';
+
+function StringToUint8Array(str) {
var arr = [];
for (var i = 0, j = str.length; i < j; ++i) {
arr.push(str.charCodeAt(i));
@@ -1596,6 +2495,162 @@ function macStringToUint8Array(str) {
return new Uint8Array(arr);
}
+async function publicGenKeyFunc(keyAlias:string, huksOptions:huks.HuksOptions) {
+ console.info(`enter callback generateKeyItem`);
+ try {
+ await generateKeyItem(keyAlias, huksOptions)
+ .then((data) => {
+ console.info(`callback: generateKeyItem success, data = ${JSON.stringify(data)}`);
+ })
+ .catch(error => {
+ console.error(`callback: generateKeyItem failed, code: ${error.code}, msg: ${error.message}`);
+ });
+ } catch (error) {
+ console.error(`callback: generateKeyItem input arg invalid, code: ${error.code}, msg: ${error.message}`);
+ }
+}
+
+function generateKeyItem(keyAlias:string, huksOptions:huks.HuksOptions) {
+ return new Promise((resolve, reject) => {
+ try {
+ huks.generateKeyItem(keyAlias, huksOptions, function (error, data) {
+ if (error) {
+ reject(error);
+ } else {
+ resolve(data);
+ }
+ });
+ } catch (error) {
+ throw(error);
+ }
+ });
+}
+
+async function publicInitFunc(keyAlias:string, huksOptions:huks.HuksOptions) {
+ console.info(`enter callback doInit`);
+ try {
+ await initSession(keyAlias, huksOptions)
+ .then ((data) => {
+ console.info(`callback1: doInit success, data = ${JSON.stringify(data)}`);
+ handle = data.handle;
+ })
+ .catch((error) => {
+ console.error(`callback1: doInit failed, code: ${error.code}, msg: ${error.message}`);
+ });
+ } catch (error) {
+ console.error(`callback: doInit input arg invalid, code: ${error.code}, msg: ${error.message}`);
+ }
+}
+
+function initSession(keyAlias:string, huksOptions:huks.HuksOptions) : Promise {
+ return new Promise((resolve, reject) => {
+ try {
+ huks.initSession(keyAlias, huksOptions, function (error, data) {
+ if (error) {
+ reject(error);
+ } else {
+ resolve(data);
+ }
+ });
+ } catch (error) {
+ throw(error);
+ }
+ });
+}
+
+async function publicUpdateFunc(handle:number, huksOptions:huks.HuksOptions) {
+ console.info(`enter callback doUpdate`);
+ try {
+ await updateSession(handle, huksOptions)
+ .then ((data) => {
+ console.info(`callback: doUpdate success, data = ${JSON.stringify(data)}`);
+ })
+ .catch(error => {
+ console.error(`callback: doUpdate failed, code: ${error.code}, msg: ${error.message}`);
+ });
+ } catch (error) {
+ console.error(`callback: doUpdate input arg invalid, code: ${error.code}, msg: ${error.message}`);
+ }
+}
+
+function updateSession(handle:number, huksOptions:huks.HuksOptions) : Promise {
+ return new Promise((resolve, reject) => {
+ try {
+ huks.updateSession(handle, huksOptions, function (error, data) {
+ if (error) {
+ reject(error);
+ } else {
+ resolve(data);
+ }
+ });
+ } catch (error) {
+ throw(error);
+ }
+ });
+}
+
+async function publicFinishFunc(handle:number, huksOptions:huks.HuksOptions) {
+ console.info(`enter callback doFinish`);
+ try {
+ await finishSession(handle, huksOptions)
+ .then ((data) => {
+ console.info(`callback: doFinish success, data = ${JSON.stringify(data)}`);
+ })
+ .catch(error => {
+ console.error(`callback: doFinish failed, code: ${error.code}, msg: ${error.message}`);
+ });
+ } catch (error) {
+ console.error(`callback: doFinish input arg invalid, code: ${error.code}, msg: ${error.message}`);
+ }
+}
+
+function finishSession(handle:number, huksOptions:huks.HuksOptions) : Promise {
+ return new Promise((resolve, reject) => {
+ try {
+ huks.finishSession(handle, huksOptions, function (error, data) {
+ if (error) {
+ reject(error);
+ } else {
+ resolve(data);
+ }
+ });
+ } catch (error) {
+ throw(error);
+ }
+ });
+}
+
+async function publicDeleteKeyFunc(keyAlias:string, huksOptions:huks.HuksOptions) {
+ console.info(`enter callback deleteKeyItem`);
+ try {
+ await deleteKeyItem(keyAlias, huksOptions)
+ .then ((data) => {
+ console.info(`callback: deleteKeyItem key success, data = ${JSON.stringify(data)}`);
+ })
+ .catch(error => {
+ console.error(`callback: deleteKeyItem failed, code: ${error.code}, msg: ${error.message}`);
+ });
+ } catch (error) {
+ console.error(`callback: deleteKeyItem input arg invalid, code: ${error.code}, msg: ${error.message}`);
+ }
+}
+
+function deleteKeyItem(keyAlias:string, huksOptions:huks.HuksOptions) {
+ return new Promise((resolve, reject) => {
+ try {
+ huks.deleteKeyItem(keyAlias, huksOptions, function (error, data) {
+ if (error) {
+ reject(error);
+ } else {
+ resolve(data);
+ }
+ });
+ } catch (error) {
+ throw(error);
+ }
+ });
+}
+
var srcKeyAlias = "sm3KeyAlias";
var hmacInData = 'sm3TestIndata';
var handle;
@@ -1625,43 +2680,44 @@ async function testMac() {
}
/* 生成密钥 */
- await huks.generateKey(srcKeyAlias, huksOptions).then((data) => {
- console.info('test generateKey data = ' + JSON.stringify(data));
- }).catch((err) => {
- console.info(`test init err: " + ${JSON.stringify(err)}`);
- });
+ await publicGenKeyFunc(srcKeyAlias, huksOptions);
/* 修改init时的参数集并进行mac操作 */
huksOptions.properties.splice(3, 3);
- await huks.init(srcKeyAlias, huksOptions).then((data) => {
- console.info(`test init data: ${JSON.stringify(data)}`);
- handle = data.handle;
- }).catch((err) => {
- console.info(`test init err: " + ${JSON.stringify(err)}`);
- });
- huksOptions.inData = macStringToUint8Array(hmacInData);
- await huks.update(handle, huksOptions).then((data) => {
- console.info(`test init data: ${JSON.stringify(data)}`);
- }).catch((err) => {
- console.info(`test init err: " + ${JSON.stringify(err)}`);
- });
+ await publicInitFunc(srcKeyAlias, huksOptions);
+ huksOptions.inData = StringToUint8Array(hmacInData);
+ await publicUpdateFunc(handle, huksOptions);
huksOptions.inData = new Uint8Array(new Array());
- await huks.finish(handle, huksOptions).then((data) => {
- console.info(`test update data: ${JSON.stringify(data)}`);
- }).catch((err) => {
- console.info('test update err information: ' + JSON.stringify(err));
- });
-
+ await publicFinishFunc(handle, huksOptions);
+
huksOptions.properties.splice(1, 0, {
tag: huks.HuksTag.HUKS_TAG_KEY_SIZE,
value: huks.HuksKeySize.HUKS_AES_KEY_SIZE_256,
});
+ await publicDeleteKeyFunc(srcKeyAlias, huksOptions);
+}
- await huks.deleteKey(srcKeyAlias, huksOptions).then((data) => {
- console.info(`test deleteKey data: ${JSON.stringify(data)}`);
- }).catch((err) => {
- console.info('test deleteKey err information: ' + JSON.stringify(err));
- });
+@Entry
+@Component
+struct Index {
+ build() {
+ Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) {
+ Button() {
+ Text('testMac')
+ .fontSize(30)
+ .fontWeight(FontWeight.Bold)
+ }.type(ButtonType.Capsule)
+ .margin({
+ top: 20
+ })
+ .backgroundColor('#0D9FFB')
+ .onClick(()=>{
+ testMac();
+ })
+ }
+ .width('100%')
+ .height('100%')
+ }
}
```
@@ -1699,30 +2755,123 @@ RSA512, RSA768, RSA1024, RSA2048, RSA3072, RSA4096, ECC224, ECC256, ECC384, ECC5
```ts
/* 证书AttestID操作示例如下*/
-function stringToUint8Array(str) {
+import huks from '@ohos.security.huks';
+
+function StringToUint8Array(str) {
var arr = [];
for (var i = 0, j = str.length; i < j; ++i) {
arr.push(str.charCodeAt(i));
}
- var tmpUint8Array = new Uint8Array(arr);
- return tmpUint8Array;
+ return new Uint8Array(arr);
+}
+
+async function publicGenKeyFunc(keyAlias:string, huksOptions:huks.HuksOptions) {
+ console.info(`enter callback generateKeyItem`);
+ try {
+ await generateKeyItem(keyAlias, huksOptions)
+ .then((data) => {
+ console.info(`callback: generateKeyItem success, data = ${JSON.stringify(data)}`);
+ })
+ .catch(error => {
+ console.error(`callback: generateKeyItem failed, code: ${error.code}, msg: ${error.message}`);
+ });
+ } catch (error) {
+ console.error(`callback: generateKeyItem input arg invalid, code: ${error.code}, msg: ${error.message}`);
+ }
+}
+
+function generateKeyItem(keyAlias:string, huksOptions:huks.HuksOptions) {
+ return new Promise((resolve, reject) => {
+ try {
+ huks.generateKeyItem(keyAlias, huksOptions, function (error, data) {
+ if (error) {
+ reject(error);
+ } else {
+ resolve(data);
+ }
+ });
+ } catch (error) {
+ throw(error);
+ }
+ });
+}
+
+async function publicAttestKey(keyAlias:string, huksOptions:huks.HuksOptions) {
+ console.info(`enter callback attestKeyItem`);
+ try {
+ await attestKeyItem(keyAlias, huksOptions)
+ .then ((data) => {
+ console.info(`callback: attestKeyItem success, data = ${JSON.stringify(data)}`);
+ })
+ .catch(error => {
+ console.error(`callback: attestKeyItem failed, code: ${error.code}, msg: ${error.message}`);
+ });
+ } catch (error) {
+ console.error(`callback: attestKeyItem input arg invalid, code: ${error.code}, msg: ${error.message}`);
+ }
+}
+
+function attestKeyItem(keyAlias:string, huksOptions:huks.HuksOptions) : Promise{
+ return new Promise((resolve, reject) => {
+ try {
+ huks.attestKeyItem(keyAlias, huksOptions, function (error, data) {
+ if (error) {
+ reject(error);
+ } else {
+ resolve(data);
+ }
+ });
+ } catch (error) {
+ throw(error);
+ }
+ });
+}
+
+async function publicDeleteKeyFunc(keyAlias:string, huksOptions:huks.HuksOptions) {
+ console.info(`enter callback deleteKeyItem`);
+ try {
+ await deleteKeyItem(keyAlias, huksOptions)
+ .then ((data) => {
+ console.info(`callback: deleteKeyItem key success, data = ${JSON.stringify(data)}`);
+ })
+ .catch(error => {
+ console.error(`callback: deleteKeyItem failed, code: ${error.code}, msg: ${error.message}`);
+ });
+ } catch (error) {
+ console.error(`callback: deleteKeyItem input arg invalid, code: ${error.code}, msg: ${error.message}`);
+ }
}
-function printLog(...data) {
- console.error(data.toString());
+function deleteKeyItem(keyAlias:string, huksOptions:huks.HuksOptions) {
+ return new Promise((resolve, reject) => {
+ try {
+ huks.deleteKeyItem(keyAlias, huksOptions, function (error, data) {
+ if (error) {
+ reject(error);
+ } else {
+ resolve(data);
+ }
+ });
+ } catch (error) {
+ throw(error);
+ }
+ });
}
-let securityLevel = stringToUint8Array('sec_level');
-let challenge = stringToUint8Array('challenge_data');
-let versionInfo = stringToUint8Array('version_info');
-let udid = stringToUint8Array('udid');
-let serial = stringToUint8Array('serial');
-let deviceId = stringToUint8Array('device_id');
-let idAliasString = "id attest";
+var securityLevel = StringToUint8Array('sec_level');
+var challenge = StringToUint8Array('challenge_data');
+var versionInfo = StringToUint8Array('version_info');
+var udid = StringToUint8Array('udid');
+var serial = StringToUint8Array('serial');
+var deviceId = StringToUint8Array('device_id');
+var idAliasString = "id attest";
+
+async function testAttestId() {
+ var aliasString = idAliasString;
+ var aliasUint8 = StringToUint8Array(aliasString);
-/* 集成生成密钥参数集 & 生成密钥 */
-function generateKey(alias) {
- let properties = new Array();
+ /* 集成生成密钥参数集 & 生成密钥 */
+ var properties = new Array();
properties[0] = {
tag: huks.HuksTag.HUKS_TAG_ALGORITHM,
value: huks.HuksKeyAlg.HUKS_ALG_RSA
@@ -1755,54 +2904,71 @@ function generateKey(alias) {
tag: huks.HuksTag.HUKS_TAG_BLOCK_MODE,
value: huks.HuksCipherMode.HUKS_MODE_ECB
};
- let options = {
+ var options = {
properties: properties
};
- huks.generateKey(alias, options);
-}
-
-async function attestId() {
- let aliasString = idAliasString;
- let aliasUint8 = stringToUint8Array(aliasString);
+ await publicGenKeyFunc(aliasString, options);
/* 集成证书参数集 */
- let properties = new Array();
- properties[0] = {
+ var attestProperties = new Array();
+ attestProperties[0] = {
tag: huks.HuksTag.HUKS_TAG_ATTESTATION_ID_SEC_LEVEL_INFO,
value: securityLevel
};
- properties[1] = {
+ attestProperties[1] = {
tag: huks.HuksTag.HUKS_TAG_ATTESTATION_CHALLENGE,
value: challenge
};
- properties[2] = {
+ attestProperties[2] = {
tag: huks.HuksTag.HUKS_TAG_ATTESTATION_ID_VERSION_INFO,
value: versionInfo
};
- properties[3] = {
+ attestProperties[3] = {
tag: huks.HuksTag.HUKS_TAG_ATTESTATION_ID_ALIAS,
value: aliasUint8
};
- properties[4] = {
+ attestProperties[4] = {
tag: huks.HuksTag.HUKS_TAG_ATTESTATION_ID_UDID,
value: udid
};
- properties[5] = {
+ attestProperties[5] = {
tag: huks.HuksTag.HUKS_TAG_ATTESTATION_ID_SERIAL,
value: serial
};
- properties[6] = {
+ attestProperties[6] = {
tag: huks.HuksTag.HUKS_TAG_ATTESTATION_ID_DEVICE,
value: deviceId
};
- let options = {
- properties: properties
+ var huksOptions = {
+ properties: attestProperties
};
- generateKey(aliasString);
- huks.attestKey(aliasString, options, function (err, data) {
- printLog(`key attest result : ${JSON.stringify(data)}`);
- });
+ await publicAttestKey(aliasString, huksOptions);
+
+ await publicDeleteKeyFunc(aliasString, options);
+}
+
+@Entry
+@Component
+struct Index {
+ build() {
+ Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) {
+ Button() {
+ Text('testAttestId')
+ .fontSize(30)
+ .fontWeight(FontWeight.Bold)
+ }.type(ButtonType.Capsule)
+ .margin({
+ top: 20
+ })
+ .backgroundColor('#0D9FFB')
+ .onClick(()=>{
+ testAttestId();
+ })
+ }
+ .width('100%')
+ .height('100%')
+ }
}
```
@@ -1838,27 +3004,119 @@ RSA512, RSA768, RSA1024, RSA2048, RSA3072, RSA4096, ECC224, ECC256, ECC384, ECC5
```ts
/* 证书AttestKey操作示例如下*/
-function stringToUint8Array(str) {
+import huks from '@ohos.security.huks';
+
+function StringToUint8Array(str) {
var arr = [];
for (var i = 0, j = str.length; i < j; ++i) {
arr.push(str.charCodeAt(i));
}
- var tmpUint8Array = new Uint8Array(arr);
- return tmpUint8Array;
+ return new Uint8Array(arr);
+}
+
+async function publicGenKeyFunc(keyAlias:string, huksOptions:huks.HuksOptions) {
+ console.info(`enter callback generateKeyItem`);
+ try {
+ await generateKeyItem(keyAlias, huksOptions)
+ .then((data) => {
+ console.info(`callback: generateKeyItem success, data = ${JSON.stringify(data)}`);
+ })
+ .catch(error => {
+ console.error(`callback: generateKeyItem failed, code: ${error.code}, msg: ${error.message}`);
+ });
+ } catch (error) {
+ console.error(`callback: generateKeyItem input arg invalid, code: ${error.code}, msg: ${error.message}`);
+ }
+}
+
+function generateKeyItem(keyAlias:string, huksOptions:huks.HuksOptions) {
+ return new Promise((resolve, reject) => {
+ try {
+ huks.generateKeyItem(keyAlias, huksOptions, function (error, data) {
+ if (error) {
+ reject(error);
+ } else {
+ resolve(data);
+ }
+ });
+ } catch (error) {
+ throw(error);
+ }
+ });
+}
+
+async function publicAttestKey(keyAlias:string, huksOptions:huks.HuksOptions) {
+ console.info(`enter callback attestKeyItem`);
+ try {
+ await attestKeyItem(keyAlias, huksOptions)
+ .then ((data) => {
+ console.info(`callback: attestKeyItem success, data = ${JSON.stringify(data)}`);
+ })
+ .catch(error => {
+ console.error(`callback: attestKeyItem failed, code: ${error.code}, msg: ${error.message}`);
+ });
+ } catch (error) {
+ console.error(`callback: attestKeyItem input arg invalid, code: ${error.code}, msg: ${error.message}`);
+ }
+}
+
+function attestKeyItem(keyAlias:string, huksOptions:huks.HuksOptions) : Promise{
+ return new Promise((resolve, reject) => {
+ try {
+ huks.attestKeyItem(keyAlias, huksOptions, function (error, data) {
+ if (error) {
+ reject(error);
+ } else {
+ resolve(data);
+ }
+ });
+ } catch (error) {
+ throw(error);
+ }
+ });
+}
+
+async function publicDeleteKeyFunc(keyAlias:string, huksOptions:huks.HuksOptions) {
+ console.info(`enter callback deleteKeyItem`);
+ try {
+ await deleteKeyItem(keyAlias, huksOptions)
+ .then ((data) => {
+ console.info(`callback: deleteKeyItem key success, data = ${JSON.stringify(data)}`);
+ })
+ .catch(error => {
+ console.error(`callback: deleteKeyItem failed, code: ${error.code}, msg: ${error.message}`);
+ });
+ } catch (error) {
+ console.error(`callback: deleteKeyItem input arg invalid, code: ${error.code}, msg: ${error.message}`);
+ }
}
-function printLog(...data) {
- console.error(data.toString());
+function deleteKeyItem(keyAlias:string, huksOptions:huks.HuksOptions) {
+ return new Promise((resolve, reject) => {
+ try {
+ huks.deleteKeyItem(keyAlias, huksOptions, function (error, data) {
+ if (error) {
+ reject(error);
+ } else {
+ resolve(data);
+ }
+ });
+ } catch (error) {
+ throw(error);
+ }
+ });
}
-let securityLevel = stringToUint8Array('sec_level');
-let challenge = stringToUint8Array('challenge_data');
-let versionInfo = stringToUint8Array('version_info');
-let keyAliasString = "key attest";
+var securityLevel = StringToUint8Array('sec_level');
+var challenge = StringToUint8Array('challenge_data');
+var versionInfo = StringToUint8Array('version_info');
+var keyAliasString = "key attest";
-/* 集成生成密钥参数集 & 生成密钥 */
-function generateKey(alias) {
- let properties = new Array();
+async function testAttestKey() {
+ var aliasString = keyAliasString;
+ var aliasUint8 = StringToUint8Array(aliasString);
+
+ var properties = new Array();
properties[0] = {
tag: huks.HuksTag.HUKS_TAG_ALGORITHM,
value: huks.HuksKeyAlg.HUKS_ALG_RSA
@@ -1891,41 +3149,59 @@ function generateKey(alias) {
tag: huks.HuksTag.HUKS_TAG_BLOCK_MODE,
value: huks.HuksCipherMode.HUKS_MODE_ECB
};
- let options = {
+ var options = {
properties: properties
};
- huks.generateKey(alias, options);
-}
-
-async function attestKey() {
- let aliasString = keyAliasString;
- let aliasUint8 = stringToUint8Array(aliasString);
+ await publicGenKeyFunc(aliasString, options);
/* 集成证书参数集 */
- let properties = new Array();
- properties[0] = {
+ var attestProperties = new Array();
+ attestProperties[0] = {
tag: huks.HuksTag.HUKS_TAG_ATTESTATION_ID_SEC_LEVEL_INFO,
value: securityLevel
};
- properties[1] = {
+ attestProperties[1] = {
tag: huks.HuksTag.HUKS_TAG_ATTESTATION_CHALLENGE,
value: challenge
};
- properties[2] = {
+ attestProperties[2] = {
tag: huks.HuksTag.HUKS_TAG_ATTESTATION_ID_VERSION_INFO,
value: versionInfo
};
- properties[3] = {
+ attestProperties[3] = {
tag: huks.HuksTag.HUKS_TAG_ATTESTATION_ID_ALIAS,
value: aliasUint8
};
- let options = {
- properties: properties
+ var huksOptions = {
+ properties: attestProperties
};
- generateKey(aliasString);
- huks.attestKey(aliasString, options, function (err, data) {
- printLog(`key attest result : ${JSON.stringify(data)}`);
- });
+
+ await publicAttestKey(aliasString, huksOptions);
+
+ await publicDeleteKeyFunc(aliasString, options);
+}
+
+@Entry
+@Component
+struct Index {
+ build() {
+ Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) {
+ Button() {
+ Text('testAttestKey')
+ .fontSize(30)
+ .fontWeight(FontWeight.Bold)
+ }.type(ButtonType.Capsule)
+ .margin({
+ top: 20
+ })
+ .backgroundColor('#0D9FFB')
+ .onClick(()=>{
+ testAttestKey();
+ })
+ }
+ .width('100%')
+ .height('100%')
+ }
}
```