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