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