未验证 提交 01398859 编写于 作者: O openharmony_ci 提交者: Gitee

!10246 更新代码demo

Merge pull request !10246 from zhangcheng/master
...@@ -12,7 +12,7 @@ HUKS所管理的密钥可以由应用导入或者由应用调用HUKS接口生成 ...@@ -12,7 +12,7 @@ HUKS所管理的密钥可以由应用导入或者由应用调用HUKS接口生成
```js ```js
import huks from '@ohos.security.huks' import huks from '@ohos.security.huks'
``` ```
## HuksErrorCode ## HuksErrorCode<sup>(deprecated)</sup>
表示错误码的枚举。 表示错误码的枚举。
...@@ -95,6 +95,113 @@ import huks from '@ohos.security.huks' ...@@ -95,6 +95,113 @@ import huks from '@ohos.security.huks'
| HUKS_ERROR_INTERNAL_ERROR | -999 |表示内部错误。| | HUKS_ERROR_INTERNAL_ERROR | -999 |表示内部错误。|
| HUKS_ERROR_UNKNOWN_ERROR | -1000 |表示未知错误。| | HUKS_ERROR_UNKNOWN_ERROR | -1000 |表示未知错误。|
## HuksExceptionErrCode<sup>9+</sup>
表示错误码的枚举以及对应的错误信息, 错误码表示错误类型,错误信息展示错误详情。
**系统能力**: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 ## HuksKeyPurpose
...@@ -448,12 +555,14 @@ import huks from '@ohos.security.huks' ...@@ -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_PUBLIC_KEY_DATA | HuksTagType.HUKS_TAG_TYPE_BYTES \| 20002 | 预留。 |
| HUKS_TAG_ASYMMETRIC_PRIVATE_KEY_DATA | HuksTagType.HUKS_TAG_TYPE_BYTES \| 20003 | 预留。 | | HUKS_TAG_ASYMMETRIC_PRIVATE_KEY_DATA | HuksTagType.HUKS_TAG_TYPE_BYTES \| 20003 | 预留。 |
## huks.generateKey ## huks.generateKey<sup>(deprecated)</sup>
generateKey(keyAlias: string, options: HuksOptions, callback: AsyncCallback\<HuksResult>) : void generateKey(keyAlias: string, options: HuksOptions, callback: AsyncCallback\<HuksResult>) : void
生成密钥,使用Callback回调异步返回结果。 生成密钥,使用Callback回调异步返回结果。
> **说明:** 从API Version 9开始废弃,建议使用[huks.generateKeyItem<sup>9+</sup>](#huksgeneratekeyitem9)替代。
**系统能力**:SystemCapability.Security.Huks **系统能力**:SystemCapability.Security.Huks
**参数:** **参数:**
...@@ -498,12 +607,14 @@ var options = { ...@@ -498,12 +607,14 @@ var options = {
huks.generateKey(keyAlias, options, function (err, data){}); huks.generateKey(keyAlias, options, function (err, data){});
``` ```
## huks.generateKey ## huks.generateKey<sup>(deprecated)</sup>
generateKey(keyAlias: string, options: HuksOptions) : Promise\<HuksResult> generateKey(keyAlias: string, options: HuksOptions) : Promise\<HuksResult>
生成密钥,使用Promise方式异步返回结果。 生成密钥,使用Promise方式异步返回结果。
> **说明:** 从API Version 9开始废弃,建议使用[huks.generateKeyItem<sup>9+</sup>](#huksgeneratekeyitem9-1)替代。
**系统能力**:SystemCapability.Security.Huks **系统能力**:SystemCapability.Security.Huks
**参数:** **参数:**
...@@ -549,12 +660,125 @@ var options = { ...@@ -549,12 +660,125 @@ var options = {
var result = huks.generateKey(keyAlias, options); var result = huks.generateKey(keyAlias, options);
``` ```
## huks.deleteKey ## huks.generateKeyItem<sup>9+</sup>
generateKeyItem(keyAlias: string, options: HuksOptions, callback: AsyncCallback\<void>) : void
生成密钥,使用Callback回调异步返回结果。
**系统能力**:SystemCapability.Security.Huks
**参数:**
| 参数名 | 类型 | 必填 | 说明 |
| -------- | --------------------------- | ---- | --------------------------------------------- |
| keyAlias | string | 是 | 别名。 |
| options | [HuksOptions](#huksoptions) | 是 | 用于存放生成key所需TAG。 |
| callback | AsyncCallback\<void> | 是 | 不返回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.generateKeyItem<sup>9+</sup>
generateKeyItem(keyAlias: string, options: HuksOptions) : Promise\<void>
生成密钥,使用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<sup>(deprecated)</sup>
deleteKey(keyAlias: string, options: HuksOptions, callback: AsyncCallback\<HuksResult>) : void deleteKey(keyAlias: string, options: HuksOptions, callback: AsyncCallback\<HuksResult>) : void
删除密钥,使用Callback回调异步返回结果。 删除密钥,使用Callback回调异步返回结果。
> **说明:** 从API Version 9开始废弃,建议使用[huks.deleteKeyItem<sup>9+</sup>](#huksdeletekeyitem9)替代。
**系统能力**:SystemCapability.Security.Huks **系统能力**:SystemCapability.Security.Huks
**参数:** **参数:**
...@@ -576,12 +800,14 @@ var emptyOptions = { ...@@ -576,12 +800,14 @@ var emptyOptions = {
huks.deleteKey(keyAlias, emptyOptions, function (err, data) {}); huks.deleteKey(keyAlias, emptyOptions, function (err, data) {});
``` ```
## huks.deleteKey ## huks.deleteKey<sup>(deprecated)</sup>
deleteKey(keyAlias: string, options: HuksOptions) : Promise\<HuksResult> deleteKey(keyAlias: string, options: HuksOptions) : Promise\<HuksResult>
删除密钥,使用Promise方式异步返回结果。 删除密钥,使用Promise方式异步返回结果。
> **说明:** 从API Version 9开始废弃,建议使用[huks.deleteKeyItem<sup>9+</sup>](#huksdeletekeyitem9-1)替代。
**系统能力**:SystemCapability.Security.Huks **系统能力**:SystemCapability.Security.Huks
**参数:** **参数:**
...@@ -608,6 +834,79 @@ var emptyOptions = { ...@@ -608,6 +834,79 @@ var emptyOptions = {
var result = huks.deleteKey(keyAlias, emptyOptions); var result = huks.deleteKey(keyAlias, emptyOptions);
``` ```
## huks.deleteKeyItem<sup>9+</sup>
deleteKeyItem(keyAlias: string, options: HuksOptions, callback: AsyncCallback\<void>) : void
删除密钥,使用Callback回调异步返回结果。
**系统能力**:SystemCapability.Security.Huks
**参数:**
| 参数名 | 类型 | 必填 | 说明 |
| -------- | --------------------------- | ---- | --------------------------------------------- |
| keyAlias | string | 是 | 密钥别名,应为生成key时传入的别名。 |
| options | [HuksOptions](#huksoptions) | 是 | 空对象(此处传空即可)。 |
| callback | AsyncCallback\<void> | 是 | 不返回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.deleteKeyItem<sup>9+</sup>
deleteKeyItem(keyAlias: string, options: HuksOptions) : Promise\<void>
删除密钥,使用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 ## huks.getSdkVersion
getSdkVersion(options: HuksOptions) : string getSdkVersion(options: HuksOptions) : string
...@@ -638,12 +937,14 @@ var emptyOptions = { ...@@ -638,12 +937,14 @@ var emptyOptions = {
var result = huks.getSdkVersion(emptyOptions); var result = huks.getSdkVersion(emptyOptions);
``` ```
## huks.importKey ## huks.importKey<sup>(deprecated)</sup>
importKey(keyAlias: string, options: HuksOptions, callback: AsyncCallback\<HuksResult>) : void importKey(keyAlias: string, options: HuksOptions, callback: AsyncCallback\<HuksResult>) : void
导入明文密钥,使用Callback方式回调异步返回结果 。 导入明文密钥,使用Callback方式回调异步返回结果 。
> **说明:** 从API Version 9开始废弃,建议使用[huks.importKeyItem<sup>9+</sup>](#huksimportkeyitem9)替代。
**系统能力**:SystemCapability.Security.Huks **系统能力**:SystemCapability.Security.Huks
**参数:** **参数:**
...@@ -696,12 +997,14 @@ var options = { ...@@ -696,12 +997,14 @@ var options = {
huks.importKey(keyAlias, options, function (err, data){}); huks.importKey(keyAlias, options, function (err, data){});
``` ```
## huks.importKey ## huks.importKey<sup>(deprecated)</sup>
importKey(keyAlias: string, options: HuksOptions) : Promise\<HuksResult> importKey(keyAlias: string, options: HuksOptions) : Promise\<HuksResult>
导入明文密钥,使用Promise方式异步返回结果。 导入明文密钥,使用Promise方式异步返回结果。
> **说明:** 从API Version 9开始废弃,建议使用[huks.importKeyItem<sup>9+</sup>](#huksimportkeyitem9-1)替代。
**系统能力**:SystemCapability.Security.Huks **系统能力**:SystemCapability.Security.Huks
**参数:** **参数:**
...@@ -761,121 +1064,268 @@ var huksoptions = { ...@@ -761,121 +1064,268 @@ var huksoptions = {
var result = huks.importKey(keyAlias, huksoptions); var result = huks.importKey(keyAlias, huksoptions);
``` ```
## huks.attestkey<sup>9+</sup> ## huks.importKeyItem<sup>9+</sup>
attestKey(keyAlias: string, options: HuksOptions, callback: AsyncCallback\<HuksResult>) : void importKeyItem(keyAlias: string, options: HuksOptions, callback: AsyncCallback\<void>) : void
获取密钥证书,使用Callback方式回调异步返回结果 。 导入明文密钥,使用Callback方式回调异步返回结果 。
**系统能力**:SystemCapability.Security.Huks **系统能力**:SystemCapability.Security.Huks
**参数:** **参数:**
| 参数名 | 类型 | 必填 | 说明 | | 参数名 | 类型 | 必填 | 说明 |
| ---------------- | ----------------------------------------- | ---- | -------------------------------------------------- | | -------- | --------------------------- | ---- | --------------------------------------------- |
| keyAlias | string | 是 | 密钥别名,存放待获取证书密钥的别名。 | | keyAlias | string | 是 | 密钥别名。 |
| options | [HuksOptions](#huksoptions) | 是 | 用于获取证书时指定所需参数与数据。 | | options | [HuksOptions](#huksoptions) | 是 | 用于导入时所需TAG和需要导入的密钥。 |
| callback | AsyncCallback\<[HuksResult](#huksresult)> | 是 | 返回HUKS_SUCCESS时表示接口使用成功,其他时为错误。 | | callback | AsyncCallback\<void> | 是 | 不返回err值时表示接口使用成功,其他时为错误。 |
**示例:** **示例:**
```js ```js
let securityLevel = stringToUint8Array('sec_level'); /* 以导入AES256密钥为例 */
let challenge = stringToUint8Array('challenge_data'); var plainTextSize32 = makeRandomArr(32);
let versionInfo = stringToUint8Array('version_info'); function makeRandomArr(size) {
let keyAliasString = "key attest"; var arr = new Uint8Array(size);
for (var i = 0; i < size; i++) {
function stringToUint8Array(str) { arr[i] = Math.floor(Math.random() * 10);
var arr = [];
for (var i = 0, j = str.length; i < j; ++i) {
arr.push(str.charCodeAt(i));
} }
var tmpUint8Array = new Uint8Array(arr); return arr;
return tmpUint8Array; };
} var keyAlias = 'keyAlias';
var properties = new Array();
function printLog(...data) { properties[0] = {
console.error(data.toString());
}
async function generateKey(alias) {
let properties = new Array();
properties[0] = {
tag: huks.HuksTag.HUKS_TAG_ALGORITHM, tag: huks.HuksTag.HUKS_TAG_ALGORITHM,
value: huks.HuksKeyAlg.HUKS_ALG_RSA value: huks.HuksKeyAlg.HUKS_ALG_AES
}; };
properties[1] = { 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, tag: huks.HuksTag.HUKS_TAG_KEY_SIZE,
value: huks.HuksKeySize.HUKS_RSA_KEY_SIZE_2048 value: huks.HuksKeySize.HUKS_AES_KEY_SIZE_256
}; };
properties[3] = { properties[2] = {
tag: huks.HuksTag.HUKS_TAG_PURPOSE, tag: huks.HuksTag.HUKS_TAG_PURPOSE,
value: huks.HuksKeyPurpose.HUKS_KEY_PURPOSE_VERIFY value:
}; huks.HuksKeyPurpose.HUKS_KEY_PURPOSE_ENCRYPT | huks.HuksKeyPurpose.HUKS_KEY_PURPOSE_DECRYPT
properties[4] = { };
tag: huks.HuksTag.HUKS_TAG_DIGEST, properties[3] = {
value: huks.HuksKeyDigest.HUKS_DIGEST_SHA256
};
properties[5] = {
tag: huks.HuksTag.HUKS_TAG_PADDING, tag: huks.HuksTag.HUKS_TAG_PADDING,
value: huks.HuksKeyPadding.HUKS_PADDING_PSS value:huks.HuksKeyPadding.HUKS_PADDING_PKCS7
}; };
properties[6] = { properties[4] = {
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, tag: huks.HuksTag.HUKS_TAG_BLOCK_MODE,
value: huks.HuksCipherMode.HUKS_MODE_ECB value: huks.HuksCipherMode.HUKS_MODE_ECB
}; };
let options = { var options = {
properties: properties properties: properties,
}; inData: plainTextSize32
};
await huks.generateKey(alias, options).then(async (data) => { try {
console.error(`generateKey data ${JSON.stringify(data)}`); huks.importKeyItem(keyAlias, options, function (error, data) {
}).catch((err) => { if (error) {
console.error(`generateKey err: " + ${JSON.stringify(err)}`); 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}`);
} }
```
async function attestKey() { ## huks.importKeyItem<sup>9+</sup>
let aliasString = keyAliasString;
let aliasUint8 = stringToUint8Array(aliasString); importKeyItem(keyAlias: string, options: HuksOptions) : Promise\<void>
let properties = new Array();
properties[0] = { 导入明文密钥,使用Promise方式异步返回结果。
tag: huks.HuksTag.HUKS_TAG_ATTESTATION_ID_SEC_LEVEL_INFO,
value: securityLevel **系统能力**:SystemCapability.Security.Huks
};
properties[1] = { **参数:**
tag: huks.HuksTag.HUKS_TAG_ATTESTATION_CHALLENGE,
value: challenge | 参数名 | 类型 | 必填 | 说明 |
}; | -------- | --------------------------- | ---- | ----------------------------------- |
properties[2] = { | keyAlias | string | 是 | 密钥别名。 |
tag: huks.HuksTag.HUKS_TAG_ATTESTATION_ID_VERSION_INFO, | options | [HuksOptions](#huksoptions) | 是 | 用于导入时所需TAG和需要导入的密钥。 |
value: versionInfo
}; **示例:**
properties[3] = {
tag: huks.HuksTag.HUKS_TAG_ATTESTATION_ID_ALIAS, ```js
value: aliasUint8 /* 以导入AES128为例 */
}; var plainTextSize32 = makeRandomArr(32);
let options = {
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_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_ENCRYPT | huks.HuksKeyPurpose.HUKS_KEY_PURPOSE_DECRYPT
};
properties[3] = {
tag: huks.HuksTag.HUKS_TAG_PADDING,
value:huks.HuksKeyPadding.HUKS_PADDING_PKCS7
};
properties[4] = {
tag: huks.HuksTag.HUKS_TAG_BLOCK_MODE,
value: huks.HuksCipherMode.HUKS_MODE_ECB
};
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}`);
}
```
## huks.attestKeyItem<sup>9+</sup>
attestKeyItem(keyAlias: string, options: HuksOptions, callback: AsyncCallback\<HuksReturnResult>) : 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 properties: properties
}; };
await generateKey(aliasString); await generateKey(aliasString);
huks.attestKey(aliasString, options, function (err, data) { try {
printLog(`key attest result : ${JSON.stringify(data)}`); 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.attestkey<sup>9+</sup> ## huks.attestKeyItem<sup>9+</sup>
attestKey(keyAlias: string, options: HuksOptions) : Promise\<HuksResult> attestKeyItem(keyAlias: string, options: HuksOptions) : Promise\<HuksReturnResult>
获取密钥证书,使用Promise方式异步返回结果 。 获取密钥证书,使用Promise方式异步返回结果 。
...@@ -884,15 +1334,15 @@ attestKey(keyAlias: string, options: HuksOptions) : Promise\<HuksResult> ...@@ -884,15 +1334,15 @@ attestKey(keyAlias: string, options: HuksOptions) : Promise\<HuksResult>
**参数:** **参数:**
| 参数名 | 类型 | 必填 | 说明 | | 参数名 | 类型 | 必填 | 说明 |
| ---------------- | ----------------------------------------- | ---- | -------------------------------------------------- | | -------- | --------------------------- | ---- | ------------------------------------ |
| keyAlias | string | 是 | 密钥别名,存放待获取证书密钥的别名。 | | keyAlias | string | 是 | 密钥别名,存放待获取证书密钥的别名。 |
| options | [HuksOptions](#huksoptions) | 是 | 用于获取证书时指定所需参数与数据。 | | options | [HuksOptions](#huksoptions) | 是 | 用于获取证书时指定所需参数与数据。 |
**返回值:** **返回值:**
| 类型 | 说明 | | 类型 | 说明 |
| ----------------------------------- | -------------------------------------------------- | | ---------------------------------------------- | --------------------------------------------- |
| Promise\<[HuksResult](#huksresult)> | 返回HUKS_SUCCESS时表示接口使用成功,其他时为错误。 | | Promise<[HuksReturnResult](#huksreturnresult)> | 不返回err值时表示接口使用成功,其他时为错误。 |
**示例:** **示例:**
...@@ -911,10 +1361,6 @@ function stringToUint8Array(str) { ...@@ -911,10 +1361,6 @@ function stringToUint8Array(str) {
return tmpUint8Array; return tmpUint8Array;
} }
function printLog(...data) {
console.error(data.toString());
}
async function generateKey(alias) { async function generateKey(alias) {
let properties = new Array(); let properties = new Array();
properties[0] = { properties[0] = {
...@@ -953,11 +1399,17 @@ async function generateKey(alias) { ...@@ -953,11 +1399,17 @@ async function generateKey(alias) {
properties: properties properties: properties
}; };
await huks.generateKey(alias, options).then(async (data) => { try {
console.error(`generateKey data ${JSON.stringify(data)}`); await huks.generateKeyItem(alias, options)
}).catch((err) => { .then((data) => {
console.error(`generateKey err: " + ${JSON.stringify(err)}`); 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() { async function attestKey() {
...@@ -984,19 +1436,23 @@ async function attestKey() { ...@@ -984,19 +1436,23 @@ async function attestKey() {
properties: properties properties: properties
}; };
await generateKey(aliasString); await generateKey(aliasString);
huks.attestKey(aliasString, options) try {
.then((data) => { await huks.attestKeyItem(aliasString, options)
console.log(`test attestKey data: ${JSON.stringify(data)}`); .then ((data) => {
console.info(`promise: attestKeyItem success`);
}) })
.catch((err) => { .catch(error => {
console.log('test attestKey information: ' + JSON.stringify(err)); 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.importWrappedKey<sup>9+</sup> ## huks.importWrappedKeyItem<sup>9+</sup>
importWrappedKey(keyAlias: string, wrappingKeyAlias: string, options: HuksOptions, callback: AsyncCallback\<HuksResult>) : void importWrappedKeyItem(keyAlias: string, wrappingKeyAlias: string, options: HuksOptions, callback: AsyncCallback\<void>) : void
导入加密密钥,使用Callback方式回调异步返回结果 。 导入加密密钥,使用Callback方式回调异步返回结果 。
...@@ -1005,89 +1461,109 @@ importWrappedKey(keyAlias: string, wrappingKeyAlias: string, options: HuksOption ...@@ -1005,89 +1461,109 @@ importWrappedKey(keyAlias: string, wrappingKeyAlias: string, options: HuksOption
**参数:** **参数:**
| 参数名 | 类型 | 必填 | 说明 | | 参数名 | 类型 | 必填 | 说明 |
| ---------------- | ----------------------------------------- | ---- | -------------------------------------------------- | | ---------------- | --------------------------- | ---- | --------------------------------------------- |
| keyAlias | string | 是 | 密钥别名,存放待导入密钥的别名。 | | keyAlias | string | 是 | 密钥别名,存放待导入密钥的别名。 |
| wrappingKeyAlias | string | 是 | 密钥别名,对应密钥用于解密加密的密钥数据。 | | wrappingKeyAlias | string | 是 | 密钥别名,对应密钥用于解密加密的密钥数据。 |
| options | [HuksOptions](#huksoptions) | 是 | 用于导入时所需TAG和需要导入的加密的密钥数据。 | | options | [HuksOptions](#huksoptions) | 是 | 用于导入时所需TAG和需要导入的加密的密钥数据。 |
| callback | AsyncCallback\<[HuksResult](#huksresult)> | 是 | 返回HUKS_SUCCESS时表示接口使用成功,其他时为错误。 | | callback | AsyncCallback\<void> | 是 | 不返回err值时表示接口使用成功,其他时为错误。 |
**示例:** **示例:**
```js ```js
import huks from '@ohos.security.huks';
var exportWrappingKey; var exportWrappingKey;
var alias1 = "importAlias"; var alias1 = "importAlias";
var alias2 = "wrappingKeyAlias"; var alias2 = "wrappingKeyAlias";
async function TestGenFunc(alias, options) { async function TestGenFunc(alias, options) {
try {
await genKey(alias, options) await genKey(alias, options)
.then((data) => { .then((data) => {
console.log(`test genKey data: ${JSON.stringify(data)}`); console.info(`callback: generateKeyItem success`);
}) })
.catch((err) => { .catch(error => {
console.log('test genKey err information: ' + JSON.stringify(err)); 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) { function genKey(alias, options) {
return new Promise((resolve, reject) => { return new Promise((resolve, reject) => {
huks.generateKey(alias, options, function (err, data) { try {
console.log(`test genKey data: ${JSON.stringify(data)}`); huks.generateKeyItem(alias, options, function (error, data) {
if (err.code !== 0) { if (error) {
console.log('test genKey err information: ' + JSON.stringify(err)); reject(error);
reject(err);
} else { } else {
resolve(data); resolve(data);
} }
}); });
} catch (error) {
throw(error);
}
}); });
} }
async function TestExportFunc(alias, options) { async function TestExportFunc(alias, options) {
try {
await exportKey(alias, options) await exportKey(alias, options)
.then((data) => { .then ((data) => {
console.log(`test exportKey data: ${JSON.stringify(data)}`); console.info(`callback: exportKeyItem success, data = ${JSON.stringify(data)}`);
exportWrappingKey = data.outData;
}) })
.catch((err) => { .catch(error => {
console.log('test exportKey err information: ' + JSON.stringify(err)); 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) { function exportKey(alias, options) : Promise<huks.HuksReturnResult> {
return new Promise((resolve, reject) => { return new Promise((resolve, reject) => {
huks.exportKey(alias, options, function (err, data) { try {
console.log(`test exportKey data: ${JSON.stringify(data)}`); huks.exportKeyItem(alias, options, function (error, data) {
if (err.code !== 0) { if (error) {
console.log('test exportKey err information: ' + JSON.stringify(err)); reject(error);
reject(err);
} else { } else {
exportWrappingKey = data.outData;
resolve(data); resolve(data);
} }
}); });
} catch (error) {
throw(error);
}
}); });
} }
async function TestImportWrappedFunc(alias, wrappingAlias, options) { async function TestImportWrappedFunc(alias, wrappingAlias, options) {
try {
await importWrappedKey(alias, wrappingAlias, options) await importWrappedKey(alias, wrappingAlias, options)
.then((data) => { .then ((data) => {
console.log(`TestImportWrappedFunc data: ${JSON.stringify(data)}`); console.info(`callback: importWrappedKeyItem success`);
}) })
.catch((err) => { .catch(error => {
console.log('test importWrappedKey err information: ' + JSON.stringify(err)); 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) { function importWrappedKey(alias, wrappingAlias, options) {
return new Promise((resolve, reject) => { return new Promise((resolve, reject) => {
huks.importWrappedKey(alias, wrappingAlias, options, function (err, data) { try {
console.log(`importWrappedKey data: ${JSON.stringify(data)}`); huks.importWrappedKeyItem(alias, wrappingAlias, options, function (error, data) {
if (err.code !== 0) { if (error) {
console.log('importWrappedKey err information: ' + JSON.stringify(err)); reject(error);
reject(err);
} else { } else {
resolve(data); resolve(data);
} }
}); });
} catch (error) {
throw(error);
}
}); });
} }
...@@ -1136,6 +1612,10 @@ function makeGenerateOptions() { ...@@ -1136,6 +1612,10 @@ function makeGenerateOptions() {
tag: huks.HuksTag.HUKS_TAG_DIGEST, tag: huks.HuksTag.HUKS_TAG_DIGEST,
value: huks.HuksKeyDigest.HUKS_DIGEST_SHA256 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 = { var options = {
properties: properties properties: properties
}; };
...@@ -1161,6 +1641,10 @@ function makeImportOptions() { ...@@ -1161,6 +1641,10 @@ function makeImportOptions() {
value: huks.HuksCipherMode.HUKS_MODE_CBC value: huks.HuksCipherMode.HUKS_MODE_CBC
}; };
properties[4] = { properties[4] = {
tag: huks.HuksTag.HUKS_TAG_PADDING,
value: huks.HuksKeyPadding.HUKS_PADDING_NONE
};
properties[5] = {
tag: huks.HuksTag.HUKS_TAG_UNWRAP_ALGORITHM_SUITE, tag: huks.HuksTag.HUKS_TAG_UNWRAP_ALGORITHM_SUITE,
value: huks.HuksUnwrapSuite.HUKS_UNWRAP_SUITE_ECDH_AES_256_GCM_NOPADDING value: huks.HuksUnwrapSuite.HUKS_UNWRAP_SUITE_ECDH_AES_256_GCM_NOPADDING
}; };
...@@ -1182,9 +1666,9 @@ function huksImportWrappedKey() { ...@@ -1182,9 +1666,9 @@ function huksImportWrappedKey() {
} }
``` ```
## huks.importWrappedKey<sup>9+</sup> ## huks.importWrappedKeyItem<sup>9+</sup>
importWrappedKey(keyAlias: string, wrappingKeyAlias: string, options: HuksOptions) : Promise\<HuksResult> importWrappedKeyItem(keyAlias: string, wrappingKeyAlias: string, options: HuksOptions) : Promise\<void>
导入加密密钥,使用Promise方式异步返回结果。 导入加密密钥,使用Promise方式异步返回结果。
...@@ -1198,32 +1682,33 @@ importWrappedKey(keyAlias: string, wrappingKeyAlias: string, options: HuksOption ...@@ -1198,32 +1682,33 @@ importWrappedKey(keyAlias: string, wrappingKeyAlias: string, options: HuksOption
| wrappingKeyAlias | string | 是 | 密钥别名,对应密钥用于解密加密的密钥数据。 | | wrappingKeyAlias | string | 是 | 密钥别名,对应密钥用于解密加密的密钥数据。 |
| options | [HuksOptions](#huksoptions) | 是 | 用于导入时所需TAG和需要导入的加密的密钥数据。 | | options | [HuksOptions](#huksoptions) | 是 | 用于导入时所需TAG和需要导入的加密的密钥数据。 |
**返回值:**
| 类型 | 说明 |
| ----------------------------------- | -------------------------------------------------- |
| Promise\<[HuksResult](#huksresult)> | 返回HUKS_SUCCESS时表示接口使用成功,其他时为错误。 |
**示例:** **示例:**
```js ```js
/* 处理流程与callback类似,主要差异点为如下函数: */ /* 处理流程与callback类似,主要差异点为如下函数: */
async function TestImportWrappedFunc(alias, wrappingAlias, options) { async function TestImportWrappedFunc(alias, wrappingAlias, options) {
var result = await huks.importWrappedKey(alias, wrappingAlias, options); try {
if (result.errorCode === 0) { await huks.importWrappedKeyItem(alias, wrappingAlias, options)
console.log('test importWrappedKey success'); .then ((data) => {
} else { console.info(`promise: importWrappedKeyItem success`);
console.log('test importWrappedKey fail'); })
.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<sup>(deprecated)</sup>
exportKey(keyAlias: string, options: HuksOptions, callback: AsyncCallback\<HuksResult>) : void exportKey(keyAlias: string, options: HuksOptions, callback: AsyncCallback\<HuksResult>) : void
导出密钥,使用Callback方式回调异步返回的结果。 导出密钥,使用Callback方式回调异步返回的结果。
> **说明:** 从API Version 9开始废弃,建议使用[huks.exportKeyItem<sup>9+</sup>](#huksexportkeyitem9)替代。
**系统能力**:SystemCapability.Security.Huks **系统能力**:SystemCapability.Security.Huks
**参数:** **参数:**
...@@ -1245,12 +1730,14 @@ var emptyOptions = { ...@@ -1245,12 +1730,14 @@ var emptyOptions = {
huks.exportKey(keyAlias, emptyOptions, function (err, data){}); huks.exportKey(keyAlias, emptyOptions, function (err, data){});
``` ```
## huks.exportKey ## huks.exportKey<sup>(deprecated)</sup>
exportKey(keyAlias: string, options: HuksOptions) : Promise\<HuksResult> exportKey(keyAlias: string, options: HuksOptions) : Promise\<HuksResult>
导出密钥,使用Promise方式回调异步返回的结果。 导出密钥,使用Promise方式回调异步返回的结果。
> **说明:** 从API Version 9开始废弃,建议使用[huks.exportKeyItem<sup>9+</sup>](#huksexportkeyitem9-1))替代。
**系统能力**:SystemCapability.Security.Huks **系统能力**:SystemCapability.Security.Huks
**参数:** **参数:**
...@@ -1277,21 +1764,21 @@ var emptyOptions = { ...@@ -1277,21 +1764,21 @@ var emptyOptions = {
var result = huks.exportKey(keyAlias, emptyOptions); var result = huks.exportKey(keyAlias, emptyOptions);
``` ```
## huks.getKeyProperties ## huks.exportKeyItem<sup>9+</sup>
getKeyProperties(keyAlias: string, options: HuksOptions, callback: AsyncCallback\<HuksResult>) : void exportKeyItem(keyAlias: string, options: HuksOptions, callback: AsyncCallback\<HuksReturnResult>) : void
获取密钥属性,使用Callback回调异步返回结果。 导出密钥,使用Callback方式回调异步返回的结果。
**系统能力**:SystemCapability.Security.Huks **系统能力**:SystemCapability.Security.Huks
**参数:** **参数:**
| 参数名 | 类型 | 必填 | 说明 | | 参数名 | 类型 | 必填 | 说明 |
| -------- | ----------------------------------------- | ---- | ------------------------------------------------------------ | | -------- | ---------------------------------------------------- | ---- | ------------------------------------------------------------ |
| keyAlias | string | 是 | 密钥别名,应与所用密钥生成时使用的别名相同。 | | keyAlias | string | 是 | 密钥别名,应与所用密钥生成时使用的别名相同。 |
| options | [HuksOptions](#huksoptions) | 是 | 空对象(此处传空即可)。 | | options | [HuksOptions](#huksoptions) | 是 | 空对象(此处传空即可)。 |
| callback | AsyncCallback\<[HuksResult](#huksresult)> | 是 | errorCode:返回HUKS_SUCCESS时表示接口使用成功,其他时为错误。 | | callback | AsyncCallback<[HuksReturnResult](#huksreturnresult)> | 是 | 返回HUKS_SUCCESS时表示接口使用成功,其他时为错误。outData:返回从密钥中导出的公钥。 |
**示例:** **示例:**
...@@ -1301,29 +1788,39 @@ var keyAlias = 'keyAlias'; ...@@ -1301,29 +1788,39 @@ var keyAlias = 'keyAlias';
var emptyOptions = { var emptyOptions = {
properties: [] properties: []
}; };
huks.getKeyProperties(keyAlias, emptyOptions, function (err, data){}); 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.getKeyProperties ## huks.exportKeyItem<sup>9+</sup>
getKeyProperties(keyAlias: string, options: HuksOptions) : Promise\<HuksResult> exportKeyItem(keyAlias: string, options: HuksOptions) : Promise\<HuksReturnResult>
获取密钥属性,使用Promise回调异步返回结果。 导出密钥,使用Promise方式回调异步返回的结果。
**系统能力**:SystemCapability.Security.Huks **系统能力**:SystemCapability.Security.Huks
**参数:** **参数:**
| 参数名 | 类型 | 必填 | 说明 | | 参数名 | 类型 | 必填 | 说明 |
| -------- | ----------- | ---- | ------------------------------------------------------------ | | -------- | --------------------------- | ---- | -------------------------------------------- |
| keyAlias | string | 是 | 密钥别名,应与所用密钥生成时使用的别名相同。 | | keyAlias | string | 是 | 密钥别名,应与所用密钥生成时使用的别名相同。 |
| options | [HuksOptions](#huksoptions) | 是 | 空对象(此处传空即可)。 | | options | [HuksOptions](#huksoptions) | 是 | 空对象(此处传空即可)。 |
**返回值:** **返回值:**
| 类型 | 说明 | | 类型 | 说明 |
| ------------------ | ------------------------------------------------------------ | | ---------------------------------------------- | ------------------------------------------------------------ |
| Promise\<[HuksResult](#huksoptions)> | errorCode:返回HUKS_SUCCESS时表示接口使用成功,其他时为错误。properties:返回值为生成密钥时所需参数。 | | Promise<[HuksReturnResult](#huksreturnresult)> | 不返回err值时表示接口使用成功,其他时为错误。outData:返回从密钥中导出的公钥。 |
**示例:** **示例:**
...@@ -1333,24 +1830,36 @@ var keyAlias = 'keyAlias'; ...@@ -1333,24 +1830,36 @@ var keyAlias = 'keyAlias';
var emptyOptions = { var emptyOptions = {
properties: [] properties: []
}; };
var result = huks.getKeyProperties(keyAlias, emptyOptions); 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.isKeyExist ## huks.getKeyProperties<sup>(deprecated)</sup>
isKeyExist(keyAlias: string, options: HuksOptions, callback: AsyncCallback\<boolean>) : void getKeyProperties(keyAlias: string, options: HuksOptions, callback: AsyncCallback\<HuksResult>) : void
判断密钥是否存在,使用Callback回调异步返回结果 。 获取密钥属性,使用Callback回调异步返回结果。
> **说明:** 从API Version 9开始废弃,建议使用[huks.getKeyItemProperties<sup>9+</sup>](#huksgetkeyitemproperties9)替代。
**系统能力**:SystemCapability.Security.Huks **系统能力**:SystemCapability.Security.Huks
**参数:** **参数:**
| 参数名 | 类型 | 必填 | 说明 | | 参数名 | 类型 | 必填 | 说明 |
| -------- | ---------------------- | ---- | ------------------------------------- | | -------- | ----------------------------------------- | ---- | ------------------------------------------------------------ |
| keyAlias | string | 是 | 所需查找的密钥的别名。 | | keyAlias | string | 是 | 密钥别名,应与所用密钥生成时使用的别名相同。 |
| options | [HuksOptions](#huksoptions) | 是 | 空对象(此处传空即可)。 | | options | [HuksOptions](#huksoptions) | 是 | 空对象(此处传空即可)。 |
| callback | AsyncCallback\<boolean> | 是 | FALSE代表密钥不存在,TRUE代表密钥存在。 | | callback | AsyncCallback\<[HuksResult](#huksresult)> | 是 | errorCode:返回HUKS_SUCCESS时表示接口使用成功,其他时为错误。 |
**示例:** **示例:**
...@@ -1360,29 +1869,31 @@ var keyAlias = 'keyAlias'; ...@@ -1360,29 +1869,31 @@ var keyAlias = 'keyAlias';
var emptyOptions = { var emptyOptions = {
properties: [] properties: []
}; };
huks.isKeyExist(keyAlias, emptyOptions, function (err, data){}); huks.getKeyProperties(keyAlias, emptyOptions, function (err, data){});
``` ```
## huks.isKeyExist ## huks.getKeyProperties<sup>(deprecated)</sup>
isKeyExist(keyAlias: string, options: HuksOptions) : Promise\<boolean> getKeyProperties(keyAlias: string, options: HuksOptions) : Promise\<HuksResult>
判断密钥是否存在,使用Promise回调异步返回结果 。 获取密钥属性,使用Promise回调异步返回结果。
> **说明:** 从API Version 9开始废弃,建议使用[huks.getKeyItemProperties<sup>9+</sup>](#huksgetkeyitemproperties9-1)替代。
**系统能力**:SystemCapability.Security.Huks **系统能力**:SystemCapability.Security.Huks
**参数:** **参数:**
| 参数名 | 类型 | 必填 | 说明 | | 参数名 | 类型 | 必填 | 说明 |
| -------- | ----------- | ---- | -------------------------------- | | -------- | ----------- | ---- | ------------------------------------------------------------ |
| keyAlias | string | 是 | 所需查找的密钥的别名。 | | keyAlias | string | 是 | 密钥别名,应与所用密钥生成时使用的别名相同。 |
| options | [HuksOptions](#huksoptions) | 是 | 空对象(此处传空即可)。 | | options | [HuksOptions](#huksoptions) | 是 | 空对象(此处传空即可)。 |
**返回值:** **返回值:**
| 类型 | 说明 | | 类型 | 说明 |
| ----------------- | --------------------------------------- | | ------------------ | ------------------------------------------------------------ |
| Promise\<boolean> | FALSE代表密钥不存在,TRUE代表密钥存在。 | | Promise\<[HuksResult](#huksoptions)> | errorCode:返回HUKS_SUCCESS时表示接口使用成功,其他时为错误。properties:返回值为生成密钥时所需参数。 |
**示例:** **示例:**
...@@ -1392,18 +1903,235 @@ var keyAlias = 'keyAlias'; ...@@ -1392,18 +1903,235 @@ var keyAlias = 'keyAlias';
var emptyOptions = { var emptyOptions = {
properties: [] properties: []
}; };
var result = huks.isKeyExist(keyAlias, emptyOptions); var result = huks.getKeyProperties(keyAlias, emptyOptions);
``` ```
## huks.getKeyItemProperties<sup>9+</sup>
getKeyItemProperties(keyAlias: string, options: HuksOptions, callback: AsyncCallback\<HuksReturnResult>) : void
## huks.init 获取密钥属性,使用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.getKeyItemProperties<sup>9+</sup>
getKeyItemProperties(keyAlias: string, options: HuksOptions) : Promise\<HuksReturnResult>
获取密钥属性,使用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<sup>(deprecated)</sup>
isKeyExist(keyAlias: string, options: HuksOptions, callback: AsyncCallback\<boolean>) : void
判断密钥是否存在,使用Callback回调异步返回结果 。
**系统能力**:SystemCapability.Security.Huks
**参数:**
| 参数名 | 类型 | 必填 | 说明 |
| -------- | ---------------------- | ---- | ------------------------------------- |
| keyAlias | string | 是 | 所需查找的密钥的别名。 |
| options | [HuksOptions](#huksoptions) | 是 | 空对象(此处传空即可)。 |
| callback | AsyncCallback\<boolean> | 是 | FALSE代表密钥不存在,TRUE代表密钥存在。 |
**示例:**
```js
/* 此处options选择emptyOptions来传空 */
var keyAlias = 'keyAlias';
var emptyOptions = {
properties: []
};
huks.isKeyExist(keyAlias, emptyOptions, function (err, data){});
```
## huks.isKeyExist<sup>(deprecated)</sup>
isKeyExist(keyAlias: string, options: HuksOptions) : Promise\<boolean>
判断密钥是否存在,使用Promise回调异步返回结果 。
**系统能力**:SystemCapability.Security.Huks
**参数:**
| 参数名 | 类型 | 必填 | 说明 |
| -------- | ----------- | ---- | -------------------------------- |
| keyAlias | string | 是 | 所需查找的密钥的别名。 |
| options | [HuksOptions](#huksoptions) | 是 | 空对象(此处传空即可)。 |
**返回值:**
| 类型 | 说明 |
| ----------------- | --------------------------------------- |
| Promise\<boolean> | FALSE代表密钥不存在,TRUE代表密钥存在。 |
**示例:**
```js
/* 此处options选择emptyOptions来传空 */
var keyAlias = 'keyAlias';
var emptyOptions = {
properties: []
};
var result = huks.isKeyExist(keyAlias, emptyOptions);
```
## huks.isKeyItemExist<sup>9+</sup>
isKeyItemExist(keyAlias: string, options: HuksOptions, callback: AsyncCallback\<boolean>) : void
判断密钥是否存在,使用Callback回调异步返回结果 。
**系统能力**:SystemCapability.Security.Huks
**参数:**
| 参数名 | 类型 | 必填 | 说明 |
| -------- | --------------------------- | ---- | --------------------------------------- |
| keyAlias | string | 是 | 所需查找的密钥的别名。 |
| options | [HuksOptions](#huksoptions) | 是 | 空对象(此处传空即可)。 |
| callback | AsyncCallback\<boolean> | 是 | 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.isKeyItemExist<sup>9+</sup>
isKeyItemExist(keyAlias: string, options: HuksOptions) : Promise\<boolean>
判断密钥是否存在,使用Promise回调异步返回结果 。
**系统能力**:SystemCapability.Security.Huks
**参数:**
| 参数名 | 类型 | 必填 | 说明 |
| -------- | --------------------------- | ---- | ------------------------ |
| keyAlias | string | 是 | 所需查找的密钥的别名。 |
| options | [HuksOptions](#huksoptions) | 是 | 空对象(此处传空即可)。 |
**返回值:**
| 类型 | 说明 |
| ----------------- | --------------------------------------- |
| Promise\<boolean> | 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<sup>(deprecated)</sup>
init(keyAlias: string, options: HuksOptions, callback: AsyncCallback\<HuksHandle>) : void init(keyAlias: string, options: HuksOptions, callback: AsyncCallback\<HuksHandle>) : void
init操作密钥接口,使用Callback回调异步返回结果 。 init操作密钥接口,使用Callback回调异步返回结果 。
**系统能力**:SystemCapability.Security.Huks > **说明:** 从API Version 9开始废弃,建议使用[huks.initSession<sup>9+</sup>](#huksinitsession9-1)替代。
系统能力**:SystemCapability.Security.Huks
**参数:** **参数:**
...@@ -1414,13 +2142,15 @@ init操作密钥接口,使用Callback回调异步返回结果 。 ...@@ -1414,13 +2142,15 @@ init操作密钥接口,使用Callback回调异步返回结果 。
| callback | AsyncCallback\<[HuksHandle](#hukshandle)> | 是 | 将Init操作操作返回的handle添加到密钥管理系统的回调。 | | callback | AsyncCallback\<[HuksHandle](#hukshandle)> | 是 | 将Init操作操作返回的handle添加到密钥管理系统的回调。 |
## huks.init ## huks.init<sup>(deprecated)</sup>
init(keyAlias: string, options: HuksOptions) : Promise\<HuksHandle> init(keyAlias: string, options: HuksOptions) : Promise\<HuksHandle>
init操作密钥接口,使用Promise方式异步返回结果。 init操作密钥接口,使用Promise方式异步返回结果。
**系统能力**:SystemCapability.Security.Huks > **说明:** 从API Version 9开始废弃,建议使用[huks.initSession<sup>9+</sup>](#huksinitsession9-1)替代。
系统能力**:SystemCapability.Security.Huks
**参数:** **参数:**
...@@ -1430,14 +2160,62 @@ init操作密钥接口,使用Promise方式异步返回结果。 ...@@ -1430,14 +2160,62 @@ init操作密钥接口,使用Promise方式异步返回结果。
| options | [HuksOptions](#huksoptions) | 是 | Init参数集合。 | | options | [HuksOptions](#huksoptions) | 是 | Init参数集合。 |
| promise | Promise\<[HuksHandle](#hukshandle)> | 是 | 将Init操作返回的handle添加到密钥管理系统的回调。 | | promise | Promise\<[HuksHandle](#hukshandle)> | 是 | 将Init操作返回的handle添加到密钥管理系统的回调。 |
## huks.initSession<sup>9+</sup>
initSession(keyAlias: string, options: HuksOptions, callback: AsyncCallback\<HuksSessionHandle>) : void
initSession操作密钥接口,使用Callback回调异步返回结果 。
系统能力**:SystemCapability.Security.Huks
**参数:**
| 参数名 | 类型 | 必填 | 说明 |
| -------- | ------------------------------------------------------- | ---- | ---------------------------------------------------- |
| keyAlias | string | 是 | Init操作密钥的别名。 |
| options | [HuksOptions](#huksoptions) | 是 | Init操作的参数集合。 |
| callback | AsyncCallback\<[HuksSessionHandle](#hukssessionhandle)> | 是 | 将Init操作操作返回的handle添加到密钥管理系统的回调。 |
## huks.initSession<sup>9+</sup>
initSession(keyAlias: string, options: HuksOptions) : Promise\<HuksSessionHandle>
initSession操作密钥接口,使用Promise方式异步返回结果。
系统能力**:SystemCapability.Security.Huks
**参数:**
| 参数名 | 类型 | 必填 | 说明 |
| -------- | ------------------------------------------------- | ---- | ------------------------------------------------ |
| keyAlias | string | 是 | Init操作密钥的别名。 |
| options | [HuksOptions](#huksoptions) | 是 | Init参数集合。 |
| promise | Promise\<[HuksSessionHandle](#hukssessionhandle)> | 是 | 将Init操作返回的handle添加到密钥管理系统的回调。 |
## huks.update<sup>(deprecated)</sup>
update(handle: number, options: HuksOptions, callback: AsyncCallback\<HuksResult>) : void
update操作密钥接口,使用Callback回调异步返回结果 。
**系统能力**:SystemCapability.Security.Huks
**参数:**
| 参数名 | 类型 | 必填 | 说明 |
| -------- | ----------------------------------------- | ---- | -------------------------------------------- |
| handle | number | 是 | Update操作的handle。 |
| options | [HuksOptions](#huksoptions) | 是 | Update的参数集合。 |
| callback | AsyncCallback\<[HuksResult](#huksresult)> | 是 | 将Update操作的结果添加到密钥管理系统的回调。 |
## huks.update<sup>(deprecated)</sup> ## huks.update<sup>(deprecated)</sup>
update(handle: number, token?: Uint8Array, options: HuksOptions, callback: AsyncCallback\<HuksResult>) : void update(handle: number, options: HuksOptions, token: Uint8Array, callback: AsyncCallback\<HuksResult>) : void
update操作密钥接口,使用Callback回调异步返回结果 。 update操作密钥接口,使用Callback回调异步返回结果 。
> **说明:** 从API Version 9开始废弃,建议使用[huks.update<sup>9+</sup>](#huksupdate9-1)替代。 > **说明:** 从API Version 9开始废弃,建议使用[huks.updateSession<sup>9+</sup>](#huksupdatesession9)替代。
**系统能力**: SystemCapability.Security.Huks **系统能力**: SystemCapability.Security.Huks
...@@ -1452,11 +2230,11 @@ update操作密钥接口,使用Callback回调异步返回结果 。 ...@@ -1452,11 +2230,11 @@ update操作密钥接口,使用Callback回调异步返回结果 。
## huks.update<sup>(deprecated)</sup> ## huks.update<sup>(deprecated)</sup>
update(handle: number, token?: Uint8Array, options: HuksOptions) : Promise\<HuksResult> update(handle: number, options: HuksOptions, token?: Uint8Array) : Promise\<HuksResult>
update操作密钥接口,使用Promise方式异步返回结果。 update操作密钥接口,使用Promise方式异步返回结果。
> **说明:** 从API Version 9开始废弃,建议使用[huks.update<sup>9+</sup>](#huksupdate9)替代。 > **说明:** 从API Version 9开始废弃,建议使用[huks.updateSession<sup>9+</sup>](#huksupdatesession9-1)替代。
**系统能力**: SystemCapability.Security.Huks **系统能力**: SystemCapability.Security.Huks
...@@ -1469,63 +2247,65 @@ update操作密钥接口,使用Promise方式异步返回结果。 ...@@ -1469,63 +2247,65 @@ update操作密钥接口,使用Promise方式异步返回结果。
| options | [HuksOptions](#huksoptions) | 是 | Update操作的参数集合。 | | options | [HuksOptions](#huksoptions) | 是 | Update操作的参数集合。 |
| promise | Promise\<[HuksResult](#huksresult)> | 是 | 将Update操作的结果添加到密钥管理系统的回调。 | | promise | Promise\<[HuksResult](#huksresult)> | 是 | 将Update操作的结果添加到密钥管理系统的回调。 |
## huks.update<sup>9+</sup> ## huks.updateSession<sup>9+</sup>
update(handle: number, options: HuksOptions, callback: AsyncCallback\<HuksResult>) : void updateSession(handle: number, options: HuksOptions, callback: AsyncCallback\<HuksReturnResult>) : void
update操作密钥接口,使用Callback回调异步返回结果 。 updateSession操作密钥接口,使用Callback回调异步返回结果 。
**系统能力**:SystemCapability.Security.Huks **系统能力**:SystemCapability.Security.Huks
**参数:** **参数:**
| 参数名 | 类型 | 必填 | 说明 | | 参数名 | 类型 | 必填 | 说明 |
| -------- | ----------------------------------------- | ---- | -------------------------------------------- | | -------- | ---------------------------------------------------- | ---- | -------------------------------------------- |
| handle | number | 是 | Update操作的handle。 | | handle | number | 是 | Update操作的handle。 |
| options | [HuksOptions](#huksoptions) | 是 | Update的参数集合。 | | options | [HuksOptions](#huksoptions) | 是 | Update的参数集合。 |
| callback | AsyncCallback\<[HuksResult](#huksresult)> | 是 | 将Update操作的结果添加到密钥管理系统的回调。 | | callback | AsyncCallback<[HuksReturnResult](#huksreturnresult)> | 是 | 将Update操作的结果添加到密钥管理系统的回调。 |
## huks.update<sup>9+</sup> ## huks.updateSession<sup>9+</sup>
update(handle: number, options: HuksOptions, token: Uint8Array, callback: AsyncCallback\<HuksResult>) : void updateSession(handle: number, options: HuksOptions, token: Uint8Array, callback: AsyncCallback\<HuksReturnResult>) : void
update操作密钥接口,使用Callback回调异步返回结果 。 updateSession操作密钥接口,使用Callback回调异步返回结果 。
**系统能力**:SystemCapability.Security.Huks **系统能力**:SystemCapability.Security.Huks
**参数:** **参数:**
| 参数名 | 类型 | 必填 | 说明 | | 参数名 | 类型 | 必填 | 说明 |
| -------- | ----------------------------------------- | ---- | -------------------------------------------- | | -------- | ---------------------------------------------------- | ---- | -------------------------------------------- |
| handle | number | 是 | Update操作的handle。 | | handle | number | 是 | Update操作的handle。 |
| options | [HuksOptions](#huksoptions) | 是 | Update操作的参数集合。 | | options | [HuksOptions](#huksoptions) | 是 | Update操作的参数集合。 |
| token | Uint8Array | 是 | Update操作的token。 | | token | Uint8Array | 是 | Update操作的token。 |
| callback | AsyncCallback\<[HuksResult](#huksresult)> | 是 | 将Update操作的结果添加到密钥管理系统的回调。 | | callback | AsyncCallback<[HuksReturnResult](#huksreturnresult)> | 是 | 将Update操作的结果添加到密钥管理系统的回调。 |
## huks.update<sup>9+</sup> ## huks.updateSession<sup>9+</sup>
update(handle: number, options: HuksOptions, token?: Uint8Array) : Promise\<HuksResult> updateSession(handle: number, options: HuksOptions, token?: Uint8Array) : Promise\<HuksReturnResult>
update操作密钥接口,使用Promise方式异步返回结果。 uupdateSession操作密钥接口,使用Promise方式异步返回结果。
**系统能力**:SystemCapability.Security.Huks **系统能力**:SystemCapability.Security.Huks
**参数:** **参数:**
| 参数名 | 类型 | 必填 | 说明 | | 参数名 | 类型 | 必填 | 说明 |
| ------- | ----------------------------------- | ---- | -------------------------------------------- | | ------- | ---------------------------------------------- | ---- | -------------------------------------------- |
| handle | number | 是 | Update操作的handle。 | | handle | number | 是 | Update操作的handle。 |
| options | [HuksOptions](#huksoptions) | 是 | Update操作的参数集合。 | | options | [HuksOptions](#huksoptions) | 是 | Update操作的参数集合。 |
| token | Uint8Array | 否 | Update操作的token。 | | token | Uint8Array | 否 | Update操作的token。 |
| promise | Promise\<[HuksResult](#huksresult)> | 是 | 将Update操作的结果添加到密钥管理系统的回调。 | | promise | Promise<[HuksReturnResult](#huksreturnresult)> | 是 | 将Update操作的结果添加到密钥管理系统的回调。 |
## huks.finish ## huks.finish<sup>(deprecated)</sup>
finish(handle: number, options: HuksOptions, callback: AsyncCallback\<HuksResult>) : void finish(handle: number, options: HuksOptions, callback: AsyncCallback\<HuksResult>) : void
finish操作密钥接口,使用Callback回调异步返回结果 。 finish操作密钥接口,使用Callback回调异步返回结果 。
> **说明:** 从API Version 9开始废弃,建议使用[huks.finishSession<sup>9+</sup>](#huksfinishsession9)替代。
**系统能力**:SystemCapability.Security.Huks **系统能力**:SystemCapability.Security.Huks
**参数:** **参数:**
...@@ -1537,12 +2317,14 @@ finish操作密钥接口,使用Callback回调异步返回结果 。 ...@@ -1537,12 +2317,14 @@ finish操作密钥接口,使用Callback回调异步返回结果 。
| callback | AsyncCallback\<[HuksResult](#huksresult)> | 是 | 将Finish操作的结果添加到密钥管理系统的回调。 | | callback | AsyncCallback\<[HuksResult](#huksresult)> | 是 | 将Finish操作的结果添加到密钥管理系统的回调。 |
## huks.finish ## huks.finish<sup>(deprecated)</sup>
finish(handle: number, options: HuksOptions) : Promise\<HuksResult> finish(handle: number, options: HuksOptions) : Promise\<HuksResult>
finish操作密钥接口,使用Promise方式异步返回结果。 finish操作密钥接口,使用Promise方式异步返回结果。
> **说明:** 从API Version 9开始废弃,建议使用[huks.updateSession<sup>9+</sup>](#huksfinishsession9-1)替代。
**系统能力**:SystemCapability.Security.Huks **系统能力**:SystemCapability.Security.Huks
**参数:** **参数:**
...@@ -1553,47 +2335,66 @@ finish操作密钥接口,使用Promise方式异步返回结果。 ...@@ -1553,47 +2335,66 @@ finish操作密钥接口,使用Promise方式异步返回结果。
| options | [HuksOptions](#huksoptions) | 是 | Finish操作的参数集合。 | | options | [HuksOptions](#huksoptions) | 是 | Finish操作的参数集合。 |
| promise | Promise\<[HuksResult](#huksresult)> | 是 | promise实例,用于获取异步返回结果。 | | promise | Promise\<[HuksResult](#huksresult)> | 是 | promise实例,用于获取异步返回结果。 |
## huks.finish<sup>9+</sup> ## huks.finishSession<sup>9+</sup>
finish(handle: number, options: HuksOptions, token: Uint8Array, callback: AsyncCallback\<HuksResult>) : void finishSession(handle: number, options: HuksOptions, callback: AsyncCallback\<HuksReturnResult>) : void
finish操作密钥接口,使用Callback回调异步返回结果 。 finishSession操作密钥接口,使用Callback回调异步返回结果 。
**系统能力**:SystemCapability.Security.Huks **系统能力**:SystemCapability.Security.Huks
**参数:** **参数:**
| 参数名 | 类型 | 必填 | 说明 | | 参数名 | 类型 | 必填 | 说明 |
| -------- | ----------------------------------------- | ---- | -------------------------------------------- | | -------- | ---------------------------------------------------- | ---- | -------------------------------------------- |
| handle | number | 是 | Finish操作的handle。 | | handle | number | 是 | Finish操作的handle。 |
| options | [HuksOptions](#huksoptions) | 是 | Finish的参数集合。 | | options | [HuksOptions](#huksoptions) | 是 | Finish的参数集合。 |
| token | Uint8Array | 是 | Finish操作的token。 | | token | Uint8Array | 是 | Finish操作的token。 |
| callback | AsyncCallback\<[HuksResult](#huksresult)> | 是 | 将Finish操作的结果添加到密钥管理系统的回调。 | | callback | AsyncCallback<[HuksReturnResult](#huksreturnresult)> | 是 | 将Finish操作的结果添加到密钥管理系统的回调。 |
## huks.finishSession<sup>9+</sup>
## huks.finish<sup>9+</sup> finishSession(handle: number, options: HuksOptions, token: Uint8Array, callback: AsyncCallback\<HuksReturnResult>) : void
finish(handle: number, options: HuksOptions, token?: Uint8Array) : Promise\<HuksResult> 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.finishSession<sup>9+</sup>
finishSession(handle: number, options: HuksOptions, token?: Uint8Array) : Promise\<HuksReturnResult>
finishSession操作密钥接口,使用Promise方式异步返回结果。
**系统能力**:SystemCapability.Security.Huks **系统能力**:SystemCapability.Security.Huks
**参数:** **参数:**
| 参数名 | 类型 | 必填 | 说明 | | 参数名 | 类型 | 必填 | 说明 |
| ------- | ----------------------------------- | ---- | ----------------------------------- | | ------- | ----------------------------------------------- | ---- | ----------------------------------- |
| handle | number | 是 | Finish操作的handle。 | | handle | number | 是 | Finish操作的handle。 |
| options | [HuksOptions](#huksoptions) | 是 | Finish操作的参数集合。 | | options | [HuksOptions](#huksoptions) | 是 | Finish操作的参数集合。 |
| token | Uint8Array | 否 | Finish操作的token。 | | token | Uint8Array | 否 | Finish操作的token。 |
| promise | Promise\<[HuksResult](#huksresult)> | 是 | promise实例,用于获取异步返回结果。 | | promise | Promise\<[HuksReturnResult](#huksreturnresult)> | 是 | promise实例,用于获取异步返回结果。 |
## huks.abort ## huks.abort<sup>(deprecated)</sup>
abort(handle: number, options: HuksOptions, callback: AsyncCallback\<HuksResult>) : void abort(handle: number, options: HuksOptions, callback: AsyncCallback\<HuksResult>) : void
abort操作密钥接口,使用Callback回调异步返回结果 。 abort操作密钥接口,使用Callback回调异步返回结果 。
> **说明:** 从API Version 9开始废弃,建议使用[huks.abortSession<sup>9+</sup>](#huksabortsession9)替代。
**系统能力**:SystemCapability.Security.Huks **系统能力**:SystemCapability.Security.Huks
**参数:** **参数:**
...@@ -1612,19 +2413,6 @@ abort操作密钥接口,使用Callback回调异步返回结果 。 ...@@ -1612,19 +2413,6 @@ abort操作密钥接口,使用Callback回调异步返回结果 。
* *
* 以下以RSA1024密钥的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 keyalias = "HuksDemoRSA";
var properties = new Array(); var properties = new Array();
var options = { var options = {
...@@ -1708,112 +2496,16 @@ async function huksAbort() { ...@@ -1708,112 +2496,16 @@ async function huksAbort() {
}); });
console.log(resultMessage); 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<sup>(deprecated)</sup>
abort(handle: number, options: HuksOptions) : Promise\<HuksResult>; abort(handle: number, options: HuksOptions) : Promise\<HuksResult>;
abort操作密钥接口,使用Promise方式异步返回结果。 abort操作密钥接口,使用Promise方式异步返回结果。
> **说明:** 从API Version 9开始废弃,建议使用[huks.abortSession<sup>9+</sup>](#huksabortsession9-1)替代。
**系统能力**:SystemCapability.Security.Huks **系统能力**:SystemCapability.Security.Huks
**参数:** **参数:**
...@@ -1832,20 +2524,6 @@ abort操作密钥接口,使用Promise方式异步返回结果。 ...@@ -1832,20 +2524,6 @@ abort操作密钥接口,使用Promise方式异步返回结果。
* *
* 以下以RSA1024密钥的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 keyalias = "HuksDemoRSA";
var properties = new Array(); var properties = new Array();
var options = { var options = {
...@@ -1935,101 +2613,294 @@ function huksAbort() { ...@@ -1935,101 +2613,294 @@ function huksAbort() {
}); });
}); });
} }
@Entry ```
@Component
struct Index { ## huks.abortSession<sup>9+</sup>
build() {
Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) { abortSession(handle: number, options: HuksOptions, callback: AsyncCallback\<void>) : void
Text('Hello World')
.fontSize(50) abort操作密钥接口,使用Callback回调异步返回结果 。
.fontWeight(FontWeight.Bold)
Button() { **系统能力**:SystemCapability.Security.Huks
Text('to Promise')
.fontSize(20) **参数:**
.fontWeight(FontWeight.Bold)
}.type(ButtonType.Capsule) | 参数名 | 类型 | 必填 | 说明 |
.margin({ | -------- | --------------------------- | ---- | ------------------------------------------- |
top: 20 | handle | number | 是 | Abort操作的handle。 |
}) | options | [HuksOptions](#huksoptions) | 是 | Abort操作的参数集合。 |
.width('50%') | callback | AsyncCallback\<void> | 是 | 将Abort操作的结果添加到密钥管理系统的回调。 |
.height('10%')
.backgroundColor('#0D9FFB') **示例:**
.onClick(() => {
router.back() ```js
}) /* huks.initSession, huks.updateSession, huks.finishSession为三段式接口,需要一起使用,当
Button() { * huks.initSession和huks.updateSession
Text('generateKey') * 以及huks.finishSession操作中的任一阶段发生错误时,
.fontSize(25) * 都需要调用huks.abortSession来终止密钥的使用。
.fontWeight(FontWeight.Bold) *
}.type(ButtonType.Capsule) * 以下以RSA1024密钥的callback功能使用为例
.margin({ */
top: 20 function stringToUint8Array(str) {
}) var arr = [];
.width('50%') for (var i = 0, j = str.length; i < j; ++i) {
.height('10%') arr.push(str.charCodeAt(i));
.backgroundColor('#0D9FFB') }
.onClick(() => { var tmpUint8Array = new Uint8Array(arr);
generateKey() return tmpUint8Array;
}) }
Button() {
Text('Init') var keyAlias = "HuksDemoRSA";
.fontSize(25) var properties = new Array();
.fontWeight(FontWeight.Bold) var options = {
}.type(ButtonType.Capsule) properties: properties,
.margin({ inData: new Uint8Array(0)
top: 20 };
}) var handle;
.width('50%') async function generateKey() {
.height('10%') properties[0] = {
.backgroundColor('#0D9FFB') tag: huks.HuksTag.HUKS_TAG_ALGORITHM,
.onClick(() => { value: huks.HuksKeyAlg.HUKS_ALG_RSA
huksInit() };
}) properties[1] = {
Button() { tag: huks.HuksTag.HUKS_TAG_KEY_SIZE,
Text('Update') value: huks.HuksKeySize.HUKS_RSA_KEY_SIZE_1024
.fontSize(25) };
.fontWeight(FontWeight.Bold) properties[2] = {
}.type(ButtonType.Capsule) tag: huks.HuksTag.HUKS_TAG_PURPOSE,
.margin({ value: huks.HuksKeyPurpose.HUKS_KEY_PURPOSE_ENCRYPT
top: 20 };
}) properties[3] = {
.width('50%') tag: huks.HuksTag.HUKS_TAG_PADDING,
.height('10%') value: huks.HuksKeyPadding.HUKS_PADDING_PKCS1_V1_5
.backgroundColor('#0D9FFB') };
.onClick(() => { properties[4] = {
huksUpdate() tag: huks.HuksTag.HUKS_TAG_DIGEST,
}) value: huks.HuksKeyDigest.HUKS_DIGEST_SHA256
Button() { };
Text('Finish') properties[5] = {
.fontSize(25) tag: huks.HuksTag.HUKS_TAG_BLOCK_MODE,
.fontWeight(FontWeight.Bold) value: huks.HuksCipherMode.HUKS_MODE_ECB,
}.type(ButtonType.Capsule) }
.margin({
top: 20 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.abortSession<sup>9+</sup>
abortSession(handle: number, options: HuksOptions) : Promise\<void>;
abort操作密钥接口,使用Promise方式异步返回结果。
**系统能力**:SystemCapability.Security.Huks
**参数:**
| 参数名 | 类型 | 必填 | 说明 |
| ------- | --------------------------- | ---- | ------------------------------------------- |
| handle | number | 是 | Abort操作的handle。 |
| options | [HuksOptions](#huksoptions) | 是 | Abort操作的参数集合。 |
| promise | Promise\<void> | 是 | 将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`);
}) })
.width('50%') .catch(error => {
.height('10%') console.error(`promise: generateKeyItem failed, code: ${error.code}, msg: ${error.message}`);
.backgroundColor('#0D9FFB') });
.onClick(() => { } catch (error) {
huksFinish() 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;
}) })
Button() { .catch(error => {
Text('Abort') console.error(`promise: initSession key failed, code: ${error.code}, msg: ${error.message}`);
.fontSize(25) });
.fontWeight(FontWeight.Bold) } catch (error) {
}.type(ButtonType.Capsule) console.error(`promise: initSession input arg invalid, code: ${error.code}, msg: ${error.message}`);
.margin({ }
top: 20 }
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)}`);
}) })
.width('50%') .catch(error => {
.height('10%') console.error(`promise: updateSession failed, code: ${error.code}, msg: ${error.message}`);
.backgroundColor('#0D9FFB') });
.onClick(() => { } catch (error) {
huksAbort() 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}`);
} }
.width('100%') }
.height('100%')
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}`);
} }
} }
``` ```
...@@ -2056,7 +2927,7 @@ struct Index { ...@@ -2056,7 +2927,7 @@ struct Index {
| properties | Array\<[HuksParam](#huksparam)> | 否 | 属性,用于存HuksParam的数组。 | | properties | Array\<[HuksParam](#huksparam)> | 否 | 属性,用于存HuksParam的数组。 |
| inData | Uint8Array | 否 | 输入数据。 | | inData | Uint8Array | 否 | 输入数据。 |
## HuksHandle ## HuksHandle<sup>(deprecated)</sup>
huks Handle结构体。 huks Handle结构体。
...@@ -2068,8 +2939,18 @@ huks Handle结构体。 ...@@ -2068,8 +2939,18 @@ huks Handle结构体。
| handle | number | 是 | 表示handle值。 | | handle | number | 是 | 表示handle值。 |
| token | Uint8Array | 否 | 表示[init](#huksinit)操作之后获取到的challenge信息。 | | token | Uint8Array | 否 | 表示[init](#huksinit)操作之后获取到的challenge信息。 |
## HuksSessionHandle<sup>9+</sup>
huks Handle结构体。
**系统能力**:SystemCapability.Security.Huks
| 参数名 | 类型 | 必填 | 说明 |
| --------- | ---------- | ---- | ---------------------------------------------------- |
| handle | number | 是 | 表示handle值。 |
| challenge | Uint8Array | 否 | 表示[init](#huksinit)操作之后获取到的challenge信息。 |
## HuksResult ## HuksResult<sup>(deprecated)</sup>
调用接口返回的result。 调用接口返回的result。
...@@ -2084,3 +2965,16 @@ huks Handle结构体。 ...@@ -2084,3 +2965,16 @@ huks Handle结构体。
| properties | Array\<[HuksParam](#huksparam)> | 否 | 表示属性信息。 | | properties | Array\<[HuksParam](#huksparam)> | 否 | 表示属性信息。 |
| certChains | Array\<string> | 否 | 表示证书链数据。 | | certChains | Array\<string> | 否 | 表示证书链数据。 |
## HuksReturnResult<sup>9+</sup>
调用接口返回的result。
**系统能力**:SystemCapability.Security.Huks
| 参数名 | 类型 | 必填 | 说明 |
| ---------- | ------------------------------- | ---- | ---------------- |
| outData | Uint8Array | 否 | 表示输出数据。 |
| properties | Array\<[HuksParam](#huksparam)> | 否 | 表示属性信息。 |
| certChains | Array\<string> | 否 | 表示证书链数据。 |
\ No newline at end of file
# HUKS开发指导 # HUKS开发指导
## 场景介绍 HUKS(OpenHarmony Universal KeyStore,OpenHarmony通用密钥库系统)向应用提供密钥库能力,包括密钥管理及密钥的密码学操作等功能。HUKS所管理的密钥可以由应用导入或者由应用调用HUKS接口生成。
HUKS(OpenHarmony Universal KeyStore,OpenHarmony通用密钥库系统)向应用提供密钥库能力,包括密钥管理及密钥的密码学操作等功能。HUKS所管理的密钥可以由应用导入或者由应用调用HUKS接口生成。 > **说明**
>
## 基于JS的开发指导 > 本开发指导基于API version 9,仅适用于eTS语言开发
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操作是否成功。 在使用HUKS的接口开发前,需要引入HUKS模块
```js ```ts
var properties = new Array(); import huks from '@ohos.security.huks'
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的开发指导
### 密钥导入导出 ### 密钥导入导出
...@@ -168,98 +52,252 @@ RSA512, RSA768, RSA1024, RSA2048, RSA3072, RSA4096, ECC224, ECC256, ECC384, ECC5 ...@@ -168,98 +52,252 @@ RSA512, RSA768, RSA1024, RSA2048, RSA3072, RSA4096, ECC224, ECC256, ECC384, ECC5
**示例:** **示例:**
```ts ```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<huks.HuksReturnResult> {
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 srcKeyAlias = 'hukRsaKeyAlias';
var srcKeyAliasSecond = 'huksRsaKeyAliasSecond'; var srcKeyAliasSecond = 'huksRsaKeyAliasSecond';
var exportKey; 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() { async function testImportExport() {
/* 集成生成密钥参数集 */ /* 集成生成密钥参数集 */
var properties = new Array(); var exportProperties = new Array();
properties[0] = { exportProperties[0] = {
tag: huks.HuksTag.HUKS_TAG_ALGORITHM, tag: huks.HuksTag.HUKS_TAG_ALGORITHM,
value: huks.HuksKeyAlg.HUKS_ALG_RSA, value: huks.HuksKeyAlg.HUKS_ALG_RSA,
} }
properties[1] = { exportProperties[1] = {
tag: huks.HuksTag.HUKS_TAG_PURPOSE, tag: huks.HuksTag.HUKS_TAG_PURPOSE,
value: value:
huks.HuksKeyPurpose.HUKS_KEY_PURPOSE_ENCRYPT | huks.HuksKeyPurpose.HUKS_KEY_PURPOSE_ENCRYPT |
huks.HuksKeyPurpose.HUKS_KEY_PURPOSE_DECRYPT, huks.HuksKeyPurpose.HUKS_KEY_PURPOSE_DECRYPT,
} }
properties[2] = { exportProperties[2] = {
tag: huks.HuksTag.HUKS_TAG_KEY_SIZE, tag: huks.HuksTag.HUKS_TAG_KEY_SIZE,
value: huks.HuksKeySize.HUKS_RSA_KEY_SIZE_512, value: huks.HuksKeySize.HUKS_RSA_KEY_SIZE_512,
} }
properties[3] = { exportProperties[3] = {
tag: huks.HuksTag.HUKS_TAG_BLOCK_MODE, tag: huks.HuksTag.HUKS_TAG_BLOCK_MODE,
value: huks.HuksCipherMode.HUKS_MODE_ECB, value: huks.HuksCipherMode.HUKS_MODE_ECB,
} }
properties[4] = { exportProperties[4] = {
tag: huks.HuksTag.HUKS_TAG_PADDING, tag: huks.HuksTag.HUKS_TAG_PADDING,
value: huks.HuksKeyPadding.HUKS_PADDING_PKCS1_V1_5, value: huks.HuksKeyPadding.HUKS_PADDING_PKCS1_V1_5,
} }
properties[5] = { exportProperties[5] = {
tag: huks.HuksTag.HUKS_TAG_DIGEST, tag: huks.HuksTag.HUKS_TAG_DIGEST,
value: huks.HuksKeyDigest.HUKS_DIGEST_SHA256, value: huks.HuksKeyDigest.HUKS_DIGEST_SHA256,
} }
var huksOptions = { var huksOptions = {
properties: properties, properties: exportProperties,
inData: new Uint8Array(new Array()) inData: new Uint8Array(new Array())
} }
/* 生成密钥 */ /* 生成密钥 */
await huks.generateKey(srcKeyAlias, huksOptions).then((data) => { await publicGenKeyFunc(srcKeyAlias, huksOptions);
console.info(`test generateKey data: ${JSON.stringify(data)}`);
}).catch((err) => {
console.info('test generateKey err information: ' + JSON.stringify(err));
});
/* 导出密钥 */ /* 导出密钥 */
await huks.exportKey(srcKeyAlias, huksOptions).then((data) => { await publicExportKeyFunc(srcKeyAlias, huksOptions);
console.info(`test ExportKey data: ${JSON.stringify(data)}`);
exportKey = data.outData;
}).catch((err) => {
console.info('test ImportKey err information: ' + JSON.stringify(err));
});
/* 集成导入密钥参数集 */ /* 集成导入密钥参数集 */
var propertiesEncrypt = new Array(); var importProperties = new Array();
propertiesEncrypt[0] = { importProperties[0] = {
tag: huks.HuksTag.HUKS_TAG_ALGORITHM, tag: huks.HuksTag.HUKS_TAG_ALGORITHM,
value: huks.HuksKeyAlg.HUKS_ALG_RSA, value: huks.HuksKeyAlg.HUKS_ALG_ECC
} };
propertiesEncrypt[1] = { importProperties[1] = {
tag: huks.HuksTag.HUKS_TAG_KEY_SIZE, tag: huks.HuksTag.HUKS_TAG_KEY_SIZE,
value: huks.HuksKeySize.HUKS_RSA_KEY_SIZE_512, value: huks.HuksKeySize.HUKS_ECC_KEY_SIZE_256
} };
propertiesEncrypt[2] = { importProperties[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] = {
tag: huks.HuksTag.HUKS_TAG_PURPOSE, tag: huks.HuksTag.HUKS_TAG_PURPOSE,
value: huks.HuksKeyPurpose.HUKS_KEY_PURPOSE_ENCRYPT, value: huks.HuksKeyPurpose.HUKS_KEY_PURPOSE_UNWRAP
} };
var encryptOptions = { importProperties[3] = {
properties: propertiesEncrypt, tag: huks.HuksTag.HUKS_TAG_DIGEST,
inData: new Uint8Array(new Array()) 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 publicImportKeyFunc(srcKeyAliasSecond, importOptions);
await huks.importKey(srcKeyAliasSecond, encryptOptions).then((data) => {
console.info(`test ImportKey data: ${JSON.stringify(data)}`); await publicDeleteKeyFunc(srcKeyAlias, huksOptions);
}).catch((err) => { await publicDeleteKeyFunc(srcKeyAliasSecond, importOptions);
console.info('test ImportKey err information: ' + JSON.stringify(err)); }
});
@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,206 +337,275 @@ AES128, AES192, AES256, RSA512, RSA768, RSA1024, RSA2048, RSA3072, RSA4096, Hmac ...@@ -299,206 +337,275 @@ AES128, AES192, AES256, RSA512, RSA768, RSA1024, RSA2048, RSA3072, RSA4096, Hmac
**示例:** **示例:**
```ts ```ts
var inputEccPair = new Uint8Array([ import huks from '@ohos.security.huks';
0x02, 0x00, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x20, 0x00, 0x00,
0x00, 0x20, 0x00, 0x00, 0x00, 0x20, 0x00, 0x00, 0x00, 0xa5, 0xb8, async function publicExportKeyFunc(keyAlias:string, huksOptions:huks.HuksOptions) {
0xa3, 0x78, 0x1d, 0x6d, 0x76, 0xe0, 0xb3, 0xf5, 0x6f, 0x43, 0x9d, console.info(`enter callback export`);
0xcf, 0x60, 0xf6, 0x0b, 0x3f, 0x64, 0x45, 0xa8, 0x3f, 0x1a, 0x96, try {
0xf1, 0xa1, 0xa4, 0x5d, 0x3e, 0x2c, 0x3f, 0x13, 0xd7, 0x81, 0xf7, await exportKeyItem(keyAlias, huksOptions)
0x2a, 0xb5, 0x8d, 0x19, 0x3d, 0x9b, 0x96, 0xc7, 0x6a, 0x10, 0xf0, .then ((data) => {
0xaa, 0xbc, 0x91, 0x6f, 0x4d, 0xa7, 0x09, 0xb3, 0x57, 0x88, 0x19, console.info(`callback: exportKeyItem success, data = ${JSON.stringify(data)}`);
0x6f, 0x00, 0x4b, 0xad, 0xee, 0x34, 0x35, 0xfb, 0x8b, 0x9f, 0x12, if (data.outData !== null) {
0xa0, 0x83, 0x19, 0xbe, 0x6a, 0x6f, 0x63, 0x2a, 0x7c, 0x86, 0xba, exportKey = data.outData;
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";
async function TestGenFunc(alias, options) {
await genKey(alias, options).then((data) => {
console.log(`test genKey data: ${JSON.stringify(data)}`);
}) })
.catch((err) => { .catch(error => {
console.log('test genKey err information: ' + JSON.stringify(err)); 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 genKey(alias, options) { function exportKeyItem(keyAlias:string, huksOptions:huks.HuksOptions) : Promise<huks.HuksReturnResult> {
return new Promise((resolve, reject) => { return new Promise((resolve, reject) => {
huks.importKey(alias, options, function (err, data) { try {
console.log(`test genKey data: ${JSON.stringify(data)}`); huks.exportKeyItem(keyAlias, huksOptions, function (error, data) {
if (err.code !== 0) { if (error) {
console.log('test genKey err information: ' + JSON.stringify(err)); reject(error);
reject(err);
} else { } else {
resolve(data); resolve(data);
} }
}); });
} catch (error) {
throw(error);
}
}); });
} }
async function TestExportFunc(alias, options) { async function publicImportKeyFunc(keyAlias:string, huksOptions:huks.HuksOptions) {
await exportKey(alias, options).then((data) => { console.info(`enter promise importKeyItem`);
console.log(`test exportKey data: ${JSON.stringify(data)}`); try {
await importKeyItem(keyAlias, huksOptions)
.then ((data) => {
console.info(`callback: importKeyItem success, data = ${JSON.stringify(data)}`);
}) })
.catch((err) => { .catch(error => {
console.log('test exportKey err information: ' + JSON.stringify(err)); 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 exportKey(alias, options) { function importKeyItem(keyAlias:string, huksOptions:huks.HuksOptions) {
return new Promise((resolve, reject) => { return new Promise((resolve, reject) => {
huks.exportKey(alias, options, function (err, data) { try {
console.log(`test exportKey data: ${JSON.stringify(data)}`); huks.importKeyItem(keyAlias, huksOptions, function (error, data) {
if (err.code !== 0) { if (error) {
console.log('test exportKey err information: ' + JSON.stringify(err)); reject(error);
reject(err);
} else { } else {
exportWrappingKey = data.outData;
resolve(data); resolve(data);
} }
}); });
} catch (error) {
throw(error);
}
}); });
} }
async function TestImportWrappedFunc(alias, wrappingAlias, options) { async function publicImportWrappedKey(keyAlias:string, wrappingKeyAlias:string, huksOptions:huks.HuksOptions) {
var result = await huks.importWrappedKey(alias, wrappingAlias, options); console.info(`enter callback importWrappedKeyItem`);
if (result.errorCode === 0) { try {
console.error('test importWrappedKey success'); await importWrappedKeyItem(keyAlias, wrappingKeyAlias, huksOptions)
} else { .then ((data) => {
console.error('test importWrappedKey fail'); 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}`);
} }
} }
async function TestImportWrappedKeyFunc( function importWrappedKeyItem(keyAlias:string, wrappingKeyAlias:string, huksOptions:huks.HuksOptions) {
importAlias, return new Promise((resolve, reject) => {
wrappingAlias, try {
genOptions, huks.importWrappedKeyItem(keyAlias, wrappingKeyAlias, huksOptions, function (error, data) {
importOptions if (error) {
) { reject(error);
await TestGenFunc(wrappingAlias, genOptions); } else {
await TestExportFunc(wrappingAlias, genOptions); resolve(data);
}
});
} catch (error) {
throw(error);
}
});
}
/* 以下操作不需要调用HUKS接口,此处不给出具体实现。 async function publicDeleteKeyFunc(keyAlias:string, huksOptions:huks.HuksOptions) {
* 假设待导入的密钥为keyA console.info(`enter callback deleteKeyItem`);
* 1.生成ECC公私钥keyB,公钥为keyB_pub, 私钥为keyB_pri try {
* 2.使用keyB_pri和wrappingAlias密钥中获取的公钥进行密钥协商,协商出共享密钥share_key await deleteKeyItem(keyAlias, huksOptions)
* 3.随机生成密钥kek,用于加密keyA,采用AES-GCM加密,加密过程中需要记录:nonce1/aad1/加密后的密文keyA_enc/加密后的tag1。 .then ((data) => {
* 4.使用share_key加密kek,采用AES-GCM加密,加密过程中需要记录:nonce2/aad2/加密后的密文kek_enc/加密后的tag2。 console.info(`callback: deleteKeyItem key success, data = ${JSON.stringify(data)}`);
* 5.拼接importOptions.inData字段,满足以下格式: })
* keyB_pub的长度(4字节) + keyB_pub的数据 + aad2的长度(4字节) + aad2的数据 + .catch(error => {
* nonce2的长度(4字节) + nonce2的数据 + tag2的长度(4字节) + tag2的数据 + console.error(`callback: deleteKeyItem failed, code: ${error.code}, msg: ${error.message}`);
* kek_enc的长度(4字节) + kek_enc的数据 + aad1的长度(4字节) + aad1的数据 + });
* nonce1的长度(4字节) + nonce1的数据 + tag1的长度(4字节) + tag1的数据 + } catch (error) {
* keyA长度占用的内存长度(4字节) + keyA的长度 + keyA_enc的长度(4字节) + keyA_enc的数据 console.error(`callback: deleteKeyItem input arg invalid, code: ${error.code}, msg: ${error.message}`);
*/ }
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]);
importOptions.inData = inputKey; function deleteKeyItem(keyAlias:string, huksOptions:huks.HuksOptions) {
await TestImportWrappedFunc(importAlias, wrappingAlias, importOptions); return new Promise((resolve, reject) => {
try {
huks.deleteKeyItem(keyAlias, huksOptions, function (error, data) {
if (error) {
reject(error);
} else {
resolve(data);
}
});
} catch (error) {
throw(error);
}
});
} }
function makePubKeyOptions() { var importAlias = "importAlias";
var properties = new Array(); var wrapAlias = "wrappingKeyAlias";
properties[0] = { 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, tag: huks.HuksTag.HUKS_TAG_ALGORITHM,
value: huks.HuksKeyAlg.HUKS_ALG_ECC value: huks.HuksKeyAlg.HUKS_ALG_ECC
}; };
properties[1] = { properties[1] = {
tag: huks.HuksTag.HUKS_TAG_KEY_SIZE, tag: huks.HuksTag.HUKS_TAG_KEY_SIZE,
value: huks.HuksKeySize.HUKS_ECC_KEY_SIZE_256 value: huks.HuksKeySize.HUKS_ECC_KEY_SIZE_256
}; };
properties[2] = { properties[2] = {
tag: huks.HuksTag.HUKS_TAG_PURPOSE, tag: huks.HuksTag.HUKS_TAG_PURPOSE,
value: huks.HuksKeyPurpose.HUKS_KEY_PURPOSE_UNWRAP value: huks.HuksKeyPurpose.HUKS_KEY_PURPOSE_UNWRAP
}; };
properties[3] = { properties[3] = {
tag: huks.HuksTag.HUKS_TAG_DIGEST, tag: huks.HuksTag.HUKS_TAG_DIGEST,
value: huks.HuksKeyDigest.HUKS_DIGEST_SHA256 value: huks.HuksKeyDigest.HUKS_DIGEST_SHA256
}; };
properties[4] = { properties[4] = {
tag: huks.HuksTag.HUKS_TAG_IMPORT_KEY_TYPE, tag: huks.HuksTag.HUKS_TAG_IMPORT_KEY_TYPE,
value: huks.HuksImportKeyType.HUKS_KEY_TYPE_KEY_PAIR, value: huks.HuksImportKeyType.HUKS_KEY_TYPE_KEY_PAIR,
}; };
var options = { var huksOptions = {
properties: properties, properties: properties,
inData: inputEccPair inData: inputEccPair
}; };
return options;
}
function makeImportOptions() { var importProperties = new Array();
var properties = new Array(); importProperties[0] = {
properties[0] = {
tag: huks.HuksTag.HUKS_TAG_ALGORITHM, tag: huks.HuksTag.HUKS_TAG_ALGORITHM,
value: huks.HuksKeyAlg.HUKS_ALG_AES value: huks.HuksKeyAlg.HUKS_ALG_AES
}; };
properties[1] = { importProperties[1] = {
tag: huks.HuksTag.HUKS_TAG_KEY_SIZE, tag: huks.HuksTag.HUKS_TAG_KEY_SIZE,
value: huks.HuksKeySize.HUKS_AES_KEY_SIZE_256 value: huks.HuksKeySize.HUKS_AES_KEY_SIZE_256
}; };
properties[2] = { importProperties[2] = {
tag: huks.HuksTag.HUKS_TAG_PURPOSE, tag: huks.HuksTag.HUKS_TAG_PURPOSE,
value: value: huks.HuksKeyPurpose.HUKS_KEY_PURPOSE_ENCRYPT | huks.HuksKeyPurpose.HUKS_KEY_PURPOSE_DECRYPT
huks.HuksKeyPurpose.HUKS_KEY_PURPOSE_ENCRYPT | };
huks.HuksKeyPurpose.HUKS_KEY_PURPOSE_DECRYPT importProperties[3] = {
};
properties[3] = {
tag: huks.HuksTag.HUKS_TAG_BLOCK_MODE, tag: huks.HuksTag.HUKS_TAG_BLOCK_MODE,
value: huks.HuksCipherMode.HUKS_MODE_CBC value: huks.HuksCipherMode.HUKS_MODE_CBC
}; };
properties[4] = { importProperties[4] = {
tag: huks.HuksTag.HUKS_TAG_PADDING, tag: huks.HuksTag.HUKS_TAG_PADDING,
value: huks.HuksKeyPadding.HUKS_PADDING_NONE value: huks.HuksKeyPadding.HUKS_PADDING_NONE
}; };
properties[5] = { importProperties[5] = {
tag: huks.HuksTag.HUKS_TAG_UNWRAP_ALGORITHM_SUITE, tag: huks.HuksTag.HUKS_TAG_UNWRAP_ALGORITHM_SUITE,
value: huks.HuksUnwrapSuite.HUKS_UNWRAP_SUITE_ECDH_AES_256_GCM_NOPADDING value: huks.HuksUnwrapSuite.HUKS_UNWRAP_SUITE_ECDH_AES_256_GCM_NOPADDING
}; };
var options = { var importOptions = {
properties: properties properties: importProperties,
}; inData: new Uint8Array(new Array())
return options; };
async function importWrappedKeyItemTest() {
console.info(`enter ImportWrapKey test`);
await publicImportKeyFunc(wrapAlias, huksOptions);
await publicExportKeyFunc(wrapAlias, huksOptions);
/* 以下操作不需要调用HUKS接口,此处不给出具体实现。
* 假设待导入的密钥为keyA
* 1.生成ECC公私钥keyB,公钥为keyB_pub, 私钥为keyB_pri
* 2.使用keyB_pri和wrappingAlias密钥中获取的公钥进行密钥协商,协商出共享密钥share_key
* 3.随机生成密钥kek,用于加密keyA,采用AES-GCM加密,加密过程中需要记录:nonce1/aad1/加密后的密文keyA_enc/加密后的tag1。
* 4.使用share_key加密kek,采用AES-GCM加密,加密过程中需要记录:nonce2/aad2/加密后的密文kek_enc/加密后的tag2。
* 5.拼接importOptions.inData字段,满足以下格式:
* keyB_pub的长度(4字节) + keyB_pub的数据 + aad2的长度(4字节) + aad2的数据 +
* nonce2的长度(4字节) + nonce2的数据 + tag2的长度(4字节) + tag2的数据 +
* kek_enc的长度(4字节) + kek_enc的数据 + aad1的长度(4字节) + aad1的数据 +
* nonce1的长度(4字节) + nonce1的数据 + tag1的长度(4字节) + tag1的数据 +
* 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
]);
importOptions.inData = inputKey;
await publicImportWrappedKey(importAlias, wrapAlias, importOptions);
await publicDeleteKeyFunc(wrapAlias, huksOptions);
await publicDeleteKeyFunc(importAlias, importOptions);
} }
function huksImportWrappedKey() { @Entry
var genOptions = makePubKeyOptions(); @Component
var importOptions = makeImportOptions(); struct Index {
TestImportWrappedKeyFunc( build() {
importAlias, Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) {
wrapAlias, Button() {
genOptions, Text('importWrappedKeyItemTest')
importOptions .fontSize(30)
); .fontWeight(FontWeight.Bold)
}.type(ButtonType.Capsule)
.margin({
top: 20
})
.backgroundColor('#0D9FFB')
.onClick(()=>{
importWrappedKeyItemTest();
})
}
.width('100%')
.height('100%')
}
} }
``` ```
...@@ -544,38 +651,184 @@ function huksImportWrappedKey() { ...@@ -544,38 +651,184 @@ function huksImportWrappedKey() {
| encryptOptions | HuksOptions | 是 | 用于存放加密key所需TAG。 | | encryptOptions | HuksOptions | 是 | 用于存放加密key所需TAG。 |
| decryptOptions | HuksOptions | 是 | 用于存放解密key所需TAG。 | | decryptOptions | HuksOptions | 是 | 用于存放解密key所需TAG。 |
关于接口的具体信息,可在[API参考文档](../reference/apis/js-apis-huks.md)中查看。 关于接口的具体信息,可在[API参考文档](../reference/apis/js-apis-huks.md)中查看。
**示例1:**
```ts
/* Cipher操作支持RSA、AES、SM4类型的密钥。
*
* 以下以SM4 128密钥的Promise操作使用为例
*/
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 Uint8ArrayToString(fileData) {
var dataString = '';
for (var i = 0; i < fileData.length; i++) {
dataString += String.fromCharCode(fileData[i]);
}
return dataString;
}
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<huks.HuksReturnResult> {
return new Promise((resolve, reject) => {
try {
huks.updateSession(handle, huksOptions, function (error, data) {
if (error) {
reject(error);
} else {
resolve(data);
}
});
} catch (error) {
throw(error);
}
});
}
**示例1:** 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}`);
}
}
```ts function finishSession(handle:number, huksOptions:huks.HuksOptions) : Promise<huks.HuksReturnResult> {
/* Cipher操作支持RSA、AES、SM4类型的密钥。 return new Promise((resolve, reject) => {
* try {
* 以下以SM4 128密钥的Promise操作使用为例 huks.finishSession(handle, huksOptions, function (error, data) {
*/ if (error) {
function sm4CipherStringToUint8Array(str) { reject(error);
var arr = []; } else {
for (var i = 0, j = str.length; i < j; ++i) { resolve(data);
arr.push(str.charCodeAt(i));
} }
return new Uint8Array(arr); });
} catch (error) {
throw(error);
}
});
} }
function sm4CipherUint8ArrayToString(fileData) {
var dataString = ''; async function publicDeleteKeyFunc(keyAlias:string, huksOptions:huks.HuksOptions) {
for (var i = 0; i < fileData.length; i++) { console.info(`enter callback deleteKeyItem`);
dataString += String.fromCharCode(fileData[i]); 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}`);
} }
return dataString;
} }
var handle; 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 IV = '0000000000000000';
var cipherInData = 'Hks_SM4_Cipher_Test_101010101010101010110_string'; var cipherInData = 'Hks_SM4_Cipher_Test_101010101010101010110_string';
var srcKeyAlias = 'huksCipherSm4SrcKeyAlias'; var srcKeyAlias = 'huksCipherSm4SrcKeyAlias';
var encryptUpdateResult = new Array(); 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(); var properties = new Array();
properties[0] = { properties[0] = {
...@@ -628,7 +881,7 @@ async function testCipher() { ...@@ -628,7 +881,7 @@ async function testCipher() {
} }
propertiesEncrypt[5] = { propertiesEncrypt[5] = {
tag: huks.HuksTag.HUKS_TAG_IV, tag: huks.HuksTag.HUKS_TAG_IV,
value: sm4CipherStringToUint8Array(IV), value: StringToUint8Array(IV),
} }
var encryptOptions = { var encryptOptions = {
properties: propertiesEncrypt, properties: propertiesEncrypt,
...@@ -636,38 +889,22 @@ async function testCipher() { ...@@ -636,38 +889,22 @@ async function testCipher() {
} }
/* 生成密钥 */ /* 生成密钥 */
await huks.generateKey(srcKeyAlias, huksOptions).then((data) => { await publicGenKeyFunc(srcKeyAlias, huksOptions);
console.info(`test generateKey data: ${JSON.stringify(data)}`);
}).catch((err) => {
console.info('test generateKey err information: ' + JSON.stringify(err));
});
/* 进行密钥加密操作 */ /* 进行密钥加密操作 */
await huks.init(srcKeyAlias, encryptOptions).then((data) => { await publicInitFunc(srcKeyAlias, encryptOptions);
console.info(`test init data: ${JSON.stringify(data)}`);
handle = data.handle; encryptOptions.inData = StringToUint8Array(cipherInData);
}).catch((err) => { await publicUpdateFunc(handle, encryptOptions);
console.info('test init err information: ' + JSON.stringify(err)); encryptUpdateResult = updateResult;
});
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);
});
encryptOptions.inData = new Uint8Array(new Array()); encryptOptions.inData = new Uint8Array(new Array());
await huks.finish(handle, encryptOptions).then((data) => { await publicFinishFunc(handle, encryptOptions);
console.info(`test finish data: ${JSON.stringify(data)}`); if (finishOutData === cipherInData) {
var finishData = sm4CipherUint8ArrayToString(new Uint8Array(encryptUpdateResult));
if (finishData === cipherInData) {
console.info('test finish encrypt err '); console.info('test finish encrypt err ');
} else { } else {
console.info('test finish encrypt success'); console.info('test finish encrypt success');
} }
}).catch((err) => {
console.info('test finish err information: ' + JSON.stringify(err));
});
/* 修改加密参数集为解密参数集 */ /* 修改加密参数集为解密参数集 */
propertiesEncrypt.splice(1, 1, { propertiesEncrypt.splice(1, 1, {
...@@ -680,37 +917,43 @@ async function testCipher() { ...@@ -680,37 +917,43 @@ async function testCipher() {
} }
/* 进行解密操作 */ /* 进行解密操作 */
await huks.init(srcKeyAlias, decryptOptions).then((data) => { await publicInitFunc(srcKeyAlias, decryptOptions);
console.info(`test init data: ${JSON.stringify(data)}`);
handle = data.handle;
}).catch((err) => {
console.info('test init err information: ' + JSON.stringify(err));
});
decryptOptions.inData = new Uint8Array(encryptUpdateResult); decryptOptions.inData = new Uint8Array(encryptUpdateResult);
await huks.update(handle, decryptOptions).then(async (data) => { await publicUpdateFunc(handle, decryptOptions);
console.info(`test update data ${JSON.stringify(data)}`);
decryptUpdateResult = Array.from(data.outData);
}).catch((err) => {
console.info('test update err information: ' + err);
});
decryptOptions.inData = new Uint8Array(new Array()); decryptOptions.inData = new Uint8Array(new Array());
await huks.finish(handle, decryptOptions).then((data) => { await publicFinishFunc(handle, decryptOptions);
console.info(`test finish data: ${JSON.stringify(data)}`); if (finishOutData === cipherInData) {
var finishData = sm4CipherUint8ArrayToString(new Uint8Array(decryptUpdateResult));
if (finishData === cipherInData) {
console.info('test finish decrypt success '); console.info('test finish decrypt success ');
} else { } else {
console.info('test finish decrypt err'); console.info('test finish decrypt err');
} }
}).catch((err) => {
console.info('test finish err information: ' + JSON.stringify(err));
});
await huks.deleteKey(srcKeyAlias, huksOptions).then((data) => { await publicDeleteKeyFunc(srcKeyAlias, huksOptions);
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('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() { ...@@ -721,14 +964,17 @@ async function testCipher() {
* *
* 以下以AES128 GCM密钥的Promise操作使用为例 * 以下以AES128 GCM密钥的Promise操作使用为例
*/ */
function aesCipherStringToUint8Array(str) { import huks from '@ohos.security.huks';
function StringToUint8Array(str) {
var arr = []; var arr = [];
for (var i = 0, j = str.length; i < j; ++i) { for (var i = 0, j = str.length; i < j; ++i) {
arr.push(str.charCodeAt(i)); arr.push(str.charCodeAt(i));
} }
return new Uint8Array(arr); return new Uint8Array(arr);
} }
function aesCipherUint8ArrayToString(fileData) {
function Uint8ArrayToString(fileData) {
var dataString = ''; var dataString = '';
for (var i = 0; i < fileData.length; i++) { for (var i = 0; i < fileData.length; i++) {
dataString += String.fromCharCode(fileData[i]); dataString += String.fromCharCode(fileData[i]);
...@@ -736,15 +982,160 @@ function aesCipherUint8ArrayToString(fileData) { ...@@ -736,15 +982,160 @@ function aesCipherUint8ArrayToString(fileData) {
return dataString; return dataString;
} }
async function aesCipher() { async function publicGenKeyFunc(keyAlias:string, huksOptions:huks.HuksOptions) {
var handle; console.info(`enter callback generateKeyItem`);
var AAD = '0000000000000000'; try {
var NONCE = '000000000000'; await generateKeyItem(keyAlias, huksOptions)
var AEAD = '0000000000000000'; .then((data) => {
var cipherInData = 'Hks_AES_Cipher_Test_00000000000000000000000000000000000000000000000000000_string'; console.info(`callback: generateKeyItem success, data = ${JSON.stringify(data)}`);
var srcKeyAlias = 'huksCipherAesSrcKeyAlias'; })
var encryptUpdateResult = new Array(); .catch(error => {
var decryptUpdateResult = new Array(); 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<huks.HuksReturnResult> {
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<huks.HuksReturnResult> {
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(); var properties = new Array();
properties[0] = { properties[0] = {
...@@ -769,7 +1160,7 @@ async function aesCipher() { ...@@ -769,7 +1160,7 @@ async function aesCipher() {
tag: huks.HuksTag.HUKS_TAG_PADDING, tag: huks.HuksTag.HUKS_TAG_PADDING,
value: huks.HuksKeyPadding.HUKS_PADDING_NONE, value: huks.HuksKeyPadding.HUKS_PADDING_NONE,
} }
var HuksOptions = { var huksOptions = {
properties: properties, properties: properties,
inData: new Uint8Array(new Array()) inData: new Uint8Array(new Array())
} }
...@@ -801,15 +1192,15 @@ async function aesCipher() { ...@@ -801,15 +1192,15 @@ async function aesCipher() {
} }
propertiesEncrypt[6] = { propertiesEncrypt[6] = {
tag: huks.HuksTag.HUKS_TAG_ASSOCIATED_DATA, tag: huks.HuksTag.HUKS_TAG_ASSOCIATED_DATA,
value: aesCipherStringToUint8Array(AAD), value: StringToUint8Array(AAD),
} }
propertiesEncrypt[7] = { propertiesEncrypt[7] = {
tag: huks.HuksTag.HUKS_TAG_NONCE, tag: huks.HuksTag.HUKS_TAG_NONCE,
value: aesCipherStringToUint8Array(NONCE), value: StringToUint8Array(NONCE),
} }
propertiesEncrypt[8] = { propertiesEncrypt[8] = {
tag: huks.HuksTag.HUKS_TAG_AE_TAG, tag: huks.HuksTag.HUKS_TAG_AE_TAG,
value: aesCipherStringToUint8Array(AEAD), value: StringToUint8Array(AEAD),
} }
var encryptOptions = { var encryptOptions = {
properties: propertiesEncrypt, properties: propertiesEncrypt,
...@@ -817,39 +1208,24 @@ async function aesCipher() { ...@@ -817,39 +1208,24 @@ async function aesCipher() {
} }
/* 生成密钥 */ /* 生成密钥 */
await huks.generateKey(srcKeyAlias, HuksOptions).then((data) => { await publicGenKeyFunc(srcKeyAlias, huksOptions);
console.info(`test generateKey data: ${JSON.stringify(data)}`);
}).catch((err) => {
console.info('test generateKey err information: ' + JSON.stringify(err));
});
/* 进行密钥加密操作 */ /* 进行密钥加密操作 */
await huks.init(srcKeyAlias, encryptOptions).then((data) => { await publicInitFunc(srcKeyAlias, encryptOptions);
console.info(`test init data: ${JSON.stringify(data)}`);
handle = data.handle; encryptOptions.inData = StringToUint8Array(cipherInData.slice(0,64));
}).catch((err) => { await publicUpdateFunc(handle, encryptOptions);
console.info('test init err information: ' + JSON.stringify(err)); encryptUpdateResult = updateResult;
});
encryptOptions.inData = aesCipherStringToUint8Array(cipherInData.slice(0,64)); encryptOptions.inData = StringToUint8Array(cipherInData.slice(64,80));
await huks.update(handle, encryptOptions).then(async (data) => { await publicFinishFunc(handle, encryptOptions);
console.info(`test update data ${JSON.stringify(data)}`); encryptUpdateResult = updateResult;
encryptUpdateResult = Array.from(data.outData); finishOutData = Uint8ArrayToString(new Uint8Array(encryptUpdateResult));
}).catch((err) => { if (finishOutData === cipherInData) {
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 '); console.info('test finish encrypt err ');
} else { } else {
console.info('test finish encrypt success'); console.info('test finish encrypt success');
} }
}).catch((err) => {
console.info('test finish err information: ' + JSON.stringify(err));
});
/* 修改加密参数集为解密参数集 */ /* 修改加密参数集为解密参数集 */
propertiesEncrypt.splice(1, 1, { propertiesEncrypt.splice(1, 1, {
...@@ -866,38 +1242,46 @@ async function aesCipher() { ...@@ -866,38 +1242,46 @@ async function aesCipher() {
} }
/* 进行解密操作 */ /* 进行解密操作 */
await huks.init(srcKeyAlias, decryptOptions).then((data) => { await publicInitFunc(srcKeyAlias, decryptOptions);
console.info(`test init data: ${JSON.stringify(data)}`);
handle = data.handle;
}).catch((err) => {
console.info('test init err information: ' + JSON.stringify(err));
});
decryptOptions.inData = new Uint8Array(encryptUpdateResult.slice(0,64)); decryptOptions.inData = new Uint8Array(encryptUpdateResult.slice(0,64));
await huks.update(handle, decryptOptions).then(async (data) => { await publicUpdateFunc(handle, decryptOptions);
console.info(`test update data ${JSON.stringify(data)}`); decryptUpdateResult = updateResult;
decryptUpdateResult = Array.from(data.outData);
}).catch((err) => {
console.info('test update err information: ' + err);
});
decryptOptions.inData = new Uint8Array(encryptUpdateResult.slice(64,encryptUpdateResult.length)); decryptOptions.inData = new Uint8Array(encryptUpdateResult.slice(64,encryptUpdateResult.length));
await huks.finish(handle, decryptOptions).then((data) => { await publicFinishFunc(handle, decryptOptions);
console.info(`test finish data: ${JSON.stringify(data)}`); decryptUpdateResult = updateResult;
decryptUpdateResult = decryptUpdateResult.concat(Array.from(data.outData)); finishOutData = Uint8ArrayToString(new Uint8Array(decryptUpdateResult));
var finishData = aesCipherUint8ArrayToString(new Uint8Array(decryptUpdateResult)); if (finishOutData === cipherInData) {
if (finishData === cipherInData) {
console.info('test finish decrypt success '); console.info('test finish decrypt success ');
} else { } else {
console.info('test finish decrypt err'); console.info('test finish decrypt err');
} }
}).catch((err) => {
console.info('test finish err information: ' + JSON.stringify(err));
});
await huks.deleteKey(srcKeyAlias, HuksOptions).then((data) => { await publicDeleteKeyFunc(srcKeyAlias, huksOptions);
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('testAesCipher')
.fontSize(30)
.fontWeight(FontWeight.Bold)
}.type(ButtonType.Capsule)
.margin({
top: 20
})
.backgroundColor('#0D9FFB')
.onClick(()=>{
testAesCipher();
})
}
.width('100%')
.height('100%')
}
} }
``` ```
...@@ -939,191 +1323,392 @@ Update过程只将inData发送到Core中记录在ctx中,不进行Hash计算, ...@@ -939,191 +1323,392 @@ Update过程只将inData发送到Core中记录在ctx中,不进行Hash计算,
在使用示例前,需要先了解几个预先定义的变量: 在使用示例前,需要先了解几个预先定义的变量:
| 参数名 | 类型 | 必填 | 说明 | | 参数名 | 类型 | 必填 | 说明 |
| -------------------- | ----------- | ---- | ------------------------ | | ----------------- | ----------- | ---- | ------------------------ |
| srcRsaKeyAliasSign | string | 是 | 生成密钥别名。 | | generateKeyAlias | string | 是 | 生成密钥别名。 |
| srcRsaKeyAliasVerify | string | 是 | 导入密钥别名。 | | importKeyAlias | string | 是 | 导入密钥别名。 |
| rsaSignOptions | HuksOptions | 是 | 用于存放生成key所需TAG。 | | genrateKeyOptions | HuksOptions | 是 | 用于存放生成key所需TAG。 |
| rsaSignOptionsSecond | HuksOptions | 是 | 用于存放签名key所需TAG。 | | signOptions | HuksOptions | 是 | 用于存放签名key所需TAG。 |
| rsaVerifyOptions | HuksOptions | 是 | 用于存放验签key所需TAG。 | | verifyOptions | HuksOptions | 是 | 用于存放验签key所需TAG。 |
关于接口的具体信息,可在[API参考文档](../reference/apis/js-apis-huks.md)中查看。 关于接口的具体信息,可在[API参考文档](../reference/apis/js-apis-huks.md)中查看。
**示例:** **示例:**
```ts
/* Sign/Verify操作支持RSA、ECC、SM2、ED25519、DSA类型的密钥。
*
* 以下以SM2密钥的Callback操作使用为例
*/
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 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<huks.HuksSessionHandle> {
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<huks.HuksReturnResult> {
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 = 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<huks.HuksReturnResult> {
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<huks.HuksReturnResult> {
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}`);
}
}
```ts function deleteKeyItem(keyAlias:string, huksOptions:huks.HuksOptions) {
/* Sign/Verify操作支持RSA、ECC、SM2、ED25519、DSA类型的密钥。 return new Promise((resolve, reject) => {
* try {
* 以下以RSA512密钥的Promise操作使用为例 huks.deleteKeyItem(keyAlias, huksOptions, function (error, data) {
*/ if (error) {
function rsaSignVerifyStringToUint8Array(str) { reject(error);
var arr = []; } else {
for (var i = 0, j = str.length; i < j; ++i) { resolve(data);
arr.push(str.charCodeAt(i));
} }
return new Uint8Array(arr); });
} catch (error) {
throw(error);
}
});
} }
var rsaSignHandle; var signVerifyInData = 'signVerifyInDataForTest';
var rsaSignVerifyInData = 'signVerifyInData'; var generateKeyAlias = 'generateKeyAliasForTest';
var srcRsaKeyAliasSign = 'huksSignVerifySrcKeyAliasSign'; var importKeyAlias = 'importKeyAliasForTest';
var srcRsaKeyAliasVerify = 'huksSignVerifySrcKeyAliasVerify'; var handle;
var finishRsaSignData; var exportKey;
var rsaExportSignKey; var finishOutData;
async function testSignVerify() { /* 集成生成密钥参数集 */
/* 集成生成密钥参数集 & 签名参数集 & 验签参数集 */ var generateKeyProperties = new Array();
var rsaSignProperties = new Array(); generateKeyProperties[0] = {
rsaSignProperties[0] = {
tag: huks.HuksTag.HUKS_TAG_ALGORITHM, tag: huks.HuksTag.HUKS_TAG_ALGORITHM,
value: huks.HuksKeyAlg.HUKS_ALG_RSA, value: huks.HuksKeyAlg.HUKS_ALG_SM2,
} }
rsaSignProperties[1] = { generateKeyProperties[1] = {
tag: huks.HuksTag.HUKS_TAG_PURPOSE, tag: huks.HuksTag.HUKS_TAG_PURPOSE,
value: huks.HuksKeyPurpose.HUKS_KEY_PURPOSE_SIGN, value:
} huks.HuksKeyPurpose.HUKS_KEY_PURPOSE_SIGN |
rsaSignProperties[2] = { huks.HuksKeyPurpose.HUKS_KEY_PURPOSE_VERIFY,
}
generateKeyProperties[2] = {
tag: huks.HuksTag.HUKS_TAG_KEY_SIZE, tag: huks.HuksTag.HUKS_TAG_KEY_SIZE,
value: huks.HuksKeySize.HUKS_RSA_KEY_SIZE_512, value: huks.HuksKeySize.HUKS_SM2_KEY_SIZE_256,
} }
rsaSignProperties[3] = { generateKeyProperties[3] = {
tag: huks.HuksTag.HUKS_TAG_DIGEST, tag: huks.HuksTag.HUKS_TAG_DIGEST,
value: huks.HuksKeyDigest.HUKS_DIGEST_MD5, value: huks.HuksKeyDigest.HUKS_DIGEST_SM3,
} }
rsaSignProperties[4] = { var genrateKeyOptions = {
tag: huks.HuksTag.HUKS_TAG_PADDING, properties: generateKeyProperties,
value: huks.HuksKeyPadding.HUKS_PADDING_PKCS1_V1_5,
}
var rsaSignOptions = {
properties: rsaSignProperties,
inData: new Uint8Array(new Array()) inData: new Uint8Array(new Array())
} }
var rsaPropertiesSign = new Array(); /* 集成签名参数集 */
rsaPropertiesSign[0] = { var signProperties = new Array();
signProperties[0] = {
tag: huks.HuksTag.HUKS_TAG_ALGORITHM, tag: huks.HuksTag.HUKS_TAG_ALGORITHM,
value: huks.HuksKeyAlg.HUKS_ALG_RSA, value: huks.HuksKeyAlg.HUKS_ALG_SM2,
} }
rsaPropertiesSign[1] = { signProperties[1] = {
tag: huks.HuksTag.HUKS_TAG_PURPOSE, tag: huks.HuksTag.HUKS_TAG_PURPOSE,
value: value:
huks.HuksKeyPurpose.HUKS_KEY_PURPOSE_SIGN huks.HuksKeyPurpose.HUKS_KEY_PURPOSE_SIGN
} }
rsaPropertiesSign[2] = { signProperties[2] = {
tag: huks.HuksTag.HUKS_TAG_DIGEST, tag: huks.HuksTag.HUKS_TAG_DIGEST,
value: huks.HuksKeyDigest.HUKS_DIGEST_MD5, value: huks.HuksKeyDigest.HUKS_DIGEST_SM3,
} }
rsaPropertiesSign[3] = { signProperties[3] = {
tag: huks.HuksTag.HUKS_TAG_KEY_SIZE, tag: huks.HuksTag.HUKS_TAG_KEY_SIZE,
value: huks.HuksKeySize.HUKS_RSA_KEY_SIZE_512, value: huks.HuksKeySize.HUKS_SM2_KEY_SIZE_256,
} }
rsaPropertiesSign[4] = { var signOptions = {
tag: huks.HuksTag.HUKS_TAG_PADDING, properties: signProperties,
value: huks.HuksKeyPadding.HUKS_PADDING_PKCS1_V1_5,
}
var rsaSignOptionsSecond = {
properties: rsaPropertiesSign,
inData: new Uint8Array(new Array()) inData: new Uint8Array(new Array())
} }
var rsaPropertiesVerify = new Array(); /* 集成验签参数集 */
rsaPropertiesVerify[0] = { var verifyProperties = new Array();
verifyProperties[0] = {
tag: huks.HuksTag.HUKS_TAG_ALGORITHM, tag: huks.HuksTag.HUKS_TAG_ALGORITHM,
value: huks.HuksKeyAlg.HUKS_ALG_RSA, value: huks.HuksKeyAlg.HUKS_ALG_SM2,
} }
rsaPropertiesVerify[1] = { verifyProperties[1] = {
tag: huks.HuksTag.HUKS_TAG_PURPOSE, tag: huks.HuksTag.HUKS_TAG_PURPOSE,
value: huks.HuksKeyPurpose.HUKS_KEY_PURPOSE_VERIFY value: huks.HuksKeyPurpose.HUKS_KEY_PURPOSE_VERIFY
} }
rsaPropertiesVerify[2] = { verifyProperties[2] = {
tag: huks.HuksTag.HUKS_TAG_DIGEST, tag: huks.HuksTag.HUKS_TAG_DIGEST,
value: huks.HuksKeyDigest.HUKS_DIGEST_MD5, value: huks.HuksKeyDigest.HUKS_DIGEST_SM3,
} }
rsaPropertiesVerify[3] = { verifyProperties[3] = {
tag: huks.HuksTag.HUKS_TAG_KEY_SIZE, tag: huks.HuksTag.HUKS_TAG_KEY_SIZE,
value: huks.HuksKeySize.HUKS_RSA_KEY_SIZE_512, value: huks.HuksKeySize.HUKS_SM2_KEY_SIZE_256,
} }
rsaPropertiesVerify[4] = { var verifyOptions = {
tag: huks.HuksTag.HUKS_TAG_PADDING, properties: verifyProperties,
value: huks.HuksKeyPadding.HUKS_PADDING_PKCS1_V1_5,
}
var rsaVerifyOptions = {
properties: rsaPropertiesVerify,
inData: new Uint8Array(new Array()) inData: new Uint8Array(new Array())
} }
async function testSm2SignVerify() {
/* 生成密钥 */ /* 生成密钥 */
await huks.generateKey(srcRsaKeyAliasSign, rsaSignOptions).then((data) => { await publicGenKeyFunc(generateKeyAlias, genrateKeyOptions);
console.info(`test generateKey data: ${JSON.stringify(data)}`);
}).catch((err) => { /* 签名 */
console.info('test generateKey err information: ' + JSON.stringify(err)); var signHandle;
}); var signFinishOutData;
await publicInitFunc(generateKeyAlias, signOptions);
/* 对密钥进行签名操作 */
await huks.init(srcRsaKeyAliasSign, rsaSignOptionsSecond).then((data) => { signHandle = handle;
console.info(`test init data: ${JSON.stringify(data)}`); signOptions.inData = StringToUint8Array(signVerifyInData)
rsaSignHandle = data.handle; await publicUpdateFunc(signHandle, signOptions);
}).catch((err) => {
console.info('test init err information: ' + JSON.stringify(err)); signOptions.inData = new Uint8Array(new Array());
}); await publicFinishFunc(signHandle, signOptions);
rsaSignOptionsSecond.inData = rsaSignVerifyStringToUint8Array(rsaSignVerifyInData) signFinishOutData = finishOutData;
await huks.update(rsaSignHandle, rsaSignOptionsSecond).then(async (data) => {
console.info(`test update data ${JSON.stringify(data)}`); /* 导出密钥 */
}).catch((err) => { await publicExportKeyFunc(generateKeyAlias, genrateKeyOptions);
console.info('test update err information: ' + err);
}); /* 导入密钥 */
rsaSignOptionsSecond.inData = new Uint8Array(new Array()); verifyOptions.inData = exportKey;
await huks.finish(rsaSignHandle, rsaSignOptionsSecond).then((data) => { await publicImportKeyFunc(importKeyAlias, verifyOptions);
console.info(`test finish data: ${JSON.stringify(data)}`);
finishRsaSignData = data.outData; /* 验证签名 */
}).catch((err) => { var verifyHandle;
console.info('test finish err information: ' + JSON.stringify(err)); await publicInitFunc(importKeyAlias, verifyOptions);
});
verifyHandle = handle;
/* 通过导出导入模拟获取一段密钥数据 */
await huks.exportKey(srcRsaKeyAliasSign, rsaSignOptions).then((data) => { verifyOptions.inData = StringToUint8Array(signVerifyInData)
console.info(`test exportKey data: ${JSON.stringify(data)}`); await publicUpdateFunc(verifyHandle, verifyOptions);
rsaExportSignKey = data.outData;
}).catch((err) => { verifyOptions.inData = signFinishOutData;
console.info('test exportKey err information: ' + JSON.stringify(err)); await publicFinishFunc(verifyHandle, verifyOptions);
});
rsaVerifyOptions.inData = rsaExportSignKey; await publicDeleteKeyFunc(generateKeyAlias, genrateKeyOptions);
await huks.importKey(srcRsaKeyAliasVerify, rsaVerifyOptions).then((data) => { await publicDeleteKeyFunc(importKeyAlias, genrateKeyOptions);
console.info(`test ImportKey data: ${JSON.stringify(data)}`); }
}).catch((err) => {
console.info('test exportKey err information: ' + JSON.stringify(err)); @Entry
}); @Component
struct Index {
/* 对密钥进行验签 */ build() {
await huks.init(srcRsaKeyAliasVerify, rsaVerifyOptions).then((data) => { Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) {
console.info(`test init data: ${JSON.stringify(data)}`); Button() {
rsaSignHandle = data.handle; Text('testSm2SignVerify')
}).catch((err) => { .fontSize(30)
console.info('test init err information: ' + JSON.stringify(err)); .fontWeight(FontWeight.Bold)
}); }.type(ButtonType.Capsule)
rsaVerifyOptions.inData = rsaSignVerifyStringToUint8Array(rsaSignVerifyInData); .margin({
await huks.update(rsaSignHandle, rsaVerifyOptions).then(async (data) => { top: 20
console.info(`test update data ${JSON.stringify(data)}`); })
}).catch((err) => { .backgroundColor('#0D9FFB')
console.info('test update err information: ' + err); .onClick(()=>{
}); testSm2SignVerify();
rsaVerifyOptions.inData = finishRsaSignData; })
await huks.finish(rsaSignHandle, rsaVerifyOptions).then((data) => { }
console.info(`test finish data: ${JSON.stringify(data)}`); .width('100%')
}).catch((err) => { .height('100%')
console.info('test finish err information: ' + JSON.stringify(err)); }
});
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));
});
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));
});
} }
``` ```
...@@ -1185,7 +1770,9 @@ HksFinish对paramSet中参数的要求: ...@@ -1185,7 +1770,9 @@ HksFinish对paramSet中参数的要求:
* *
* 以下以X25519 256 TEMP密钥的Promise操作使用为例 * 以下以X25519 256 TEMP密钥的Promise操作使用为例
*/ */
function AgreeStringToUint8Array(str) { import huks from '@ohos.security.huks';
function StringToUint8Array(str) {
var arr = []; var arr = [];
for (var i = 0, j = str.length; i < j; ++i) { for (var i = 0, j = str.length; i < j; ++i) {
arr.push(str.charCodeAt(i)); arr.push(str.charCodeAt(i));
...@@ -1193,9 +1780,199 @@ function AgreeStringToUint8Array(str) { ...@@ -1193,9 +1780,199 @@ function AgreeStringToUint8Array(str) {
return new Uint8Array(arr); 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<huks.HuksSessionHandle> {
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<huks.HuksReturnResult> {
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<huks.HuksReturnResult> {
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<huks.HuksReturnResult> {
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 srcKeyAliasFirst = "AgreeX25519KeyFirstAlias";
var srcKeyAliasSecond = "AgreeX25519KeySecondAlias"; var srcKeyAliasSecond = "AgreeX25519KeySecondAlias";
var agreeX25519InData = 'AgreeX25519TestIndata'; var agreeX25519InData = 'AgreeX25519TestIndata';
var handle;
var exportKey;
var exportKeyFrist; var exportKeyFrist;
var exportKeySecond; var exportKeySecond;
...@@ -1232,28 +2009,13 @@ async function testAgree() { ...@@ -1232,28 +2009,13 @@ async function testAgree() {
} }
/* 1.生成两个密钥并导出 */ /* 1.生成两个密钥并导出 */
await huks.generateKey(srcKeyAliasFirst, HuksOptions).then((data) => { await publicGenKeyFunc(srcKeyAliasFirst, HuksOptions);
console.info('test generateKey data = ' + JSON.stringify(data)); await publicGenKeyFunc(srcKeyAliasSecond, HuksOptions);
}).catch((err) => {
console.info(`test generateKey err: " + ${JSON.stringify(err)}`); await publicExportKeyFunc(srcKeyAliasFirst, HuksOptions);
}); exportKeyFrist = exportKey;
await huks.generateKey(srcKeyAliasSecond, HuksOptions).then((data) => { await publicExportKeyFunc(srcKeyAliasFirst, HuksOptions);
console.info('test generateKey data = ' + JSON.stringify(data)); exportKeySecond = exportKey;
}).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)}`);
});
/* 集成第一个协商参数集 */ /* 集成第一个协商参数集 */
var finishProperties = new Array(); var finishProperties = new Array();
...@@ -1285,7 +2047,7 @@ async function testAgree() { ...@@ -1285,7 +2047,7 @@ async function testAgree() {
} }
finishProperties[6] = { finishProperties[6] = {
tag: huks.HuksTag.HUKS_TAG_KEY_ALIAS, tag: huks.HuksTag.HUKS_TAG_KEY_ALIAS,
value: AgreeStringToUint8Array(srcKeyAliasFirst+ 'final'), value: StringToUint8Array(srcKeyAliasFirst+ 'final'),
} }
finishProperties[7] = { finishProperties[7] = {
tag: huks.HuksTag.HUKS_TAG_PADDING, tag: huks.HuksTag.HUKS_TAG_PADDING,
...@@ -1297,67 +2059,57 @@ async function testAgree() { ...@@ -1297,67 +2059,57 @@ async function testAgree() {
} }
var finishOptionsFrist = { var finishOptionsFrist = {
properties: finishProperties, properties: finishProperties,
inData: AgreeStringToUint8Array(agreeX25519InData) inData: StringToUint8Array(agreeX25519InData)
} }
/* 对第一个密钥进行协商 */ /* 对第一个密钥进行协商 */
await huks.init(srcKeyAliasFirst, HuksOptions).then((data) => { await publicInitFunc(srcKeyAliasFirst, HuksOptions);
console.info(`test init data: ${JSON.stringify(data)}`);
handle = data.handle;
}).catch((err) => {
console.info(`test init err: " + ${JSON.stringify(err)}`);
});
HuksOptions.inData = exportKeySecond; HuksOptions.inData = exportKeySecond;
await huks.update(handle, HuksOptions).then((data) => { await publicUpdateFunc(handle, HuksOptions);
console.info(`test update data: ${JSON.stringify(data)}`); await publicFinishFunc(handle, finishOptionsFrist);
}).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));
});
/* 集成第二个协商参数集 */ /* 集成第二个协商参数集 */
var finishOptionsSecond = { var finishOptionsSecond = {
properties: finishProperties, properties: finishProperties,
inData: AgreeStringToUint8Array(agreeX25519InData) inData: StringToUint8Array(agreeX25519InData)
} }
finishOptionsSecond.properties.splice(6, 1, { finishOptionsSecond.properties.splice(6, 1, {
tag: huks.HuksTag.HUKS_TAG_KEY_ALIAS, tag: huks.HuksTag.HUKS_TAG_KEY_ALIAS,
value: AgreeStringToUint8Array(srcKeyAliasSecond + 'final'), value: StringToUint8Array(srcKeyAliasSecond + 'final'),
}) })
/* 对第二个密钥进行协商 */ /* 对第二个密钥进行协商 */
await huks.init(srcKeyAliasSecond, HuksOptions).then((data) => { await publicInitFunc(srcKeyAliasSecond, HuksOptions);
console.info(`test init data: ${JSON.stringify(data)}`);
handle = data.handle;
}).catch((err) => {
console.info(`test init err: " + ${JSON.stringify(err)}`);
});
HuksOptions.inData = exportKeyFrist; HuksOptions.inData = exportKeyFrist;
await huks.update(handle, HuksOptions).then((data) => { await publicUpdateFunc(handle, HuksOptions);
console.info(`test update data: ${JSON.stringify(data)}`); await publicFinishFunc(handle, finishOptionsSecond);
}).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 huks.deleteKey(srcKeyAliasFirst, huksOptions).then((data) => {
console.info(`test deleteKey data: ${JSON.stringify(data)}`); await publicDeleteKeyFunc(srcKeyAliasFirst, HuksOptions);
}).catch((err) => { await publicDeleteKeyFunc(srcKeyAliasSecond, HuksOptions);
console.info('test deleteKey err information: ' + JSON.stringify(err)); }
});
await huks.deleteKey(srcKeyAliasSecond, huksOptions).then((data) => { @Entry
console.info(`test deleteKey data: ${JSON.stringify(data)}`); @Component
}).catch((err) => { struct Index {
console.info('test deleteKey err information: ' + JSON.stringify(err)); 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%')
}
} }
``` ```
...@@ -1407,21 +2159,163 @@ HksFinish对paramSet中参数的要求: ...@@ -1407,21 +2159,163 @@ HksFinish对paramSet中参数的要求:
| huksOptions | HuksOptions | 是 | 生成密钥参数集。 | | huksOptions | HuksOptions | 是 | 生成密钥参数集。 |
| finishOptions | HuksOptions | 是 | 派生密钥参数集。 | | finishOptions | HuksOptions | 是 | 派生密钥参数集。 |
关于接口的具体信息,可在[API参考文档](../reference/apis/js-apis-huks.md)中查看。 关于接口的具体信息,可在[API参考文档](../reference/apis/js-apis-huks.md)中查看。
**示例:**
```ts
/* derive操作支持HKDF、pbdkf类型的密钥。
*
* 以下以HKDF256密钥的Promise操作使用为例
*/
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 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<huks.HuksReturnResult> {
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<huks.HuksReturnResult> {
return new Promise((resolve, reject) => {
try {
huks.finishSession(handle, huksOptions, function (error, data) {
if (error) {
reject(error);
} else {
resolve(data);
}
});
} catch (error) {
throw(error);
}
});
}
```ts async function publicDeleteKeyFunc(keyAlias:string, huksOptions:huks.HuksOptions) {
/* derive操作支持HKDF、pbdkf类型的密钥。 console.info(`enter callback deleteKeyItem`);
* try {
* 以下以HKDF256密钥的Promise操作使用为例 await deleteKeyItem(keyAlias, huksOptions)
*/ .then ((data) => {
function hkdfStringToUint8Array(str) { console.info(`callback: deleteKeyItem key success, data = ${JSON.stringify(data)}`);
var arr = []; })
for (var i = 0, j = str.length; i < j; ++i) { .catch(error => {
arr.push(str.charCodeAt(i)); 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}`);
} }
return new Uint8Array(arr); }
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 deriveHkdfInData = "deriveHkdfTestIndata";
...@@ -1454,11 +2348,7 @@ async function testDerive() { ...@@ -1454,11 +2348,7 @@ async function testDerive() {
} }
/* 生成密钥 */ /* 生成密钥 */
await huks.generateKey(srcKeyAlias, huksOptions).then((data) => { await publicGenKeyFunc(srcKeyAlias, huksOptions);
console.info('test generateKey data = ' + JSON.stringify(data));
}).catch((err) => {
console.info(`test init err: " + ${JSON.stringify(err)}`);
});
/* 调整init时的参数集 */ /* 调整init时的参数集 */
huksOptions.properties.splice(0, 1, { huksOptions.properties.splice(0, 1, {
...@@ -1499,7 +2389,7 @@ async function testDerive() { ...@@ -1499,7 +2389,7 @@ async function testDerive() {
} }
finishProperties[6] = { finishProperties[6] = {
tag: huks.HuksTag.HUKS_TAG_KEY_ALIAS, tag: huks.HuksTag.HUKS_TAG_KEY_ALIAS,
value: hkdfStringToUint8Array(srcKeyAlias), value: StringToUint8Array(srcKeyAlias),
} }
finishProperties[7] = { finishProperties[7] = {
tag: huks.HuksTag.HUKS_TAG_PADDING, tag: huks.HuksTag.HUKS_TAG_PADDING,
...@@ -1515,23 +2405,11 @@ async function testDerive() { ...@@ -1515,23 +2405,11 @@ async function testDerive() {
} }
/* 进行派生操作 */ /* 进行派生操作 */
await huks.init(srcKeyAlias, huksOptions).then((data) => { await publicInitFunc(srcKeyAlias, huksOptions);
console.log(`test init data: ${JSON.stringify(data)}`);
handle = data.handle; huksOptions.inData = StringToUint8Array(deriveHkdfInData);
}).catch((err) => { await publicUpdateFunc(handle, huksOptions);
console.log(`test init err: " + ${JSON.stringify(err)}`); await publicFinishFunc(handle, finishOptions);
});
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));
});
huksOptions.properties.splice(0, 1, { huksOptions.properties.splice(0, 1, {
tag: huks.HuksTag.HUKS_TAG_ALGORITHM, tag: huks.HuksTag.HUKS_TAG_ALGORITHM,
...@@ -1542,11 +2420,30 @@ async function testDerive() { ...@@ -1542,11 +2420,30 @@ async function testDerive() {
value: huks.HuksKeySize.HUKS_AES_KEY_SIZE_128, value: huks.HuksKeySize.HUKS_AES_KEY_SIZE_128,
}); });
await huks.deleteKey(srcKeyAlias, huksOptions).then((data) => { await publicDeleteKeyFunc(srcKeyAlias, huksOptions);
console.log(`test deleteKey data: ${JSON.stringify(data)}`); }
}).catch((err) => {
console.log('test deleteKey err information: ' + JSON.stringify(err)); @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无要求 ...@@ -1588,7 +2485,9 @@ HksInit对paramSet中参数的要求,其他三段式接口对paramSet无要求
* *
* 以下以SM3 256密钥的Promise操作使用为例 * 以下以SM3 256密钥的Promise操作使用为例
*/ */
function macStringToUint8Array(str) { import huks from '@ohos.security.huks';
function StringToUint8Array(str) {
var arr = []; var arr = [];
for (var i = 0, j = str.length; i < j; ++i) { for (var i = 0, j = str.length; i < j; ++i) {
arr.push(str.charCodeAt(i)); arr.push(str.charCodeAt(i));
...@@ -1596,6 +2495,162 @@ function macStringToUint8Array(str) { ...@@ -1596,6 +2495,162 @@ function macStringToUint8Array(str) {
return new Uint8Array(arr); 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<huks.HuksSessionHandle> {
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<huks.HuksReturnResult> {
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<huks.HuksReturnResult> {
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 srcKeyAlias = "sm3KeyAlias";
var hmacInData = 'sm3TestIndata'; var hmacInData = 'sm3TestIndata';
var handle; var handle;
...@@ -1625,43 +2680,44 @@ async function testMac() { ...@@ -1625,43 +2680,44 @@ async function testMac() {
} }
/* 生成密钥 */ /* 生成密钥 */
await huks.generateKey(srcKeyAlias, huksOptions).then((data) => { await publicGenKeyFunc(srcKeyAlias, huksOptions);
console.info('test generateKey data = ' + JSON.stringify(data));
}).catch((err) => {
console.info(`test init err: " + ${JSON.stringify(err)}`);
});
/* 修改init时的参数集并进行mac操作 */ /* 修改init时的参数集并进行mac操作 */
huksOptions.properties.splice(3, 3); huksOptions.properties.splice(3, 3);
await huks.init(srcKeyAlias, huksOptions).then((data) => { await publicInitFunc(srcKeyAlias, huksOptions);
console.info(`test init data: ${JSON.stringify(data)}`); huksOptions.inData = StringToUint8Array(hmacInData);
handle = data.handle; await publicUpdateFunc(handle, huksOptions);
}).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)}`);
});
huksOptions.inData = new Uint8Array(new Array()); huksOptions.inData = new Uint8Array(new Array());
await huks.finish(handle, huksOptions).then((data) => { await publicFinishFunc(handle, huksOptions);
console.info(`test update data: ${JSON.stringify(data)}`);
}).catch((err) => {
console.info('test update err information: ' + JSON.stringify(err));
});
huksOptions.properties.splice(1, 0, { huksOptions.properties.splice(1, 0, {
tag: huks.HuksTag.HUKS_TAG_KEY_SIZE, tag: huks.HuksTag.HUKS_TAG_KEY_SIZE,
value: huks.HuksKeySize.HUKS_AES_KEY_SIZE_256, value: huks.HuksKeySize.HUKS_AES_KEY_SIZE_256,
}); });
await publicDeleteKeyFunc(srcKeyAlias, huksOptions);
}
await huks.deleteKey(srcKeyAlias, huksOptions).then((data) => { @Entry
console.info(`test deleteKey data: ${JSON.stringify(data)}`); @Component
}).catch((err) => { struct Index {
console.info('test deleteKey err information: ' + JSON.stringify(err)); 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 ...@@ -1699,30 +2755,123 @@ RSA512, RSA768, RSA1024, RSA2048, RSA3072, RSA4096, ECC224, ECC256, ECC384, ECC5
```ts ```ts
/* 证书AttestID操作示例如下*/ /* 证书AttestID操作示例如下*/
function stringToUint8Array(str) { import huks from '@ohos.security.huks';
function StringToUint8Array(str) {
var arr = []; var arr = [];
for (var i = 0, j = str.length; i < j; ++i) { for (var i = 0, j = str.length; i < j; ++i) {
arr.push(str.charCodeAt(i)); arr.push(str.charCodeAt(i));
} }
var tmpUint8Array = new Uint8Array(arr); return new Uint8Array(arr);
return tmpUint8Array; }
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<huks.HuksReturnResult>{
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) { function deleteKeyItem(keyAlias:string, huksOptions:huks.HuksOptions) {
console.error(data.toString()); 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'); var securityLevel = StringToUint8Array('sec_level');
let challenge = stringToUint8Array('challenge_data'); var challenge = StringToUint8Array('challenge_data');
let versionInfo = stringToUint8Array('version_info'); var versionInfo = StringToUint8Array('version_info');
let udid = stringToUint8Array('udid'); var udid = StringToUint8Array('udid');
let serial = stringToUint8Array('serial'); var serial = StringToUint8Array('serial');
let deviceId = stringToUint8Array('device_id'); var deviceId = StringToUint8Array('device_id');
let idAliasString = "id attest"; var idAliasString = "id attest";
/* 集成生成密钥参数集 & 生成密钥 */ async function testAttestId() {
function generateKey(alias) { var aliasString = idAliasString;
let properties = new Array(); var aliasUint8 = StringToUint8Array(aliasString);
/* 集成生成密钥参数集 & 生成密钥 */
var properties = new Array();
properties[0] = { properties[0] = {
tag: huks.HuksTag.HUKS_TAG_ALGORITHM, tag: huks.HuksTag.HUKS_TAG_ALGORITHM,
value: huks.HuksKeyAlg.HUKS_ALG_RSA value: huks.HuksKeyAlg.HUKS_ALG_RSA
...@@ -1755,54 +2904,71 @@ function generateKey(alias) { ...@@ -1755,54 +2904,71 @@ function generateKey(alias) {
tag: huks.HuksTag.HUKS_TAG_BLOCK_MODE, tag: huks.HuksTag.HUKS_TAG_BLOCK_MODE,
value: huks.HuksCipherMode.HUKS_MODE_ECB value: huks.HuksCipherMode.HUKS_MODE_ECB
}; };
let options = { var options = {
properties: properties properties: properties
}; };
huks.generateKey(alias, options); await publicGenKeyFunc(aliasString, options);
}
async function attestId() {
let aliasString = idAliasString;
let aliasUint8 = stringToUint8Array(aliasString);
/* 集成证书参数集 */ /* 集成证书参数集 */
let properties = new Array(); var attestProperties = new Array();
properties[0] = { attestProperties[0] = {
tag: huks.HuksTag.HUKS_TAG_ATTESTATION_ID_SEC_LEVEL_INFO, tag: huks.HuksTag.HUKS_TAG_ATTESTATION_ID_SEC_LEVEL_INFO,
value: securityLevel value: securityLevel
}; };
properties[1] = { attestProperties[1] = {
tag: huks.HuksTag.HUKS_TAG_ATTESTATION_CHALLENGE, tag: huks.HuksTag.HUKS_TAG_ATTESTATION_CHALLENGE,
value: challenge value: challenge
}; };
properties[2] = { attestProperties[2] = {
tag: huks.HuksTag.HUKS_TAG_ATTESTATION_ID_VERSION_INFO, tag: huks.HuksTag.HUKS_TAG_ATTESTATION_ID_VERSION_INFO,
value: versionInfo value: versionInfo
}; };
properties[3] = { attestProperties[3] = {
tag: huks.HuksTag.HUKS_TAG_ATTESTATION_ID_ALIAS, tag: huks.HuksTag.HUKS_TAG_ATTESTATION_ID_ALIAS,
value: aliasUint8 value: aliasUint8
}; };
properties[4] = { attestProperties[4] = {
tag: huks.HuksTag.HUKS_TAG_ATTESTATION_ID_UDID, tag: huks.HuksTag.HUKS_TAG_ATTESTATION_ID_UDID,
value: udid value: udid
}; };
properties[5] = { attestProperties[5] = {
tag: huks.HuksTag.HUKS_TAG_ATTESTATION_ID_SERIAL, tag: huks.HuksTag.HUKS_TAG_ATTESTATION_ID_SERIAL,
value: serial value: serial
}; };
properties[6] = { attestProperties[6] = {
tag: huks.HuksTag.HUKS_TAG_ATTESTATION_ID_DEVICE, tag: huks.HuksTag.HUKS_TAG_ATTESTATION_ID_DEVICE,
value: deviceId value: deviceId
}; };
let options = { var huksOptions = {
properties: properties properties: attestProperties
}; };
generateKey(aliasString); await publicAttestKey(aliasString, huksOptions);
huks.attestKey(aliasString, options, function (err, data) {
printLog(`key attest result : ${JSON.stringify(data)}`); 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 ...@@ -1838,27 +3004,119 @@ RSA512, RSA768, RSA1024, RSA2048, RSA3072, RSA4096, ECC224, ECC256, ECC384, ECC5
```ts ```ts
/* 证书AttestKey操作示例如下*/ /* 证书AttestKey操作示例如下*/
function stringToUint8Array(str) { import huks from '@ohos.security.huks';
function StringToUint8Array(str) {
var arr = []; var arr = [];
for (var i = 0, j = str.length; i < j; ++i) { for (var i = 0, j = str.length; i < j; ++i) {
arr.push(str.charCodeAt(i)); arr.push(str.charCodeAt(i));
} }
var tmpUint8Array = new Uint8Array(arr); return new Uint8Array(arr);
return tmpUint8Array; }
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<huks.HuksReturnResult>{
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) { function deleteKeyItem(keyAlias:string, huksOptions:huks.HuksOptions) {
console.error(data.toString()); 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'); var securityLevel = StringToUint8Array('sec_level');
let challenge = stringToUint8Array('challenge_data'); var challenge = StringToUint8Array('challenge_data');
let versionInfo = stringToUint8Array('version_info'); var versionInfo = StringToUint8Array('version_info');
let keyAliasString = "key attest"; var keyAliasString = "key attest";
/* 集成生成密钥参数集 & 生成密钥 */ async function testAttestKey() {
function generateKey(alias) { var aliasString = keyAliasString;
let properties = new Array(); var aliasUint8 = StringToUint8Array(aliasString);
var properties = new Array();
properties[0] = { properties[0] = {
tag: huks.HuksTag.HUKS_TAG_ALGORITHM, tag: huks.HuksTag.HUKS_TAG_ALGORITHM,
value: huks.HuksKeyAlg.HUKS_ALG_RSA value: huks.HuksKeyAlg.HUKS_ALG_RSA
...@@ -1891,41 +3149,59 @@ function generateKey(alias) { ...@@ -1891,41 +3149,59 @@ function generateKey(alias) {
tag: huks.HuksTag.HUKS_TAG_BLOCK_MODE, tag: huks.HuksTag.HUKS_TAG_BLOCK_MODE,
value: huks.HuksCipherMode.HUKS_MODE_ECB value: huks.HuksCipherMode.HUKS_MODE_ECB
}; };
let options = { var options = {
properties: properties properties: properties
}; };
huks.generateKey(alias, options); await publicGenKeyFunc(aliasString, options);
}
async function attestKey() {
let aliasString = keyAliasString;
let aliasUint8 = stringToUint8Array(aliasString);
/* 集成证书参数集 */ /* 集成证书参数集 */
let properties = new Array(); var attestProperties = new Array();
properties[0] = { attestProperties[0] = {
tag: huks.HuksTag.HUKS_TAG_ATTESTATION_ID_SEC_LEVEL_INFO, tag: huks.HuksTag.HUKS_TAG_ATTESTATION_ID_SEC_LEVEL_INFO,
value: securityLevel value: securityLevel
}; };
properties[1] = { attestProperties[1] = {
tag: huks.HuksTag.HUKS_TAG_ATTESTATION_CHALLENGE, tag: huks.HuksTag.HUKS_TAG_ATTESTATION_CHALLENGE,
value: challenge value: challenge
}; };
properties[2] = { attestProperties[2] = {
tag: huks.HuksTag.HUKS_TAG_ATTESTATION_ID_VERSION_INFO, tag: huks.HuksTag.HUKS_TAG_ATTESTATION_ID_VERSION_INFO,
value: versionInfo value: versionInfo
}; };
properties[3] = { attestProperties[3] = {
tag: huks.HuksTag.HUKS_TAG_ATTESTATION_ID_ALIAS, tag: huks.HuksTag.HUKS_TAG_ATTESTATION_ID_ALIAS,
value: aliasUint8 value: aliasUint8
}; };
let options = { var huksOptions = {
properties: properties properties: attestProperties
}; };
generateKey(aliasString);
huks.attestKey(aliasString, options, function (err, data) { await publicAttestKey(aliasString, huksOptions);
printLog(`key attest result : ${JSON.stringify(data)}`);
}); 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%')
}
} }
``` ```
......
Markdown is supported
0% .
You are about to add 0 people to the discussion. Proceed with caution.
先完成此消息的编辑!
想要评论请 注册