• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1# @ohos.security.huks (通用密钥库系统)(系统接口)
2
3<!--Kit: Universal Keystore Kit-->
4<!--Subsystem: Security-->
5<!--Owner: @wutiantian-gitee-->
6<!--Designer: @HighLowWorld-->
7<!--Tester: @wxy1234564846-->
8<!--Adviser: @zengyawen-->
9
10向应用提供密钥库能力,应用可调用接口,指定用户身份操作密钥。
11
12> **说明:**
13> - 本模块首批接口从API version 12开始支持。后续版本的新增接口,采用上角标单独标记接口的起始版本。
14> - 当前页面仅包含本模块的系统接口,其他公开接口参见[@ohos.security.huks (通用密钥库系统)](js-apis-huks.md)。
15
16## 导入模块
17
18```ts
19import { huks } from '@kit.UniversalKeystoreKit';
20```
21
22## huks.generateKeyItemAsUser
23
24generateKeyItemAsUser(userId: number, keyAlias: string, huksOptions: HuksOptions) : Promise\<void>
25
26指定用户身份生成密钥,使用Promise方式异步返回结果。基于密钥不出TEE原则,通过promise不会返回密钥材料内容,只用于表示此次调用是否成功。
27
28**系统接口**:此接口为系统接口。
29
30**需要权限**:ohos.permission.INTERACT_ACROSS_LOCAL_ACCOUNTS
31
32**系统能力**:SystemCapability.Security.Huks.Extension
33
34**参数:**
35
36| 参数名   | 类型                        | 必填 | 说明                     |
37| -------- | --------------------------- | ---- | ------------------------ |
38| userId   | number                      | 是   | 用户ID。                 |
39| keyAlias | string                      | 是   | 密钥别名。密钥别名的最大长度为128字节,建议不包含个人信息等敏感词汇。               |
40| huksOptions  | [HuksOptions](js-apis-huks.md#huksoptions) | 是   | 用于存放生成key所需的[属性标签](capi-native-huks-type-h.md#枚举)。其中密钥使用的算法、密钥用途、密钥长度为必选参数。 |
41
42**返回值:**
43
44| 类型                | 说明                            |
45| ------------------- | ------------------------------- |
46| Promise&lt;void&gt; | Promise对象。无返回结果的Promise对象。 |
47
48**错误码:**
49
50以下错误码的详细介绍请参见[HUKS错误码](errorcode-huks.md)。
51
52| 错误码ID | 错误信息      |
53| -------- | ------------- |
54| 201 | the application permission is not sufficient, which may be caused by lack of cross-account permission, or the system has not been unlocked by user, or the user does not exist. |
55| 202 | non-system applications are not allowed to use system APIs. |
56| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified. 2. Incorrect parameter types. 3. Parameter verification failed. |
57| 801 | api is not supported. |
58| 12000001 | algorithm mode is not supported. |
59| 12000002 | algorithm param is missing. |
60| 12000003 | algorithm param is invalid. |
61| 12000004 | operating file failed. |
62| 12000005 | IPC communication failed. |
63| 12000006 | error occurred in crypto engine. |
64| 12000012 | Device environment or input parameter abnormal. |
65| 12000013 | queried credential does not exist. |
66| 12000014 | memory is insufficient. |
67| 12000015 | Failed to obtain the security information via UserIAM. |
68| 12000017 | The key with same alias is already exist. |
69
70**示例:**
71
72- 以下代码示例接口调用的前置条件:
73
74  调用方必须是运行在User0~99(包含0和99)用户身份下的系统应用,同时需要申请ohos.permission.INTERACT_ACROSS_LOCAL_ACCOUNTS权限。允许应用安装到User0的配置指导,请参考[singleton|bool|false|是否允许应用安装到单用户下(U0)](../../../../zh-cn/device-dev/subsystems/subsys-app-privilege-config-guide.md#可由设备厂商配置的特权)
75
76```ts
77import { huks } from '@kit.UniversalKeystoreKit';
78import { BusinessError } from "@kit.BasicServicesKit"
79
80const aesKeyAlias = 'test_aesKeyAlias';
81const userId = 100;
82const userIdStorageLevel = huks.HuksAuthStorageLevel.HUKS_AUTH_STORAGE_LEVEL_CE;
83
84function GetAesGenerateProperties(): Array<huks.HuksParam> {
85  return [{
86    tag: huks.HuksTag.HUKS_TAG_ALGORITHM,
87    value: huks.HuksKeyAlg.HUKS_ALG_AES
88  }, {
89    tag: huks.HuksTag.HUKS_TAG_KEY_SIZE,
90    value: huks.HuksKeySize.HUKS_AES_KEY_SIZE_128
91  }, {
92    tag: huks.HuksTag.HUKS_TAG_PURPOSE,
93    value: huks.HuksKeyPurpose.HUKS_KEY_PURPOSE_ENCRYPT |
94    huks.HuksKeyPurpose.HUKS_KEY_PURPOSE_DECRYPT
95  }, {
96    tag: huks.HuksTag.HUKS_TAG_PADDING,
97    value: huks.HuksKeyPadding.HUKS_PADDING_PKCS7
98  }, {
99    tag: huks.HuksTag.HUKS_TAG_BLOCK_MODE,
100    value: huks.HuksCipherMode.HUKS_MODE_CBC
101  }, {
102    tag: huks.HuksTag.HUKS_TAG_AUTH_STORAGE_LEVEL,
103    value: userIdStorageLevel,
104  }]
105}
106
107async function GenerateKey(keyAlias: string, genProperties: Array<huks.HuksParam>) {
108  const options: huks.HuksOptions = {
109    properties: genProperties
110  }
111  await huks.generateKeyItemAsUser(userId, keyAlias, options).then((data) => {
112    console.info("成功生成了一个别名为:" + keyAlias + " 的密钥")
113  }).catch((err: BusinessError) => {
114    console.error("密钥生成失败,错误码是: " + err.code + " 错误码信息: " + err.message)
115  })
116}
117
118
119export default function HuksAsUserTest() {
120  console.info('begin huks as user test')
121  GenerateKey(aesKeyAlias, GetAesGenerateProperties())
122}
123```
124
125## huks.deleteKeyItemAsUser
126
127deleteKeyItemAsUser(userId: number, keyAlias: string, huksOptions: HuksOptions) : Promise\<void>
128
129指定用户身份删除密钥,使用Promise方式异步返回结果。
130
131**系统接口**:此接口为系统接口。
132
133**需要权限**: ohos.permission.INTERACT_ACROSS_LOCAL_ACCOUNTS
134
135**系统能力**:SystemCapability.Security.Huks.Extension
136
137**参数:**
138
139| 参数名   | 类型                        | 必填 | 说明                                |
140| -------- | --------------------------- | ---- | ----------------------------------- |
141| userId   | number                      | 是   | 用户ID。                 |
142| keyAlias | string                      | 是   | 密钥别名,应为生成key时传入的别名。 |
143| huksOptions  | [HuksOptions](js-apis-huks.md#huksoptions) | 是   | 用于删除时指定密钥的属性TAG,如使用[HuksAuthStorageLevel](js-apis-huks.md#huksauthstoragelevel11)指定需删除密钥的安全级别,<br>可传空,当API version ≥ 12时,传空默认为CE,当API version < 12时,传空默认为DE。            |
144
145**返回值:**
146
147| 类型                | 说明                            |
148| ------------------- | ------------------------------- |
149| Promise&lt;void&gt; | Promise对象。无返回结果的Promise对象。 |
150
151**错误码:**
152
153以下错误码的详细介绍请参见[HUKS错误码](errorcode-huks.md)。
154
155| 错误码ID | 错误信息      |
156| -------- | ------------- |
157| 201 | the application permission is not sufficient, which may be caused by lack of cross-account permission, or the system has not been unlocked by user, or the user does not exist. |
158| 202 | non-system applications are not allowed to use system APIs. |
159| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified. 2. Incorrect parameter types. 3. Parameter verification failed. |
160| 801 | api is not supported. |
161| 12000004 | operating file failed. |
162| 12000005 | IPC communication failed. |
163| 12000011 | queried entity does not exist. |
164| 12000012 | Device environment or input parameter abnormal. |
165| 12000014 | memory is insufficient. |
166
167**示例:**
168
169- 以下代码示例接口调用的前置条件同上文[generateKeyItemAsUser](#huksgeneratekeyitemasuser)的前置条件
170
171```ts
172import { huks } from '@kit.UniversalKeystoreKit';
173import { BusinessError } from "@kit.BasicServicesKit"
174
175const aesKeyAlias = 'test_aesKeyAlias';
176const userId = 100;
177const userIdStorageLevel = huks.HuksAuthStorageLevel.HUKS_AUTH_STORAGE_LEVEL_CE;
178
179function GetAesGenerateProperties(): Array<huks.HuksParam> {
180  return [{
181    tag: huks.HuksTag.HUKS_TAG_ALGORITHM,
182    value: huks.HuksKeyAlg.HUKS_ALG_AES
183  }, {
184    tag: huks.HuksTag.HUKS_TAG_KEY_SIZE,
185    value: huks.HuksKeySize.HUKS_AES_KEY_SIZE_128
186  }, {
187    tag: huks.HuksTag.HUKS_TAG_PURPOSE,
188    value: huks.HuksKeyPurpose.HUKS_KEY_PURPOSE_ENCRYPT |
189    huks.HuksKeyPurpose.HUKS_KEY_PURPOSE_DECRYPT
190  }, {
191    tag: huks.HuksTag.HUKS_TAG_PADDING,
192    value: huks.HuksKeyPadding.HUKS_PADDING_PKCS7
193  }, {
194    tag: huks.HuksTag.HUKS_TAG_BLOCK_MODE,
195    value: huks.HuksCipherMode.HUKS_MODE_CBC
196  }, {
197    tag: huks.HuksTag.HUKS_TAG_AUTH_STORAGE_LEVEL,
198    value: userIdStorageLevel,
199  }]
200}
201
202async function GenerateKey(keyAlias: string, genProperties: Array<huks.HuksParam>) {
203  const options: huks.HuksOptions = {
204    properties: genProperties
205  }
206  await huks.generateKeyItemAsUser(userId, keyAlias, options).then((data) => {
207  }).catch((err: BusinessError) => {
208    console.error("密钥生成失败,错误码是: " + err.code + " 错误码信息: " + err.message)
209  })
210}
211
212async function DeleteKey(keyAlias: string) {
213  const options: huks.HuksOptions = {
214    properties: [{
215      tag: huks.HuksTag.HUKS_TAG_AUTH_STORAGE_LEVEL,
216      value: userIdStorageLevel,
217    }]
218  }
219  await huks.deleteKeyItemAsUser(userId, keyAlias, options).then((data) => {
220    console.info("别名为: " + keyAlias + " 密钥删除成功!")
221  }).catch((err: BusinessError) => {
222    console.error("密钥删除失败,错误码是: " + err.code + " 错误码信息: " + err.message)
223  })
224}
225
226async function TestHuksDelete() {
227  await GenerateKey(aesKeyAlias, GetAesGenerateProperties())
228  await DeleteKey(aesKeyAlias)
229}
230
231export default function HuksAsUserTest() {
232  console.info('begin huks as user test')
233  TestHuksDelete()
234}
235```
236
237## huks.importKeyItemAsUser
238
239importKeyItemAsUser(userId: number, keyAlias: string, huksOptions: HuksOptions) : Promise\<void>
240
241指定用户身份导入明文密钥,使用Promise方式异步返回结果。
242
243**系统接口**:此接口为系统接口。
244
245**需要权限**: ohos.permission.INTERACT_ACROSS_LOCAL_ACCOUNTS
246
247**系统能力**:SystemCapability.Security.Huks.Extension
248
249**参数:**
250
251| 参数名   | 类型                        | 必填 | 说明                                |
252| -------- | --------------------------- | ---- | ----------------------------------- |
253| userId   | number                      | 是   | 用户ID。                 |
254| keyAlias | string                      | 是   | 密钥别名。密钥别名的最大长度为128字节,建议不包含个人信息等敏感词汇。                          |
255| huksOptions  | [HuksOptions](js-apis-huks.md#huksoptions) | 是   | 用于导入时所需TAG和需要导入的密钥。其中密钥使用的算法、密钥用途、密钥长度为必选参数。 |
256
257**返回值:**
258
259| 类型                | 说明                            |
260| ------------------- | ------------------------------- |
261| Promise&lt;void&gt; | Promise对象。无返回结果的Promise对象。 |
262
263**错误码:**
264
265以下错误码的详细介绍请参见[HUKS错误码](errorcode-huks.md)。
266
267| 错误码ID | 错误信息      |
268| -------- | ------------- |
269| 201 | the application permission is not sufficient, which may be caused by lack of cross-account permission, or the system has not been unlocked by user, or the user does not exist. |
270| 202 | non-system applications are not allowed to use system APIs. |
271| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified. 2. Incorrect parameter types. 3. Parameter verification failed. |
272| 801 | api is not supported. |
273| 12000001 | algorithm mode is not supported. |
274| 12000002 | algorithm param is missing. |
275| 12000003 | algorithm param is invalid. |
276| 12000004 | operating file failed. |
277| 12000005 | IPC communication failed. |
278| 12000006 | error occurred in crypto engine. |
279| 12000011 | queried entity does not exist. |
280| 12000012 | Device environment or input parameter abnormal. |
281| 12000013 | queried credential does not exist. |
282| 12000014 | memory is insufficient. |
283| 12000015 | Failed to obtain the security information via UserIAM. |
284| 12000017 | The key with same alias is already exist. |
285
286**示例:**
287
288- 以下代码示例接口调用的前置条件同上文[generateKeyItemAsUser](#huksgeneratekeyitemasuser)的前置条件
289
290```ts
291import { huks } from '@kit.UniversalKeystoreKit';
292import { BusinessError } from "@kit.BasicServicesKit"
293
294const aesKeyAlias = 'test_aesKeyAlias';
295const userId = 100;
296const userIdStorageLevel = huks.HuksAuthStorageLevel.HUKS_AUTH_STORAGE_LEVEL_CE;
297const plainAesKey128 = new Uint8Array([
298  0xfb, 0x8b, 0x9f, 0x12, 0xa0, 0x83, 0x19, 0xbe, 0x6a, 0x6f, 0x63, 0x2a, 0x7c, 0x86, 0xba, 0xca
299]);
300
301function GetAesGenerateProperties(): Array<huks.HuksParam> {
302  return [{
303    tag: huks.HuksTag.HUKS_TAG_ALGORITHM,
304    value: huks.HuksKeyAlg.HUKS_ALG_AES
305  }, {
306    tag: huks.HuksTag.HUKS_TAG_KEY_SIZE,
307    value: huks.HuksKeySize.HUKS_AES_KEY_SIZE_128
308  }, {
309    tag: huks.HuksTag.HUKS_TAG_PURPOSE,
310    value: huks.HuksKeyPurpose.HUKS_KEY_PURPOSE_ENCRYPT |
311    huks.HuksKeyPurpose.HUKS_KEY_PURPOSE_DECRYPT
312  }, {
313    tag: huks.HuksTag.HUKS_TAG_PADDING,
314    value: huks.HuksKeyPadding.HUKS_PADDING_PKCS7
315  }, {
316    tag: huks.HuksTag.HUKS_TAG_BLOCK_MODE,
317    value: huks.HuksCipherMode.HUKS_MODE_CBC
318  }, {
319    tag: huks.HuksTag.HUKS_TAG_AUTH_STORAGE_LEVEL,
320    value: userIdStorageLevel,
321  }]
322}
323
324async function ImportPlainKey(keyAlias: string, importProperties: Array<huks.HuksParam>, plainKey: Uint8Array) {
325  const options: huks.HuksOptions = {
326    properties: importProperties,
327    inData: plainKey
328  }
329  await huks.importKeyItemAsUser(userId, keyAlias, options).then((data) => {
330    console.info("成功导入了一个别名为:" + keyAlias + " 的密钥")
331  }).catch((err: BusinessError) => {
332    console.error("密钥导入失败,错误码是: " + err.code + " 错误码信息: " + err.message)
333  })
334}
335
336export default function HuksAsUserTest() {
337  console.info('begin huks as user test')
338  ImportPlainKey(aesKeyAlias, GetAesGenerateProperties(), plainAesKey128)
339}
340```
341
342
343## huks.attestKeyItemAsUser
344
345attestKeyItemAsUser(userId: number, keyAlias: string, huksOptions: HuksOptions) : Promise\<HuksReturnResult>
346
347指定用户身份获取密钥证书,使用Promise方式异步返回结果。
348
349**系统接口**:此接口为系统接口。
350
351**需要权限**:ohos.permission.ATTEST_KEY, ohos.permission.INTERACT_ACROSS_LOCAL_ACCOUNTS 必须同时拥有两个权限。
352
353**系统能力**:SystemCapability.Security.Huks.Extension
354
355**参数:**
356
357| 参数名   | 类型                        | 必填 | 说明                                 |
358| -------- | --------------------------- | ---- | ------------------------------------ |
359| userId   | number                      | 是   | 用户ID。                 |
360| keyAlias | string                      | 是   | 密钥别名,存放待获取证书密钥的别名。 |
361| huksOptions  | [HuksOptions](js-apis-huks.md#huksoptions) | 是   | 用于获取证书时指定所需参数与数据。   |
362
363**返回值:**
364
365| 类型                                           | 说明                                          |
366| ---------------------------------------------- | --------------------------------------------- |
367| Promise<[HuksReturnResult](js-apis-huks.md#huksreturnresult9)> | Promise对象。当调用成功时,HuksReturnResult的certChains成员非空,为获取到的证书链,否则为失败。 |
368
369**错误码:**
370
371以下错误码的详细介绍请参见[HUKS错误码](errorcode-huks.md)。
372
373| 错误码ID | 错误信息      |
374| -------- | ------------- |
375| 201 | the application permission is not sufficient, which may be caused by lack of cross-account permission, or the system has not been unlocked by user, or the user does not exist. |
376| 202 | non-system applications are not allowed to use system APIs. |
377| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified. 2. Incorrect parameter types. 3. Parameter verification failed. |
378| 801 | api is not supported. |
379| 12000001 | algorithm mode is not supported. |
380| 12000002 | algorithm param is missing. |
381| 12000003 | algorithm param is invalid. |
382| 12000004 | operating file failed. |
383| 12000005 | IPC communication failed. |
384| 12000006 | error occurred in crypto engine. |
385| 12000011 | queried entity does not exist. |
386| 12000012 | Device environment or input parameter abnormal. |
387| 12000014 | memory is insufficient. |
388
389**示例:**
390
391- 以下代码示例接口调用的前置条件同上文[generateKeyItemAsUser](#huksgeneratekeyitemasuser)的前置条件
392
393```ts
394import { huks } from '@kit.UniversalKeystoreKit';
395import { BusinessError } from "@kit.BasicServicesKit"
396
397function StringToUint8Array(str: string) {
398  let arr: number[] = [];
399  for (let i = 0, j = str.length; i < j; ++i) {
400    arr.push(str.charCodeAt(i));
401  }
402  return new Uint8Array(arr);
403}
404
405const rsaKeyAlias = 'test_rsaKeyAlias';
406const userId = 100;
407const userIdStorageLevel = huks.HuksAuthStorageLevel.HUKS_AUTH_STORAGE_LEVEL_CE;
408
409const securityLevel = StringToUint8Array('sec_level');
410const challenge = StringToUint8Array('challenge_data');
411const versionInfo = StringToUint8Array('version_info');
412
413function GetRSA4096GenerateProperties(): Array<huks.HuksParam> {
414  return [{
415    tag: huks.HuksTag.HUKS_TAG_ALGORITHM,
416    value: huks.HuksKeyAlg.HUKS_ALG_RSA
417  }, {
418    tag: huks.HuksTag.HUKS_TAG_KEY_SIZE,
419    value: huks.HuksKeySize.HUKS_RSA_KEY_SIZE_4096
420  }, {
421    tag: huks.HuksTag.HUKS_TAG_PURPOSE,
422    value: huks.HuksKeyPurpose.HUKS_KEY_PURPOSE_ENCRYPT |
423    huks.HuksKeyPurpose.HUKS_KEY_PURPOSE_DECRYPT
424  }, {
425    tag: huks.HuksTag.HUKS_TAG_DIGEST,
426    value: huks.HuksKeyDigest.HUKS_DIGEST_SHA256
427  }, {
428    tag: huks.HuksTag.HUKS_TAG_PADDING,
429    value: huks.HuksKeyPadding.HUKS_PADDING_PKCS1_V1_5
430  }, {
431    tag: huks.HuksTag.HUKS_TAG_BLOCK_MODE,
432    value: huks.HuksCipherMode.HUKS_MODE_ECB
433  }, {
434    tag: huks.HuksTag.HUKS_TAG_AUTH_STORAGE_LEVEL,
435    value: userIdStorageLevel,
436  }]
437}
438
439async function GenerateKey(keyAlias: string, genProperties: Array<huks.HuksParam>) {
440  const options: huks.HuksOptions = {
441    properties: genProperties
442  }
443  await huks.generateKeyItemAsUser(userId, keyAlias, options).then((data) => {
444    console.info("成功生成了一个别名为:" + keyAlias + " 的密钥")
445  }).catch((err: BusinessError) => {
446    console.error("密钥生成失败,错误码是: " + err.code + " 错误码信息: " + err.message)
447  })
448}
449
450function GetAttestKeyProperties(keyAlias: string): Array<huks.HuksParam> {
451  return new Array<huks.HuksParam>({
452    tag: huks.HuksTag.HUKS_TAG_ATTESTATION_ID_SEC_LEVEL_INFO,
453    value: securityLevel
454  }, {
455    tag: huks.HuksTag.HUKS_TAG_ATTESTATION_CHALLENGE,
456    value: challenge
457  }, {
458    tag: huks.HuksTag.HUKS_TAG_ATTESTATION_ID_VERSION_INFO,
459    value: versionInfo
460  }, {
461    tag: huks.HuksTag.HUKS_TAG_ATTESTATION_ID_ALIAS,
462    value: StringToUint8Array(keyAlias)
463  }, {
464    tag: huks.HuksTag.HUKS_TAG_AUTH_STORAGE_LEVEL,
465    value: userIdStorageLevel,
466  })
467}
468
469async function LetKeyAttest(keyAlias: string, keyOptions: Array<huks.HuksParam>) {
470  let attestOptions: huks.HuksOptions = {
471    properties: keyOptions,
472  }
473  console.info('开始attest')
474  await huks.attestKeyItemAsUser(userId, keyAlias, attestOptions).then((data) => {
475    console.info('attestation ok!')
476    console.debug(`拿到的证书链是${JSON.stringify(data)}`) // 这里是调试信息,实际业务功能开发无需打印证书链。
477    for (let i = 0; data?.certChains?.length && i < data?.certChains?.length; ++i) {
478      console.debug(`证书${i}是${data.certChains[i]}`) // 这里是调试信息,实际业务功能开发无需打印证书链。
479    }
480    console.info("attest 成功")
481  }).catch((err: BusinessError) => {
482    console.error("attest 失败,错误码是: " + err.code + " 错误码信息: " + err.message)
483  })
484}
485
486async function TestHuksAttest() {
487  await GenerateKey(rsaKeyAlias, GetRSA4096GenerateProperties())
488  await LetKeyAttest(rsaKeyAlias, GetAttestKeyProperties(rsaKeyAlias))
489}
490
491export default function HuksAsUserTest() {
492  console.info('begin huks as user test')
493  TestHuksAttest()
494}
495```
496
497## huks.anonAttestKeyItemAsUser
498
499anonAttestKeyItemAsUser(userId: number, keyAlias: string, huksOptions: HuksOptions) : Promise\<HuksReturnResult>
500
501指定用户身份获取匿名化密钥证书,使用Promise方式异步返回结果。
502
503该操作需要联网进行,且耗时较长。
504
505**系统接口**:此接口为系统接口。
506
507**需要权限**: ohos.permission.INTERACT_ACROSS_LOCAL_ACCOUNTS
508
509**系统能力**:SystemCapability.Security.Huks.Extension
510
511**参数:**
512
513| 参数名   | 类型                        | 必填 | 说明                                 |
514| -------- | --------------------------- | ---- | ------------------------------------ |
515| userId   | number                      | 是   | 用户ID。                 |
516| keyAlias | string                      | 是   | 密钥别名,存放待获取证书密钥的别名。 |
517| huksOptions  | [HuksOptions](js-apis-huks.md#huksoptions) | 是   | 用于获取证书时指定所需参数与数据。   |
518
519**返回值:**
520
521| 类型                                           | 说明                                          |
522| ---------------------------------------------- | --------------------------------------------- |
523| Promise<[HuksReturnResult](js-apis-huks.md#huksreturnresult9)> | Promise对象。当调用成功时,HuksReturnResult的certChains成员非空,为获取到的证书链,否则为失败。 |
524
525**错误码:**
526
527以下错误码的详细介绍请参见[HUKS错误码](errorcode-huks.md)。
528
529| 错误码ID | 错误信息      |
530| -------- | ------------- |
531| 201 | the application permission is not sufficient, which may be caused by lack of cross-account permission, or the system has not been unlocked by user, or the user does not exist. |
532| 202 | non-system applications are not allowed to use system APIs. |
533| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified. 2. Incorrect parameter types. 3. Parameter verification failed. |
534| 801 | api is not supported. |
535| 12000001 | algorithm mode is not supported. |
536| 12000002 | algorithm param is missing. |
537| 12000003 | algorithm param is invalid. |
538| 12000004 | operating file failed. |
539| 12000005 | IPC communication failed. |
540| 12000006 | error occurred in crypto engine. |
541| 12000011 | queried entity does not exist. |
542| 12000012 | Device environment or input parameter abnormal. |
543| 12000014 | memory is insufficient. |
544
545**示例:**
546
547- 以下代码示例接口调用的前置条件同上文[generateKeyItemAsUser](#huksgeneratekeyitemasuser)的前置条件
548
549```ts
550import { huks } from '@kit.UniversalKeystoreKit';
551import { BusinessError } from "@kit.BasicServicesKit"
552
553function StringToUint8Array(str: string) {
554  let arr: number[] = [];
555  for (let i = 0, j = str.length; i < j; ++i) {
556    arr.push(str.charCodeAt(i));
557  }
558  return new Uint8Array(arr);
559}
560
561const rsaKeyAlias = 'test_rsaKeyAlias';
562const userId = 100;
563const userIdStorageLevel = huks.HuksAuthStorageLevel.HUKS_AUTH_STORAGE_LEVEL_CE;
564
565const securityLevel = StringToUint8Array('sec_level');
566const challenge = StringToUint8Array('challenge_data');
567const versionInfo = StringToUint8Array('version_info');
568
569function GetRSA4096GenerateProperties(): Array<huks.HuksParam> {
570  return [{
571    tag: huks.HuksTag.HUKS_TAG_ALGORITHM,
572    value: huks.HuksKeyAlg.HUKS_ALG_RSA
573  }, {
574    tag: huks.HuksTag.HUKS_TAG_KEY_SIZE,
575    value: huks.HuksKeySize.HUKS_RSA_KEY_SIZE_4096
576  }, {
577    tag: huks.HuksTag.HUKS_TAG_PURPOSE,
578    value: huks.HuksKeyPurpose.HUKS_KEY_PURPOSE_ENCRYPT |
579    huks.HuksKeyPurpose.HUKS_KEY_PURPOSE_DECRYPT
580  }, {
581    tag: huks.HuksTag.HUKS_TAG_DIGEST,
582    value: huks.HuksKeyDigest.HUKS_DIGEST_SHA256
583  }, {
584    tag: huks.HuksTag.HUKS_TAG_PADDING,
585    value: huks.HuksKeyPadding.HUKS_PADDING_PKCS1_V1_5
586  }, {
587    tag: huks.HuksTag.HUKS_TAG_BLOCK_MODE,
588    value: huks.HuksCipherMode.HUKS_MODE_ECB
589  }, {
590    tag: huks.HuksTag.HUKS_TAG_AUTH_STORAGE_LEVEL,
591    value: userIdStorageLevel,
592  }]
593}
594
595async function GenerateKey(keyAlias: string, genProperties: Array<huks.HuksParam>) {
596  const options: huks.HuksOptions = {
597    properties: genProperties
598  }
599  await huks.generateKeyItemAsUser(userId, keyAlias, options).then((data) => {
600    console.info("成功生成了一个别名为:" + keyAlias + " 的密钥")
601  }).catch((err: BusinessError) => {
602    console.error("密钥生成失败,错误码是: " + err.code + " 错误码信息: " + err.message)
603  })
604}
605
606function GetAttestKeyProperties(keyAlias: string): Array<huks.HuksParam> {
607  return new Array<huks.HuksParam>({
608    tag: huks.HuksTag.HUKS_TAG_ATTESTATION_ID_SEC_LEVEL_INFO,
609    value: securityLevel
610  }, {
611    tag: huks.HuksTag.HUKS_TAG_ATTESTATION_CHALLENGE,
612    value: challenge
613  }, {
614    tag: huks.HuksTag.HUKS_TAG_ATTESTATION_ID_VERSION_INFO,
615    value: versionInfo
616  }, {
617    tag: huks.HuksTag.HUKS_TAG_ATTESTATION_ID_ALIAS,
618    value: StringToUint8Array(keyAlias)
619  }, {
620    tag: huks.HuksTag.HUKS_TAG_AUTH_STORAGE_LEVEL,
621    value: userIdStorageLevel,
622  })
623}
624
625async function LetKeyAnonAttest(keyAlias: string, keyOptions: Array<huks.HuksParam>) {
626  let attestOptions: huks.HuksOptions = {
627    properties: keyOptions,
628  }
629  console.info('开始匿名attest')
630  await huks.anonAttestKeyItemAsUser(userId, keyAlias, attestOptions).then((data) => {
631    console.info('匿名attestation ok!')
632    console.debug(`拿到的证书链是${JSON.stringify(data)}`)
633    for (let i = 0; data?.certChains?.length && i < data?.certChains?.length; ++i) {
634      console.info(`证书${i}是${data.certChains[i]}`)
635    }
636    console.info("匿名 attest 成功")
637  }).catch((err: BusinessError) => {
638    console.error("匿名 attest 失败,错误码是: " + err.code + " 错误码信息: " + err.message)
639  })
640}
641
642
643async function TestHuksAnonAttest() {
644  await GenerateKey(rsaKeyAlias, GetRSA4096GenerateProperties())
645  await LetKeyAnonAttest(rsaKeyAlias, GetAttestKeyProperties(rsaKeyAlias))
646}
647
648export default function HuksAsUserTest() {
649  console.info('begin huks as user test')
650  TestHuksAnonAttest()
651}
652```
653
654## huks.importWrappedKeyItemAsUser
655
656importWrappedKeyItemAsUser(userId: number, keyAlias: string, wrappingKeyAlias: string, huksOptions: HuksOptions) : Promise\<void>
657
658指定用户身份导入加密密钥,使用Promise方式异步返回结果。
659
660**系统接口**:此接口为系统接口。
661
662**需要权限**: ohos.permission.INTERACT_ACROSS_LOCAL_ACCOUNTS
663
664**系统能力**:SystemCapability.Security.Huks.Extension
665
666**参数:**
667
668| 参数名           | 类型                        | 必填 | 说明                                          |
669| ---------------- | --------------------------- | ---- | --------------------------------------------- |
670| userId   | number                      | 是   | 用户ID。                 |
671| keyAlias         | string                      | 是   | 密钥别名,存放待导入密钥的别名。              |
672| wrappingKeyAlias | string                      | 是   | 密钥别名,对应密钥用于解密加密的密钥数据。    |
673| huksOptions          | [HuksOptions](js-apis-huks.md#huksoptions) | 是   | 用于导入时所需TAG和需要导入的加密的密钥数据。其中密钥使用的算法、密钥用途、密钥长度为必选参数。 |
674
675**返回值:**
676
677| 类型                | 说明                            |
678| ------------------- | ------------------------------- |
679| Promise&lt;void&gt; | Promise对象。无返回结果的Promise对象。 |
680
681**错误码:**
682
683以下错误码的详细介绍请参见[HUKS错误码](errorcode-huks.md)。
684
685| 错误码ID | 错误信息      |
686| -------- | ------------- |
687| 201 | the application permission is not sufficient, which may be caused by lack of cross-account permission, or the system has not been unlocked by user, or the user does not exist. |
688| 202 | non-system applications are not allowed to use system APIs. |
689| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified. 2. Incorrect parameter types. 3. Parameter verification failed. |
690| 801 | api is not supported. |
691| 12000001 | algorithm mode is not supported. |
692| 12000002 | algorithm param is missing. |
693| 12000003 | algorithm param is invalid. |
694| 12000004 | operating file failed. |
695| 12000005 | IPC communication failed. |
696| 12000006 | error occurred in crypto engine. |
697| 12000011 | queried entity does not exist. |
698| 12000012 | Device environment or input parameter abnormal. |
699| 12000013 | queried credential does not exist. |
700| 12000014 | memory is insufficient. |
701| 12000015 | Failed to obtain the security information via UserIAM. |
702| 12000017 | The key with same alias is already exist. |
703
704**示例:**
705
706- 以下代码示例接口调用的前置条件同上文[generateKeyItemAsUser](#huksgeneratekeyitemasuser)的前置条件。
707- 注意:下文密码学相关的变量(如initializationVector、associatedData、nonce)赋值,均为参考样例,不能直接适用于业务功能逻辑。开发者需要根据自身场景使用合适的初始值。
708
709```ts
710import { huks } from '@kit.UniversalKeystoreKit';
711import { BusinessError } from "@kit.BasicServicesKit"
712
713const userIdStorageLevel = huks.HuksAuthStorageLevel.HUKS_AUTH_STORAGE_LEVEL_CE;
714const initializationVector = '0000000000000000';
715const associatedData = "abababababababab";
716const nonce = "hahahahahaha";
717const tagSize = 16;
718const unsignedInt32Bytes = 4;
719const importedAes192PlainKey = "The aes192 key to import";
720const callerAes256Kek = "This is kek to encrypt aes192 key";
721const callerKeyAlias = "test_caller_key_ecdh_aes192";
722const callerKekAliasAes256 = "test_caller_kek_ecdh_aes256";
723const callerAgreeKeyAliasAes256 = "test_caller_agree_key_ecdh_aes256";
724const importedKeyAliasAes192 = "test_import_key_ecdh_aes192";
725const mask = [0x000000FF, 0x0000FF00, 0x00FF0000, 0xFF000000];
726
727
728function StringToUint8Array(str: string) {
729  let arr: number[] = [];
730  for (let i = 0, j = str.length; i < j; ++i) {
731    arr.push(str.charCodeAt(i));
732  }
733  return new Uint8Array(arr);
734}
735
736function SubUint8ArrayOf(arrayBuf: Uint8Array, start: number, end: number) {
737  let arr: Array<number> = [];
738  for (let i = start; i < end && i < arrayBuf.length; ++i) {
739    arr.push(arrayBuf[i]);
740  }
741  return new Uint8Array(arr);
742}
743
744function AssignLength(length: number, arrayBuf: Uint8Array, startIndex: number) {
745  let index = startIndex;
746  for (let i = 0; i < 4; i++) {
747    arrayBuf[index++] = (length & mask[i]) >> (i * 8);
748  }
749  return 4;
750}
751
752function AssignData(data: Uint8Array, arrayBuf: Uint8Array, startIndex: number) {
753  let index = startIndex;
754  for (let i = 0; i < data.length; i++) {
755    arrayBuf[index++] = data[i];
756  }
757  return data.length;
758}
759
760const genWrappingKeyParams: huks.HuksOptions = {
761  properties: [
762    {
763      tag: huks.HuksTag.HUKS_TAG_ALGORITHM,
764      value: huks.HuksKeyAlg.HUKS_ALG_ECC
765    },
766    {
767      tag: huks.HuksTag.HUKS_TAG_PURPOSE,
768      value: huks.HuksKeyPurpose.HUKS_KEY_PURPOSE_UNWRAP
769    },
770    {
771      tag: huks.HuksTag.HUKS_TAG_KEY_SIZE,
772      value: huks.HuksKeySize.HUKS_ECC_KEY_SIZE_256
773    },
774    {
775      tag: huks.HuksTag.HUKS_TAG_PADDING,
776      value: huks.HuksKeyPadding.HUKS_PADDING_NONE
777    },
778    {
779      tag: huks.HuksTag.HUKS_TAG_AUTH_STORAGE_LEVEL,
780      value: userIdStorageLevel,
781    }
782  ]
783}
784
785const genCallerEcdhParams: huks.HuksOptions = {
786  properties: [
787    {
788      tag: huks.HuksTag.HUKS_TAG_ALGORITHM,
789      value: huks.HuksKeyAlg.HUKS_ALG_ECC
790    },
791    {
792      tag: huks.HuksTag.HUKS_TAG_PURPOSE,
793      value: huks.HuksKeyPurpose.HUKS_KEY_PURPOSE_AGREE
794    },
795    {
796      tag: huks.HuksTag.HUKS_TAG_KEY_SIZE,
797      value: huks.HuksKeySize.HUKS_CURVE25519_KEY_SIZE_256
798    },
799    {
800      tag: huks.HuksTag.HUKS_TAG_AUTH_STORAGE_LEVEL,
801      value: userIdStorageLevel,
802    }
803  ]
804}
805
806const importParamsCallerKek: huks.HuksOptions = {
807  properties: [
808    {
809      tag: huks.HuksTag.HUKS_TAG_ALGORITHM,
810      value: huks.HuksKeyAlg.HUKS_ALG_AES
811    },
812    {
813      tag: huks.HuksTag.HUKS_TAG_PURPOSE,
814      value: huks.HuksKeyPurpose.HUKS_KEY_PURPOSE_ENCRYPT
815    },
816    {
817      tag: huks.HuksTag.HUKS_TAG_KEY_SIZE,
818      value: huks.HuksKeySize.HUKS_AES_KEY_SIZE_256
819    },
820    {
821      tag: huks.HuksTag.HUKS_TAG_PADDING,
822      value: huks.HuksKeyPadding.HUKS_PADDING_NONE
823    },
824    {
825      tag: huks.HuksTag.HUKS_TAG_BLOCK_MODE,
826      value: huks.HuksCipherMode.HUKS_MODE_GCM
827    },
828    {
829      tag: huks.HuksTag.HUKS_TAG_DIGEST,
830      value: huks.HuksKeyDigest.HUKS_DIGEST_NONE
831    },
832    {
833      tag: huks.HuksTag.HUKS_TAG_IV,
834      value: StringToUint8Array(initializationVector)
835    },
836    {
837      tag: huks.HuksTag.HUKS_TAG_AUTH_STORAGE_LEVEL,
838      value: userIdStorageLevel,
839    }
840  ],
841  inData: StringToUint8Array(callerAes256Kek)
842}
843
844const importParamsAgreeKey: huks.HuksOptions = {
845  properties: [
846    {
847      tag: huks.HuksTag.HUKS_TAG_ALGORITHM,
848      value: huks.HuksKeyAlg.HUKS_ALG_AES
849    },
850    {
851      tag: huks.HuksTag.HUKS_TAG_PURPOSE,
852      value: huks.HuksKeyPurpose.HUKS_KEY_PURPOSE_ENCRYPT
853    },
854    {
855      tag: huks.HuksTag.HUKS_TAG_KEY_SIZE,
856      value: huks.HuksKeySize.HUKS_AES_KEY_SIZE_256
857    },
858    {
859      tag: huks.HuksTag.HUKS_TAG_PADDING,
860      value: huks.HuksKeyPadding.HUKS_PADDING_NONE
861    },
862    {
863      tag: huks.HuksTag.HUKS_TAG_BLOCK_MODE,
864      value: huks.HuksCipherMode.HUKS_MODE_GCM
865    },
866    {
867      tag: huks.HuksTag.HUKS_TAG_DIGEST,
868      value: huks.HuksKeyDigest.HUKS_DIGEST_NONE
869    },
870    {
871      tag: huks.HuksTag.HUKS_TAG_IV,
872      value: StringToUint8Array(initializationVector)
873    },
874    {
875      tag: huks.HuksTag.HUKS_TAG_AUTH_STORAGE_LEVEL,
876      value: userIdStorageLevel,
877    }
878  ]
879}
880
881const callerAgreeParams: huks.HuksOptions = {
882  properties: [
883    {
884      tag: huks.HuksTag.HUKS_TAG_ALGORITHM,
885      value: huks.HuksKeyAlg.HUKS_ALG_ECDH
886    },
887    {
888      tag: huks.HuksTag.HUKS_TAG_PURPOSE,
889      value: huks.HuksKeyPurpose.HUKS_KEY_PURPOSE_AGREE
890    },
891    {
892      tag: huks.HuksTag.HUKS_TAG_KEY_SIZE,
893      value: huks.HuksKeySize.HUKS_CURVE25519_KEY_SIZE_256
894    },
895    {
896      tag: huks.HuksTag.HUKS_TAG_AUTH_STORAGE_LEVEL,
897      value: userIdStorageLevel,
898    }
899  ]
900}
901
902const encryptKeyCommonParams: huks.HuksOptions = {
903  properties: [
904    {
905      tag: huks.HuksTag.HUKS_TAG_ALGORITHM,
906      value: huks.HuksKeyAlg.HUKS_ALG_AES
907    },
908    {
909      tag: huks.HuksTag.HUKS_TAG_PURPOSE,
910      value: huks.HuksKeyPurpose.HUKS_KEY_PURPOSE_ENCRYPT
911    },
912    {
913      tag: huks.HuksTag.HUKS_TAG_KEY_SIZE,
914      value: huks.HuksKeySize.HUKS_AES_KEY_SIZE_256
915    },
916    {
917      tag: huks.HuksTag.HUKS_TAG_PADDING,
918      value: huks.HuksKeyPadding.HUKS_PADDING_NONE
919    },
920    {
921      tag: huks.HuksTag.HUKS_TAG_BLOCK_MODE,
922      value: huks.HuksCipherMode.HUKS_MODE_GCM
923    },
924    {
925      tag: huks.HuksTag.HUKS_TAG_NONCE,
926      value: StringToUint8Array(nonce)
927    },
928    {
929      tag: huks.HuksTag.HUKS_TAG_ASSOCIATED_DATA,
930      value: StringToUint8Array(associatedData)
931    },
932    {
933      tag: huks.HuksTag.HUKS_TAG_AUTH_STORAGE_LEVEL,
934      value: userIdStorageLevel,
935    }
936  ]
937}
938
939const importWrappedAes192Params: huks.HuksOptions = {
940  properties: [
941    {
942      tag: huks.HuksTag.HUKS_TAG_ALGORITHM,
943      value: huks.HuksKeyAlg.HUKS_ALG_AES
944    },
945    {
946      tag: huks.HuksTag.HUKS_TAG_PURPOSE,
947      value: huks.HuksKeyPurpose.HUKS_KEY_PURPOSE_ENCRYPT |
948      huks.HuksKeyPurpose.HUKS_KEY_PURPOSE_DECRYPT
949    },
950    {
951      tag: huks.HuksTag.HUKS_TAG_KEY_SIZE,
952      value: huks.HuksKeySize.HUKS_AES_KEY_SIZE_192
953    },
954    {
955      tag: huks.HuksTag.HUKS_TAG_PADDING,
956      value: huks.HuksKeyPadding.HUKS_PADDING_NONE
957    },
958    {
959      tag: huks.HuksTag.HUKS_TAG_BLOCK_MODE,
960      value: huks.HuksCipherMode.HUKS_MODE_CBC
961    },
962    {
963      tag: huks.HuksTag.HUKS_TAG_DIGEST,
964      value: huks.HuksKeyDigest.HUKS_DIGEST_NONE
965    },
966    {
967      tag: huks.HuksTag.HUKS_TAG_UNWRAP_ALGORITHM_SUITE,
968      value: huks.HuksUnwrapSuite.HUKS_UNWRAP_SUITE_ECDH_AES_256_GCM_NOPADDING
969    },
970    {
971      tag: huks.HuksTag.HUKS_TAG_IV,
972      value: StringToUint8Array(initializationVector)
973    },
974    {
975      tag: huks.HuksTag.HUKS_TAG_AUTH_STORAGE_LEVEL,
976      value: userIdStorageLevel,
977    }
978  ]
979}
980
981async function PublicImportKeyItemFunc(
982  userId: number,
983  keyAlias: string, huksOptions: huks.HuksOptions) {
984  console.info(`enter promise importKeyItemAsUser`);
985  try {
986    await huks.importKeyItemAsUser(userId, keyAlias, huksOptions)
987      .then(data => {
988        console.info(`promise: importKeyItemAsUser success, data = ${JSON.stringify(data)}`);
989      }).catch((err: BusinessError) => {
990        console.error(`promise: importKeyItemAsUser failed, code: ${err.code}, msg: ${err.message}`);
991      })
992  } catch (err) {
993    console.error(`promise: importKeyItemAsUser input arg invalid, code: ${err.code}, msg: ${err.message}`);
994  }
995}
996
997async function PublicDeleteKeyItemFunc(
998  userId: number,
999  keyAlias: string, huksOptions: huks.HuksOptions) {
1000  console.info(`enter promise deleteKeyItemAsUser`);
1001  try {
1002    await huks.deleteKeyItemAsUser(userId, keyAlias, huksOptions)
1003      .then(data => {
1004        console.info(`promise: deleteKeyItemAsUser key success, data = ${JSON.stringify(data)}`);
1005      })
1006      .catch((err: BusinessError) => {
1007        console.error(`promise: deleteKeyItemAsUser failed, code: ${err.code}, msg: ${err.message}`);
1008      })
1009  } catch (err) {
1010    console.error(`promise: deleteKeyItemAsUser input arg invalid, code: ${err.code}, msg: ${err.message}`);
1011  }
1012}
1013
1014async function PublicImportWrappedKeyFunc(
1015  userId: number,
1016  keyAlias: string, wrappingKeyAlias: string, huksOptions: huks.HuksOptions) {
1017  console.info(`enter callback importWrappedKeyItemAsUser`);
1018  console.info(`publicImportWrappedKeyFunc huksOptions = ${JSON.stringify(huksOptions)}`);
1019  try {
1020    await huks.importWrappedKeyItemAsUser(userId, keyAlias, wrappingKeyAlias, huksOptions)
1021      .then((data) => {
1022        console.info(`callback: importWrappedKeyItemAsUser success, data = ${JSON.stringify(data)}`);
1023        console.info(`importWrappedKeyItemAsUser 成功 data = ${JSON.stringify(data)}`)
1024      })
1025      .catch((err: BusinessError) => {
1026        console.error(`callback: importWrappedKeyItemAsUser failed, code: ${err.code}, msg: ${err.message}`);
1027      });
1028  } catch (error) {
1029    console.error(`callback: importWrappedKeyItemAsUser input arg invalid, code: ${error.code}, msg: ${error.message}`);
1030  }
1031}
1032
1033async function PublicInitFunc(
1034  userId: number,
1035  srcKeyAlias: string, huksOptions: huks.HuksOptions) {
1036  let handle: number = 0;
1037  console.info(`enter promise doInit`);
1038  try {
1039    await huks.initSessionAsUser(userId, srcKeyAlias, huksOptions)
1040      .then((data) => {
1041        console.info(`promise: initSessionAsUser success, data = ${JSON.stringify(data)}`);
1042        handle = data.handle;
1043      })
1044      .catch((err: BusinessError) => {
1045        console.error(`promise: initSessionAsUser key failed, code: ${err.code}, msg: ${err.message}`);
1046      });
1047  } catch (error) {
1048    console.error(`promise: doInit input arg invalid, code: ${error.code}, msg: ${error.message}`);
1049  }
1050  return handle;
1051}
1052
1053async function PublicUpdateSessionFunction(handle: number, huksOptions: huks.HuksOptions) {
1054  if (huksOptions?.inData?.length == undefined) {
1055    return [];
1056  }
1057  const maxUpdateSize = 64;
1058  const inData = huksOptions.inData;
1059  const lastInDataPosition = inData.length - 1;
1060  let inDataSegSize = maxUpdateSize;
1061  let inDataSegPosition = 0;
1062  let isFinished = false;
1063  let outData: Array<number> = [];
1064
1065  while (inDataSegPosition <= lastInDataPosition) {
1066    if (inDataSegPosition + maxUpdateSize > lastInDataPosition) {
1067      isFinished = true;
1068      inDataSegSize = lastInDataPosition - inDataSegPosition + 1;
1069      console.info(`enter promise doUpdate`);
1070      break;
1071    }
1072    huksOptions.inData = new Uint8Array(
1073      Array.from(inData).slice(inDataSegPosition, inDataSegPosition + inDataSegSize)
1074    );
1075    console.info(`enter promise doUpdate`);
1076    try {
1077      await huks.updateSession(handle, huksOptions)
1078        .then((data) => {
1079          console.info(`promise: doUpdate success, data = ${JSON.stringify(data)}`);
1080          if (data.outData == undefined) {
1081            console.error('data.outData is undefined');
1082            return;
1083          }
1084          outData = outData.concat(Array.from(data.outData));
1085        })
1086        .catch((err: BusinessError) => {
1087          console.error(`promise: doUpdate failed, code: ${err.code}, msg: ${err.message}`);
1088        });
1089    } catch (error) {
1090      console.error(`promise: doUpdate input arg invalid, code: ${error.code}, msg: ${error.message}`);
1091    }
1092    if ((!isFinished) && (inDataSegPosition + maxUpdateSize > lastInDataPosition)) {
1093      console.error(`update size invalid isFinished = ${isFinished}`);
1094      console.error(`inDataSegPosition = ${inDataSegPosition}`);
1095      console.error(`lastInDataPosition = ${lastInDataPosition}`);
1096      return [];
1097    }
1098    inDataSegPosition += maxUpdateSize;
1099  }
1100  return outData;
1101}
1102
1103async function PublicFinishSession(handle: number, huksOptions: huks.HuksOptions, inData: Array<number>) {
1104  let outData: Array<number> = [];
1105  console.info(`enter promise doFinish`);
1106  try {
1107    await huks.finishSession(handle, huksOptions)
1108      .then((data) => {
1109        console.info(`promise: doFinish success, data = ${JSON.stringify(data)}`);
1110        if (data.outData == undefined) {
1111          console.error('data.outData is undefined');
1112          return;
1113        }
1114        outData = inData.concat(Array.from(data.outData));
1115      })
1116      .catch((err: BusinessError) => {
1117        console.error(`promise: doFinish key failed, code: ${err.code}, msg: ${err.message}`);
1118      });
1119  } catch (error) {
1120    console.error(`promise: doFinish input arg invalid, code: ${error.code}, msg: ${error.message}`);
1121  }
1122  return new Uint8Array(outData);
1123}
1124
1125async function CipherFunction(
1126  userId: number,
1127  keyAlias: string, huksOptions: huks.HuksOptions) {
1128  const handle = await PublicInitFunc(userId, keyAlias, huksOptions);
1129  const tmpData = await PublicUpdateSessionFunction(handle, huksOptions);
1130  const outData = await PublicFinishSession(handle, huksOptions, tmpData);
1131  return outData;
1132}
1133
1134async function AgreeFunction(
1135  userId: number,
1136  keyAlias: string, huksOptions: huks.HuksOptions, huksPublicKey: Uint8Array) {
1137  const handle = await PublicInitFunc(userId, keyAlias, huksOptions);
1138  let outSharedKey: Uint8Array = new Uint8Array;
1139  huksOptions.inData = huksPublicKey;
1140  console.info(`enter promise doUpdate`);
1141  try {
1142    await huks.updateSession(handle, huksOptions)
1143      .then((data) => {
1144        console.info(`promise: doUpdate success, data = ${JSON.stringify(data)}`);
1145      })
1146      .catch((err: BusinessError) => {
1147        console.error(`promise: doUpdate failed, code: ${err.code}, msg: ${err.message}`);
1148      });
1149  } catch (error) {
1150    console.error(`promise: doUpdate input arg invalid, code: ${error.code}, msg: ${error.message}`);
1151  }
1152  console.info(`enter promise doInit`);
1153  try {
1154    await huks.finishSession(handle, huksOptions)
1155      .then((data) => {
1156        console.info(`promise: doInit success, data = ${JSON.stringify(data)}`);
1157        if (data.outData == undefined) {
1158          console.error('data.outData is undefined');
1159          return;
1160        }
1161        outSharedKey = data.outData;
1162      })
1163      .catch((err: BusinessError) => {
1164        console.error(`promise: doInit key failed, code: ${err.code}, msg: ${err.message}`);
1165      });
1166  } catch (error) {
1167    console.error(`promise: doInit input arg invalid, code: ${error.code}, msg: ${error.message}`);
1168  }
1169  return outSharedKey;
1170}
1171
1172async function ImportKekAndAgreeSharedSecret(
1173  userId: number,
1174  callerKekAlias: string, importKekParams: huks.HuksOptions,
1175  callerKeyAlias: string, huksPublicKey: Uint8Array, agreeParams: huks.HuksOptions) {
1176  await PublicImportKeyItemFunc(userId, callerKekAlias, importKekParams);
1177
1178  importParamsAgreeKey.inData = await AgreeFunction(userId, callerKeyAlias, agreeParams, huksPublicKey);
1179
1180  await PublicImportKeyItemFunc(userId, callerAgreeKeyAliasAes256, importParamsAgreeKey);
1181}
1182
1183async function GenerateAndExportPublicKey(
1184  userId: number,
1185  keyAlias: string, huksOptions: huks.HuksOptions): Promise<Uint8Array> {
1186  try {
1187    await huks.generateKeyItemAsUser(userId, keyAlias, huksOptions)
1188      .then(data => {
1189        console.info(`promise: generateKeyItemAsUser success, data = ${JSON.stringify(data)}`);
1190      })
1191      .catch((err: BusinessError) => {
1192        console.error(`callback: generateKeyItemAsUser failed, code: ${err.code}, msg: ${err.message}`);
1193      })
1194  } catch (err) {
1195    console.error(`callback: generateKeyItemAsUser invalid, code: ${err.code}, msg: ${err.message}`);
1196  }
1197
1198
1199  let result = new Uint8Array([])
1200  try {
1201    await huks.exportKeyItemAsUser(userId, keyAlias, huksOptions)
1202      .then((data) => {
1203        console.info(`promise: exportKeyItemAsUser success, data = ${JSON.stringify(data)}`);
1204        if (data.outData == undefined) {
1205          console.error('data.outData is undefined');
1206          return;
1207        }
1208        result = data.outData;
1209      })
1210      .catch((err: BusinessError) => {
1211        console.error(`promise: exportKeyItemAsUser failed, code: ${err.code}, msg: ${err.message}`);
1212      });
1213  } catch (e) {
1214    console.error(`promise: generate pubKey failed, code: ${e.code}, msg: ${e.message}`);
1215  }
1216  return result
1217}
1218
1219interface KeyEncAndKekEnc {
1220  outPlainKeyEncData: Uint8Array,
1221  outKekEncData: Uint8Array,
1222  outKekEncTag: Uint8Array,
1223  outAgreeKeyEncTag: Uint8Array,
1224}
1225
1226async function EncryptImportedPlainKeyAndKek(
1227  userId: number,
1228  keyAlias: string): Promise<KeyEncAndKekEnc> {
1229  encryptKeyCommonParams.inData = StringToUint8Array(keyAlias)
1230  const plainKeyEncData = await CipherFunction(userId, callerKekAliasAes256, encryptKeyCommonParams);
1231  const result: KeyEncAndKekEnc = {
1232    outPlainKeyEncData: new Uint8Array([]),
1233    outKekEncData: new Uint8Array([]),
1234    outKekEncTag: new Uint8Array([]),
1235    outAgreeKeyEncTag: new Uint8Array([]),
1236  }
1237  result.outKekEncTag = SubUint8ArrayOf(plainKeyEncData, plainKeyEncData.length - tagSize, plainKeyEncData.length)
1238  result.outPlainKeyEncData = SubUint8ArrayOf(plainKeyEncData, 0, plainKeyEncData.length - tagSize)
1239
1240  encryptKeyCommonParams.inData = StringToUint8Array(callerAes256Kek)
1241  const kekEncData = await CipherFunction(userId, callerAgreeKeyAliasAes256, encryptKeyCommonParams)
1242  result.outAgreeKeyEncTag = SubUint8ArrayOf(kekEncData, kekEncData.length - tagSize, kekEncData.length)
1243  result.outKekEncData = SubUint8ArrayOf(kekEncData, 0, kekEncData.length - tagSize)
1244
1245  return result
1246}
1247
1248async function BuildWrappedDataAndImportWrappedKey(plainKey: string, huksPubKey: Uint8Array,
1249  callerSelfPublicKey: Uint8Array, encData: KeyEncAndKekEnc) {
1250  const plainKeySizeBuff = new Uint8Array(4);
1251  AssignLength(plainKey.length, plainKeySizeBuff, 0);
1252
1253  const wrappedData = new Uint8Array(
1254    unsignedInt32Bytes + huksPubKey.length +
1255      unsignedInt32Bytes + associatedData.length +
1256      unsignedInt32Bytes + nonce.length +
1257      unsignedInt32Bytes + tagSize +
1258      unsignedInt32Bytes + encData.outKekEncData.length +
1259      unsignedInt32Bytes + associatedData.length +
1260      unsignedInt32Bytes + nonce.length +
1261      unsignedInt32Bytes + tagSize +
1262      unsignedInt32Bytes + plainKeySizeBuff.length +
1263      unsignedInt32Bytes + encData.outPlainKeyEncData.length
1264  );
1265  let index = 0;
1266  const associatedDataArray = StringToUint8Array(associatedData);
1267  const nonceArray = StringToUint8Array(nonce);
1268
1269  index += AssignLength(callerSelfPublicKey.length, wrappedData, index); // 4
1270  index += AssignData(callerSelfPublicKey, wrappedData, index); // 91
1271  index += AssignLength(associatedDataArray.length, wrappedData, index); // 4
1272  index += AssignData(associatedDataArray, wrappedData, index); // 16
1273  index += AssignLength(nonceArray.length, wrappedData, index); // 4
1274  index += AssignData(nonceArray, wrappedData, index); // 12
1275  index += AssignLength(encData.outAgreeKeyEncTag.length, wrappedData, index); // 4
1276  index += AssignData(encData.outAgreeKeyEncTag, wrappedData, index); // 16
1277  index += AssignLength(encData.outKekEncData.length, wrappedData, index); // 4
1278  index += AssignData(encData.outKekEncData, wrappedData, index); // 32
1279  index += AssignLength(associatedDataArray.length, wrappedData, index); // 4
1280  index += AssignData(associatedDataArray, wrappedData, index); // 16
1281  index += AssignLength(nonceArray.length, wrappedData, index); // 4
1282  index += AssignData(nonceArray, wrappedData, index); // 12
1283  index += AssignLength(encData.outKekEncTag.length, wrappedData, index); // 4
1284  index += AssignData(encData.outKekEncTag, wrappedData, index); // 16
1285  index += AssignLength(plainKeySizeBuff.length, wrappedData, index); // 4
1286  index += AssignData(plainKeySizeBuff, wrappedData, index); // 4
1287  index += AssignLength(encData.outPlainKeyEncData.length, wrappedData, index); // 4
1288  index += AssignData(encData.outPlainKeyEncData, wrappedData, index); // 24
1289
1290  return wrappedData;
1291}
1292
1293export async function HuksSecurityImportTest(userId: number) {
1294  const srcKeyAliasWrap = 'HUKS_Basic_Capability_Import_0200';
1295  const huksPubKey: Uint8Array = await GenerateAndExportPublicKey(userId, srcKeyAliasWrap, genWrappingKeyParams);
1296  const callerSelfPublicKey: Uint8Array = await GenerateAndExportPublicKey(userId, callerKeyAlias, genCallerEcdhParams);
1297
1298  await ImportKekAndAgreeSharedSecret(
1299    userId,
1300    callerKekAliasAes256, importParamsCallerKek, callerKeyAlias, huksPubKey, callerAgreeParams);
1301  const encData: KeyEncAndKekEnc = await EncryptImportedPlainKeyAndKek(userId, importedAes192PlainKey);
1302  const wrappedData =
1303    await BuildWrappedDataAndImportWrappedKey(importedAes192PlainKey, huksPubKey, callerSelfPublicKey, encData);
1304  importWrappedAes192Params.inData = wrappedData;
1305  await PublicImportWrappedKeyFunc(userId,
1306    importedKeyAliasAes192, srcKeyAliasWrap, importWrappedAes192Params);
1307  await PublicDeleteKeyItemFunc(userId, srcKeyAliasWrap, genWrappingKeyParams);
1308  await PublicDeleteKeyItemFunc(userId, callerKeyAlias, genCallerEcdhParams);
1309  await PublicDeleteKeyItemFunc(userId, importedKeyAliasAes192, importWrappedAes192Params);
1310  await PublicDeleteKeyItemFunc(userId, callerKekAliasAes256, callerAgreeParams);
1311}
1312
1313export default function HuksAsUserTest() {
1314  console.info('begin huks as user test')
1315
1316  const userId = 100;
1317  HuksSecurityImportTest(userId)
1318}
1319```
1320
1321## huks.exportKeyItemAsUser
1322
1323exportKeyItemAsUser(userId: number, keyAlias: string, huksOptions: HuksOptions) : Promise\<HuksReturnResult>
1324
1325指定用户身份导出密钥,使用Promise方式回调异步返回的结果。
1326
1327**系统接口**:此接口为系统接口。
1328
1329**需要权限**: ohos.permission.INTERACT_ACROSS_LOCAL_ACCOUNTS
1330
1331**系统能力**:SystemCapability.Security.Huks.Extension
1332
1333**参数:**
1334
1335| 参数名   | 类型                        | 必填 | 说明                                         |
1336| -------- | --------------------------- | ---- | -------------------------------------------- |
1337| userId   | number                      | 是   | 用户ID。                 |
1338| keyAlias | string                      | 是   | 密钥别名,应与所用密钥生成时使用的别名相同。 |
1339| huksOptions  | [HuksOptions](js-apis-huks.md#huksoptions) | 是   | 空对象(此处传空即可)。                     |
1340
1341**返回值:**
1342
1343| 类型                                           | 说明                                                         |
1344| ---------------------------------------------- | ------------------------------------------------------------ |
1345| Promise<[HuksReturnResult](js-apis-huks.md#huksreturnresult9)> | Promise对象。 当调用成功时,HuksReturnResult的outData成员非空,为从密钥中导出的公钥,否则为失败。 |
1346
1347**错误码:**
1348
1349以下错误码的详细介绍请参见[HUKS错误码](errorcode-huks.md)。
1350
1351| 错误码ID | 错误信息      |
1352| -------- | ------------- |
1353| 201 | the application permission is not sufficient, which may be caused by lack of cross-account permission, or the system has not been unlocked by user, or the user does not exist. |
1354| 202 | non-system applications are not allowed to use system APIs. |
1355| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified. 2. Incorrect parameter types. 3. Parameter verification failed. |
1356| 801 | api is not supported. |
1357| 12000001 | algorithm mode is not supported. |
1358| 12000002 | algorithm param is missing. |
1359| 12000003 | algorithm param is invalid. |
1360| 12000004 | operating file failed. |
1361| 12000005 | IPC communication failed. |
1362| 12000006 | error occurred in crypto engine. |
1363| 12000011 | queried entity does not exist. |
1364| 12000012 | Device environment or input parameter abnormal. |
1365| 12000014 | memory is insufficient. |
1366
1367**示例:**
1368
1369- 以下代码示例接口调用的前置条件同上文[generateKeyItemAsUser](#huksgeneratekeyitemasuser)的前置条件
1370
1371```ts
1372import { huks } from '@kit.UniversalKeystoreKit';
1373import { BusinessError } from "@kit.BasicServicesKit"
1374
1375const rsaKeyAlias = 'test_rsaKeyAlias';
1376const userId = 100;
1377const userIdStorageLevel = huks.HuksAuthStorageLevel.HUKS_AUTH_STORAGE_LEVEL_CE;
1378
1379function GetRSA4096GenerateProperties(): Array<huks.HuksParam> {
1380  return [{
1381    tag: huks.HuksTag.HUKS_TAG_ALGORITHM,
1382    value: huks.HuksKeyAlg.HUKS_ALG_RSA
1383  }, {
1384    tag: huks.HuksTag.HUKS_TAG_KEY_SIZE,
1385    value: huks.HuksKeySize.HUKS_RSA_KEY_SIZE_4096
1386  }, {
1387    tag: huks.HuksTag.HUKS_TAG_PURPOSE,
1388    value: huks.HuksKeyPurpose.HUKS_KEY_PURPOSE_ENCRYPT |
1389    huks.HuksKeyPurpose.HUKS_KEY_PURPOSE_DECRYPT
1390  }, {
1391    tag: huks.HuksTag.HUKS_TAG_DIGEST,
1392    value: huks.HuksKeyDigest.HUKS_DIGEST_SHA256
1393  }, {
1394    tag: huks.HuksTag.HUKS_TAG_PADDING,
1395    value: huks.HuksKeyPadding.HUKS_PADDING_PKCS1_V1_5
1396  }, {
1397    tag: huks.HuksTag.HUKS_TAG_BLOCK_MODE,
1398    value: huks.HuksCipherMode.HUKS_MODE_ECB
1399  }, {
1400    tag: huks.HuksTag.HUKS_TAG_AUTH_STORAGE_LEVEL,
1401    value: userIdStorageLevel,
1402  }]
1403}
1404
1405async function GenerateKey(keyAlias: string, genProperties: Array<huks.HuksParam>) {
1406  const options: huks.HuksOptions = {
1407    properties: genProperties
1408  }
1409  await huks.generateKeyItemAsUser(userId, keyAlias, options).then((data) => {
1410    console.info("成功生成了一个别名为:" + keyAlias + " 的密钥")
1411  }).catch((err: BusinessError) => {
1412    console.error("密钥生成失败,错误码是: " + err.code + " 错误码信息: " + err.message)
1413  })
1414}
1415
1416async function ExportPublicKey(keyAlias: string) {
1417  const options: huks.HuksOptions = {
1418    properties: [{
1419      tag: huks.HuksTag.HUKS_TAG_AUTH_STORAGE_LEVEL,
1420      value: userIdStorageLevel,
1421    }]
1422  }
1423  await huks.exportKeyItemAsUser(userId, keyAlias, options).then((data) => {
1424    console.info("成功将别名为:" + keyAlias + " 的公钥导出, data 的长度为" + data?.outData?.length)
1425  }).catch((err: BusinessError) => {
1426    console.error("密钥导出失败,错误码是: " + err.code + " 错误码信息: " + err.message)
1427  })
1428}
1429
1430async function ExportHuksTest() {
1431  await GenerateKey(rsaKeyAlias, GetRSA4096GenerateProperties())
1432  await ExportPublicKey(rsaKeyAlias)
1433}
1434
1435export default function HuksAsUserTest() {
1436  console.info('begin huks as user test')
1437  ExportHuksTest()
1438}
1439```
1440
1441## huks.getKeyItemPropertiesAsUser
1442
1443getKeyItemPropertiesAsUser(userId: number, keyAlias: string, huksOptions: HuksOptions) : Promise\<HuksReturnResult>
1444
1445指定用户身份获取密钥属性,使用Promise回调异步返回结果。
1446
1447**系统接口**:此接口为系统接口。
1448
1449**需要权限**: ohos.permission.INTERACT_ACROSS_LOCAL_ACCOUNTS
1450
1451**系统能力**:SystemCapability.Security.Huks.Extension
1452
1453**参数:**
1454
1455| 参数名   | 类型                        | 必填 | 说明                                         |
1456| -------- | --------------------------- | ---- | -------------------------------------------- |
1457| userId   | number                      | 是   | 用户ID。                 |
1458| keyAlias | string                      | 是   | 密钥别名,应与所用密钥生成时使用的别名相同。 |
1459| huksOptions  | [HuksOptions](js-apis-huks.md#huksoptions) | 是   | 空对象(此处传空即可)。                     |
1460
1461**返回值:**
1462
1463| 类型                                            | 说明                                                         |
1464| ----------------------------------------------- | ------------------------------------------------------------ |
1465| Promise\<[HuksReturnResult](js-apis-huks.md#huksreturnresult9)> | Promise对象。当调用成功时,HuksReturnResult的properties成员非空,为生成密钥时所需参数,否则为失败。
1466
1467**错误码:**
1468
1469以下错误码的详细介绍请参见[HUKS错误码](errorcode-huks.md)。
1470
1471| 错误码ID | 错误信息      |
1472| -------- | ------------- |
1473| 201 | the application permission is not sufficient, which may be caused by lack of cross-account permission, or the system has not been unlocked by user, or the user does not exist. |
1474| 202 | non-system applications are not allowed to use system APIs. |
1475| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified. 2. Incorrect parameter types. 3. Parameter verification failed. |
1476| 801 | api is not supported. |
1477| 12000001 | algorithm mode is not supported. |
1478| 12000002 | algorithm param is missing. |
1479| 12000003 | algorithm param is invalid. |
1480| 12000004 | operating file failed. |
1481| 12000005 | IPC communication failed. |
1482| 12000006 | error occurred in crypto engine. |
1483| 12000011 | queried entity does not exist. |
1484| 12000012 | Device environment or input parameter abnormal. |
1485| 12000014 | memory is insufficient. |
1486
1487**示例:**
1488
1489- 以下代码示例接口调用的前置条件同上文[generateKeyItemAsUser](#huksgeneratekeyitemasuser)的前置条件
1490
1491```ts
1492import { huks } from '@kit.UniversalKeystoreKit';
1493import { BusinessError } from "@kit.BasicServicesKit"
1494
1495const aesKeyAlias = 'test_aesKeyAlias';
1496const userId = 100;
1497const userIdStorageLevel = huks.HuksAuthStorageLevel.HUKS_AUTH_STORAGE_LEVEL_CE;
1498
1499function GetAesGenerateProperties(): Array<huks.HuksParam> {
1500  return [{
1501    tag: huks.HuksTag.HUKS_TAG_ALGORITHM,
1502    value: huks.HuksKeyAlg.HUKS_ALG_AES
1503  }, {
1504    tag: huks.HuksTag.HUKS_TAG_KEY_SIZE,
1505    value: huks.HuksKeySize.HUKS_AES_KEY_SIZE_128
1506  }, {
1507    tag: huks.HuksTag.HUKS_TAG_PURPOSE,
1508    value: huks.HuksKeyPurpose.HUKS_KEY_PURPOSE_ENCRYPT |
1509    huks.HuksKeyPurpose.HUKS_KEY_PURPOSE_DECRYPT
1510  }, {
1511    tag: huks.HuksTag.HUKS_TAG_PADDING,
1512    value: huks.HuksKeyPadding.HUKS_PADDING_PKCS7
1513  }, {
1514    tag: huks.HuksTag.HUKS_TAG_BLOCK_MODE,
1515    value: huks.HuksCipherMode.HUKS_MODE_CBC
1516  }, {
1517    tag: huks.HuksTag.HUKS_TAG_AUTH_STORAGE_LEVEL,
1518    value: userIdStorageLevel,
1519  }]
1520}
1521
1522async function GenerateKey(keyAlias: string, genProperties: Array<huks.HuksParam>) {
1523  const options: huks.HuksOptions = {
1524    properties: genProperties
1525  }
1526  await huks.generateKeyItemAsUser(userId, keyAlias, options).then((data) => {
1527    console.info("成功生成了一个别名为:" + keyAlias + " 的密钥")
1528  }).catch((err: BusinessError) => {
1529    console.error("密钥生成失败,错误码是: " + err.code + " 错误码信息: " + err.message)
1530  })
1531}
1532
1533async function GetKeyProperties(keyAlias: string) {
1534  const options: huks.HuksOptions = {
1535    properties: [{
1536      tag: huks.HuksTag.HUKS_TAG_AUTH_STORAGE_LEVEL,
1537      value: userIdStorageLevel,
1538    }]
1539  }
1540  await huks.getKeyItemPropertiesAsUser(userId, keyAlias, options).then((data) => {
1541    console.info("获取密钥属性成功!属性为: " + JSON.stringify(data))
1542  }).catch((err: BusinessError) => {
1543    console.error("获取密钥属性失败,错误码是: " + err.code + " 错误码信息: " + err.message)
1544  })
1545}
1546
1547async function TestHuksGet() {
1548  await GenerateKey(aesKeyAlias, GetAesGenerateProperties())
1549  await GetKeyProperties(aesKeyAlias)
1550}
1551
1552export default function HuksAsUserTest() {
1553  console.info('begin huks as user test')
1554  TestHuksGet()
1555}
1556```
1557
1558## huks.hasKeyItemAsUser
1559
1560hasKeyItemAsUser(userId: number, keyAlias: string, huksOptions: HuksOptions) : Promise\<boolean>
1561
1562指定用户身份判断密钥是否存在,使用Promise回调异步返回结果。
1563
1564**系统接口**:此接口为系统接口。
1565
1566**需要权限**: ohos.permission.INTERACT_ACROSS_LOCAL_ACCOUNTS
1567
1568**系统能力**:SystemCapability.Security.Huks.Extension
1569
1570**参数:**
1571
1572| 参数名   | 类型                        | 必填 | 说明                     |
1573| -------- | --------------------------- | ---- | ------------------------ |
1574| userId   | number                      | 是   | 用户ID。                 |
1575| keyAlias | string                      | 是   | 所需查找的密钥的别名。   |
1576| huksOptions  | [HuksOptions](js-apis-huks.md#huksoptions) | 是   | 用于查询时指定密钥的属性TAG,如使用[HuksAuthStorageLevel](js-apis-huks.md#huksauthstoragelevel11)指定需查询密钥的安全级别,<br>可传空,当API version ≥ 12时,传空默认为CE,当API version < 12时,传空默认为DE。     |
1577
1578**返回值:**
1579
1580| 类型              | 说明                                    |
1581| ----------------- | --------------------------------------- |
1582| Promise\<boolean> | Promise对象。若密钥存在,返回值为true,若密钥不存在,返回值为false。 |
1583
1584**错误码:**
1585
1586以下错误码的详细介绍请参见[HUKS错误码](errorcode-huks.md)。
1587
1588| 错误码ID | 错误信息      |
1589| -------- | ------------- |
1590| 201 | the application permission is not sufficient, which may be caused by lack of cross-account permission, or the system has not been unlocked by user, or the user does not exist. |
1591| 202 | non-system applications are not allowed to use system APIs. |
1592| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified. 2. Incorrect parameter types. 3. Parameter verification failed. |
1593| 801 | api is not supported. |
1594| 12000002 | algorithm param is missing. |
1595| 12000003 | algorithm param is invalid. |
1596| 12000004 | operating file failed. |
1597| 12000005 | IPC communication failed. |
1598| 12000006 | error occurred in crypto engine. |
1599| 12000012 | Device environment or input parameter abnormal. |
1600| 12000014 | memory is insufficient. |
1601
1602**示例:**
1603
1604- 以下代码示例接口调用的前置条件同上文[generateKeyItemAsUser](#huksgeneratekeyitemasuser)的前置条件
1605
1606```ts
1607import { huks } from '@kit.UniversalKeystoreKit';
1608import { BusinessError } from "@kit.BasicServicesKit"
1609
1610const aesKeyAlias = 'test_aesKeyAlias';
1611const userId = 100;
1612const userIdStorageLevel = huks.HuksAuthStorageLevel.HUKS_AUTH_STORAGE_LEVEL_CE;
1613
1614function GetAesGenerateProperties(): Array<huks.HuksParam> {
1615  return [{
1616    tag: huks.HuksTag.HUKS_TAG_ALGORITHM,
1617    value: huks.HuksKeyAlg.HUKS_ALG_AES
1618  }, {
1619    tag: huks.HuksTag.HUKS_TAG_KEY_SIZE,
1620    value: huks.HuksKeySize.HUKS_AES_KEY_SIZE_128
1621  }, {
1622    tag: huks.HuksTag.HUKS_TAG_PURPOSE,
1623    value: huks.HuksKeyPurpose.HUKS_KEY_PURPOSE_ENCRYPT |
1624    huks.HuksKeyPurpose.HUKS_KEY_PURPOSE_DECRYPT
1625  }, {
1626    tag: huks.HuksTag.HUKS_TAG_PADDING,
1627    value: huks.HuksKeyPadding.HUKS_PADDING_PKCS7
1628  }, {
1629    tag: huks.HuksTag.HUKS_TAG_BLOCK_MODE,
1630    value: huks.HuksCipherMode.HUKS_MODE_CBC
1631  }, {
1632    tag: huks.HuksTag.HUKS_TAG_AUTH_STORAGE_LEVEL,
1633    value: userIdStorageLevel,
1634  }]
1635}
1636
1637async function GenerateKey(keyAlias: string, genProperties: Array<huks.HuksParam>) {
1638  const options: huks.HuksOptions = {
1639    properties: genProperties
1640  }
1641  await huks.generateKeyItemAsUser(userId, keyAlias, options).then((data) => {
1642    console.info("成功生成了一个别名为:" + keyAlias + " 的密钥")
1643  }).catch((err: BusinessError) => {
1644    console.error("密钥生成失败,错误码是: " + err.code + " 错误码信息: " + err.message)
1645  })
1646}
1647
1648async function HasKey(keyAlias: string) {
1649  const options: huks.HuksOptions = {
1650    properties: [{
1651      tag: huks.HuksTag.HUKS_TAG_AUTH_STORAGE_LEVEL,
1652      value: userIdStorageLevel,
1653    }]
1654  }
1655  await huks.hasKeyItemAsUser(userId, keyAlias, options).then((data) => {
1656    console.info("别名为: " + keyAlias + "的密钥查询存在结果" + JSON.stringify(data))
1657  }).catch((err: BusinessError) => {
1658    console.error("密钥查询失败,错误码是: " + err.code + " 错误码信息: " + err.message)
1659  })
1660}
1661
1662async function TestHuksHasKey() {
1663  await GenerateKey(aesKeyAlias, GetAesGenerateProperties())
1664  await HasKey(aesKeyAlias)
1665}
1666
1667export default function HuksAsUserTest() {
1668  console.info('begin huks as user test')
1669  TestHuksHasKey()
1670}
1671```
1672
1673## huks.initSessionAsUser
1674
1675initSessionAsUser(userId: number, keyAlias: string, huksOptions: HuksOptions) : Promise\<HuksSessionHandle>
1676
1677指定用户身份操作密钥接口,使用Promise方式异步返回结果。huks.initSessionAsUser, huks.updateSession, huks.finishSession为三段式接口,需要一起使用。
1678
1679**系统接口**:此接口为系统接口。
1680
1681**需要权限**: ohos.permission.INTERACT_ACROSS_LOCAL_ACCOUNTS
1682
1683**系统能力**:SystemCapability.Security.Huks.Extension
1684
1685**参数:**
1686
1687| 参数名   | 类型                                              | 必填 | 说明                                             |
1688| -------- | ------------------------------------------------- | ---- | ------------------------------------------------ |
1689| userId   | number                                            | 是   | 用户ID。                 |
1690| keyAlias | string                                            | 是   | initSessionAsUser操作密钥的别名。                             |
1691| huksOptions  | [HuksOptions](js-apis-huks.md#huksoptions)        | 是   | initSessionAsUser参数集合。                                   |
1692
1693**返回值**:
1694
1695| 类型                                | 说明                                               |
1696| ----------------------------------- | -------------------------------------------------- |
1697| Promise\<[HuksSessionHandle](js-apis-huks.md#hukssessionhandle9)> | Promise对象。将initSessionAsUser操作返回的handle添加到密钥管理系统的回调。 |
1698
1699**错误码:**
1700
1701以下错误码的详细介绍请参见[HUKS错误码](errorcode-huks.md)。
1702
1703| 错误码ID | 错误信息      |
1704| -------- | ------------- |
1705| 201 | the application permission is not sufficient, which may be caused by lack of cross-account permission, or the system has not been unlocked by user, or the user does not exist. |
1706| 202 | non-system applications are not allowed to use system APIs. |
1707| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified. 2. Incorrect parameter types. 3. Parameter verification failed. |
1708| 801 | api is not supported. |
1709| 12000001 | algorithm mode is not supported. |
1710| 12000002 | algorithm param is missing. |
1711| 12000003 | algorithm param is invalid. |
1712| 12000004 | operating file failed. |
1713| 12000005 | IPC communication failed. |
1714| 12000006 | error occurred in crypto engine. |
1715| 12000010 | the number of sessions has reached limit. |
1716| 12000011 | queried entity does not exist. |
1717| 12000012 | Device environment or input parameter abnormal. |
1718| 12000014 | memory is insufficient. |
1719
1720**示例:**
1721
1722- 以下代码示例接口调用的前置条件同上文[generateKeyItemAsUser](#huksgeneratekeyitemasuser)的前置条件
1723- 注意:下文密码学相关的变量(如initializationVector)赋值,均为参考样例,不能直接适用于业务功能逻辑。开发者需要根据自身场景使用合适的初始值。
1724
1725```ts
1726import { huks } from '@kit.UniversalKeystoreKit';
1727import { BusinessError } from "@kit.BasicServicesKit"
1728
1729const aesKeyAlias = 'test_aesKeyAlias';
1730const userId = 100;
1731const userIdStorageLevel = huks.HuksAuthStorageLevel.HUKS_AUTH_STORAGE_LEVEL_CE;
1732const initializationVector = '001122334455';
1733const plainText = '123456789';
1734
1735function StringToUint8Array(str: string) {
1736  let arr: number[] = [];
1737  for (let i = 0, j = str.length; i < j; ++i) {
1738    arr.push(str.charCodeAt(i));
1739  }
1740  return new Uint8Array(arr);
1741}
1742
1743function Uint8ArrayToString(fileData: Uint8Array) {
1744  let dataString = '';
1745  for (let i = 0; i < fileData.length; i++) {
1746    dataString += String.fromCharCode(fileData[i]);
1747  }
1748  return dataString;
1749}
1750
1751function GetAesGenerateProperties(): Array<huks.HuksParam> {
1752  return [{
1753    tag: huks.HuksTag.HUKS_TAG_ALGORITHM,
1754    value: huks.HuksKeyAlg.HUKS_ALG_AES
1755  }, {
1756    tag: huks.HuksTag.HUKS_TAG_KEY_SIZE,
1757    value: huks.HuksKeySize.HUKS_AES_KEY_SIZE_128
1758  }, {
1759    tag: huks.HuksTag.HUKS_TAG_PURPOSE,
1760    value: huks.HuksKeyPurpose.HUKS_KEY_PURPOSE_ENCRYPT |
1761    huks.HuksKeyPurpose.HUKS_KEY_PURPOSE_DECRYPT
1762  }, {
1763    tag: huks.HuksTag.HUKS_TAG_PADDING,
1764    value: huks.HuksKeyPadding.HUKS_PADDING_PKCS7
1765  }, {
1766    tag: huks.HuksTag.HUKS_TAG_BLOCK_MODE,
1767    value: huks.HuksCipherMode.HUKS_MODE_CBC
1768  }, {
1769    tag: huks.HuksTag.HUKS_TAG_AUTH_STORAGE_LEVEL,
1770    value: userIdStorageLevel,
1771  }]
1772}
1773
1774function GetAesEncryptProperties(): Array<huks.HuksParam> {
1775  return [{
1776    tag: huks.HuksTag.HUKS_TAG_ALGORITHM,
1777    value: huks.HuksKeyAlg.HUKS_ALG_AES
1778  }, {
1779    tag: huks.HuksTag.HUKS_TAG_KEY_SIZE,
1780    value: huks.HuksKeySize.HUKS_AES_KEY_SIZE_128
1781  }, {
1782    tag: huks.HuksTag.HUKS_TAG_PURPOSE,
1783    value: huks.HuksKeyPurpose.HUKS_KEY_PURPOSE_ENCRYPT
1784  }, {
1785    tag: huks.HuksTag.HUKS_TAG_PADDING,
1786    value: huks.HuksKeyPadding.HUKS_PADDING_PKCS7
1787  }, {
1788    tag: huks.HuksTag.HUKS_TAG_BLOCK_MODE,
1789    value: huks.HuksCipherMode.HUKS_MODE_CBC
1790  }, {
1791    tag: huks.HuksTag.HUKS_TAG_IV,
1792    value: StringToUint8Array(initializationVector)
1793  }, {
1794    tag: huks.HuksTag.HUKS_TAG_AUTH_STORAGE_LEVEL,
1795    value: userIdStorageLevel,
1796  }]
1797}
1798
1799function GetAesDecryptProperties(): Array<huks.HuksParam> {
1800  return [{
1801    tag: huks.HuksTag.HUKS_TAG_ALGORITHM,
1802    value: huks.HuksKeyAlg.HUKS_ALG_AES
1803  }, {
1804    tag: huks.HuksTag.HUKS_TAG_KEY_SIZE,
1805    value: huks.HuksKeySize.HUKS_AES_KEY_SIZE_128
1806  }, {
1807    tag: huks.HuksTag.HUKS_TAG_PURPOSE,
1808    value: huks.HuksKeyPurpose.HUKS_KEY_PURPOSE_DECRYPT
1809  }, {
1810    tag: huks.HuksTag.HUKS_TAG_PADDING,
1811    value: huks.HuksKeyPadding.HUKS_PADDING_PKCS7
1812  }, {
1813    tag: huks.HuksTag.HUKS_TAG_BLOCK_MODE,
1814    value: huks.HuksCipherMode.HUKS_MODE_CBC
1815  }, {
1816    tag: huks.HuksTag.HUKS_TAG_IV,
1817    value: StringToUint8Array(initializationVector)
1818  }, {
1819    tag: huks.HuksTag.HUKS_TAG_AUTH_STORAGE_LEVEL,
1820    value: userIdStorageLevel,
1821  }]
1822}
1823
1824async function GenerateKey(keyAlias: string, genProperties: Array<huks.HuksParam>) {
1825  const options: huks.HuksOptions = {
1826    properties: genProperties
1827  }
1828  await huks.generateKeyItemAsUser(userId, keyAlias, options).then((data) => {
1829    console.info("成功生成了一个别名为:" + keyAlias + " 的密钥")
1830  }).catch((err: BusinessError) => {
1831    console.error("密钥生成失败,错误码是: " + err.code + " 错误码信息: " + err.message)
1832  })
1833}
1834
1835async function EncryptData(keyAlias: string, encryptProperties: Array<huks.HuksParam>): Promise<Uint8Array> {
1836  const options: huks.HuksOptions = {
1837    properties: encryptProperties,
1838    inData: StringToUint8Array(plainText)
1839  }
1840  let handle: number = 0;
1841  let cipherData: Uint8Array = new Uint8Array([]);
1842  await huks.initSessionAsUser(userId, keyAlias, options).then((data) => {
1843    handle = data.handle;
1844  }).catch((err: BusinessError) => {
1845    console.error("密钥初始化失败,错误码是: " + err.code + " 错误码信息: " + err.message)
1846  })
1847  await huks.finishSession(handle, options).then((data) => {
1848    console.info("加密数据成功, 密文是: " + Uint8ArrayToString(data.outData))
1849    if (data.outData != undefined) {
1850      cipherData = data.outData
1851    }
1852    console.info("running time result success!")
1853  }).catch((err: BusinessError) => {
1854    console.error("加密流程捕获了异常,错误码是: " + err.code + " 错误码信息: " + err.message)
1855  })
1856  return cipherData
1857}
1858
1859async function DecryptData(keyAlias: string, decryptProperties: Array<huks.HuksParam>, cipherData: Uint8Array) {
1860  const options: huks.HuksOptions = {
1861    properties: decryptProperties,
1862    inData: cipherData
1863  }
1864  let handle: number = 0;
1865  await huks.initSessionAsUser(userId, keyAlias, options).then((data) => {
1866    handle = data.handle;
1867  }).catch((err: BusinessError) => {
1868    console.error("密钥初始化失败,错误码是: " + err.code + " 错误码信息: " + err.message)
1869  })
1870  await huks.finishSession(handle, options).then((data) => {
1871    console.info("解密成功, 解密的明文是: " + Uint8ArrayToString(data.outData))
1872  }).catch((err: BusinessError) => {
1873    console.error("解密流程捕获了异常,错误码是: " + err.code + " 错误码信息: " + err.message)
1874  })
1875}
1876
1877async function TestHuksInit() {
1878  await GenerateKey(aesKeyAlias, GetAesGenerateProperties())
1879  let cipherData: Uint8Array = await EncryptData(aesKeyAlias, GetAesEncryptProperties())
1880  await DecryptData(aesKeyAlias, GetAesDecryptProperties(), cipherData)
1881}
1882
1883export default function HuksAsUserTest() {
1884  console.info('begin huks as user test')
1885  TestHuksInit()
1886}
1887```
1888