1# @ohos.security.huks (HUKS) 2 3The **HUKS** module provides KeyStore (KS) capabilities for applications, including key management and key cryptography operations. 4The keys managed by OpenHarmony Universal KeyStore (HUKS) can be imported by applications or generated by calling the HUKS APIs. 5 6> **NOTE** 7> 8> The initial APIs of this module are supported since API version 8. Newly added APIs will be marked with a superscript to indicate their earliest API version. 9 10## Modules to Import 11 12```js 13import huks from '@ohos.security.huks' 14``` 15 16## HuksParam 17 18Defines the **param** in the **properties** array of **options** used in the APIs. 19 20**System capability**: SystemCapability.Security.Huks 21 22| Name| Type | Mandatory| Description | 23| ------ | ----------------------------------- | ---- | ------------ | 24| tag | [HuksTag](#hukstag) | Yes | Tag. | 25| value | boolean\|number\|bigint\|Uint8Array | Yes | Value of the tag.| 26 27## HuksOptions 28 29Defines the **options** used in the APIs. 30 31**System capability**: SystemCapability.Security.Huks 32 33| Name | Type | Mandatory| Description | 34| ---------- | ----------------- | ---- | ------------------------ | 35| properties | Array\<[HuksParam](#huksparam)> | No | Properties used to hold the **HuksParam** array.| 36| inData | Uint8Array | No | Input data. | 37 38## HuksSessionHandle<sup>9+</sup> 39 40Defines the HUKS handle structure. 41 42**System capability**: SystemCapability.Security.Huks 43 44| Name | Type | Mandatory| Description | 45| --------- | ---------- | ---- | ---------------------------------------------------- | 46| handle | number | Yes | Value of the handle. | 47| challenge | Uint8Array | No | Challenge obtained after the [initSession](#huksinitsession9) operation.| 48 49## HuksReturnResult<sup>9+</sup> 50 51Defines the **HuksResult** structure. 52 53**System capability**: SystemCapability.Security.Huks 54 55 56 57| Name | Type | Mandatory| Description | 58| ---------- | ------------------------------- | ---- | ---------------- | 59| outData | Uint8Array | No | Output data. | 60| properties | Array\<[HuksParam](#huksparam)> | No | Property information. | 61| certChains | Array\<string> | No | Certificate chain information.| 62 63 64## huks.generateKeyItem<sup>9+</sup> 65 66generateKeyItem(keyAlias: string, options: HuksOptions, callback: AsyncCallback\<void>) : void 67 68Generates a key. This API uses an asynchronous callback to return the result. 69 70**System capability**: SystemCapability.Security.Huks 71 72**Parameters** 73 74| Name | Type | Mandatory| Description | 75| -------- | --------------------------- | ---- | --------------------------------------------- | 76| keyAlias | string | Yes | Alias of the key. | 77| options | [HuksOptions](#huksoptions) | Yes | Tags required for generating the key. The algorithm, key purpose, and key length are mandatory.| 78| callback | AsyncCallback\<void> | Yes | Callback invoked to return the result. If the operation is successful, no **err** value is returned; otherwise, an error code is returned.| 79 80**Example** 81 82```js 83/* Generate an ECC key of 256 bits. */ 84let keyAlias = 'keyAlias'; 85let properties = new Array(); 86properties[0] = { 87 tag: huks.HuksTag.HUKS_TAG_ALGORITHM, 88 value: huks.HuksKeyAlg.HUKS_ALG_ECC 89}; 90properties[1] = { 91 tag: huks.HuksTag.HUKS_TAG_KEY_SIZE, 92 value: huks.HuksKeySize.HUKS_ECC_KEY_SIZE_256 93}; 94properties[2] = { 95 tag: huks.HuksTag.HUKS_TAG_PURPOSE, 96 value: 97 huks.HuksKeyPurpose.HUKS_KEY_PURPOSE_SIGN | 98 huks.HuksKeyPurpose.HUKS_KEY_PURPOSE_VERIFY 99}; 100properties[3] = { 101 tag: huks.HuksTag.HUKS_TAG_DIGEST, 102 value: huks.HuksKeyDigest.HUKS_DIGEST_SHA256 103}; 104let options = { 105 properties: properties 106}; 107try { 108 huks.generateKeyItem(keyAlias, options, function (error, data) { 109 if (error) { 110 console.error(`callback: generateKeyItem failed, code: ${error.code}, msg: ${error.message}`); 111 } else { 112 console.info(`callback: generateKeyItem key success`); 113 } 114 }); 115} catch (error) { 116 console.error(`callback: generateKeyItem input arg invalid, code: ${error.code}, msg: ${error.message}`); 117} 118``` 119 120## huks.generateKeyItem<sup>9+</sup> 121 122generateKeyItem(keyAlias: string, options: HuksOptions) : Promise\<void> 123 124Generates a key. This API uses a promise to return the result. 125 126**System capability**: SystemCapability.Security.Huks 127 128**Parameters** 129 130| Name | Type | Mandatory| Description | 131| -------- | --------------------------- | ---- | ------------------------ | 132| keyAlias | string | Yes | Alias of the key. | 133| options | [HuksOptions](#huksoptions) | Yes | Tags required for generating the key. The algorithm, key purpose, and key length are mandatory.| 134 135**Example** 136 137```js 138/* Generate an ECC key of 256 bits. */ 139let keyAlias = 'keyAlias'; 140let properties = new Array(); 141properties[0] = { 142 tag: huks.HuksTag.HUKS_TAG_ALGORITHM, 143 value: huks.HuksKeyAlg.HUKS_ALG_ECC 144}; 145properties[1] = { 146 tag: huks.HuksTag.HUKS_TAG_KEY_SIZE, 147 value: huks.HuksKeySize.HUKS_ECC_KEY_SIZE_256 148}; 149properties[2] = { 150 tag: huks.HuksTag.HUKS_TAG_PURPOSE, 151 value: 152 huks.HuksKeyPurpose.HUKS_KEY_PURPOSE_SIGN | 153 huks.HuksKeyPurpose.HUKS_KEY_PURPOSE_VERIFY 154}; 155properties[3] = { 156 tag: huks.HuksTag.HUKS_TAG_DIGEST, 157 value: huks.HuksKeyDigest.HUKS_DIGEST_SHA256 158}; 159let options = { 160 properties: properties 161}; 162try { 163 huks.generateKeyItem(keyAlias, options) 164 .then((data) => { 165 console.info(`promise: generateKeyItem success`); 166 }) 167 .catch(error => { 168 console.error(`promise: generateKeyItem failed, code: ${error.code}, msg: ${error.message}`); 169 }); 170} catch (error) { 171 console.error(`promise: generateKeyItem input arg invalid, code: ${error.code}, msg: ${error.message}`); 172} 173``` 174 175## huks.deleteKeyItem<sup>9+</sup> 176 177deleteKeyItem(keyAlias: string, options: HuksOptions, callback: AsyncCallback\<void>) : void 178 179Deletes a key. This API uses an asynchronous callback to return the result. 180 181**System capability**: SystemCapability.Security.Huks 182 183**Parameters** 184 185| Name | Type | Mandatory| Description | 186| -------- | --------------------------- | ---- | --------------------------------------------- | 187| keyAlias | string | Yes | Key alias passed in when the key was generated. | 188| options | [HuksOptions](#huksoptions) | Yes | Empty object (leave this parameter empty). | 189| callback | AsyncCallback\<void> | Yes | Callback invoked to return the result. If the operation is successful, no **err** value is returned; otherwise, an error code is returned.| 190 191**Example** 192 193```js 194/* Set options to emptyOptions. */ 195let keyAlias = 'keyAlias'; 196let emptyOptions = { 197 properties: [] 198}; 199try { 200 huks.deleteKeyItem(keyAlias, emptyOptions, function (error, data) { 201 if (error) { 202 console.error(`callback: deleteKeyItem failed, code: ${error.code}, msg: ${error.message}`); 203 } else { 204 console.info(`callback: deleteKeyItem key success`); 205 } 206 }); 207} catch (error) { 208 console.error(`callback: deleteKeyItem input arg invalid, code: ${error.code}, msg: ${error.message}`); 209} 210``` 211 212## huks.deleteKeyItem<sup>9+</sup> 213 214deleteKeyItem(keyAlias: string, options: HuksOptions) : Promise\<void> 215 216Deletes a key. This API uses a promise to return the result. 217 218**System capability**: SystemCapability.Security.Huks 219 220**Parameters** 221 222| Name | Type | Mandatory| Description | 223| -------- | --------------------------- | ---- | ----------------------------------- | 224| keyAlias | string | Yes | Key alias passed in when the key was generated.| 225| options | [HuksOptions](#huksoptions) | Yes | Empty object (leave this parameter empty). | 226 227**Example** 228 229```js 230/* Set options to emptyOptions. */ 231let keyAlias = 'keyAlias'; 232let emptyOptions = { 233 properties: [] 234}; 235try { 236 huks.deleteKeyItem(keyAlias, emptyOptions) 237 .then ((data) => { 238 console.info(`promise: deleteKeyItem key success`); 239 }) 240 .catch(error => { 241 console.error(`promise: deleteKeyItem failed, code: ${error.code}, msg: ${error.message}`); 242 }); 243} catch (error) { 244 console.error(`promise: deleteKeyItem input arg invalid, code: ${error.code}, msg: ${error.message}`); 245} 246``` 247 248## huks.getSdkVersion 249 250getSdkVersion(options: HuksOptions) : string 251 252Obtains the SDK version of the current system. 253 254**System capability**: SystemCapability.Security.Huks 255 256**Parameters** 257 258| Name | Type | Mandatory| Description | 259| ------- | ---------- | ---- | ------------------------- | 260| options | [HuksOptions](#huksoptions) | Yes | Empty object, which is used to hold the SDK version.| 261 262**Return value** 263 264| Type | Description | 265| ------ | ------------- | 266| string | SDK version obtained.| 267 268**Example** 269 270```js 271/* Set options to emptyOptions. */ 272let emptyOptions = { 273 properties: [] 274}; 275let result = huks.getSdkVersion(emptyOptions); 276``` 277 278## huks.importKeyItem<sup>9+</sup> 279 280importKeyItem(keyAlias: string, options: HuksOptions, callback: AsyncCallback\<void>) : void 281 282Imports a key in plaintext. This API uses an asynchronous callback to return the result. 283 284**System capability**: SystemCapability.Security.Huks 285 286**Parameters** 287 288| Name | Type | Mandatory| Description | 289| -------- | --------------------------- | ---- | --------------------------------------------- | 290| keyAlias | string | Yes | Alias of the key. | 291| options | [HuksOptions](#huksoptions) | Yes | Tags required for the import and key to import. The algorithm, key purpose, and key length are mandatory.| 292| callback | AsyncCallback\<void> | Yes | Callback invoked to return the result. If the operation is successful, no **err** value is returned; otherwise, an error code is returned.| 293 294**Example** 295 296```js 297/* Import an AES key of 256 bits. */ 298let plainTextSize32 = makeRandomArr(32); 299function makeRandomArr(size) { 300 let arr = new Uint8Array(size); 301 for (let i = 0; i < size; i++) { 302 arr[i] = Math.floor(Math.random() * 10); 303 } 304 return arr; 305}; 306let keyAlias = 'keyAlias'; 307let properties = new Array(); 308properties[0] = { 309 tag: huks.HuksTag.HUKS_TAG_ALGORITHM, 310 value: huks.HuksKeyAlg.HUKS_ALG_AES 311}; 312properties[1] = { 313 tag: huks.HuksTag.HUKS_TAG_KEY_SIZE, 314 value: huks.HuksKeySize.HUKS_AES_KEY_SIZE_256 315}; 316properties[2] = { 317 tag: huks.HuksTag.HUKS_TAG_PURPOSE, 318 value: 319 huks.HuksKeyPurpose.HUKS_KEY_PURPOSE_ENCRYPT | huks.HuksKeyPurpose.HUKS_KEY_PURPOSE_DECRYPT 320}; 321properties[3] = { 322 tag: huks.HuksTag.HUKS_TAG_PADDING, 323 value:huks.HuksKeyPadding.HUKS_PADDING_PKCS7 324}; 325properties[4] = { 326 tag: huks.HuksTag.HUKS_TAG_BLOCK_MODE, 327 value: huks.HuksCipherMode.HUKS_MODE_ECB 328}; 329let options = { 330 properties: properties, 331 inData: plainTextSize32 332}; 333try { 334 huks.importKeyItem(keyAlias, options, function (error, data) { 335 if (error) { 336 console.error(`callback: importKeyItem failed, code: ${error.code}, msg: ${error.message}`); 337 } else { 338 console.info(`callback: importKeyItem success`); 339 } 340 }); 341} catch (error) { 342 console.error(`callback: importKeyItem input arg invalid, code: ${error.code}, msg: ${error.message}`); 343} 344``` 345 346## huks.importKeyItem<sup>9+</sup> 347 348importKeyItem(keyAlias: string, options: HuksOptions) : Promise\<void> 349 350Imports a key in plaintext. This API uses a promise to return the result. 351 352**System capability**: SystemCapability.Security.Huks 353 354**Parameters** 355 356| Name | Type | Mandatory| Description | 357| -------- | --------------------------- | ---- | ----------------------------------- | 358| keyAlias | string | Yes | Alias of the key. | 359| options | [HuksOptions](#huksoptions) | Yes | Tags required for the import and key to import. The algorithm, key purpose, and key length are mandatory.| 360 361**Example** 362 363```js 364/* Import an AES key of 128 bits. */ 365let plainTextSize32 = makeRandomArr(32); 366 367function makeRandomArr(size) { 368 let arr = new Uint8Array(size); 369 for (let i = 0; i < size; i++) { 370 arr[i] = Math.floor(Math.random() * 10); 371 } 372 return arr; 373}; 374 375/* Step 1 Generate a key. */ 376let keyAlias = 'keyAlias'; 377let properties = new Array(); 378properties[0] = { 379 tag: huks.HuksTag.HUKS_TAG_ALGORITHM, 380 value: huks.HuksKeyAlg.HUKS_ALG_AES 381}; 382properties[1] = { 383 tag: huks.HuksTag.HUKS_TAG_KEY_SIZE, 384 value: huks.HuksKeySize.HUKS_AES_KEY_SIZE_128 385}; 386properties[2] = { 387 tag: huks.HuksTag.HUKS_TAG_PURPOSE, 388 value: huks.HuksKeyPurpose.HUKS_KEY_PURPOSE_ENCRYPT | huks.HuksKeyPurpose.HUKS_KEY_PURPOSE_DECRYPT 389}; 390properties[3] = { 391 tag: huks.HuksTag.HUKS_TAG_PADDING, 392 value:huks.HuksKeyPadding.HUKS_PADDING_PKCS7 393}; 394properties[4] = { 395 tag: huks.HuksTag.HUKS_TAG_BLOCK_MODE, 396 value: huks.HuksCipherMode.HUKS_MODE_ECB 397}; 398let huksoptions = { 399 properties: properties, 400 inData: plainTextSize32 401}; 402try { 403 huks.importKeyItem(keyAlias, huksoptions) 404 .then ((data) => { 405 console.info(`promise: importKeyItem success`); 406 }) 407 .catch(error => { 408 console.error(`promise: importKeyItem failed, code: ${error.code}, msg: ${error.message}`); 409 }); 410} catch (error) { 411 console.error(`promise: importKeyItem input arg invalid, code: ${error.code}, msg: ${error.message}`); 412} 413``` 414 415## huks.attestKeyItem<sup>9+</sup> 416 417attestKeyItem(keyAlias: string, options: HuksOptions, callback: AsyncCallback\<HuksReturnResult>) : void 418 419Obtains the certificate used to verify a key. This API uses an asynchronous callback to return the result. 420 421**System capability**: SystemCapability.Security.Huks 422 423**Parameters** 424 425| Name | Type | Mandatory| Description | 426| -------- | ---------------------------------------------------- | ---- | --------------------------------------------- | 427| keyAlias | string | Yes | Alias of the key. The certificate to be obtained stores the key. | 428| options | [HuksOptions](#huksoptions) | Yes | Parameters and data required for obtaining the certificate. | 429| callback | AsyncCallback<[HuksReturnResult](#huksreturnresult9)> | Yes | Callback invoked to return the result. If the operation is successful, no **err** value is returned; otherwise, an error code is returned.| 430 431**Example** 432 433```js 434let securityLevel = stringToUint8Array('sec_level'); 435let challenge = stringToUint8Array('challenge_data'); 436let versionInfo = stringToUint8Array('version_info'); 437let keyAliasString = "key attest"; 438 439function stringToUint8Array(str) { 440 let arr = []; 441 for (let i = 0, j = str.length; i < j; ++i) { 442 arr.push(str.charCodeAt(i)); 443 } 444 let tmpUint8Array = new Uint8Array(arr); 445 return tmpUint8Array; 446} 447 448async function generateKey(alias) { 449 let properties = new Array(); 450 properties[0] = { 451 tag: huks.HuksTag.HUKS_TAG_ALGORITHM, 452 value: huks.HuksKeyAlg.HUKS_ALG_RSA 453 }; 454 properties[1] = { 455 tag: huks.HuksTag.HUKS_TAG_KEY_STORAGE_FLAG, 456 value: huks.HuksKeyStorageType.HUKS_STORAGE_PERSISTENT 457 }; 458 properties[2] = { 459 tag: huks.HuksTag.HUKS_TAG_KEY_SIZE, 460 value: huks.HuksKeySize.HUKS_RSA_KEY_SIZE_2048 461 }; 462 properties[3] = { 463 tag: huks.HuksTag.HUKS_TAG_PURPOSE, 464 value: huks.HuksKeyPurpose.HUKS_KEY_PURPOSE_VERIFY 465 }; 466 properties[4] = { 467 tag: huks.HuksTag.HUKS_TAG_DIGEST, 468 value: huks.HuksKeyDigest.HUKS_DIGEST_SHA256 469 }; 470 properties[5] = { 471 tag: huks.HuksTag.HUKS_TAG_PADDING, 472 value: huks.HuksKeyPadding.HUKS_PADDING_PSS 473 }; 474 properties[6] = { 475 tag: huks.HuksTag.HUKS_TAG_KEY_GENERATE_TYPE, 476 value: huks.HuksKeyGenerateType.HUKS_KEY_GENERATE_TYPE_DEFAULT 477 }; 478 properties[7] = { 479 tag: huks.HuksTag.HUKS_TAG_BLOCK_MODE, 480 value: huks.HuksCipherMode.HUKS_MODE_ECB 481 }; 482 let options = { 483 properties: properties 484 }; 485 486 try { 487 huks.generateKeyItem(alias, options, function (error, data) { 488 if (error) { 489 console.error(`callback: generateKeyItem failed, code: ${error.code}, msg: ${error.message}`); 490 } else { 491 console.info(`callback: generateKeyItem success`); 492 } 493 }); 494 } catch (error) { 495 console.error(`callback: generateKeyItem input arg invalid, code: ${error.code}, msg: ${error.message}`); 496 } 497} 498 499async function attestKey() { 500 let aliasString = keyAliasString; 501 let aliasUint8 = stringToUint8Array(aliasString); 502 let properties = new Array(); 503 properties[0] = { 504 tag: huks.HuksTag.HUKS_TAG_ATTESTATION_ID_SEC_LEVEL_INFO, 505 value: securityLevel 506 }; 507 properties[1] = { 508 tag: huks.HuksTag.HUKS_TAG_ATTESTATION_CHALLENGE, 509 value: challenge 510 }; 511 properties[2] = { 512 tag: huks.HuksTag.HUKS_TAG_ATTESTATION_ID_VERSION_INFO, 513 value: versionInfo 514 }; 515 properties[3] = { 516 tag: huks.HuksTag.HUKS_TAG_ATTESTATION_ID_ALIAS, 517 value: aliasUint8 518 }; 519 let options = { 520 properties: properties 521 }; 522 await generateKey(aliasString); 523 try { 524 huks.attestKeyItem(aliasString, options, function (error, data) { 525 if (error) { 526 console.error(`callback: attestKeyItem failed, code: ${error.code}, msg: ${error.message}`); 527 } else { 528 console.info(`callback: attestKeyItem success`); 529 } 530 }); 531 } catch (error) { 532 console.error(`callback: attestKeyItem input arg invalid, code: ${error.code}, msg: ${error.message}`); 533 } 534} 535``` 536 537## huks.attestKeyItem<sup>9+</sup> 538 539attestKeyItem(keyAlias: string, options: HuksOptions) : Promise\<HuksReturnResult> 540 541Obtains the certificate used to verify a key. This API uses a promise to return the result. 542 543**System capability**: SystemCapability.Security.Huks 544 545**Parameters** 546 547| Name | Type | Mandatory| Description | 548| -------- | --------------------------- | ---- | ------------------------------------ | 549| keyAlias | string | Yes | Alias of the key. The certificate to be obtained stores the key.| 550| options | [HuksOptions](#huksoptions) | Yes | Parameters and data required for obtaining the certificate. | 551 552**Return value** 553 554| Type | Description | 555| ---------------------------------------------- | --------------------------------------------- | 556| Promise<[HuksReturnResult](#huksreturnresult9)> | Promise used to return the result. If the operation is successful, no **err** value is returned; otherwise, an error code is returned.| 557 558**Example** 559 560```js 561let securityLevel = stringToUint8Array('sec_level'); 562let challenge = stringToUint8Array('challenge_data'); 563let versionInfo = stringToUint8Array('version_info'); 564let keyAliasString = "key attest"; 565 566function stringToUint8Array(str) { 567 let arr = []; 568 for (let i = 0, j = str.length; i < j; ++i) { 569 arr.push(str.charCodeAt(i)); 570 } 571 let tmpUint8Array = new Uint8Array(arr); 572 return tmpUint8Array; 573} 574 575async function generateKey(alias) { 576 let properties = new Array(); 577 properties[0] = { 578 tag: huks.HuksTag.HUKS_TAG_ALGORITHM, 579 value: huks.HuksKeyAlg.HUKS_ALG_RSA 580 }; 581 properties[1] = { 582 tag: huks.HuksTag.HUKS_TAG_KEY_STORAGE_FLAG, 583 value: huks.HuksKeyStorageType.HUKS_STORAGE_PERSISTENT 584 }; 585 properties[2] = { 586 tag: huks.HuksTag.HUKS_TAG_KEY_SIZE, 587 value: huks.HuksKeySize.HUKS_RSA_KEY_SIZE_2048 588 }; 589 properties[3] = { 590 tag: huks.HuksTag.HUKS_TAG_PURPOSE, 591 value: huks.HuksKeyPurpose.HUKS_KEY_PURPOSE_VERIFY 592 }; 593 properties[4] = { 594 tag: huks.HuksTag.HUKS_TAG_DIGEST, 595 value: huks.HuksKeyDigest.HUKS_DIGEST_SHA256 596 }; 597 properties[5] = { 598 tag: huks.HuksTag.HUKS_TAG_PADDING, 599 value: huks.HuksKeyPadding.HUKS_PADDING_PSS 600 }; 601 properties[6] = { 602 tag: huks.HuksTag.HUKS_TAG_KEY_GENERATE_TYPE, 603 value: huks.HuksKeyGenerateType.HUKS_KEY_GENERATE_TYPE_DEFAULT 604 }; 605 properties[7] = { 606 tag: huks.HuksTag.HUKS_TAG_BLOCK_MODE, 607 value: huks.HuksCipherMode.HUKS_MODE_ECB 608 }; 609 let options = { 610 properties: properties 611 }; 612 613 try { 614 await huks.generateKeyItem(alias, options) 615 .then((data) => { 616 console.info(`promise: generateKeyItem success`); 617 }) 618 .catch(error => { 619 console.error(`promise: generateKeyItem failed, code: ${error.code}, msg: ${error.message}`); 620 }); 621 } catch (error) { 622 console.error(`promise: generateKeyItem input arg invalid, code: ${error.code}, msg: ${error.message}`); 623 } 624} 625 626async function attestKey() { 627 let aliasString = keyAliasString; 628 let aliasUint8 = stringToUint8Array(aliasString); 629 let properties = new Array(); 630 properties[0] = { 631 tag: huks.HuksTag.HUKS_TAG_ATTESTATION_ID_SEC_LEVEL_INFO, 632 value: securityLevel 633 }; 634 properties[1] = { 635 tag: huks.HuksTag.HUKS_TAG_ATTESTATION_CHALLENGE, 636 value: challenge 637 }; 638 properties[2] = { 639 tag: huks.HuksTag.HUKS_TAG_ATTESTATION_ID_VERSION_INFO, 640 value: versionInfo 641 }; 642 properties[3] = { 643 tag: huks.HuksTag.HUKS_TAG_ATTESTATION_ID_ALIAS, 644 value: aliasUint8 645 }; 646 let options = { 647 properties: properties 648 }; 649 await generateKey(aliasString); 650 try { 651 await huks.attestKeyItem(aliasString, options) 652 .then ((data) => { 653 console.info(`promise: attestKeyItem success`); 654 }) 655 .catch(error => { 656 console.error(`promise: attestKeyItem failed, code: ${error.code}, msg: ${error.message}`); 657 }); 658 } catch (error) { 659 console.error(`promise: attestKeyItem input arg invalid, code: ${error.code}, msg: ${error.message}`); 660 } 661} 662``` 663 664## huks.importWrappedKeyItem<sup>9+</sup> 665 666importWrappedKeyItem(keyAlias: string, wrappingKeyAlias: string, options: HuksOptions, callback: AsyncCallback\<void>) : void 667 668Imports a wrapped key. This API uses an asynchronous callback to return the result. 669 670**System capability**: SystemCapability.Security.Huks 671 672**Parameters** 673 674| Name | Type | Mandatory| Description | 675| ---------------- | --------------------------- | ---- | --------------------------------------------- | 676| keyAlias | string | Yes | Alias of the wrapped key to import. | 677| wrappingKeyAlias | string | Yes | Alias of the data used to unwrap the key imported. | 678| options | [HuksOptions](#huksoptions) | Yes | Tags required for the import and the wrapped key to import. The algorithm, key purpose, and key length are mandatory.| 679| callback | AsyncCallback\<void> | Yes | Callback invoked to return the result. If the operation is successful, no **err** value is returned; otherwise, an error code is returned.| 680 681**Example** 682 683```js 684import huks from '@ohos.security.huks'; 685 686let exportWrappingKey; 687let alias1 = "importAlias"; 688let alias2 = "wrappingKeyAlias"; 689 690async function TestGenFunc(alias, options) { 691 try { 692 await genKey(alias, options) 693 .then((data) => { 694 console.info(`callback: generateKeyItem success`); 695 }) 696 .catch(error => { 697 console.error(`callback: generateKeyItem failed, code: ${error.code}, msg: ${error.message}`); 698 }); 699 } catch (error) { 700 console.error(`callback: generateKeyItem input arg invalid, code: ${error.code}, msg: ${error.message}`); 701 } 702} 703 704function genKey(alias, options) { 705 return new Promise((resolve, reject) => { 706 try { 707 huks.generateKeyItem(alias, options, function (error, data) { 708 if (error) { 709 reject(error); 710 } else { 711 resolve(data); 712 } 713 }); 714 } catch (error) { 715 throw(error); 716 } 717 }); 718} 719 720async function TestExportFunc(alias, options) { 721 try { 722 await exportKey(alias, options) 723 .then ((data) => { 724 console.info(`callback: exportKeyItem success, data = ${JSON.stringify(data)}`); 725 exportWrappingKey = data.outData; 726 }) 727 .catch(error => { 728 console.error(`callback: exportKeyItem failed, code: ${error.code}, msg: ${error.message}`); 729 }); 730 } catch (error) { 731 console.error(`callback: exportKeyItem input arg invalid, code: ${error.code}, msg: ${error.message}`); 732 } 733} 734 735function exportKey(alias, options) : Promise<huks.HuksReturnResult> { 736 return new Promise((resolve, reject) => { 737 try { 738 huks.exportKeyItem(alias, options, function (error, data) { 739 if (error) { 740 reject(error); 741 } else { 742 resolve(data); 743 } 744 }); 745 } catch (error) { 746 throw(error); 747 } 748 }); 749} 750 751async function TestImportWrappedFunc(alias, wrappingAlias, options) { 752 try { 753 await importWrappedKey(alias, wrappingAlias, options) 754 .then ((data) => { 755 console.info(`callback: importWrappedKeyItem success`); 756 }) 757 .catch(error => { 758 console.error(`callback: importWrappedKeyItem failed, code: ${error.code}, msg: ${error.message}`); 759 }); 760 } catch (error) { 761 console.error(`callback: importWrappedKeyItem input arg invalid, code: ${error.code}, msg: ${error.message}`); 762 } 763} 764 765function importWrappedKey(alias, wrappingAlias, options) { 766 return new Promise((resolve, reject) => { 767 try { 768 huks.importWrappedKeyItem(alias, wrappingAlias, options, function (error, data) { 769 if (error) { 770 reject(error); 771 } else { 772 resolve(data); 773 } 774 }); 775 } catch (error) { 776 throw(error); 777 } 778 }); 779} 780 781async function TestImportWrappedKeyFunc( 782 alias, 783 wrappingAlias, 784 genOptions, 785 importOptions 786) { 787 await TestGenFunc(wrappingAlias, genOptions); 788 await TestExportFunc(wrappingAlias, genOptions); 789 790 /*The following operations do not invoke the HUKS APIs, and the specific implementation is not provided here. 791 * For example, import **keyA**. 792 * 1. Use ECC to generate a public and private key pair **keyB**. The public key is **keyB_pub**, and the private key is **keyB_pri**. 793 * 2. Use **keyB_pri** and the public key obtained from **wrappingAlias** to negotiate the shared key **share_key**. 794 * 3. Randomly generate a key **kek** and use it to encrypt **keyA** with AES-GCM. During the encryption, record **nonce1**, **aad1**, ciphertext **keyA_enc**, and encrypted **tag1**. 795 * 4. Use **share_key** to encrypt **kek** with AES-GCM. During the encryption, record **nonce2**, **aad2**, ciphertext **kek_enc**, and encrypted **tag2**. 796 * 5. Generate the **importOptions.inData** field in the following format: 797 * keyB_pub length (4 bytes) + keyB_pub + aad2 length (4 bytes) + aad2 + 798 * nonce2 length (4 bytes) + nonce2 + tag2 length (4 bytes) + tag2 + 799 * kek_enc length (4 bytes) + kek_enc + aad1 length (4 bytes) + aad1 + 800 * nonce1 length (4 bytes) + nonce1 + tag1 length (4 bytes) + tag1 + 801 * Memory occupied by the keyA length (4 bytes) + keyA length + keyA_enc length (4 bytes) + keyA_enc 802 */ 803 let inputKey = new Uint8Array([0x02, 0x00, 0x00, 0x00]); 804 importOptions.inData = inputKey; 805 await TestImportWrappedFunc(alias, wrappingAlias, importOptions); 806} 807 808function makeGenerateOptions() { 809 let properties = new Array(); 810 properties[0] = { 811 tag: huks.HuksTag.HUKS_TAG_ALGORITHM, 812 value: huks.HuksKeyAlg.HUKS_ALG_ECC 813 }; 814 properties[1] = { 815 tag: huks.HuksTag.HUKS_TAG_KEY_SIZE, 816 value: huks.HuksKeySize.HUKS_ECC_KEY_SIZE_256 817 }; 818 properties[2] = { 819 tag: huks.HuksTag.HUKS_TAG_PURPOSE, 820 value: huks.HuksKeyPurpose.HUKS_KEY_PURPOSE_UNWRAP 821 }; 822 properties[3] = { 823 tag: huks.HuksTag.HUKS_TAG_DIGEST, 824 value: huks.HuksKeyDigest.HUKS_DIGEST_SHA256 825 }; 826 properties[4] = { 827 tag: huks.HuksTag.HUKS_TAG_IMPORT_KEY_TYPE, 828 value: huks.HuksImportKeyType.HUKS_KEY_TYPE_KEY_PAIR, 829 }; 830 let options = { 831 properties: properties 832 }; 833 return options; 834}; 835 836function makeImportOptions() { 837 let properties = new Array(); 838 properties[0] = { 839 tag: huks.HuksTag.HUKS_TAG_ALGORITHM, 840 value: huks.HuksKeyAlg.HUKS_ALG_AES 841 }; 842 properties[1] = { 843 tag: huks.HuksTag.HUKS_TAG_KEY_SIZE, 844 value: huks.HuksKeySize.HUKS_AES_KEY_SIZE_256 845 }; 846 properties[2] = { 847 tag: huks.HuksTag.HUKS_TAG_PURPOSE, 848 value: huks.HuksKeyPurpose.HUKS_KEY_PURPOSE_ENCRYPT | huks.HuksKeyPurpose.HUKS_KEY_PURPOSE_DECRYPT 849 }; 850 properties[3] = { 851 tag: huks.HuksTag.HUKS_TAG_BLOCK_MODE, 852 value: huks.HuksCipherMode.HUKS_MODE_CBC 853 }; 854 properties[4] = { 855 tag: huks.HuksTag.HUKS_TAG_PADDING, 856 value: huks.HuksKeyPadding.HUKS_PADDING_NONE 857 }; 858 properties[5] = { 859 tag: huks.HuksTag.HUKS_TAG_UNWRAP_ALGORITHM_SUITE, 860 value: huks.HuksUnwrapSuite.HUKS_UNWRAP_SUITE_ECDH_AES_256_GCM_NOPADDING 861 }; 862 let options = { 863 properties: properties 864 }; 865 return options; 866}; 867 868function huksImportWrappedKey() { 869 let genOptions = makeGenerateOptions(); 870 let importOptions = makeImportOptions(); 871 TestImportWrappedKeyFunc( 872 alias1, 873 alias2, 874 genOptions, 875 importOptions 876 ); 877} 878``` 879 880## huks.importWrappedKeyItem<sup>9+</sup> 881 882importWrappedKeyItem(keyAlias: string, wrappingKeyAlias: string, options: HuksOptions) : Promise\<void> 883 884Imports a wrapped key. This API uses a promise to return the result. 885 886**System capability**: SystemCapability.Security.Huks 887 888**Parameters** 889 890| Name | Type | Mandatory| Description | 891| ---------------- | --------------------------- | ---- | --------------------------------------------- | 892| keyAlias | string | Yes | Alias of the wrapped key to import. | 893| wrappingKeyAlias | string | Yes | Alias of the data used to unwrap the key imported. | 894| options | [HuksOptions](#huksoptions) | Yes | Tags required for the import and the wrapped key to import. The algorithm, key purpose, and key length are mandatory.| 895 896**Example** 897 898```js 899/* The process is similar as if a callback is used, except the following:*/ 900async function TestImportWrappedFunc(alias, wrappingAlias, options) { 901 try { 902 await huks.importWrappedKeyItem(alias, wrappingAlias, options) 903 .then ((data) => { 904 console.info(`promise: importWrappedKeyItem success`); 905 }) 906 .catch(error => { 907 console.error(`promise: importWrappedKeyItem failed, code: ${error.code}, msg: ${error.message}`); 908 }); 909 } catch (error) { 910 console.error(`promise: importWrappedKeyItem input arg invalid, code: ${error.code}, msg: ${error.message}`); 911 } 912} 913``` 914 915## huks.exportKeyItem<sup>9+</sup> 916 917exportKeyItem(keyAlias: string, options: HuksOptions, callback: AsyncCallback\<HuksReturnResult>) : void 918 919Exports a key. This API uses an asynchronous callback to return the result. 920 921**System capability**: SystemCapability.Security.Huks 922 923**Parameters** 924 925| Name | Type | Mandatory| Description | 926| -------- | ---------------------------------------------------- | ---- | ------------------------------------------------------------ | 927| keyAlias | string | Yes | Key alias, which must be the same as the alias used when the key was generated. | 928| options | [HuksOptions](#huksoptions) | Yes | Empty object (leave this parameter empty). | 929| callback | AsyncCallback<[HuksReturnResult](#huksreturnresult9)> | Yes | Callback invoked to return the result. If the operation is successful, no **err** value is returned; otherwise, an error code is returned. **outData** contains the public key exported.| 930 931**Example** 932 933```js 934/* Set options to emptyOptions. */ 935let keyAlias = 'keyAlias'; 936let emptyOptions = { 937 properties: [] 938}; 939try { 940 huks.exportKeyItem(keyAlias, emptyOptions, function (error, data) { 941 if (error) { 942 console.error(`callback: exportKeyItem failed, code: ${error.code}, msg: ${error.message}`); 943 } else { 944 console.info(`callback: exportKeyItem success, data = ${JSON.stringify(data)}`); 945 } 946 }); 947} catch (error) { 948 console.error(`callback: exportKeyItem input arg invalid, code: ${error.code}, msg: ${error.message}`); 949} 950``` 951 952## huks.exportKeyItem<sup>9+</sup> 953 954exportKeyItem(keyAlias: string, options: HuksOptions) : Promise\<HuksReturnResult> 955 956Exports a key. This API uses a promise to return the result. 957 958**System capability**: SystemCapability.Security.Huks 959 960**Parameters** 961 962| Name | Type | Mandatory| Description | 963| -------- | --------------------------- | ---- | -------------------------------------------- | 964| keyAlias | string | Yes | Key alias, which must be the same as the alias used when the key was generated.| 965| options | [HuksOptions](#huksoptions) | Yes | Empty object (leave this parameter empty). | 966 967**Return value** 968 969| Type | Description | 970| ---------------------------------------------- | ------------------------------------------------------------ | 971| Promise<[HuksReturnResult](#huksreturnresult9)> | Promise used to return the result. If the operation is successful, no **err** value is returned and **outData** contains the public key exported. If the operation fails, an error code is returned. | 972 973**Example** 974 975```js 976/* Set options to emptyOptions. */ 977let keyAlias = 'keyAlias'; 978let emptyOptions = { 979 properties: [] 980}; 981try { 982 huks.exportKeyItem(keyAlias, emptyOptions) 983 .then ((data) => { 984 console.info(`promise: exportKeyItem success, data = ${JSON.stringify(data)}`); 985 }) 986 .catch(error => { 987 console.error(`promise: exportKeyItem failed, code: ${error.code}, msg: ${error.message}`); 988 }); 989} catch (error) { 990 console.error(`promise: exportKeyItem input arg invalid, code: ${error.code}, msg: ${error.message}`); 991} 992``` 993 994## huks.getKeyItemProperties<sup>9+</sup> 995 996getKeyItemProperties(keyAlias: string, options: HuksOptions, callback: AsyncCallback\<HuksReturnResult>) : void 997 998Obtains key properties. This API uses an asynchronous callback to return the result. 999 1000**System capability**: SystemCapability.Security.Huks 1001 1002**Parameters** 1003 1004| Name | Type | Mandatory| Description | 1005| -------- | ---------------------------------------------------- | ---- | ------------------------------------------------------------ | 1006| keyAlias | string | Yes | Key alias, which must be the same as the alias used when the key was generated. | 1007| options | [HuksOptions](#huksoptions) | Yes | Empty object (leave this parameter empty). | 1008| callback | AsyncCallback<[HuksReturnResult](#huksreturnresult9)> | Yes | Callback invoked to return the result. If the operation is successful, no **err** value is returned and **properties** contains the parameters required for generating the key. If the operation fails, an error code is returned. | 1009 1010**Example** 1011 1012```js 1013/* Set options to emptyOptions. */ 1014let keyAlias = 'keyAlias'; 1015let emptyOptions = { 1016 properties: [] 1017}; 1018try { 1019 huks.getKeyItemProperties(keyAlias, emptyOptions, function (error, data) { 1020 if (error) { 1021 console.error(`callback: getKeyItemProperties failed, code: ${error.code}, msg: ${error.message}`); 1022 } else { 1023 console.info(`callback: getKeyItemProperties success, data = ${JSON.stringify(data)}`); 1024 } 1025 }); 1026} catch (error) { 1027 console.error(`callback: getKeyItemProperties input arg invalid, code: ${error.code}, msg: ${error.message}`); 1028} 1029``` 1030 1031## huks.getKeyItemProperties<sup>9+</sup> 1032 1033getKeyItemProperties(keyAlias: string, options: HuksOptions) : Promise\<HuksReturnResult> 1034 1035Obtains key properties. This API uses a promise to return the result. 1036 1037**System capability**: SystemCapability.Security.Huks 1038 1039**Parameters** 1040 1041| Name | Type | Mandatory| Description | 1042| -------- | --------------------------- | ---- | -------------------------------------------- | 1043| keyAlias | string | Yes | Key alias, which must be the same as the alias used when the key was generated.| 1044| options | [HuksOptions](#huksoptions) | Yes | Empty object (leave this parameter empty). | 1045 1046**Return value** 1047 1048| Type | Description | 1049| ----------------------------------------------- | ------------------------------------------------------------ | 1050| Promise\<[HuksReturnResult](#huksreturnresult9)> | Promise used to return the result. If the operation is successful, no **err** value is returned and **properties** contains the parameters required for generating the key. If the operation fails, an error code is returned. | 1051 1052**Example** 1053 1054```js 1055/* Set options to emptyOptions. */ 1056let keyAlias = 'keyAlias'; 1057let emptyOptions = { 1058 properties: [] 1059}; 1060try { 1061 huks.getKeyItemProperties(keyAlias, emptyOptions) 1062 .then ((data) => { 1063 console.info(`promise: getKeyItemProperties success, data = ${JSON.stringify(data)}`); 1064 }) 1065 .catch(error => { 1066 console.error(`promise: getKeyItemProperties failed, code: ${error.code}, msg: ${error.message}`); 1067 }); 1068} catch (error) { 1069 console.error(`promise: getKeyItemProperties input arg invalid, code: ${error.code}, msg: ${error.message}`); 1070} 1071``` 1072 1073## huks.isKeyItemExist<sup>9+</sup> 1074 1075isKeyItemExist(keyAlias: string, options: HuksOptions, callback: AsyncCallback\<boolean>) : void 1076 1077Checks whether a key exists. This API uses an asynchronous callback to return the result. 1078 1079**System capability**: SystemCapability.Security.Huks 1080 1081**Parameters** 1082 1083| Name | Type | Mandatory| Description | 1084| -------- | --------------------------- | ---- | --------------------------------------- | 1085| keyAlias | string | Yes | Alias of the key to check. | 1086| options | [HuksOptions](#huksoptions) | Yes | Empty object (leave this parameter empty). | 1087| callback | AsyncCallback\<boolean> | Yes | Callback invoked to return the result. The value **TRUE** means that the key exists; **FALSE** means the opposite.| 1088 1089**Example** 1090 1091```js 1092/* Set options to emptyOptions. */ 1093let keyAlias = 'keyAlias'; 1094let emptyOptions = { 1095 properties: [] 1096}; 1097try { 1098 huks.isKeyItemExist(keyAlias, emptyOptions, function (error, data) { 1099 if (error) { 1100 console.error(`callback: isKeyItemExist failed, code: ${error.code}, msg: ${error.message}`); 1101 } else { 1102 console.info(`callback: isKeyItemExist success, data = ${JSON.stringify(data)}`); 1103 } 1104 }); 1105} catch (error) { 1106 console.error(`promise: isKeyItemExist input arg invalid, code: ${error.code}, msg: ${error.message}`); 1107} 1108``` 1109 1110## huks.isKeyItemExist<sup>9+</sup> 1111 1112isKeyItemExist(keyAlias: string, options: HuksOptions) : Promise\<boolean> 1113 1114Checks whether a key exists. This API uses a promise to return the result. 1115 1116**System capability**: SystemCapability.Security.Huks 1117 1118**Parameters** 1119 1120| Name | Type | Mandatory| Description | 1121| -------- | --------------------------- | ---- | ------------------------ | 1122| keyAlias | string | Yes | Alias of the key to check. | 1123| options | [HuksOptions](#huksoptions) | Yes | Empty object (leave this parameter empty).| 1124 1125**Return value** 1126 1127| Type | Description | 1128| ----------------- | --------------------------------------- | 1129| Promise\<boolean> | Promise used to return the result. The value **TRUE** means that the key exists; **FALSE** means the opposite.| 1130 1131**Example** 1132 1133```js 1134/* Set options to emptyOptions. */ 1135let keyAlias = 'keyAlias'; 1136let emptyOptions = { 1137 properties: [] 1138}; 1139try { 1140 huks.isKeyItemExist(keyAlias, emptyOptions) 1141 .then ((data) => { 1142 console.info(`promise: isKeyItemExist success, data = ${JSON.stringify(data)}`); 1143 }) 1144 .catch(error => { 1145 console.error(`promise: isKeyItemExist failed, code: ${error.code}, msg: ${error.message}`); 1146 }); 1147} catch (error) { 1148 console.error(`promise: isKeyItemExist input arg invalid, code: ${error.code}, msg: ${error.message}`); 1149} 1150``` 1151 1152## huks.initSession<sup>9+</sup> 1153 1154initSession(keyAlias: string, options: HuksOptions, callback: AsyncCallback\<HuksSessionHandle>) : void 1155 1156Initializes the data for a key operation. This API uses an asynchronous callback to return the result. **huks.initSession**, **huks.updateSession**, and **huks.finishSession** must be used together. 1157 1158**System capability**: SystemCapability.Security.Huks 1159 1160**Parameters** 1161 1162| Name | Type | Mandatory| Description | 1163| -------- | ------------------------------------------------------- | ---- | ---------------------------------------------------- | 1164| keyAlias | string | Yes | Alias of the key involved in the **initSession** operation. | 1165| options | [HuksOptions](#huksoptions) | Yes | Parameter set used for the **initSession** operation. | 1166| callback | AsyncCallback\<[HuksSessionHandle](#hukssessionhandle9)> | Yes | Callback invoked to return a session handle for subsequent operations.| 1167 1168## huks.initSession<sup>9+</sup> 1169 1170initSession(keyAlias: string, options: HuksOptions) : Promise\<HuksSessionHandle> 1171 1172Initializes the data for a key operation. This API uses a promise to return the result. **huks.initSession**, **huks.updateSession**, and **huks.finishSession** must be used together. 1173 1174**System capability**: SystemCapability.Security.Huks 1175 1176**Parameters** 1177 1178| Name | Type | Mandatory| Description | 1179| -------- | ------------------------------------------------- | ---- | ------------------------------------------------ | 1180| keyAlias | string | Yes | Alias of the key involved in the **initSession** operation. | 1181| options | [HuksOptions](#huksoptions) | Yes | Parameter set used for the **initSession** operation. | 1182 1183**Return value** 1184 1185| Type | Description | 1186| ----------------------------------- | -------------------------------------------------- | 1187| Promise\<[HuksSessionHandle](#hukssessionhandle9)> | Promise used to return a session handle for subsequent operations.| 1188 1189## huks.updateSession<sup>9+</sup> 1190 1191updateSession(handle: number, options: HuksOptions, callback: AsyncCallback\<HuksReturnResult>) : void 1192 1193Updates the key operation by segment. This API uses an asynchronous callback to return the result. **huks.initSession**, **huks.updateSession**, and **huks.finishSession** must be used together. 1194 1195**System capability**: SystemCapability.Security.Huks 1196 1197**Parameters** 1198 1199| Name | Type | Mandatory| Description | 1200| -------- | ---------------------------------------------------- | ---- | -------------------------------------------- | 1201| handle | number | Yes | Handle for the **updateSession** operation. | 1202| options | [HuksOptions](#huksoptions) | Yes | Parameter set used for the **updateSession** operation. | 1203| callback | AsyncCallback<[HuksReturnResult](#huksreturnresult9)> | Yes | Callback invoked to return the **updateSession** operation result.| 1204 1205 1206## huks.updateSession<sup>9+</sup> 1207 1208updateSession(handle: number, options: HuksOptions, token: Uint8Array, callback: AsyncCallback\<HuksReturnResult>) : void 1209 1210Updates the key operation by segment. This API uses an asynchronous callback to return the result. **huks.initSession**, **huks.updateSession**, and **huks.finishSession** must be used together. 1211 1212**System capability**: SystemCapability.Security.Huks 1213 1214**Parameters** 1215 1216| Name | Type | Mandatory| Description | 1217| -------- | ---------------------------------------------------- | ---- | -------------------------------------------- | 1218| handle | number | Yes | Handle for the **updateSession** operation. | 1219| options | [HuksOptions](#huksoptions) | Yes | Parameter set used for the **updateSession** operation. | 1220| token | Uint8Array | Yes | Token of the **updateSession** operation. | 1221| callback | AsyncCallback<[HuksReturnResult](#huksreturnresult9)> | Yes | Callback invoked to return the **updateSession** operation result.| 1222 1223## huks.updateSession<sup>9+</sup> 1224 1225updateSession(handle: number, options: HuksOptions, token?: Uint8Array) : Promise\<HuksReturnResult> 1226 1227Updates the key operation by segment. This API uses a promise to return the result. **huks.initSession**, **huks.updateSession**, and **huks.finishSession** must be used together. 1228 1229**System capability**: SystemCapability.Security.Huks 1230 1231**Parameters** 1232 1233| Name | Type | Mandatory| Description | 1234| ------- | ---------------------------------------------- | ---- | -------------------------------------------- | 1235| handle | number | Yes | Handle for the **updateSession** operation. | 1236| options | [HuksOptions](#huksoptions) | Yes | Parameter set used for the **updateSession** operation. | 1237| token | Uint8Array | No | Token of the **updateSession** operation. | 1238 1239**Return value** 1240 1241| Type | Description | 1242| ----------------------------------- | -------------------------------------------------- | 1243| Promise<[HuksReturnResult](#huksreturnresult9)> | Promise used to return the **updateSession** operation result.| 1244 1245## huks.finishSession<sup>9+</sup> 1246 1247finishSession(handle: number, options: HuksOptions, callback: AsyncCallback\<HuksReturnResult>) : void 1248 1249Completes the key operation and releases resources. This API uses an asynchronous callback to return the result. **huks.initSession**, **huks.updateSession**, and **huks.finishSession** must be used together. 1250 1251**System capability**: SystemCapability.Security.Huks 1252 1253**Parameters** 1254 1255| Name | Type | Mandatory| Description | 1256| -------- | ---------------------------------------------------- | ---- | -------------------------------------------- | 1257| handle | number | Yes | Handle for the **finishSession** operation. | 1258| options | [HuksOptions](#huksoptions) | Yes | Parameter set used for the **finishSession** operation. | 1259| token | Uint8Array | Yes | Token of the **finishSession** operation. | 1260| callback | AsyncCallback<[HuksReturnResult](#huksreturnresult9)> | Yes | Callback invoked to return the **finishSession** operation result. | 1261 1262## huks.finishSession<sup>9+</sup> 1263 1264finishSession(handle: number, options: HuksOptions, token: Uint8Array, callback: AsyncCallback\<HuksReturnResult>) : void 1265 1266Completes the key operation and releases resources. This API uses an asynchronous callback to return the result. **huks.initSession**, **huks.updateSession**, and **huks.finishSession** must be used together. 1267 1268**System capability**: SystemCapability.Security.Huks 1269 1270**Parameters** 1271 1272| Name | Type | Mandatory| Description | 1273| -------- | ----------------------------------------------------- | ---- | -------------------------------------------- | 1274| handle | number | Yes | Handle for the **finishSession** operation. | 1275| options | [HuksOptions](#huksoptions) | Yes | Parameter set used for the **finishSession** operation. | 1276| token | Uint8Array | Yes | Token of the **finishSession** operation. | 1277| callback | AsyncCallback\<[HuksReturnResult](#huksreturnresult9)> | Yes | Callback invoked to return the **finishSession** operation result. | 1278 1279## huks.finishSession<sup>9+</sup> 1280 1281finishSession(handle: number, options: HuksOptions, token?: Uint8Array) : Promise\<HuksReturnResult> 1282 1283Completes the key operation and releases resources. This API uses a promise to return the result. **huks.initSession**, **huks.updateSession**, and **huks.finishSession** must be used together. 1284 1285**System capability**: SystemCapability.Security.Huks 1286 1287**Parameters** 1288 1289| Name | Type | Mandatory| Description | 1290| ------- | ----------------------------------------------- | ---- | ----------------------------------- | 1291| handle | number | Yes | Handle for the **finishSession** operation. | 1292| options | [HuksOptions](#huksoptions) | Yes | Parameter set used for the **finishSession** operation. | 1293| token | Uint8Array | No | Token of the **finishSession** operation. | 1294 1295**Return value** 1296 1297| Type | Description | 1298| ----------------------------------- | -------------------------------------------------- | 1299| Promise\<[HuksReturnResult](#huksreturnresult9)> | Promise used to return the result.| 1300 1301## huks.abortSession<sup>9+</sup> 1302 1303abortSession(handle: number, options: HuksOptions, callback: AsyncCallback\<void>) : void 1304 1305Aborts a key operation. This API uses an asynchronous callback to return the result. 1306 1307**System capability**: SystemCapability.Security.Huks 1308 1309**Parameters** 1310 1311| Name | Type | Mandatory| Description | 1312| -------- | --------------------------- | ---- | ------------------------------------------- | 1313| handle | number | Yes | Handle for the **abortSession** operation. | 1314| options | [HuksOptions](#huksoptions) | Yes | Parameter set used for the **abortSession** operation. | 1315| callback | AsyncCallback\<void> | Yes | Callback that returns no value. | 1316 1317**Example** 1318 1319```js 1320/* huks.initSession, huks.updateSession, and huks.finishSession must be used together. 1321 * If an error occurs in any of huks.initSession, huks.updateSession, 1322 * and huks.finishSession operations, 1323 * huks.abortSession must be called to terminate the use of the key. 1324 * 1325 * The following uses the callback of an RSA1024 key as an example. 1326 */ 1327function stringToUint8Array(str) { 1328 let arr = []; 1329 for (let i = 0, j = str.length; i < j; ++i) { 1330 arr.push(str.charCodeAt(i)); 1331 } 1332 let tmpUint8Array = new Uint8Array(arr); 1333 return tmpUint8Array; 1334} 1335 1336let keyAlias = "HuksDemoRSA"; 1337let properties = new Array(); 1338let options = { 1339 properties: properties, 1340 inData: new Uint8Array(0) 1341}; 1342let handle; 1343async function generateKey() { 1344 properties[0] = { 1345 tag: huks.HuksTag.HUKS_TAG_ALGORITHM, 1346 value: huks.HuksKeyAlg.HUKS_ALG_RSA 1347 }; 1348 properties[1] = { 1349 tag: huks.HuksTag.HUKS_TAG_KEY_SIZE, 1350 value: huks.HuksKeySize.HUKS_RSA_KEY_SIZE_1024 1351 }; 1352 properties[2] = { 1353 tag: huks.HuksTag.HUKS_TAG_PURPOSE, 1354 value: huks.HuksKeyPurpose.HUKS_KEY_PURPOSE_ENCRYPT 1355 }; 1356 properties[3] = { 1357 tag: huks.HuksTag.HUKS_TAG_PADDING, 1358 value: huks.HuksKeyPadding.HUKS_PADDING_PKCS1_V1_5 1359 }; 1360 properties[4] = { 1361 tag: huks.HuksTag.HUKS_TAG_DIGEST, 1362 value: huks.HuksKeyDigest.HUKS_DIGEST_SHA256 1363 }; 1364 properties[5] = { 1365 tag: huks.HuksTag.HUKS_TAG_BLOCK_MODE, 1366 value: huks.HuksCipherMode.HUKS_MODE_ECB, 1367 } 1368 1369 try { 1370 await huks.generateKeyItem(keyAlias, options, function (error, data) { 1371 if (error) { 1372 console.error(`callback: generateKeyItem failed, code: ${error.code}, msg: ${error.message}`); 1373 } else { 1374 console.info(`callback: generateKeyItem success`); 1375 } 1376 }); 1377 } catch (error) { 1378 console.error(`callback: generateKeyItem input arg invalid, code: ${error.code}, msg: ${error.message}`); 1379 } 1380} 1381 1382async function huksInit() { 1383 console.log('enter huksInit'); 1384 try { 1385 huks.initSession(keyAlias, options, function (error, data) { 1386 if (error) { 1387 console.error(`callback: initSession failed, code: ${error.code}, msg: ${error.message}`); 1388 } else { 1389 console.info(`callback: initSession success, data = ${JSON.stringify(data)}`); 1390 handle = data.handle; 1391 } 1392 }); 1393 } catch (error) { 1394 console.error(`callback: initSession input arg invalid, code: ${error.code}, msg: ${error.message}`); 1395 } 1396} 1397 1398async function huksUpdate() { 1399 console.log('enter huksUpdate'); 1400 options.inData = stringToUint8Array("huksHmacTest"); 1401 try { 1402 huks.updateSession(handle, options, function (error, data) { 1403 if (error) { 1404 console.error(`callback: updateSession failed, code: ${error.code}, msg: ${error.message}`); 1405 } else { 1406 console.info(`callback: updateSession success, data = ${JSON.stringify(data)}`); 1407 } 1408 }); 1409 } catch (error) { 1410 console.error(`callback: updateSession input arg invalid, code: ${error.code}, msg: ${error.message}`); 1411 } 1412} 1413 1414async function huksFinish() { 1415 console.log('enter huksFinish'); 1416 options.inData = new Uint8Array(0); 1417 try { 1418 huks.finishSession(handle, options, function (error, data) { 1419 if (error) { 1420 console.error(`callback: finishSession failed, code: ${error.code}, msg: ${error.message}`); 1421 } else { 1422 console.info(`callback: finishSession success, data = ${JSON.stringify(data)}`); 1423 } 1424 }); 1425 } catch (error) { 1426 console.error(`callback: finishSession input arg invalid, code: ${error.code}, msg: ${error.message}`); 1427 } 1428} 1429 1430async function huksAbort() { 1431 console.log('enter huksAbort'); 1432 try { 1433 huks.abortSession(handle, options, function (error, data) { 1434 if (error) { 1435 console.error(`callback: abortSession failed, code: ${error.code}, msg: ${error.message}`); 1436 } else { 1437 console.info(`callback: abortSession success`); 1438 } 1439 }); 1440 } catch (error) { 1441 console.error(`callback: abortSession input arg invalid, code: ${error.code}, msg: ${error.message}`); 1442 } 1443} 1444``` 1445 1446## huks.abortSession<sup>9+</sup> 1447 1448abortSession(handle: number, options: HuksOptions) : Promise\<void>; 1449 1450Aborts a key operation. This API uses a promise to return the result. 1451 1452**System capability**: SystemCapability.Security.Huks 1453 1454**Parameters** 1455 1456| Name | Type | Mandatory| Description | 1457| ------- | --------------------------- | ---- | ------------------------------------------- | 1458| handle | number | Yes | Handle for the **abortSession** operation. | 1459| options | [HuksOptions](#huksoptions) | Yes | Parameter set used for the **abortSession** operation. | 1460 1461**Return value** 1462 1463| Type | Description | 1464| ----------------------------------- | -------------------------------------------------- | 1465| Promise\<void> | Promise used to return the **abortSession** operation result.| 1466 1467**Example** 1468 1469```js 1470/* huks.initSession, huks.updateSession, and huks.finishSession must be used together. 1471 * If an error occurs in any of huks.initSession, huks.updateSession, 1472 * and huks.finishSession operations, 1473 * huks.abortSession must be called to terminate the use of the key. 1474 * 1475 * The following uses the callback of an RSA1024 key as an example. 1476 */ 1477function stringToUint8Array(str) { 1478 let arr = []; 1479 for (let i = 0, j = str.length; i < j; ++i) { 1480 arr.push(str.charCodeAt(i)); 1481 } 1482 let tmpUint8Array = new Uint8Array(arr); 1483 return tmpUint8Array; 1484} 1485 1486let keyAlias = "HuksDemoRSA"; 1487let properties = new Array(); 1488let options = { 1489 properties: properties, 1490 inData: new Uint8Array(0) 1491}; 1492let handle; 1493async function generateKey() { 1494 properties[0] = { 1495 tag: huks.HuksTag.HUKS_TAG_ALGORITHM, 1496 value: huks.HuksKeyAlg.HUKS_ALG_RSA 1497 }; 1498 properties[1] = { 1499 tag: huks.HuksTag.HUKS_TAG_KEY_SIZE, 1500 value: huks.HuksKeySize.HUKS_RSA_KEY_SIZE_1024 1501 }; 1502 properties[2] = { 1503 tag: huks.HuksTag.HUKS_TAG_PURPOSE, 1504 value: huks.HuksKeyPurpose.HUKS_KEY_PURPOSE_ENCRYPT 1505 }; 1506 properties[3] = { 1507 tag: huks.HuksTag.HUKS_TAG_PADDING, 1508 value: huks.HuksKeyPadding.HUKS_PADDING_PKCS1_V1_5 1509 }; 1510 properties[4] = { 1511 tag: huks.HuksTag.HUKS_TAG_DIGEST, 1512 value: huks.HuksKeyDigest.HUKS_DIGEST_SHA256 1513 }; 1514 properties[5] = { 1515 tag: huks.HuksTag.HUKS_TAG_BLOCK_MODE, 1516 value: huks.HuksCipherMode.HUKS_MODE_ECB, 1517 } 1518 1519 try { 1520 await huks.generateKeyItem(keyAlias, options) 1521 .then((data) => { 1522 console.info(`promise: generateKeyItem success`); 1523 }) 1524 .catch(error => { 1525 console.error(`promise: generateKeyItem failed, code: ${error.code}, msg: ${error.message}`); 1526 }); 1527 } catch (error) { 1528 console.error(`promise: generateKeyItem input arg invalid, code: ${error.code}, msg: ${error.message}`); 1529 } 1530} 1531 1532async function huksInit() { 1533 console.log('enter huksInit'); 1534 try { 1535 await huks.initSession(keyAlias, options) 1536 .then ((data) => { 1537 console.info(`promise: initSession success, data = ${JSON.stringify(data)}`); 1538 handle = data.handle; 1539 }) 1540 .catch(error => { 1541 console.error(`promise: initSession key failed, code: ${error.code}, msg: ${error.message}`); 1542 }); 1543 } catch (error) { 1544 console.error(`promise: initSession input arg invalid, code: ${error.code}, msg: ${error.message}`); 1545 } 1546} 1547 1548async function huksUpdate() { 1549 console.log('enter huksUpdate'); 1550 options.inData = stringToUint8Array("huksHmacTest"); 1551 try { 1552 await huks.updateSession(handle, options) 1553 .then ((data) => { 1554 console.info(`promise: updateSession success, data = ${JSON.stringify(data)}`); 1555 }) 1556 .catch(error => { 1557 console.error(`promise: updateSession failed, code: ${error.code}, msg: ${error.message}`); 1558 }); 1559 } catch (error) { 1560 console.error(`promise: updateSession input arg invalid, code: ${error.code}, msg: ${error.message}`); 1561 } 1562} 1563 1564async function huksFinish() { 1565 console.log('enter huksFinish'); 1566 options.inData = new Uint8Array(0); 1567 try { 1568 await huks.finishSession(handle, options) 1569 .then ((data) => { 1570 console.info(`promise: finishSession success, data = ${JSON.stringify(data)}`); 1571 }) 1572 .catch(error => { 1573 console.error(`promise: finishSession failed, code: ${error.code}, msg: ${error.message}`); 1574 }); 1575 } catch (error) { 1576 console.error(`promise: finishSession input arg invalid, code: ${error.code}, msg: ${error.message}`); 1577 } 1578} 1579 1580async function huksAbort() { 1581 console.log('enter huksAbort'); 1582 try { 1583 await huks.abortSession(handle, options) 1584 .then ((data) => { 1585 console.info(`promise: abortSession success`); 1586 }) 1587 .catch(error => { 1588 console.error(`promise: abortSession failed, code: ${error.code}, msg: ${error.message}`); 1589 }); 1590 } catch (error) { 1591 console.error(`promise: abortSession input arg invalid, code: ${error.code}, msg: ${error.message}`); 1592 } 1593} 1594``` 1595 1596 1597## HuksExceptionErrCode<sup>9+</sup> 1598 1599Enumerates the error codes. 1600 1601For details about the error codes, see [KUKS Error Codes](../errorcodes/errorcode-huks.md). 1602 1603**System capability**: SystemCapability.Security.Huks 1604 1605| Name | Value| Description | 1606| ---------------------------------------------- | -------- |--------------------------- | 1607| HUKS_ERR_CODE_PERMISSION_FAIL | 201 | Permission verification failed. | 1608| HUKS_ERR_CODE_ILLEGAL_ARGUMENT | 401 | Invalid parameters are detected. | 1609| HUKS_ERR_CODE_NOT_SUPPORTED_API | 801 | The API is not supported. | 1610| HUKS_ERR_CODE_FEATURE_NOT_SUPPORTED | 12000001 | The feature is not supported. | 1611| HUKS_ERR_CODE_MISSING_CRYPTO_ALG_ARGUMENT | 12000002 | Key algorithm parameters are missing. | 1612| HUKS_ERR_CODE_INVALID_CRYPTO_ALG_ARGUMENT | 12000003 | Invalid key algorithm parameters are detected. | 1613| HUKS_ERR_CODE_FILE_OPERATION_FAIL | 12000004 | The file operation failed. | 1614| HUKS_ERR_CODE_COMMUNICATION_FAIL | 12000005 | The communication failed. | 1615| HUKS_ERR_CODE_CRYPTO_FAIL | 12000006 | Failed to operate the algorithm library. | 1616| HUKS_ERR_CODE_KEY_AUTH_PERMANENTLY_INVALIDATED | 12000007 | Failed to access the key because the key has expired.| 1617| HUKS_ERR_CODE_KEY_AUTH_VERIFY_FAILED | 12000008 | Failed to access the key because the authentication has failed.| 1618| HUKS_ERR_CODE_KEY_AUTH_TIME_OUT | 12000009 | Key access timed out.| 1619| HUKS_ERR_CODE_SESSION_LIMIT | 12000010 | The number of key operation sessions has reached the limit. | 1620| HUKS_ERR_CODE_ITEM_NOT_EXIST | 12000011 | The target object does not exist. | 1621| HUKS_ERR_CODE_EXTERNAL_ERROR | 12000012 | An external error occurs. | 1622| HUKS_ERR_CODE_CREDENTIAL_NOT_EXIST | 12000013 | The credential does not exist. | 1623| HUKS_ERR_CODE_INSUFFICIENT_MEMORY | 12000014 | The memory is insufficient. | 1624| HUKS_ERR_CODE_CALL_SERVICE_FAILED | 12000015 | Failed to call other system services. | 1625 1626## HuksKeyPurpose 1627 1628Enumerates the key purposes. 1629 1630**System capability**: SystemCapability.Security.Huks 1631 1632| Name | Value | Description | 1633| ------------------------ | ---- | -------------------------------- | 1634| HUKS_KEY_PURPOSE_ENCRYPT | 1 | Used to encrypt the plaintext.| 1635| HUKS_KEY_PURPOSE_DECRYPT | 2 | Used to decrypt the cipher text.| 1636| HUKS_KEY_PURPOSE_SIGN | 4 | Used for signing. | 1637| HUKS_KEY_PURPOSE_VERIFY | 8 | Used to verify the signature. | 1638| HUKS_KEY_PURPOSE_DERIVE | 16 | Used to derive a key. | 1639| HUKS_KEY_PURPOSE_WRAP | 32 | Used for an encrypted export. | 1640| HUKS_KEY_PURPOSE_UNWRAP | 64 | Used for an encrypted import. | 1641| HUKS_KEY_PURPOSE_MAC | 128 | Used to generate a message authentication code (MAC). | 1642| HUKS_KEY_PURPOSE_AGREE | 256 | Used for key agreement. | 1643 1644## HuksKeyDigest 1645 1646Enumerates the digest algorithms. 1647 1648**System capability**: SystemCapability.Security.Huks 1649 1650| Name | Value | Description | 1651| ---------------------- | ---- | ---------------------------------------- | 1652| HUKS_DIGEST_NONE | 0 | No digest algorithm| 1653| HUKS_DIGEST_MD5 | 1 | MD5| 1654| HUKS_DIGEST_SM3<sup>9+</sup> | 2 | SM3| 1655| HUKS_DIGEST_SHA1 | 10 | SHA-1| 1656| HUKS_DIGEST_SHA224 | 11 | SHA-224| 1657| HUKS_DIGEST_SHA256 | 12 | SHA-256| 1658| HUKS_DIGEST_SHA384 | 13 | SHA-384| 1659| HUKS_DIGEST_SHA512 | 14 | SHA-512| 1660 1661## HuksKeyPadding 1662 1663Enumerates the padding algorithms. 1664 1665**System capability**: SystemCapability.Security.Huks 1666 1667| Name | Value | Description | 1668| ---------------------- | ---- | ---------------------------------------- | 1669| HUKS_PADDING_NONE | 0 | No padding algorithm| 1670| HUKS_PADDING_OAEP | 1 | Optimal Asymmetric Encryption Padding (OAEP)| 1671| HUKS_PADDING_PSS | 2 | Probabilistic Signature Scheme (PSS)| 1672| HUKS_PADDING_PKCS1_V1_5 | 3 | Public Key Cryptography Standards (PKCS) #1 v1.5| 1673| HUKS_PADDING_PKCS5 | 4 | PKCS #5| 1674| HUKS_PADDING_PKCS7 | 5 | PKCS #7| 1675 1676## HuksCipherMode 1677 1678Enumerates the cipher modes. 1679 1680**System capability**: SystemCapability.Security.Huks 1681 1682| Name | Value | Description | 1683| ------------- | ---- | --------------------- | 1684| HUKS_MODE_ECB | 1 | Electronic Code Block (ECB) mode| 1685| HUKS_MODE_CBC | 2 | Cipher Block Chaining (CBC) mode| 1686| HUKS_MODE_CTR | 3 | Counter (CTR) mode| 1687| HUKS_MODE_OFB | 4 | Output Feedback (OFB) mode| 1688| HUKS_MODE_CCM | 31 | Counter with CBC-MAC (CCM) mode| 1689| HUKS_MODE_GCM | 32 | Galois/Counter (GCM) mode| 1690 1691## HuksKeySize 1692 1693Enumerates the key sizes. 1694 1695**System capability**: SystemCapability.Security.Huks 1696 1697| Name | Value | Description | 1698| ---------------------------------- | ---- | ------------------------------------------ | 1699| HUKS_RSA_KEY_SIZE_512 | 512 | Rivest-Shamir-Adleman (RSA) key of 512 bits | 1700| HUKS_RSA_KEY_SIZE_768 | 768 | RSA key of 768 bits | 1701| HUKS_RSA_KEY_SIZE_1024 | 1024 | RSA key of 1024 bits | 1702| HUKS_RSA_KEY_SIZE_2048 | 2048 | RSA key of 2048 bits | 1703| HUKS_RSA_KEY_SIZE_3072 | 3072 | RSA key of 3072 bits | 1704| HUKS_RSA_KEY_SIZE_4096 | 4096 | RSA key of 4096 bits | 1705| HUKS_ECC_KEY_SIZE_224 | 224 | Elliptic Curve Cryptography (ECC) key of 224 bits | 1706| HUKS_ECC_KEY_SIZE_256 | 256 | ECC key of 256 bits | 1707| HUKS_ECC_KEY_SIZE_384 | 384 | ECC key of 384 bits | 1708| HUKS_ECC_KEY_SIZE_521 | 521 | ECC key of 521 bits | 1709| HUKS_AES_KEY_SIZE_128 | 128 | Advanced Encryption Standard (AES) key of 128 bits | 1710| HUKS_AES_KEY_SIZE_192 | 192 | AES key of 192 bits | 1711| HUKS_AES_KEY_SIZE_256 | 256 | AES key of 256 bits | 1712| HUKS_AES_KEY_SIZE_512 | 512 | AES key of 512 bits | 1713| HUKS_CURVE25519_KEY_SIZE_256 | 256 | Curve25519 key of 256 bits| 1714| HUKS_DH_KEY_SIZE_2048 | 2048 | Diffie-Hellman (DH) key of 2048 bits | 1715| HUKS_DH_KEY_SIZE_3072 | 3072 | DH key of 3072 bits | 1716| HUKS_DH_KEY_SIZE_4096 | 4096 | DH key of 4096 bits | 1717| HUKS_SM2_KEY_SIZE_256<sup>9+</sup> | 256 | ShangMi2 (SM2) key of 256 bits | 1718| HUKS_SM4_KEY_SIZE_128<sup>9+</sup> | 128 | ShangMi4 (SM4) key of 128 bits | 1719 1720## HuksKeyAlg 1721 1722Enumerates the key algorithms. 1723 1724**System capability**: SystemCapability.Security.Huks 1725 1726| Name | Value | Description | 1727| ------------------------- | ---- | --------------------- | 1728| HUKS_ALG_RSA | 1 | RSA | 1729| HUKS_ALG_ECC | 2 | ECC | 1730| HUKS_ALG_DSA | 3 | DSA | 1731| HUKS_ALG_AES | 20 | AES | 1732| HUKS_ALG_HMAC | 50 | HMAC | 1733| HUKS_ALG_HKDF | 51 | HKDF | 1734| HUKS_ALG_PBKDF2 | 52 | PBKDF2 | 1735| HUKS_ALG_ECDH | 100 | ECDH | 1736| HUKS_ALG_X25519 | 101 | X25519 | 1737| HUKS_ALG_ED25519 | 102 | ED25519| 1738| HUKS_ALG_DH | 103 | DH | 1739| HUKS_ALG_SM2<sup>9+</sup> | 150 | SM2 | 1740| HUKS_ALG_SM3<sup>9+</sup> | 151 | SM3 | 1741| HUKS_ALG_SM4<sup>9+</sup> | 152 | SM4 | 1742 1743## HuksKeyGenerateType 1744 1745Enumerates the key generation types. 1746 1747**System capability**: SystemCapability.Security.Huks 1748 1749| Name | Value | Description | 1750| ------------------------------ | ---- | ---------------- | 1751| HUKS_KEY_GENERATE_TYPE_DEFAULT | 0 | Key generated by default.| 1752| HUKS_KEY_GENERATE_TYPE_DERIVE | 1 | Derived key.| 1753| HUKS_KEY_GENERATE_TYPE_AGREE | 2 | Key generated by agreement.| 1754 1755## HuksKeyFlag 1756 1757Enumerates the key generation modes. 1758 1759**System capability**: SystemCapability.Security.Huks 1760 1761| Name | Value | Description | 1762| -------------------------- | ---- | ------------------------------------ | 1763| HUKS_KEY_FLAG_IMPORT_KEY | 1 | Import a key using an API. | 1764| HUKS_KEY_FLAG_GENERATE_KEY | 2 | Generate a key by using an API. | 1765| HUKS_KEY_FLAG_AGREE_KEY | 3 | Generate a key by using a key agreement API.| 1766| HUKS_KEY_FLAG_DERIVE_KEY | 4 | Derive a key by using an API.| 1767 1768## HuksKeyStorageType 1769 1770Enumerates the key storage modes. 1771 1772**System capability**: SystemCapability.Security.Huks 1773 1774| Name | Value | Description | 1775| ----------------------- | ---- | ------------------------------ | 1776| HUKS_STORAGE_TEMP | 0 | The key is managed locally. | 1777| HUKS_STORAGE_PERSISTENT | 1 | The key is managed by the HUKS service.| 1778 1779## HuksSendType 1780 1781Enumerates the tag transfer modes. 1782 1783**System capability**: SystemCapability.Security.Huks 1784 1785| Name | Value | Description | 1786| -------------------- | ---- | ----------------- | 1787| HUKS_SEND_TYPE_ASYNC | 0 | The tag is sent asynchronously.| 1788| HUKS_SEND_TYPE_SYNC | 1 | The tag is sent synchronously.| 1789 1790## HuksUnwrapSuite<sup>9+</sup> 1791 1792Enumerates the algorithm suites used for importing an encrypted key. 1793 1794**System capability**: SystemCapability.Security.Huks 1795 1796| Name | Value | Description | 1797| ---------------------------------------------- | ---- | ----------------------------------------------------- | 1798| HUKS_UNWRAP_SUITE_X25519_AES_256_GCM_NOPADDING | 1 | Use X25519 for key agreement and then use AES-256 GCM to encrypt the key.| 1799| HUKS_UNWRAP_SUITE_ECDH_AES_256_GCM_NOPADDING | 2 | Use ECDH for key agreement and then use AES-256 GCM to encrypt the key. | 1800 1801## HuksImportKeyType<sup>9+</sup> 1802 1803Enumerates the types of keys to import. By default, a public key is imported. This field is not required when a symmetric key is imported. 1804 1805**System capability**: SystemCapability.Security.Huks 1806 1807| Name | Value | Description | 1808| ------------------------- | ---- | ------------------------------ | 1809| HUKS_KEY_TYPE_PUBLIC_KEY | 0 | Public key | 1810| HUKS_KEY_TYPE_PRIVATE_KEY | 1 | Private key | 1811| HUKS_KEY_TYPE_KEY_PAIR | 2 | Public and private key pair| 1812 1813## HuksUserAuthType<sup>9+</sup> 1814 1815Enumerates the user authentication types. 1816 1817**System capability**: SystemCapability.Security.Huks 1818 1819| Name | Value | Description | 1820| ------------------------------- | ---- | ------------------------- | 1821| HUKS_USER_AUTH_TYPE_FINGERPRINT | 1 << 0 | Fingerprint authentication. | 1822| HUKS_USER_AUTH_TYPE_FACE | 1 << 1 | Facial authentication.| 1823| HUKS_USER_AUTH_TYPE_PIN | 1 << 2 | PIN authentication.| 1824 1825## HuksAuthAccessType<sup>9+</sup> 1826 1827Enumerates the access control types. 1828 1829**System capability**: SystemCapability.Security.Huks 1830 1831| Name | Value | Description | 1832| --------------------------------------- | ---- | ------------------------------------------------ | 1833| HUKS_AUTH_ACCESS_INVALID_CLEAR_PASSWORD | 1 << 0 | The key becomes invalid after the password is cleared. | 1834| HUKS_AUTH_ACCESS_INVALID_NEW_BIO_ENROLL | 1 << 1 | The key becomes invalid after a new biometric feature is added.| 1835 1836## HuksChallengeType<sup>9+</sup> 1837 1838Enumerates the types of the challenges generated when a key is used. 1839 1840**System capability**: SystemCapability.Security.Huks 1841 1842| Name | Value | Description | 1843| ------------------------------- | ---- | ------------------------------ | 1844| HUKS_CHALLENGE_TYPE_NORMAL | 0 | Normal challenge, which is of 32 bytes by default.| 1845| HUKS_CHALLENGE_TYPE_CUSTOM | 1 | Custom challenge, which supports only one authentication for multiple keys.| 1846| HUKS_CHALLENGE_TYPE_NONE | 2 | Challenge is not required.| 1847 1848## HuksChallengePosition<sup>9+</sup> 1849 1850Enumerates the positions of the 8-byte valid value in a custom challenge generated. 1851 1852**System capability**: SystemCapability.Security.Huks 1853 1854| Name | Value | Description | 1855| ------------------------------- | ---- | ------------------------------ | 1856| HUKS_CHALLENGE_POS_0 | 0 | Bytes 0 to 7.| 1857| HUKS_CHALLENGE_POS_1 | 1 | Bytes 8 to 15.| 1858| HUKS_CHALLENGE_POS_2 | 2 | Bytes 16 to 23.| 1859| HUKS_CHALLENGE_POS_3 | 3 | Bytes 24 to 31.| 1860 1861## HuksSecureSignType<sup>9+</sup> 1862 1863Defines the signature type of the key generated or imported. 1864 1865**System capability**: SystemCapability.Security.Huks 1866 1867| Name | Value | Description | 1868| ------------------------------ | ---- | ------------------------------------------------------------ | 1869| HUKS_SECURE_SIGN_WITH_AUTHINFO | 1 | The signature carries authentication information. This field is specified when a key is generated or imported. When the key is used for signing, the data will be added with the authentication information and then be signed.| 1870 1871## HuksTagType 1872 1873Enumerates the tag data types. 1874 1875**System capability**: SystemCapability.Security.Huks 1876 1877| Name | Value | Description | 1878| --------------------- | ------- | --------------------------------------- | 1879| HUKS_TAG_TYPE_INVALID | 0 << 28 | Invalid tag type. | 1880| HUKS_TAG_TYPE_INT | 1 << 28 | Number of the int type. | 1881| HUKS_TAG_TYPE_UINT | 2 << 28 | Number of the uint type.| 1882| HUKS_TAG_TYPE_ULONG | 3 << 28 | BigInt. | 1883| HUKS_TAG_TYPE_BOOL | 4 << 28 | Boolean. | 1884| HUKS_TAG_TYPE_BYTES | 5 << 28 | Uint8Array. | 1885 1886## HuksTag 1887 1888Enumerates the tags used to invoke parameters. 1889 1890**System capability**: SystemCapability.Security.Huks 1891 1892| Name | Value | Description | 1893| -------------------------------------------- | ---------------------------------------- | ------------------------------------------------------------ | 1894| HUKS_TAG_INVALID | HuksTagType.HUKS_TAG_TYPE_INVALID \| 0 | Invalid tag. | 1895| HUKS_TAG_ALGORITHM | HuksTagType.HUKS_TAG_TYPE_UINT \| 1 | Algorithm. | 1896| HUKS_TAG_PURPOSE | HuksTagType.HUKS_TAG_TYPE_UINT \| 2 | Purpose of the key. | 1897| HUKS_TAG_KEY_SIZE | HuksTagType.HUKS_TAG_TYPE_UINT \| 3 | Key size. | 1898| HUKS_TAG_DIGEST | HuksTagType.HUKS_TAG_TYPE_UINT \| 4 | Digest algorithm. | 1899| HUKS_TAG_PADDING | HuksTagType.HUKS_TAG_TYPE_UINT \| 5 | Padding algorithm. | 1900| HUKS_TAG_BLOCK_MODE | HuksTagType.HUKS_TAG_TYPE_UINT \| 6 | Cipher mode. | 1901| HUKS_TAG_KEY_TYPE | HuksTagType.HUKS_TAG_TYPE_UINT \| 7 | Key type. | 1902| HUKS_TAG_ASSOCIATED_DATA | HuksTagType.HUKS_TAG_TYPE_BYTES \| 8 | Associated authentication data. | 1903| HUKS_TAG_NONCE | HuksTagType.HUKS_TAG_TYPE_BYTES \| 9 | Field for key encryption and decryption. | 1904| HUKS_TAG_IV | HuksTagType.HUKS_TAG_TYPE_BYTES \| 10 | IV. | 1905| HUKS_TAG_INFO | HuksTagType.HUKS_TAG_TYPE_BYTES \| 11 | Information generated during key derivation. | 1906| HUKS_TAG_SALT | HuksTagType.HUKS_TAG_TYPE_BYTES \| 12 | Salt value used for key derivation. | 1907| HUKS_TAG_PWD | HuksTagType.HUKS_TAG_TYPE_BYTES \| 13 | Password used for key derivation. | 1908| HUKS_TAG_ITERATION | HuksTagType.HUKS_TAG_TYPE_UINT \| 14 | Number of iterations for key derivation. | 1909| HUKS_TAG_KEY_GENERATE_TYPE | HuksTagType.HUKS_TAG_TYPE_UINT \| 15 | Key generation type. | 1910| HUKS_TAG_DERIVE_MAIN_KEY | HuksTagType.HUKS_TAG_TYPE_BYTES \| 16 | Main key for key derivation. | 1911| HUKS_TAG_DERIVE_FACTOR | HuksTagType.HUKS_TAG_TYPE_BYTES \| 17 | Factor for key derivation. | 1912| HUKS_TAG_DERIVE_ALG | HuksTagType.HUKS_TAG_TYPE_UINT \| 18 | Type of the algorithm used for key derivation. | 1913| HUKS_TAG_AGREE_ALG | HuksTagType.HUKS_TAG_TYPE_UINT \| 19 | Type of the algorithm used for key agreement. | 1914| HUKS_TAG_AGREE_PUBLIC_KEY_IS_KEY_ALIAS | HuksTagType.HUKS_TAG_TYPE_BOOL \| 20 | Public key alias used in key agreement. | 1915| HUKS_TAG_AGREE_PRIVATE_KEY_ALIAS | HuksTagType.HUKS_TAG_TYPE_BYTES \| 21 | Private key alias used in key agreement. | 1916| HUKS_TAG_AGREE_PUBLIC_KEY | HuksTagType.HUKS_TAG_TYPE_BYTES \| 22 | Public key used in key agreement. | 1917| HUKS_TAG_KEY_ALIAS | HuksTagType.HUKS_TAG_TYPE_BYTES \| 23 | Key alias. | 1918| HUKS_TAG_DERIVE_KEY_SIZE | HuksTagType.HUKS_TAG_TYPE_UINT \| 24 | Size of the derived key. | 1919| HUKS_TAG_IMPORT_KEY_TYPE<sup>9+</sup> | HuksTagType.HUKS_TAG_TYPE_UINT \| 25 | Type of the imported key. | 1920| HUKS_TAG_UNWRAP_ALGORITHM_SUITE<sup>9+</sup> | HuksTagType.HUKS_TAG_TYPE_UINT \| 26 | Algorithm suite required for encrypted imports. | 1921| HUKS_TAG_ACTIVE_DATETIME | HuksTagType.HUKS_TAG_TYPE_ULONG \| 201 | Reserved. | 1922| HUKS_TAG_ORIGINATION_EXPIRE_DATETIME | HuksTagType.HUKS_TAG_TYPE_ULONG \| 202 | Reserved. | 1923| HUKS_TAG_USAGE_EXPIRE_DATETIME | HuksTagType.HUKS_TAG_TYPE_ULONG \| 203 | Reserved. | 1924| HUKS_TAG_CREATION_DATETIME | HuksTagType.HUKS_TAG_TYPE_ULONG \| 204 | Reserved. | 1925| HUKS_TAG_ALL_USERS | HuksTagType.HUKS_TAG_TYPE_BOOL \| 301 | Reserved. | 1926| HUKS_TAG_USER_ID | HuksTagType.HUKS_TAG_TYPE_UINT \| 302 | Reserved. | 1927| HUKS_TAG_NO_AUTH_REQUIRED | HuksTagType.HUKS_TAG_TYPE_BOOL \| 303 | Reserved. | 1928| HUKS_TAG_USER_AUTH_TYPE | HuksTagType.HUKS_TAG_TYPE_UINT \| 304 | User authentication type. For details, see [HuksUserAuthType](#huksuserauthtype9). This parameter must be set together with [HuksAuthAccessType](#huksauthaccesstype9). You can set a maximum of two user authentication types at a time. For example, if **HuksAuthAccessType** is **HKS_SECURE_ACCESS_INVALID_NEW_BIO_ENROLL**, you can set two of **HKS_USER_AUTH_TYPE_FACE**, **HKS_USER_AUTH_TYPE_FINGERPRINT**, and **HKS_USER_AUTH_TYPE_FACE**. | 1929| HUKS_TAG_AUTH_TIMEOUT | HuksTagType.HUKS_TAG_TYPE_UINT \| 305 | Reserved. | 1930| HUKS_TAG_AUTH_TOKEN | HuksTagType.HUKS_TAG_TYPE_BYTES \| 306 | Reserved. | 1931| HUKS_TAG_KEY_AUTH_ACCESS_TYPE<sup>9+</sup> | HuksTagType.HUKS_TAG_TYPE_UINT \| 307 | Access control type. For details, see [HuksAuthAccessType](#huksauthaccesstype9). This parameter must be set together with [HuksUserAuthType](#huksuserauthtype9). | 1932| HUKS_TAG_KEY_SECURE_SIGN_TYPE<sup>9+</sup> | HuksTagType.HUKS_TAG_TYPE_UINT \| 308 | Signature type of the key generated or imported. | 1933| HUKS_TAG_CHALLENGE_TYPE<sup>9+</sup> | HuksTagType.HUKS_TAG_TYPE_UINT \| 309 | Type of the challenge generated for a key. For details, see [HuksChallengeType](#hukschallengetype9). | 1934| HUKS_TAG_CHALLENGE_POS<sup>9+</sup> | HuksTagType.HUKS_TAG_TYPE_UINT \| 310 | Position of the 8-byte valid value in a custom challenge. For details, see [HuksChallengePosition](#hukschallengeposition9). | 1935| HUKS_TAG_ATTESTATION_CHALLENGE | HuksTagType.HUKS_TAG_TYPE_BYTES \| 501 | Challenge value used in the attestation. | 1936| HUKS_TAG_ATTESTATION_APPLICATION_ID | HuksTagType.HUKS_TAG_TYPE_BYTES \| 502 | Application ID used in the attestation. | 1937| HUKS_TAG_ATTESTATION_ID_BRAND | HuksTagType.HUKS_TAG_TYPE_BYTES \| 503 | Brand of the device. | 1938| HUKS_TAG_ATTESTATION_ID_DEVICE | HuksTagType.HUKS_TAG_TYPE_BYTES \| 504 | ID of the device. | 1939| HUKS_TAG_ATTESTATION_ID_PRODUCT | HuksTagType.HUKS_TAG_TYPE_BYTES \| 505 | Product name of the device. | 1940| HUKS_TAG_ATTESTATION_ID_SERIAL | HuksTagType.HUKS_TAG_TYPE_BYTES \| 506 | SN of the device. | 1941| HUKS_TAG_ATTESTATION_ID_IMEI | HuksTagType.HUKS_TAG_TYPE_BYTES \| 507 | International mobile equipment identity (IMEI) of the device. | 1942| HUKS_TAG_ATTESTATION_ID_MEID | HuksTagType.HUKS_TAG_TYPE_BYTES \| 508 | Mobile equipment identity (MEID) of the device. | 1943| HUKS_TAG_ATTESTATION_ID_MANUFACTURER | HuksTagType.HUKS_TAG_TYPE_BYTES \| 509 | Manufacturer of the device. | 1944| HUKS_TAG_ATTESTATION_ID_MODEL | HuksTagType.HUKS_TAG_TYPE_BYTES \| 510 | Device model. | 1945| HUKS_TAG_ATTESTATION_ID_ALIAS | HuksTagType.HUKS_TAG_TYPE_BYTES \| 511 | Key alias used in the attestation. | 1946| HUKS_TAG_ATTESTATION_ID_SOCID | HuksTagType.HUKS_TAG_TYPE_BYTES \| 512 | System-on-a-chip (SoCID) of the device. | 1947| HUKS_TAG_ATTESTATION_ID_UDID | HuksTagType.HUKS_TAG_TYPE_BYTES \| 513 | Unique device identifier (UDID) of the device. | 1948| HUKS_TAG_ATTESTATION_ID_SEC_LEVEL_INFO | HuksTagType.HUKS_TAG_TYPE_BYTES \| 514 | Security level used in the attestation. | 1949| HUKS_TAG_ATTESTATION_ID_VERSION_INFO | HuksTagType.HUKS_TAG_TYPE_BYTES \| 515 | Version information used in the attestation. | 1950| HUKS_TAG_IS_KEY_ALIAS | HuksTagType.HUKS_TAG_TYPE_BOOL \| 1001 | Whether to use the alias passed in during key generation. | 1951| HUKS_TAG_KEY_STORAGE_FLAG | HuksTagType.HUKS_TAG_TYPE_UINT \| 1002 | Key storage mode. | 1952| HUKS_TAG_IS_ALLOWED_WRAP | HuksTagType.HUKS_TAG_TYPE_BOOL \| 1003 | Reserved. | 1953| HUKS_TAG_KEY_WRAP_TYPE | HuksTagType.HUKS_TAG_TYPE_UINT \| 1004 | Reserved. | 1954| HUKS_TAG_KEY_AUTH_ID | HuksTagType.HUKS_TAG_TYPE_BYTES \| 1005 | Reserved. | 1955| HUKS_TAG_KEY_ROLE | HuksTagType.HUKS_TAG_TYPE_UINT \| 1006 | Reserved. | 1956| HUKS_TAG_KEY_FLAG | HuksTagType.HUKS_TAG_TYPE_UINT \| 1007 | Flag of the key. | 1957| HUKS_TAG_IS_ASYNCHRONIZED | HuksTagType.HUKS_TAG_TYPE_UINT \| 1008 | Reserved. | 1958| HUKS_TAG_SECURE_KEY_ALIAS | HuksTagType.HUKS_TAG_TYPE_BOOL \| 1009 | Reserved. | 1959| HUKS_TAG_SECURE_KEY_UUID | HuksTagType.HUKS_TAG_TYPE_BYTES \| 1010 | Reserved. | 1960| HUKS_TAG_KEY_DOMAIN | HuksTagType.HUKS_TAG_TYPE_UINT \| 1011 | Reserved. | 1961| HUKS_TAG_PROCESS_NAME | HuksTagType.HUKS_TAG_TYPE_BYTES \| 10001 | Process name. | 1962| HUKS_TAG_PACKAGE_NAME | HuksTagType.HUKS_TAG_TYPE_BYTES \| 10002 | Reserved. | 1963| HUKS_TAG_ACCESS_TIME | HuksTagType.HUKS_TAG_TYPE_UINT \| 10003 | Reserved. | 1964| HUKS_TAG_USES_TIME | HuksTagType.HUKS_TAG_TYPE_UINT \| 10004 | Reserved. | 1965| HUKS_TAG_CRYPTO_CTX | HuksTagType.HUKS_TAG_TYPE_ULONG \| 10005 | Reserved. | 1966| HUKS_TAG_KEY | HuksTagType.HUKS_TAG_TYPE_BYTES \| 10006 | Reserved. | 1967| HUKS_TAG_KEY_VERSION | HuksTagType.HUKS_TAG_TYPE_UINT \| 10007 | Key version. | 1968| HUKS_TAG_PAYLOAD_LEN | HuksTagType.HUKS_TAG_TYPE_UINT \| 10008 | Reserved. | 1969| HUKS_TAG_AE_TAG | HuksTagType.HUKS_TAG_TYPE_BYTES \| 10009 | Reserved. | 1970| HUKS_TAG_IS_KEY_HANDLE | HuksTagType.HUKS_TAG_TYPE_ULONG \| 10010 | Reserved. | 1971| HUKS_TAG_OS_VERSION | HuksTagType.HUKS_TAG_TYPE_UINT \| 10101 | OS version. | 1972| HUKS_TAG_OS_PATCHLEVEL | HuksTagType.HUKS_TAG_TYPE_UINT \| 10102 | OS patch level. | 1973| HUKS_TAG_SYMMETRIC_KEY_DATA | HuksTagType.HUKS_TAG_TYPE_BYTES \| 20001 | Reserved. | 1974| HUKS_TAG_ASYMMETRIC_PUBLIC_KEY_DATA | HuksTagType.HUKS_TAG_TYPE_BYTES \| 20002 | Reserved. | 1975| HUKS_TAG_ASYMMETRIC_PRIVATE_KEY_DATA | HuksTagType.HUKS_TAG_TYPE_BYTES \| 20003 | Reserved. | 1976 1977## huks.generateKey<sup>(deprecated)</sup> 1978 1979generateKey(keyAlias: string, options: HuksOptions, callback: AsyncCallback\<HuksResult>) : void 1980 1981Generates a key. This API uses an asynchronous callback to return the result. 1982 1983> **NOTE**<br>This API is deprecated since API version 9. You are advised to use [huks.generateKeyItem<sup>9+</sup>](#huksgeneratekeyitem9). 1984 1985**System capability**: SystemCapability.Security.Huks 1986 1987**Parameters** 1988 1989| Name | Type | Mandatory| Description | 1990| -------- | ----------------------------------------- | ---- | ------------------------------------------------------------ | 1991| keyAlias | string | Yes | Alias of the key. | 1992| options | [HuksOptions](#huksoptions) | Yes | Tags required for generating the key. | 1993| callback | AsyncCallback\<[HuksResult](#huksresultdeprecated)> | Yes | Callback invoked to return the result. If the operation is successful, **HUKS_SUCCESS** is returned; otherwise, an error code defined in **HuksResult** is returned.| 1994 1995**Example** 1996 1997```js 1998/* Generate an RSA key of 512 bits. */ 1999let keyAlias = 'keyAlias'; 2000let properties = new Array(); 2001properties[0] = { 2002 tag: huks.HuksTag.HUKS_TAG_ALGORITHM, 2003 value: huks.HuksKeyAlg.HUKS_ALG_RSA 2004}; 2005properties[1] = { 2006 tag: huks.HuksTag.HUKS_TAG_KEY_SIZE, 2007 value: huks.HuksKeySize.HUKS_RSA_KEY_SIZE_512 2008}; 2009properties[2] = { 2010 tag: huks.HuksTag.HUKS_TAG_PURPOSE, 2011 value: 2012huks.HuksKeyPurpose.HUKS_KEY_PURPOSE_ENCRYPT | 2013huks.HuksKeyPurpose.HUKS_KEY_PURPOSE_DECRYPT 2014}; 2015properties[3] = { 2016 tag: huks.HuksTag.HUKS_TAG_PADDING, 2017 value: huks.HuksKeyPadding.HUKS_PADDING_OAEP 2018}; 2019properties[4] = { 2020 tag: huks.HuksTag.HUKS_TAG_DIGEST, 2021 value: huks.HuksKeyDigest.HUKS_DIGEST_SHA256 2022}; 2023let options = { 2024 properties: properties 2025}; 2026huks.generateKey(keyAlias, options, function (err, data){}); 2027``` 2028 2029## huks.generateKey<sup>(deprecated)</sup> 2030 2031generateKey(keyAlias: string, options: HuksOptions) : Promise\<HuksResult> 2032 2033Generates a key. This API uses a promise to return the result. 2034 2035> **NOTE**<br>This API is deprecated since API version 9. You are advised to use [huks.generateKeyItem<sup>9+</sup>](#huksgeneratekeyitem9-1). 2036 2037**System capability**: SystemCapability.Security.Huks 2038 2039**Parameters** 2040 2041| Name | Type | Mandatory| Description | 2042| -------- | --------------------------- | ---- | ------------------------ | 2043| keyAlias | string | Yes | Alias of the key. | 2044| options | [HuksOptions](#huksoptions) | Yes | Tags required for generating the key.| 2045 2046**Return value** 2047 2048| Type | Description | 2049| ----------------------------------- | -------------------------------------------------- | 2050| Promise\<[HuksResult](#huksresultdeprecated)> | Promise used to return the result. If the operation is successful, **HUKS_SUCCESS** is returned; otherwise, an error code is returned.| 2051 2052**Example** 2053 2054```js 2055/* Generate an ECC key of 256 bits. */ 2056let keyAlias = 'keyAlias'; 2057let properties = new Array(); 2058properties[0] = { 2059 tag: huks.HuksTag.HUKS_TAG_ALGORITHM, 2060 value: huks.HuksKeyAlg.HUKS_ALG_ECC 2061}; 2062properties[1] = { 2063 tag: huks.HuksTag.HUKS_TAG_KEY_SIZE, 2064 value: huks.HuksKeySize.HUKS_ECC_KEY_SIZE_256 2065}; 2066properties[2] = { 2067 tag: huks.HuksTag.HUKS_TAG_PURPOSE, 2068 value: 2069huks.HuksKeyPurpose.HUKS_KEY_PURPOSE_SIGN | 2070huks.HuksKeyPurpose.HUKS_KEY_PURPOSE_VERIFY 2071}; 2072properties[3] = { 2073 tag: huks.HuksTag.HUKS_TAG_DIGEST, 2074 value: huks.HuksKeyDigest.HUKS_DIGEST_SHA256 2075}; 2076let options = { 2077 properties: properties 2078}; 2079let result = huks.generateKey(keyAlias, options); 2080``` 2081 2082## huks.deleteKey<sup>(deprecated)</sup> 2083 2084deleteKey(keyAlias: string, options: HuksOptions, callback: AsyncCallback\<HuksResult>) : void 2085 2086Deletes a key. This API uses an asynchronous callback to return the result. 2087 2088> **NOTE**<br>This API is deprecated since API version 9. You are advised to use [huks.deleteKeyItem<sup>9+</sup>](#huksdeletekeyitem9). 2089 2090**System capability**: SystemCapability.Security.Huks 2091 2092**Parameters** 2093 2094| Name | Type | Mandatory| Description | 2095| -------- | ----------------------------------------- | ---- | -------------------------------------------------- | 2096| keyAlias | string | Yes | Key alias passed in when the key was generated. | 2097| options | [HuksOptions](#huksoptions) | Yes | Empty object (leave this parameter empty). | 2098| callback | AsyncCallback\<[HuksResult](#huksresultdeprecated)> | Yes | Callback invoked to return the result. If the operation is successful, **HUKS_SUCCESS** is returned; otherwise, an error code is returned.| 2099 2100**Example** 2101 2102```js 2103/* Set options to emptyOptions. */ 2104let keyAlias = 'keyAlias'; 2105let emptyOptions = { 2106 properties: [] 2107}; 2108huks.deleteKey(keyAlias, emptyOptions, function (err, data) {}); 2109``` 2110 2111## huks.deleteKey<sup>(deprecated)</sup> 2112 2113deleteKey(keyAlias: string, options: HuksOptions) : Promise\<HuksResult> 2114 2115Deletes a key. This API uses a promise to return the result. 2116 2117> **NOTE**<br>This API is deprecated since API version 9. You are advised to use [huks.deleteKeyItem<sup>9+</sup>](#huksdeletekeyitem9-1). 2118 2119**System capability**: SystemCapability.Security.Huks 2120 2121**Parameters** 2122 2123| Name | Type | Mandatory| Description | 2124| -------- | ----------- | ---- | ----------------------------------------------------- | 2125| keyAlias | string | Yes | Key alias passed in when the key was generated.| 2126| options | [HuksOptions](#huksoptions) | Yes | Empty object (leave this parameter empty).| 2127 2128**Return value** 2129 2130| Type | Description | 2131| ----------------------------------- | -------------------------------------------------- | 2132| Promise\<[HuksResult](#huksresultdeprecated)> | Promise used to return the result. If the operation is successful, **HUKS_SUCCESS** is returned; otherwise, an error code is returned.| 2133 2134**Example** 2135 2136```js 2137/* Set options to emptyOptions. */ 2138let keyAlias = 'keyAlias'; 2139let emptyOptions = { 2140 properties: [] 2141}; 2142let result = huks.deleteKey(keyAlias, emptyOptions); 2143``` 2144 2145## huks.importKey<sup>(deprecated)</sup> 2146 2147importKey(keyAlias: string, options: HuksOptions, callback: AsyncCallback\<HuksResult>) : void 2148 2149Imports a key in plaintext. This API uses an asynchronous callback to return the result. 2150 2151> **NOTE**<br>This API is deprecated since API version 9. You are advised to use [huks.importKeyItem<sup>9+</sup>](#huksimportkeyitem9). 2152 2153**System capability**: SystemCapability.Security.Huks 2154 2155**Parameters** 2156 2157| Name | Type | Mandatory| Description | 2158| -------- | ------------------------ | ---- | ------------------------------------------------- | 2159| keyAlias | string | Yes | Alias of the key.| 2160| options | [HuksOptions](#huksoptions) | Yes | Tags required for the import and key to import.| 2161| callback | AsyncCallback\<[HuksResult](#huksresultdeprecated)> | Yes | Callback invoked to return the result. If the operation is successful, **HUKS_SUCCESS** is returned; otherwise, an error code is returned.| 2162 2163**Example** 2164 2165```js 2166/* Import an AES key of 256 bits. */ 2167let plainTextSize32 = makeRandomArr(32); 2168function makeRandomArr(size) { 2169 let arr = new Uint8Array(size); 2170 for (let i = 0; i < size; i++) { 2171 arr[i] = Math.floor(Math.random() * 10); 2172 } 2173 return arr; 2174}; 2175let keyAlias = 'keyAlias'; 2176let properties = new Array(); 2177properties[0] = { 2178 tag: huks.HuksTag.HUKS_TAG_ALGORITHM, 2179 value: huks.HuksKeyAlg.HUKS_ALG_AES 2180}; 2181properties[1] = { 2182 tag: huks.HuksTag.HUKS_TAG_KEY_SIZE, 2183 value: huks.HuksKeySize.HUKS_AES_KEY_SIZE_256 2184}; 2185properties[2] = { 2186 tag: huks.HuksTag.HUKS_TAG_PURPOSE, 2187 value: 2188huks.HuksKeyPurpose.HUKS_KEY_PURPOSE_ENCRYPT | huks.HuksKeyPurpose.HUKS_KEY_PURPOSE_DECRYPT 2189}; 2190properties[3] = { 2191 tag: huks.HuksTag.HUKS_TAG_PADDING, 2192 value:huks.HuksKeyPadding.HUKS_PADDING_PKCS7 2193}; 2194properties[4] = { 2195 tag: huks.HuksTag.HUKS_TAG_BLOCK_MODE, 2196 value: huks.HuksCipherMode.HUKS_MODE_ECB 2197}; 2198let options = { 2199 properties: properties, 2200 inData: plainTextSize32 2201}; 2202huks.importKey(keyAlias, options, function (err, data){}); 2203``` 2204 2205## huks.importKey<sup>(deprecated)</sup> 2206 2207importKey(keyAlias: string, options: HuksOptions) : Promise\<HuksResult> 2208 2209Imports a key in plaintext. This API uses a promise to return the result. 2210 2211> **NOTE**<br>This API is deprecated since API version 9. You are advised to use [huks.importKeyItem<sup>9+</sup>](#huksimportkeyitem9-1). 2212 2213**System capability**: SystemCapability.Security.Huks 2214 2215**Parameters** 2216 2217| Name | Type | Mandatory| Description | 2218| -------- | ----------- | ---- | ------------------------------------ | 2219| keyAlias | string | Yes | Alias of the key.| 2220| options | [HuksOptions](#huksoptions) | Yes | Tags required for the import and key to import.| 2221 2222**Return value** 2223 2224| Type | Description | 2225| ----------------------------------- | -------------------------------------------------- | 2226| Promise\<[HuksResult](#huksresultdeprecated)> | Promise used to return the result. If the operation is successful, **HUKS_SUCCESS** is returned; otherwise, an error code is returned.| 2227 2228**Example** 2229 2230```js 2231/* Import an AES key of 128 bits. */ 2232let plainTextSize32 = makeRandomArr(32); 2233 2234function makeRandomArr(size) { 2235 let arr = new Uint8Array(size); 2236 for (let i = 0; i < size; i++) { 2237 arr[i] = Math.floor(Math.random() * 10); 2238 } 2239 return arr; 2240}; 2241 2242/* Step 1 Generate a key. */ 2243let keyAlias = 'keyAlias'; 2244let properties = new Array(); 2245properties[0] = { 2246 tag: huks.HuksTag.HUKS_TAG_ALGORITHM, 2247 value: huks.HuksKeyAlg.HUKS_ALG_AES 2248}; 2249properties[1] = { 2250 tag: huks.HuksTag.HUKS_TAG_KEY_SIZE, 2251 value: huks.HuksKeySize.HUKS_AES_KEY_SIZE_128 2252}; 2253properties[2] = { 2254 tag: huks.HuksTag.HUKS_TAG_PURPOSE, 2255 value: huks.HuksKeyPurpose.HUKS_KEY_PURPOSE_ENCRYPT | huks.HuksKeyPurpose.HUKS_KEY_PURPOSE_DECRYPT 2256}; 2257properties[3] = { 2258 tag: huks.HuksTag.HUKS_TAG_PADDING, 2259 value:huks.HuksKeyPadding.HUKS_PADDING_PKCS7 2260}; 2261properties[4] = { 2262 tag: huks.HuksTag.HUKS_TAG_BLOCK_MODE, 2263 value: huks.HuksCipherMode.HUKS_MODE_ECB 2264}; 2265let huksoptions = { 2266 properties: properties, 2267 inData: plainTextSize32 2268}; 2269let result = huks.importKey(keyAlias, huksoptions); 2270``` 2271 2272## huks.exportKey<sup>(deprecated)</sup> 2273 2274exportKey(keyAlias: string, options: HuksOptions, callback: AsyncCallback\<HuksResult>) : void 2275 2276Exports a key. This API uses an asynchronous callback to return the result. 2277 2278> **NOTE**<br>This API is deprecated since API version 9. You are advised to use [huks.exportKeyItem<sup>9+</sup>](#huksexportkeyitem9). 2279 2280**System capability**: SystemCapability.Security.Huks 2281 2282**Parameters** 2283 2284| Name | Type | Mandatory| Description | 2285| -------- | ----------------------------------------- | ---- | ------------------------------------------------------------ | 2286| keyAlias | string | Yes | Key alias, which must be the same as the alias used when the key was generated. | 2287| options | [HuksOptions](#huksoptions) | Yes | Empty object (leave this parameter empty). | 2288| callback | AsyncCallback\<[HuksResult](#huksresultdeprecated)> | Yes | Callback invoked to return the result. If the operation is successful, **HUKS_SUCCESS** is returned and **outData** contains the public key exported. If the operation fails, an error code is returned. | 2289 2290**Example** 2291 2292```js 2293/* Set options to emptyOptions. */ 2294let keyAlias = 'keyAlias'; 2295let emptyOptions = { 2296 properties: [] 2297}; 2298huks.exportKey(keyAlias, emptyOptions, function (err, data){}); 2299``` 2300 2301## huks.exportKey<sup>(deprecated)</sup> 2302 2303exportKey(keyAlias: string, options: HuksOptions) : Promise\<HuksResult> 2304 2305Exports a key. This API uses a promise to return the result. 2306 2307> **NOTE**<br>This API is deprecated since API version 9. You are advised to use [huks.exportKeyItem<sup>9+</sup>](#huksexportkeyitem9-1). 2308 2309**System capability**: SystemCapability.Security.Huks 2310 2311**Parameters** 2312 2313| Name | Type | Mandatory| Description | 2314| -------- | ----------- | ---- | ------------------------------------------------------------ | 2315| keyAlias | string | Yes | Key alias, which must be the same as the alias used when the key was generated.| 2316| options | [HuksOptions](#huksoptions) | Yes | Empty object (leave this parameter empty).| 2317 2318**Return value** 2319 2320| Type | Description | 2321| ----------------------------------- | ------------------------------------------------------------ | 2322| Promise\<[HuksResult](#huksresultdeprecated)> | Promise used to return the result. If the operation is successful, **HUKS_SUCCESS** is returned and **outData** contains the public key exported. If the operation fails, an error code is returned. | 2323 2324**Example** 2325 2326```js 2327/* Set options to emptyOptions. */ 2328let keyAlias = 'keyAlias'; 2329let emptyOptions = { 2330 properties: [] 2331}; 2332let result = huks.exportKey(keyAlias, emptyOptions); 2333``` 2334 2335## huks.getKeyProperties<sup>(deprecated)</sup> 2336 2337getKeyProperties(keyAlias: string, options: HuksOptions, callback: AsyncCallback\<HuksResult>) : void 2338 2339Obtains key properties. This API uses an asynchronous callback to return the result. 2340 2341> **NOTE**<br>This API is deprecated since API version 9. You are advised to use [huks.getKeyItemProperties<sup>9+</sup>](#huksgetkeyitemproperties9). 2342 2343**System capability**: SystemCapability.Security.Huks 2344 2345**Parameters** 2346 2347| Name | Type | Mandatory| Description | 2348| -------- | ----------------------------------------- | ---- | ------------------------------------------------------------ | 2349| keyAlias | string | Yes | Key alias, which must be the same as the alias used when the key was generated. | 2350| options | [HuksOptions](#huksoptions) | Yes | Empty object (leave this parameter empty). | 2351| callback | AsyncCallback\<[HuksResult](#huksresultdeprecated)> | Yes | Callback invoked to return the result. If the operation is successful, **errorCode** is **HUKS_SUCCESS**; otherwise, an error code is returned.| 2352 2353**Example** 2354 2355```js 2356/* Set options to emptyOptions. */ 2357let keyAlias = 'keyAlias'; 2358let emptyOptions = { 2359 properties: [] 2360}; 2361huks.getKeyProperties(keyAlias, emptyOptions, function (err, data){}); 2362``` 2363 2364## huks.getKeyProperties<sup>(deprecated)</sup> 2365 2366getKeyProperties(keyAlias: string, options: HuksOptions) : Promise\<HuksResult> 2367 2368Obtains key properties. This API uses a promise to return the result. 2369 2370> **NOTE**<br>This API is deprecated since API version 9. You are advised to use [huks.getKeyItemProperties<sup>9+</sup>](#huksgetkeyitemproperties9-1). 2371 2372**System capability**: SystemCapability.Security.Huks 2373 2374**Parameters** 2375 2376| Name | Type | Mandatory| Description | 2377| -------- | ----------- | ---- | ------------------------------------------------------------ | 2378| keyAlias | string | Yes | Key alias, which must be the same as the alias used when the key was generated.| 2379| options | [HuksOptions](#huksoptions) | Yes | Empty object (leave this parameter empty).| 2380 2381**Return value** 2382 2383| Type | Description | 2384| ------------------ | ------------------------------------------------------------ | 2385| Promise\<[HuksResult](#huksoptions)> | Promise used to return the result. If the operation is successful, **errorCode** is **HUKS_SUCCESS** and **properties** contains the parameters required for generating the key. If the operation fails, an error code is returned. | 2386 2387**Example** 2388 2389```js 2390/* Set options to emptyOptions. */ 2391let keyAlias = 'keyAlias'; 2392let emptyOptions = { 2393 properties: [] 2394}; 2395let result = huks.getKeyProperties(keyAlias, emptyOptions); 2396``` 2397 2398## huks.isKeyExist<sup>(deprecated)</sup> 2399 2400isKeyExist(keyAlias: string, options: HuksOptions, callback: AsyncCallback\<boolean>) : void 2401 2402Checks whether a key exists. This API uses an asynchronous callback to return the result. 2403 2404> **NOTE**<br>This API is deprecated since API version 9. You are advised to use [huks.isKeyItemExist<sup>9+</sup>](#huksiskeyitemexist9). 2405 2406**System capability**: SystemCapability.Security.Huks 2407 2408**Parameters** 2409 2410| Name | Type | Mandatory| Description | 2411| -------- | ---------------------- | ---- | ------------------------------------- | 2412| keyAlias | string | Yes | Alias of the key to check.| 2413| options | [HuksOptions](#huksoptions) | Yes | Empty object (leave this parameter empty).| 2414| callback | AsyncCallback\<boolean> | Yes | Callback invoked to return the result. The value **TRUE** means that the key exists; **FALSE** means the opposite.| 2415 2416**Example** 2417 2418```js 2419/* Set options to emptyOptions. */ 2420let keyAlias = 'keyAlias'; 2421let emptyOptions = { 2422 properties: [] 2423}; 2424huks.isKeyExist(keyAlias, emptyOptions, function (err, data){}); 2425``` 2426 2427## huks.isKeyExist<sup>(deprecated)</sup> 2428 2429isKeyExist(keyAlias: string, options: HuksOptions) : Promise\<boolean> 2430 2431Checks whether a key exists. This API uses a promise to return the result. 2432 2433> **NOTE**<br>This API is deprecated since API version 9. You are advised to use [huks.isKeyItemExist<sup>9+</sup>](#huksiskeyitemexist9-1). 2434 2435**System capability**: SystemCapability.Security.Huks 2436 2437**Parameters** 2438 2439| Name | Type | Mandatory| Description | 2440| -------- | ----------- | ---- | -------------------------------- | 2441| keyAlias | string | Yes | Alias of the key to check.| 2442| options | [HuksOptions](#huksoptions) | Yes | Empty object (leave this parameter empty).| 2443 2444**Return value** 2445 2446| Type | Description | 2447| ----------------- | --------------------------------------- | 2448| Promise\<boolean> | Promise used to return the result. The value **TRUE** means that the key exists; **FALSE** means the opposite.| 2449 2450**Example** 2451 2452```js 2453/* Set options to emptyOptions. */ 2454let keyAlias = 'keyAlias'; 2455let emptyOptions = { 2456 properties: [] 2457}; 2458let result = huks.isKeyExist(keyAlias, emptyOptions); 2459``` 2460 2461## huks.init<sup>(deprecated)</sup> 2462 2463init(keyAlias: string, options: HuksOptions, callback: AsyncCallback\<HuksHandle>) : void 2464 2465Initializes the data for a key operation. This API uses an asynchronous callback to return the result. **huks.init**, **huks.update**, and **huks.finish** must be used together. 2466 2467> **NOTE**<br>This API is deprecated since API version 9. You are advised to use [huks.initSession<sup>9+</sup>](#huksinitsession9-1). 2468 2469**System capability**: SystemCapability.Security.Huks 2470 2471**Parameters** 2472 2473| Name | Type | Mandatory| Description | 2474| -------- | ---------------------- | ---- | ------------------------------------- | 2475| keyAlias | string | Yes | Alias of the target key.| 2476| options | [HuksOptions](#huksoptions) | Yes | Parameter set used for the **init** operation.| 2477| callback | AsyncCallback\<[HuksHandle](#hukshandledeprecated)> | Yes | Callback invoked to return a session handle for subsequent operations.| 2478 2479## huks.init<sup>(deprecated)</sup> 2480 2481init(keyAlias: string, options: HuksOptions) : Promise\<HuksHandle> 2482 2483Initializes the data for a key operation. This API uses a promise to return the result. **huks.init**, **huks.update**, and **huks.finish** must be used together. 2484 2485> **NOTE**<br>This API is deprecated since API version 9. You are advised to use [huks.initSession<sup>9+</sup>](#huksinitsession9-1). 2486 2487**System capability**: SystemCapability.Security.Huks 2488 2489**Parameters** 2490 2491| Name | Type | Mandatory| Description | 2492| -------- | ---------------------- | ---- | ------------------------------------- | 2493| keyAlias | string | Yes | Alias of the target key.| 2494| options | [HuksOptions](#huksoptions) | Yes | Parameter set used for the **init** operation.| 2495 2496**Return value** 2497 2498| Type | Description | 2499| ----------------------------------- | -------------------------------------------------- | 2500| Promise\<[HuksHandle](#hukshandledeprecated)> | Promise used to return a session handle for subsequent operations.| 2501 2502## huks.update<sup>(deprecated)</sup> 2503 2504update(handle: number, token?: Uint8Array, options: HuksOptions, callback: AsyncCallback\<HuksResult>) : void 2505 2506Updates the key operation by segment. This API uses an asynchronous callback to return the result. **huks.init**, **huks.update**, and **huks.finish** must be used together. 2507 2508> **NOTE**<br>This API is deprecated since API version 9. You are advised to use [huks.updateSession<sup>9+</sup>](#huksupdatesession9-1). 2509 2510**System capability**: SystemCapability.Security.Huks 2511 2512**Parameters** 2513 2514| Name | Type | Mandatory| Description | 2515| -------- | ----------------------------------------- | ---- | -------------------------------------------- | 2516| handle | number | Yes | Handle for the **update** operation. | 2517| token | Uint8Array | No | Token of the **update** operation. | 2518| options | [HuksOptions](#huksoptions) | Yes | Parameter set used for the **update** operation. | 2519| callback | AsyncCallback\<[HuksResult](#huksresultdeprecated)> | Yes | Callback invoked to return the **update** operation result. | 2520 2521## huks.update<sup>(deprecated)</sup> 2522 2523update(handle: number, token?: Uint8Array, options: HuksOptions) : Promise\<HuksResult>; 2524 2525Updates the key operation by segment. This API uses a promise to return the result. **huks.init**, **huks.update**, and **huks.finish** must be used together. 2526 2527> **NOTE**<br>This API is deprecated since API version 9. You are advised to use [huks.updateSession<sup>9+</sup>](#huksupdatesession9-2). 2528 2529**System capability**: SystemCapability.Security.Huks 2530 2531**Parameters** 2532 2533| Name | Type | Mandatory| Description | 2534| ------- | ----------------------------------- | ---- | -------------------------------------------- | 2535| handle | number | Yes | Handle for the **update** operation. | 2536| token | Uint8Array | No | Token of the **update** operation. | 2537| options | [HuksOptions](#huksoptions) | Yes | Parameter set used for the **update** operation. | 2538 2539**Return value** 2540 2541| Type | Description | 2542| ----------------------------------- | -------------------------------------------------- | 2543| Promise\<[HuksResult](#huksresultdeprecated)> | Promise used to return the **update** operation result. | 2544 2545## huks.finish<sup>(deprecated)</sup> 2546 2547finish(handle: number, options: HuksOptions, callback: AsyncCallback\<HuksResult>) : void 2548 2549Completes the key operation and releases resources. This API uses an asynchronous callback to return the result. **huks.init**, **huks.update**, and **huks.finish** must be used together. 2550 2551> **NOTE**<br>This API is deprecated since API version 9. You are advised to use [huks.finishSession<sup>9+</sup>](#huksfinishsession9). 2552 2553**System capability**: SystemCapability.Security.Huks 2554 2555**Parameters** 2556 2557| Name | Type | Mandatory| Description | 2558| -------- | ---------------------- | ---- | ------------------------------------- | 2559| handle | number | Yes | Handle for the **finish** operation.| 2560| options | [HuksOptions](#huksoptions) | Yes | Parameter set used for the **finish** operation.| 2561| callback | AsyncCallback\<[HuksResult](#huksresultdeprecated)> | Yes| Callback invoked to return the **finish** operation result.| 2562 2563## huks.finish<sup>(deprecated)</sup> 2564 2565finish(handle: number, options: HuksOptions) : Promise\<HuksResult> 2566 2567Completes the key operation and releases resources. This API uses a promise to return the result. **huks.init**, **huks.update**, and **huks.finish** must be used together. 2568 2569> **NOTE**<br>This API is deprecated since API version 9. You are advised to use [huks.finishSession<sup>9+</sup>](#huksfinishsession9-1). 2570 2571**System capability**: SystemCapability.Security.Huks 2572 2573**Parameters** 2574 2575| Name | Type | Mandatory| Description | 2576| -------- | ---------------------- | ---- | ------------------------------------- | 2577| handle | number | Yes | Handle for the **finish** operation.| 2578| options | [HuksOptions](#huksoptions) | Yes | Parameter set used for the **finish** operation.| 2579 2580**Return value** 2581 2582| Type | Description | 2583| ----------------------------------- | -------------------------------------------------- | 2584| Promise\<[HuksResult](#huksresultdeprecated)> | Promise used to return the result.| 2585 2586## huks.abort<sup>(deprecated)</sup> 2587 2588abort(handle: number, options: HuksOptions, callback: AsyncCallback\<HuksResult>) : void 2589 2590Aborts the use of the key. This API uses an asynchronous callback to return the result. 2591 2592> **NOTE**<br>This API is deprecated since API version 9. You are advised to use [huks.abortSession<sup>9+</sup>](#huksabortsession9). 2593 2594**System capability**: SystemCapability.Security.Huks 2595 2596**Parameters** 2597 2598| Name | Type | Mandatory| Description | 2599| -------- | ---------------------- | ---- | ------------------------------------- | 2600| handle | number | Yes | Handle for the **abort** operation.| 2601| options | [HuksOptions](#huksoptions) | Yes | Parameter set used for the **abort** operation.| 2602| callback | AsyncCallback\<[HuksResult](#huksresultdeprecated)> | Yes| Callback invoked to return the **abort** operation result. | 2603 2604**Example** 2605 2606```js 2607/* huks.init, huks.update, and huks.finish must be used together. 2608 * If an error occurs in any of them, huks.abort must be called to terminate the use of the key. 2609 * 2610 * The following uses the callback of an RSA 1024 key as an example. 2611 */ 2612let keyalias = "HuksDemoRSA"; 2613let properties = new Array(); 2614let options = { 2615 properties: properties, 2616 inData: new Uint8Array(0) 2617}; 2618let handle; 2619let resultMessage = ""; 2620async function generateKey() { 2621 properties[0] = { 2622 tag: huks.HuksTag.HUKS_TAG_ALGORITHM, 2623 value: huks.HuksKeyAlg.HUKS_ALG_RSA 2624 }; 2625 properties[1] = { 2626 tag: huks.HuksTag.HUKS_TAG_KEY_SIZE, 2627 value: huks.HuksKeySize.HUKS_RSA_KEY_SIZE_1024 2628 }; 2629 properties[2] = { 2630 tag: huks.HuksTag.HUKS_TAG_PURPOSE, 2631 value: huks.HuksKeyPurpose.HUKS_KEY_PURPOSE_ENCRYPT 2632 }; 2633 properties[3] = { 2634 tag: huks.HuksTag.HUKS_TAG_PADDING, 2635 value: huks.HuksKeyPadding.HUKS_PADDING_OAEP 2636 }; 2637 properties[4] = { 2638 tag: huks.HuksTag.HUKS_TAG_DIGEST, 2639 value: huks.HuksKeyDigest.HUKS_DIGEST_SHA256 2640 }; 2641 huks.generateKey(keyalias, options); 2642} 2643function stringToUint8Array(str) { 2644 let arr = []; 2645 for (let i = 0, j = str.length; i < j; ++i) { 2646 arr.push(str.charCodeAt(i)); 2647 } 2648 let tmpUint8Array = new Uint8Array(arr); 2649 return tmpUint8Array; 2650} 2651async function huksInit() { 2652 await huks.init(keyalias, options).then((data) => { 2653 console.log(`test init data: ${JSON.stringify(data)}`); 2654 handle = data.handle; 2655 }).catch((err) => { 2656 console.log("test init err information: " + JSON.stringify(err)) 2657 }) 2658} 2659async function huksUpdate() { 2660 options.inData = stringToUint8Array("huksHmacTest"); 2661 await huks.update(handle, options).then((data) => { 2662 if (data.errorCode === 0) { 2663 resultMessage += "update success!"; 2664 } else { 2665 resultMessage += "update fail!"; 2666 } 2667 }); 2668 console.log(resultMessage); 2669} 2670function huksFinish() { 2671 options.inData = stringToUint8Array("HuksDemoHMAC"); 2672 huks.finish(handle, options).then((data) => { 2673 if (data.errorCode === 0) { 2674 resultMessage = "finish success!"; 2675 } else { 2676 resultMessage = "finish fail errorCode: " + data.errorCode; 2677 } 2678 }).catch((err) => { 2679 resultMessage = "Failed to complete the key operation. catch errorMessage:" + JSON.stringify(err) 2680 }); 2681 console.log(resultMessage); 2682} 2683async function huksAbort() { 2684 huks.abort(handle, options).then((data) => { 2685 if (data.errorCode === 0) { 2686 resultMessage = "abort success!"; 2687 } else { 2688 resultMessage = "abort fail errorCode: " + data.errorCode; 2689 } 2690 }).catch((err) => { 2691 resultMessage = "Failed to abort the use of the key. catch errorMessage:" + JSON.stringify(err) 2692 }); 2693 console.log(resultMessage); 2694} 2695``` 2696 2697## huks.abort<sup>(deprecated)</sup> 2698 2699abort(handle: number, options: HuksOptions) : Promise\<HuksResult>; 2700 2701Aborts the use of the key. This API uses a promise to return the result. 2702 2703> **NOTE**<br>This API is deprecated since API version 9. You are advised to use [huks.abortSession<sup>9+</sup>](#huksabortsession9-1). 2704 2705**System capability**: SystemCapability.Security.Huks 2706 2707**Parameters** 2708 2709| Name | Type | Mandatory| Description | 2710| -------- | ---------------------- | ---- | ------------------------------------- | 2711| handle | number | Yes | Handle for the **abort** operation.| 2712| options | [HuksOptions](#huksoptions) | Yes | Parameter set used for the **abort** operation.| 2713 2714**Return value** 2715 2716| Type | Description | 2717| ----------------------------------- | -------------------------------------------------- | 2718| Promise\<[HuksResult](#huksresultdeprecated)> | Promise used to return the **abort** operation result.| 2719 2720**Example** 2721 2722```js 2723/* huks.init, huks.update, and huks.finish must be used together. 2724 * If an error occurs in any of them, huks.abort must be called to terminate the use of the key. 2725 * 2726 * The following uses the promise of an RSA 1024-bit key as an example. 2727 */ 2728let keyalias = "HuksDemoRSA"; 2729let properties = new Array(); 2730let options = { 2731 properties: properties, 2732 inData: new Uint8Array(0) 2733}; 2734let handle; 2735let resultMessage = ""; 2736function stringToUint8Array(str) { 2737 let arr = []; 2738 for (let i = 0, j = str.length; i < j; ++i) { 2739 arr.push(str.charCodeAt(i)); 2740 } 2741 let tmpUint8Array = new Uint8Array(arr); 2742 return tmpUint8Array; 2743} 2744 2745async function generateKey() { 2746 properties[0] = { 2747 tag: huks.HuksTag.HUKS_TAG_ALGORITHM, 2748 value: huks.HuksKeyAlg.HUKS_ALG_RSA 2749 }; 2750 properties[1] = { 2751 tag: huks.HuksTag.HUKS_TAG_KEY_SIZE, 2752 value: huks.HuksKeySize.HUKS_RSA_KEY_SIZE_1024 2753 }; 2754 properties[2] = { 2755 tag: huks.HuksTag.HUKS_TAG_PURPOSE, 2756 value: huks.HuksKeyPurpose.HUKS_KEY_PURPOSE_ENCRYPT 2757 }; 2758 properties[3] = { 2759 tag: huks.HuksTag.HUKS_TAG_PADDING, 2760 value: huks.HuksKeyPadding.HUKS_PADDING_OAEP 2761 }; 2762 properties[4] = { 2763 tag: huks.HuksTag.HUKS_TAG_DIGEST, 2764 value: huks.HuksKeyDigest.HUKS_DIGEST_SHA256 2765 }; 2766 huks.generateKey(keyalias, options, function (err, data) { }); 2767} 2768async function huksInit() { 2769 return new Promise((resolve, reject) => { 2770 huks.init(keyalias, options, async function (err, data) { 2771 if (data.errorCode === 0) { 2772 resultMessage = "init success!" 2773 handle = data.handle; 2774 } else { 2775 resultMessage = "init fail errorCode: " + data.errorCode 2776 } 2777 }); 2778 }); 2779} 2780 2781async function huksUpdate() { 2782 options.inData = stringToUint8Array("huksHmacTest"); 2783 new Promise((resolve, reject) => { 2784 huks.update(handle, options, function (err, data) { 2785 if (data.errorCode === 0) { 2786 resultMessage += "update success!"; 2787 } else { 2788 resultMessage += "update fail!"; 2789 } 2790 }); 2791 }); 2792 console.log(resultMessage); 2793 2794} 2795 2796async function huksFinish() { 2797 options.inData = stringToUint8Array("0"); 2798 new Promise((resolve, reject) => { 2799 huks.finish(handle, options, function (err, data) { 2800 if (data.errorCode === 0) { 2801 resultMessage = "finish success!"; 2802 } else { 2803 resultMessage = "finish fail errorCode: " + data.errorCode; 2804 } 2805 }); 2806 }); 2807} 2808 2809function huksAbort() { 2810 new Promise((resolve, reject) => { 2811 huks.abort(handle, options, function (err, data) { 2812 console.log(`Huks_Demo hmac huksAbort1 data ${JSON.stringify(data)}`); 2813 console.log(`Huks_Demo hmac huksAbort1 err ${JSON.stringify(err)}`); 2814 }); 2815 }); 2816} 2817``` 2818 2819## HuksHandle<sup>(deprecated)</sup> 2820 2821Defines the HUKS handle structure. 2822 2823**System capability**: SystemCapability.Security.Huks 2824 2825| Name | Type | Mandatory| Description | 2826| ---------- | ---------------- | ---- | -------- | 2827| errorCode | number | Yes | Error code.| 2828| handle | number | Yes| Value of the handle.| 2829| token | Uint8Array | No| Challenge obtained after the [init](#huksinitdeprecated) operation.| 2830 2831## HuksResult<sup>(deprecated)</sup> 2832 2833Defines the **HuksResult** structure. 2834 2835**System capability**: SystemCapability.Security.Huks 2836 2837| Name | Type | Mandatory| Description | 2838| ---------- | ------------------------------- | ---- | ---------------- | 2839| errorCode | number | Yes | Error code. | 2840| outData | Uint8Array | No | Output data. | 2841| properties | Array\<[HuksParam](#huksparam)> | No | Property information. | 2842| certChains | Array\<string> | No | Certificate chain information.| 2843 2844 2845## HuksErrorCode<sup>(deprecated)</sup> 2846 2847Enumerates the error codes. 2848 2849**System capability**: SystemCapability.Security.Huks 2850 2851| Name | Value | Description| 2852| -------------------------- | ----- | ---- | 2853| HUKS_SUCCESS | 0 |Success.| 2854| HUKS_FAILURE | -1 |Failure.| 2855| HUKS_ERROR_BAD_STATE | -2 |Incorrect state.| 2856| HUKS_ERROR_INVALID_ARGUMENT | -3 |Invalid argument.| 2857| HUKS_ERROR_NOT_SUPPORTED | -4 |Not supported.| 2858| HUKS_ERROR_NO_PERMISSION | -5 |No permission.| 2859| HUKS_ERROR_INSUFFICIENT_DATA | -6 |Insufficient data.| 2860| HUKS_ERROR_BUFFER_TOO_SMALL | -7 |Insufficient buffer.| 2861| HUKS_ERROR_INSUFFICIENT_MEMORY | -8 |Insufficient memory.| 2862| HUKS_ERROR_COMMUNICATION_FAILURE | -9 |Communication failure.| 2863| HUKS_ERROR_STORAGE_FAILURE | -10 |Insufficient storage space.| 2864| HUKS_ERROR_HARDWARE_FAILURE | -11 |Hardware fault.| 2865| HUKS_ERROR_ALREADY_EXISTS | -12 |The object already exists.| 2866| HUKS_ERROR_NOT_EXIST | -13 |The object does not exist.| 2867| HUKS_ERROR_NULL_POINTER | -14 |Null pointer.| 2868| HUKS_ERROR_FILE_SIZE_FAIL | -15 |Incorrect file size.| 2869| HUKS_ERROR_READ_FILE_FAIL | -16 |Failed to read the file.| 2870| HUKS_ERROR_INVALID_PUBLIC_KEY | -17 |Invalid public key.| 2871| HUKS_ERROR_INVALID_PRIVATE_KEY | -18 |Invalid private key.| 2872| HUKS_ERROR_INVALID_KEY_INFO | -19 |Invalid key information.| 2873| HUKS_ERROR_HASH_NOT_EQUAL | -20 |The hash values are not equal.| 2874| HUKS_ERROR_MALLOC_FAIL | -21 |MALLOC failed.| 2875| HUKS_ERROR_WRITE_FILE_FAIL | -22 |Failed to write the file.| 2876| HUKS_ERROR_REMOVE_FILE_FAIL | -23 |Failed to delete the file.| 2877| HUKS_ERROR_OPEN_FILE_FAIL | -24 |Failed to open the file.| 2878| HUKS_ERROR_CLOSE_FILE_FAIL | -25 |Failed to close the file.| 2879| HUKS_ERROR_MAKE_DIR_FAIL | -26 |Failed to create the directory.| 2880| HUKS_ERROR_INVALID_KEY_FILE | -27 |Invalid key file.| 2881| HUKS_ERROR_IPC_MSG_FAIL | -28 |Incorrect IPC information.| 2882| HUKS_ERROR_REQUEST_OVERFLOWS | -29 |Request overflows.| 2883| HUKS_ERROR_PARAM_NOT_EXIST | -30 |The parameter does not exist.| 2884| HUKS_ERROR_CRYPTO_ENGINE_ERROR | -31 |CRYPTO ENGINE error.| 2885| HUKS_ERROR_COMMUNICATION_TIMEOUT | -32 |Communication timed out.| 2886| HUKS_ERROR_IPC_INIT_FAIL | -33 |IPC initialization failed.| 2887| HUKS_ERROR_IPC_DLOPEN_FAIL | -34 |IPC DLOPEN failed.| 2888| HUKS_ERROR_EFUSE_READ_FAIL | -35 |Failed to read eFUSE.| 2889| HUKS_ERROR_NEW_ROOT_KEY_MATERIAL_EXIST | -36 |New root key material exists.| 2890| HUKS_ERROR_UPDATE_ROOT_KEY_MATERIAL_FAIL | -37 |Failed to update the root key material.| 2891| HUKS_ERROR_VERIFICATION_FAILED | -38 |Failed to verify the certificate chain.| 2892| HUKS_ERROR_CHECK_GET_ALG_FAIL | -100 |Failed to obtain the ALG. | 2893| HUKS_ERROR_CHECK_GET_KEY_SIZE_FAIL | -101 |Failed to obtain the key size.| 2894| HUKS_ERROR_CHECK_GET_PADDING_FAIL | -102 |Failed to obtain the padding algorithm.| 2895| HUKS_ERROR_CHECK_GET_PURPOSE_FAIL | -103 |Failed to obtain the key purpose.| 2896| HUKS_ERROR_CHECK_GET_DIGEST_FAIL | -104 |Failed to obtain the digest algorithm.| 2897| HUKS_ERROR_CHECK_GET_MODE_FAIL | -105 |Failed to obtain the cipher mode.| 2898| HUKS_ERROR_CHECK_GET_NONCE_FAIL | -106 |Failed to obtain the nonce.| 2899| HUKS_ERROR_CHECK_GET_AAD_FAIL | -107 |Failed to obtain the AAD.| 2900| HUKS_ERROR_CHECK_GET_IV_FAIL | -108 |Failed to obtain the initialization vector (IV).| 2901| HUKS_ERROR_CHECK_GET_AE_TAG_FAIL | -109 |Failed to obtain the AE flag.| 2902| HUKS_ERROR_CHECK_GET_SALT_FAIL | -110 |Failed to obtain the salt value.| 2903| HUKS_ERROR_CHECK_GET_ITERATION_FAIL | -111 |Failed to obtain the number of iterations.| 2904| HUKS_ERROR_INVALID_ALGORITHM | -112 |Invalid algorithm.| 2905| HUKS_ERROR_INVALID_KEY_SIZE | -113 |Invalid key size.| 2906| HUKS_ERROR_INVALID_PADDING | -114 |Invalid padding algorithm.| 2907| HUKS_ERROR_INVALID_PURPOSE | -115 |Invalid key purpose.| 2908| HUKS_ERROR_INVALID_MODE | -116 |Invalid cipher mode.| 2909| HUKS_ERROR_INVALID_DIGEST | -117 |Invalid digest algorithm.| 2910| HUKS_ERROR_INVALID_SIGNATURE_SIZE | -118 |Invalid signature size.| 2911| HUKS_ERROR_INVALID_IV | -119 |Invalid IV.| 2912| HUKS_ERROR_INVALID_AAD | -120 |Invalid AAD.| 2913| HUKS_ERROR_INVALID_NONCE | -121 |Invalid nonce.| 2914| HUKS_ERROR_INVALID_AE_TAG | -122 |Invalid AE tag.| 2915| HUKS_ERROR_INVALID_SALT | -123 |Invalid salt value.| 2916| HUKS_ERROR_INVALID_ITERATION | -124 |Invalid iteration count.| 2917| HUKS_ERROR_INVALID_OPERATION | -125 |Invalid operation.| 2918| HUKS_ERROR_INTERNAL_ERROR | -999 |Internal error.| 2919| HUKS_ERROR_UNKNOWN_ERROR | -1000 |Unknown error.| 2920