js-apis-huks.md 125.5 KB
Newer Older
A
annie_wangli 已提交
1 2
# HUKS

A
Annie_wang 已提交
3 4 5
The **HUKS** module provides KeyStore (KS) capabilities for applications, including key management and key cryptography operations.
The keys managed by OpenHarmony Universal KeyStore (HUKS) can be imported by applications or generated by calling the HUKS APIs.

A
Annie_wang 已提交
6
> ![icon-note.gif](public_sys-resources/icon-note.gif) **NOTE**<br>
7
>
A
annie_wangli 已提交
8 9 10 11 12 13 14 15
> 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.

## Modules to Import

```js
import huks from '@ohos.security.huks'
```

A
Annie_wang 已提交
16
## HuksParam
A
annie_wangli 已提交
17

A
Annie_wang 已提交
18
Defines the **param** in the **properties** array of **options** used in the APIs.
A
annie_wangli 已提交
19

A
Annie_wang 已提交
20
**System capability**: SystemCapability.Security.Huks
A
annie_wangli 已提交
21

A
Annie_wang 已提交
22 23 24 25
| Name| Type                               | Mandatory| Description        |
| ------ | ----------------------------------- | ---- | ------------ |
| tag    | [HuksTag](#hukstag)                 | Yes  | Tag.      |
| value  | boolean\|number\|bigint\|Uint8Array | Yes  | Value of the tag.|
A
annie_wangli 已提交
26

A
Annie_wang 已提交
27
## HuksOptions
A
annie_wangli 已提交
28

A
Annie_wang 已提交
29
Defines the **options** used in the APIs. 
A
annie_wangli 已提交
30 31 32

**System capability**: SystemCapability.Security.Huks

A
Annie_wang 已提交
33 34 35 36
| Name    | Type             | Mandatory| Description                    |
| ---------- | ----------------- | ---- | ------------------------ |
| properties | Array\<[HuksParam](#huksparam)> | No  | Properties used to hold the **HuksParam** array.|
| inData     | Uint8Array        | No  | Input data.              |
A
annie_wangli 已提交
37

A
Annie_wang 已提交
38
## HuksSessionHandle<sup>9+</sup>
A
annie_wangli 已提交
39

A
Annie_wang 已提交
40
Defines the HUKS handle structure.
A
annie_wangli 已提交
41 42 43

**System capability**: SystemCapability.Security.Huks

A
Annie_wang 已提交
44 45 46 47
| Name   | Type      | Mandatory| Description                                                |
| --------- | ---------- | ---- | ---------------------------------------------------- |
| handle    | number     | Yes  | Value of the handle.                                      |
| challenge | Uint8Array | No  | Challenge obtained after the [init](#huksinit) operation.|
A
annie_wangli 已提交
48

A
Annie_wang 已提交
49
## HuksReturnResult<sup>9+</sup>
A
annie_wangli 已提交
50

A
Annie_wang 已提交
51
Defines the **HuksResult** structure.
A
annie_wangli 已提交
52 53 54 55 56

**System capability**: SystemCapability.Security.Huks



A
Annie_wang 已提交
57 58 59 60 61
| Name    | Type                           | Mandatory| Description            |
| ---------- | ------------------------------- | ---- | ---------------- |
| outData    | Uint8Array                      | No  | Output data.  |
| properties | Array\<[HuksParam](#huksparam)> | No  | Property information.  |
| certChains | Array\<string>                  | No  | Certificate chain information.|
A
annie_wangli 已提交
62 63


A
Annie_wang 已提交
64
## huks.generateKeyItem<sup>9+</sup>
A
annie_wangli 已提交
65

A
Annie_wang 已提交
66
generateKeyItem(keyAlias: string, options: HuksOptions, callback: AsyncCallback\<void>) : void
A
annie_wangli 已提交
67

A
Annie_wang 已提交
68
Generates a key. This API uses an asynchronous callback to return the result.
A
annie_wangli 已提交
69 70 71

**System capability**: SystemCapability.Security.Huks

A
Annie_wang 已提交
72
**Parameters**
A
annie_wangli 已提交
73

A
Annie_wang 已提交
74 75 76 77
| Name  | Type                       | Mandatory| Description                                         |
| -------- | --------------------------- | ---- | --------------------------------------------- |
| keyAlias | string                      | Yes  | Alias of the key.                                        |
| options  | [HuksOptions](#huksoptions) | Yes  | Tags required for generating the key.                     |
A
Annie_wang 已提交
78
| callback | AsyncCallback\<void>        | Yes  | Callback that returns no value.|
A
annie_wangli 已提交
79

A
Annie_wang 已提交
80
**Example**
A
annie_wangli 已提交
81

A
Annie_wang 已提交
82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118
```js
/* Generate an ECC key of 256 bits. */
let keyAlias = 'keyAlias';
let properties = new Array();
properties[0] = {
    tag: huks.HuksTag.HUKS_TAG_ALGORITHM,
    value: huks.HuksKeyAlg.HUKS_ALG_ECC
};
properties[1] = {
    tag: huks.HuksTag.HUKS_TAG_KEY_SIZE,
    value: huks.HuksKeySize.HUKS_ECC_KEY_SIZE_256
};
properties[2] = {
    tag: huks.HuksTag.HUKS_TAG_PURPOSE,
    value:
    huks.HuksKeyPurpose.HUKS_KEY_PURPOSE_SIGN |
    huks.HuksKeyPurpose.HUKS_KEY_PURPOSE_VERIFY
};
properties[3] = {
    tag: huks.HuksTag.HUKS_TAG_DIGEST,
    value: huks.HuksKeyDigest.HUKS_DIGEST_SHA256
};
let options = {
    properties: properties
};
try {
    huks.generateKeyItem(keyAlias, options, function (error, data) {
        if (error) {
            console.error(`callback: generateKeyItem failed, code: ${error.code}, msg: ${error.message}`);
        } else {
            console.info(`callback: generateKeyItem key success`);
        }
    });
} catch (error) {
    console.error(`callback: generateKeyItem input arg invalid, code: ${error.code}, msg: ${error.message}`);
}
```
A
annie_wangli 已提交
119

A
Annie_wang 已提交
120
## huks.generateKeyItem<sup>9+</sup>
A
annie_wangli 已提交
121

A
Annie_wang 已提交
122
generateKeyItem(keyAlias: string, options: HuksOptions) : Promise\<void>
A
annie_wangli 已提交
123

A
Annie_wang 已提交
124
Generates a key. This API uses a promise to return the result.
A
annie_wangli 已提交
125 126 127

**System capability**: SystemCapability.Security.Huks

A
Annie_wang 已提交
128
**Parameters**
A
annie_wangli 已提交
129

A
Annie_wang 已提交
130 131 132 133
| Name  | Type                       | Mandatory| Description                    |
| -------- | --------------------------- | ---- | ------------------------ |
| keyAlias | string                      | Yes  | Alias of the key.              |
| options  | [HuksOptions](#huksoptions) | Yes  | Tags required for generating the key.|
A
annie_wangli 已提交
134

A
Annie_wang 已提交
135
**Example**
A
annie_wangli 已提交
136

A
Annie_wang 已提交
137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173
```js
/* Generate an ECC key of 256 bits. */
let keyAlias = 'keyAlias';
let properties = new Array();
properties[0] = {
    tag: huks.HuksTag.HUKS_TAG_ALGORITHM,
    value: huks.HuksKeyAlg.HUKS_ALG_ECC
};
properties[1] = {
    tag: huks.HuksTag.HUKS_TAG_KEY_SIZE,
    value: huks.HuksKeySize.HUKS_ECC_KEY_SIZE_256
};
properties[2] = {
    tag: huks.HuksTag.HUKS_TAG_PURPOSE,
    value:
    huks.HuksKeyPurpose.HUKS_KEY_PURPOSE_SIGN |
    huks.HuksKeyPurpose.HUKS_KEY_PURPOSE_VERIFY
};
properties[3] = {
    tag: huks.HuksTag.HUKS_TAG_DIGEST,
    value: huks.HuksKeyDigest.HUKS_DIGEST_SHA256
};
let options = {
    properties: properties
};
try {
    huks.generateKeyItem(keyAlias, options)
        .then((data) => {
            console.info(`promise: generateKeyItem success`);
        })
        .catch(error => {
            console.error(`promise: generateKeyItem failed, code: ${error.code}, msg: ${error.message}`);
        });
} catch (error) {
    console.error(`promise: generateKeyItem input arg invalid, code: ${error.code}, msg: ${error.message}`);
}
```
A
annie_wangli 已提交
174

A
Annie_wang 已提交
175
## huks.deleteKeyItem<sup>9+</sup>
A
annie_wangli 已提交
176

A
Annie_wang 已提交
177
deleteKeyItem(keyAlias: string, options: HuksOptions, callback: AsyncCallback\<void>) : void
A
annie_wangli 已提交
178

A
Annie_wang 已提交
179
Deletes a key. This API uses an asynchronous callback to return the result.
A
annie_wangli 已提交
180 181 182

**System capability**: SystemCapability.Security.Huks

A
Annie_wang 已提交
183
**Parameters**
A
annie_wangli 已提交
184

A
Annie_wang 已提交
185 186 187 188
| Name  | Type                       | Mandatory| Description                                         |
| -------- | --------------------------- | ---- | --------------------------------------------- |
| keyAlias | string                      | Yes  | Key alias passed in when the key was generated.          |
| options  | [HuksOptions](#huksoptions) | Yes  | Empty object (leave this parameter empty).                     |
A
Annie_wang 已提交
189
| callback | AsyncCallback\<void>        | Yes  | Callback that returns no value.|
A
annie_wangli 已提交
190

A
Annie_wang 已提交
191
**Example**
A
annie_wangli 已提交
192

A
Annie_wang 已提交
193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210
```js
/* Set options to emptyOptions. */
let keyAlias = 'keyAlias';
let emptyOptions = {
    properties: []
};
try {
    huks.deleteKeyItem(keyAlias, emptyOptions, function (error, data) {
        if (error) {
            console.error(`callback: deleteKeyItem failed, code: ${error.code}, msg: ${error.message}`);
        } else {
            console.info(`callback: deleteKeyItem key success`);
        }
    });
} catch (error) {
    console.error(`callback: deleteKeyItem input arg invalid, code: ${error.code}, msg: ${error.message}`);
}
```
A
annie_wangli 已提交
211

A
Annie_wang 已提交
212
## huks.deleteKeyItem<sup>9+</sup>
A
Annie_wang 已提交
213

A
Annie_wang 已提交
214
deleteKeyItem(keyAlias: string, options: HuksOptions) : Promise\<void>
A
Annie_wang 已提交
215

A
Annie_wang 已提交
216
Deletes a key. This API uses a promise to return the result.
A
Annie_wang 已提交
217 218 219

**System capability**: SystemCapability.Security.Huks

A
Annie_wang 已提交
220
**Parameters**
A
Annie_wang 已提交
221

A
Annie_wang 已提交
222 223 224 225
| Name  | Type                       | Mandatory| Description                               |
| -------- | --------------------------- | ---- | ----------------------------------- |
| keyAlias | string                      | Yes  | Key alias passed in when the key was generated.|
| options  | [HuksOptions](#huksoptions) | Yes  | Empty object (leave this parameter empty).           |
A
Annie_wang 已提交
226

A
Annie_wang 已提交
227
**Example**
A
Annie_wang 已提交
228

A
Annie_wang 已提交
229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246
```js
/* Set options to emptyOptions. */
let keyAlias = 'keyAlias';
let emptyOptions = {
    properties: []
};
try {
    huks.deleteKeyItem(keyAlias, emptyOptions)
        .then ((data) => {
            console.info(`promise: deleteKeyItem key success`);
        })
        .catch(error => {
            console.error(`promise: deleteKeyItem failed, code: ${error.code}, msg: ${error.message}`);
        });
} catch (error) {
    console.error(`promise: deleteKeyItem input arg invalid, code: ${error.code}, msg: ${error.message}`);
}
```
A
Annie_wang 已提交
247

A
Annie_wang 已提交
248
## huks.getSdkVersion
A
Annie_wang 已提交
249

A
Annie_wang 已提交
250
getSdkVersion(options: HuksOptions) : string
A
annie_wangli 已提交
251

A
Annie_wang 已提交
252
Obtains the SDK version of the current system.
A
annie_wangli 已提交
253 254 255

**System capability**: SystemCapability.Security.Huks

A
Annie_wang 已提交
256
**Parameters**
A
annie_wangli 已提交
257

A
Annie_wang 已提交
258 259 260
| Name | Type      | Mandatory| Description                     |
| ------- | ---------- | ---- | ------------------------- |
| options | [HuksOptions](#huksoptions) | Yes  | Empty object, which is used to hold the SDK version.|
A
annie_wangli 已提交
261

A
Annie_wang 已提交
262
**Return value**
A
annie_wangli 已提交
263

A
Annie_wang 已提交
264 265 266
| Type  | Description         |
| ------ | ------------- |
| string | SDK version obtained.|
A
annie_wangli 已提交
267

A
Annie_wang 已提交
268
**Example**
A
annie_wangli 已提交
269

A
Annie_wang 已提交
270 271 272 273 274 275 276
```js
/* Set options to emptyOptions. */
let emptyOptions = {
  properties: []
};
let result = huks.getSdkVersion(emptyOptions);
```
A
annie_wangli 已提交
277

A
Annie_wang 已提交
278
## huks.importKeyItem<sup>9+</sup>
A
annie_wangli 已提交
279

A
Annie_wang 已提交
280
importKeyItem(keyAlias: string, options: HuksOptions, callback: AsyncCallback\<void>) : void
A
annie_wangli 已提交
281

A
Annie_wang 已提交
282
Imports a key in plaintext. This API uses an asynchronous callback to return the result.
A
annie_wangli 已提交
283 284 285 286 287

**System capability**: SystemCapability.Security.Huks

**Parameters**

A
Annie_wang 已提交
288 289 290 291
| Name  | Type                       | Mandatory| Description                                         |
| -------- | --------------------------- | ---- | --------------------------------------------- |
| keyAlias | string                      | Yes  | Alias of the key.                                   |
| options  | [HuksOptions](#huksoptions) | Yes  | Tags required for the import and key to import.          |
A
Annie_wang 已提交
292
| callback | AsyncCallback\<void>        | Yes  | Callback that returns no value.|
A
annie_wangli 已提交
293 294 295 296

**Example**

```js
A
Annie_wang 已提交
297 298 299 300 301 302 303 304 305 306 307
/* Import an AES key of 256 bits. */
let plainTextSize32 = makeRandomArr(32);
function makeRandomArr(size) {
    let arr = new Uint8Array(size);
    for (let i = 0; i < size; i++) {
        arr[i] = Math.floor(Math.random() * 10);
    }
    return arr;
};
let keyAlias = 'keyAlias';
let properties = new Array();
A
annie_wangli 已提交
308
properties[0] = {
A
Annie_wang 已提交
309 310
    tag: huks.HuksTag.HUKS_TAG_ALGORITHM,
    value: huks.HuksKeyAlg.HUKS_ALG_AES
A
annie_wangli 已提交
311 312
};
properties[1] = {
A
Annie_wang 已提交
313 314
    tag: huks.HuksTag.HUKS_TAG_KEY_SIZE,
    value: huks.HuksKeySize.HUKS_AES_KEY_SIZE_256
A
annie_wangli 已提交
315 316
};
properties[2] = {
A
Annie_wang 已提交
317 318 319
    tag: huks.HuksTag.HUKS_TAG_PURPOSE,
    value:
    huks.HuksKeyPurpose.HUKS_KEY_PURPOSE_ENCRYPT | huks.HuksKeyPurpose.HUKS_KEY_PURPOSE_DECRYPT
A
annie_wangli 已提交
320 321
};
properties[3] = {
A
Annie_wang 已提交
322 323
    tag: huks.HuksTag.HUKS_TAG_PADDING,
    value:huks.HuksKeyPadding.HUKS_PADDING_PKCS7
A
annie_wangli 已提交
324 325
};
properties[4] = {
A
Annie_wang 已提交
326 327
    tag: huks.HuksTag.HUKS_TAG_BLOCK_MODE,
    value: huks.HuksCipherMode.HUKS_MODE_ECB
A
annie_wangli 已提交
328
};
A
Annie_wang 已提交
329 330 331
let options = {
    properties: properties,
    inData: plainTextSize32
A
annie_wangli 已提交
332
};
A
Annie_wang 已提交
333 334 335 336 337 338 339 340 341 342 343
try {
    huks.importKeyItem(keyAlias, options, function (error, data) {
        if (error) {
            console.error(`callback: importKeyItem failed, code: ${error.code}, msg: ${error.message}`);
        } else {
            console.info(`callback: importKeyItem success`);
        }
    });
} catch (error) {
    console.error(`callback: importKeyItem input arg invalid, code: ${error.code}, msg: ${error.message}`);
}
A
annie_wangli 已提交
344 345
```

A
Annie_wang 已提交
346
## huks.importKeyItem<sup>9+</sup>
A
annie_wangli 已提交
347

A
Annie_wang 已提交
348
importKeyItem(keyAlias: string, options: HuksOptions) : Promise\<void>
A
annie_wangli 已提交
349

A
Annie_wang 已提交
350
Imports a key in plaintext. This API uses a promise to return the result.
A
annie_wangli 已提交
351 352 353 354 355

**System capability**: SystemCapability.Security.Huks

**Parameters**

A
Annie_wang 已提交
356 357 358 359
| Name  | Type                       | Mandatory| Description                               |
| -------- | --------------------------- | ---- | ----------------------------------- |
| keyAlias | string                      | Yes  | Alias of the key.                         |
| options  | [HuksOptions](#huksoptions) | Yes  | Tags required for the import and key to import.|
A
annie_wangli 已提交
360 361 362 363

**Example**

```js
A
Annie_wang 已提交
364 365 366 367 368 369 370 371 372 373 374 375 376 377
/* Import an AES key of 128 bits. */
let plainTextSize32 = makeRandomArr(32);

function makeRandomArr(size) {
    let arr = new Uint8Array(size);
    for (let i = 0; i < size; i++) {
        arr[i] = Math.floor(Math.random() * 10);
    }
    return arr;
};

/* Step 1 Generate a key. */
let keyAlias = 'keyAlias';
let properties = new Array();
A
annie_wangli 已提交
378
properties[0] = {
A
Annie_wang 已提交
379 380
    tag: huks.HuksTag.HUKS_TAG_ALGORITHM,
    value: huks.HuksKeyAlg.HUKS_ALG_AES
A
annie_wangli 已提交
381 382
};
properties[1] = {
A
Annie_wang 已提交
383 384
    tag: huks.HuksTag.HUKS_TAG_KEY_SIZE,
    value: huks.HuksKeySize.HUKS_AES_KEY_SIZE_128
A
annie_wangli 已提交
385 386
};
properties[2] = {
A
Annie_wang 已提交
387 388
    tag: huks.HuksTag.HUKS_TAG_PURPOSE,
    value: huks.HuksKeyPurpose.HUKS_KEY_PURPOSE_ENCRYPT | huks.HuksKeyPurpose.HUKS_KEY_PURPOSE_DECRYPT
A
annie_wangli 已提交
389 390
};
properties[3] = {
A
Annie_wang 已提交
391 392
    tag: huks.HuksTag.HUKS_TAG_PADDING,
    value:huks.HuksKeyPadding.HUKS_PADDING_PKCS7
A
annie_wangli 已提交
393
};
A
Annie_wang 已提交
394 395 396
properties[4] = {
    tag: huks.HuksTag.HUKS_TAG_BLOCK_MODE,
    value: huks.HuksCipherMode.HUKS_MODE_ECB
A
annie_wangli 已提交
397
};
A
Annie_wang 已提交
398 399 400 401 402 403 404 405 406 407 408 409 410 411 412
let huksoptions = {
    properties: properties,
    inData: plainTextSize32
};
try {
    huks.importKeyItem(keyAlias, huksoptions)
        .then ((data) => {
            console.info(`promise: importKeyItem success`);
        })
        .catch(error => {
            console.error(`promise: importKeyItem failed, code: ${error.code}, msg: ${error.message}`);
        });
} catch (error) {
    console.error(`promise: importKeyItem input arg invalid, code: ${error.code}, msg: ${error.message}`);
}
A
annie_wangli 已提交
413 414
```

A
Annie_wang 已提交
415
## huks.attestKeyItem<sup>9+</sup>
A
annie_wangli 已提交
416

A
Annie_wang 已提交
417
attestKeyItem(keyAlias: string, options: HuksOptions, callback: AsyncCallback\<HuksReturnResult>) : void
A
annie_wangli 已提交
418

A
Annie_wang 已提交
419
Obtains the certificate used to verify a key. This API uses an asynchronous callback to return the result.
A
annie_wangli 已提交
420 421 422 423 424

**System capability**: SystemCapability.Security.Huks

**Parameters**

A
Annie_wang 已提交
425 426 427 428 429
| Name  | Type                                                | Mandatory| Description                                         |
| -------- | ---------------------------------------------------- | ---- | --------------------------------------------- |
| keyAlias | string                                               | Yes  | Alias of the key. The certificate to be obtained stores the key.         |
| options  | [HuksOptions](#huksoptions)                          | Yes  | Parameters and data required for obtaining the certificate.           |
| callback | AsyncCallback<[HuksReturnResult](#huksreturnresult)> | Yes  | Callback invoked to return the result. If the operation is successful, no **err** value is returned; otherwise, an error code is returned.|
A
annie_wangli 已提交
430 431 432 433

**Example**

```js
A
Annie_wang 已提交
434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534
let securityLevel = stringToUint8Array('sec_level');
let challenge = stringToUint8Array('challenge_data');
let versionInfo = stringToUint8Array('version_info');
let keyAliasString = "key attest";

function stringToUint8Array(str) {
    let arr = [];
    for (let i = 0, j = str.length; i < j; ++i) {
        arr.push(str.charCodeAt(i));
    }
    let tmpUint8Array = new Uint8Array(arr);
    return tmpUint8Array;
}

async function generateKey(alias) {
    let properties = new Array();
    properties[0] = {
        tag: huks.HuksTag.HUKS_TAG_ALGORITHM,
        value: huks.HuksKeyAlg.HUKS_ALG_RSA
    };
    properties[1] = {
        tag: huks.HuksTag.HUKS_TAG_KEY_STORAGE_FLAG,
        value: huks.HuksKeyStorageType.HUKS_STORAGE_PERSISTENT
    };
    properties[2] = {
        tag: huks.HuksTag.HUKS_TAG_KEY_SIZE,
        value: huks.HuksKeySize.HUKS_RSA_KEY_SIZE_2048
    };
    properties[3] = {
        tag: huks.HuksTag.HUKS_TAG_PURPOSE,
        value: huks.HuksKeyPurpose.HUKS_KEY_PURPOSE_VERIFY
    };
    properties[4] = {
        tag: huks.HuksTag.HUKS_TAG_DIGEST,
        value: huks.HuksKeyDigest.HUKS_DIGEST_SHA256
    };
    properties[5] = {
        tag: huks.HuksTag.HUKS_TAG_PADDING,
        value: huks.HuksKeyPadding.HUKS_PADDING_PSS
    };
    properties[6] = {
        tag: huks.HuksTag.HUKS_TAG_KEY_GENERATE_TYPE,
        value: huks.HuksKeyGenerateType.HUKS_KEY_GENERATE_TYPE_DEFAULT
    };
    properties[7] = {
        tag: huks.HuksTag.HUKS_TAG_BLOCK_MODE,
        value: huks.HuksCipherMode.HUKS_MODE_ECB
    };
    let options = {
        properties: properties
    };

    try {
        huks.generateKeyItem(alias, options, function (error, data) {
            if (error) {
                console.error(`callback: generateKeyItem failed, code: ${error.code}, msg: ${error.message}`);
            } else {
                console.info(`callback: generateKeyItem success`);
            }
        });
    } catch (error) {
        console.error(`callback: generateKeyItem input arg invalid, code: ${error.code}, msg: ${error.message}`);
    }
}

async function attestKey() {
    let aliasString = keyAliasString;
    let aliasUint8 = stringToUint8Array(aliasString);
    let properties = new Array();
    properties[0] = {
        tag: huks.HuksTag.HUKS_TAG_ATTESTATION_ID_SEC_LEVEL_INFO,
        value: securityLevel
    };
    properties[1] = {
        tag: huks.HuksTag.HUKS_TAG_ATTESTATION_CHALLENGE,
        value: challenge
    };
    properties[2] = {
        tag: huks.HuksTag.HUKS_TAG_ATTESTATION_ID_VERSION_INFO,
        value: versionInfo
    };
    properties[3] = {
        tag: huks.HuksTag.HUKS_TAG_ATTESTATION_ID_ALIAS,
        value: aliasUint8
    };
    let options = {
        properties: properties
    };
    await generateKey(aliasString);
    try {
        huks.attestKeyItem(aliasString, options, function (error, data) {
            if (error) {
                console.error(`callback: attestKeyItem failed, code: ${error.code}, msg: ${error.message}`);
            } else {
                console.info(`callback: attestKeyItem success`);
            }
        });
    } catch (error) {
        console.error(`callback: attestKeyItem input arg invalid, code: ${error.code}, msg: ${error.message}`);
    }
}
A
annie_wangli 已提交
535 536
```

A
Annie_wang 已提交
537
## huks.attestKeyItem<sup>9+</sup>
A
annie_wangli 已提交
538

A
Annie_wang 已提交
539
attestKeyItem(keyAlias: string, options: HuksOptions) : Promise\<HuksReturnResult>
A
annie_wangli 已提交
540

A
Annie_wang 已提交
541
Obtains the certificate used to verify a key. This API uses a promise to return the result.
A
annie_wangli 已提交
542 543 544 545 546

**System capability**: SystemCapability.Security.Huks

**Parameters**

A
Annie_wang 已提交
547 548 549 550
| Name  | Type                       | Mandatory| Description                                |
| -------- | --------------------------- | ---- | ------------------------------------ |
| keyAlias | string                      | Yes  | Alias of the key. The certificate to be obtained stores the key.|
| options  | [HuksOptions](#huksoptions) | Yes  | Parameters and data required for obtaining the certificate.  |
A
annie_wangli 已提交
551 552 553

**Return value**

A
Annie_wang 已提交
554 555
| Type                                          | Description                                         |
| ---------------------------------------------- | --------------------------------------------- |
A
Annie_wang 已提交
556
| Promise<[HuksReturnResult](#huksreturnresult)> | Promise used to return the result. If the operation is successful, no **err** value is returned; otherwise, an error code is returned.|
A
annie_wangli 已提交
557 558 559 560

**Example**

```js
A
Annie_wang 已提交
561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661
let securityLevel = stringToUint8Array('sec_level');
let challenge = stringToUint8Array('challenge_data');
let versionInfo = stringToUint8Array('version_info');
let keyAliasString = "key attest";

function stringToUint8Array(str) {
    let arr = [];
    for (let i = 0, j = str.length; i < j; ++i) {
        arr.push(str.charCodeAt(i));
    }
    let tmpUint8Array = new Uint8Array(arr);
    return tmpUint8Array;
}

async function generateKey(alias) {
    let properties = new Array();
    properties[0] = {
        tag: huks.HuksTag.HUKS_TAG_ALGORITHM,
        value: huks.HuksKeyAlg.HUKS_ALG_RSA
    };
    properties[1] = {
        tag: huks.HuksTag.HUKS_TAG_KEY_STORAGE_FLAG,
        value: huks.HuksKeyStorageType.HUKS_STORAGE_PERSISTENT
    };
    properties[2] = {
        tag: huks.HuksTag.HUKS_TAG_KEY_SIZE,
        value: huks.HuksKeySize.HUKS_RSA_KEY_SIZE_2048
    };
    properties[3] = {
        tag: huks.HuksTag.HUKS_TAG_PURPOSE,
        value: huks.HuksKeyPurpose.HUKS_KEY_PURPOSE_VERIFY
    };
    properties[4] = {
        tag: huks.HuksTag.HUKS_TAG_DIGEST,
        value: huks.HuksKeyDigest.HUKS_DIGEST_SHA256
    };
    properties[5] = {
        tag: huks.HuksTag.HUKS_TAG_PADDING,
        value: huks.HuksKeyPadding.HUKS_PADDING_PSS
    };
    properties[6] = {
        tag: huks.HuksTag.HUKS_TAG_KEY_GENERATE_TYPE,
        value: huks.HuksKeyGenerateType.HUKS_KEY_GENERATE_TYPE_DEFAULT
    };
    properties[7] = {
        tag: huks.HuksTag.HUKS_TAG_BLOCK_MODE,
        value: huks.HuksCipherMode.HUKS_MODE_ECB
    };
    let options = {
        properties: properties
    };

    try {
        await huks.generateKeyItem(alias, options)
            .then((data) => {
                console.info(`promise: generateKeyItem success`);
            })
            .catch(error => {
                console.error(`promise: generateKeyItem failed, code: ${error.code}, msg: ${error.message}`);
            });
    } catch (error) {
        console.error(`promise: generateKeyItem input arg invalid, code: ${error.code}, msg: ${error.message}`);
    }
}

async function attestKey() {
    let aliasString = keyAliasString;
    let aliasUint8 = stringToUint8Array(aliasString);
    let properties = new Array();
    properties[0] = {
        tag: huks.HuksTag.HUKS_TAG_ATTESTATION_ID_SEC_LEVEL_INFO,
        value: securityLevel
    };
    properties[1] = {
        tag: huks.HuksTag.HUKS_TAG_ATTESTATION_CHALLENGE,
        value: challenge
    };
    properties[2] = {
        tag: huks.HuksTag.HUKS_TAG_ATTESTATION_ID_VERSION_INFO,
        value: versionInfo
    };
    properties[3] = {
        tag: huks.HuksTag.HUKS_TAG_ATTESTATION_ID_ALIAS,
        value: aliasUint8
    };
    let options = {
        properties: properties
    };
    await generateKey(aliasString);
    try {
        await huks.attestKeyItem(aliasString, options)
            .then ((data) => {
                console.info(`promise: attestKeyItem success`);
            })
            .catch(error => {
                console.error(`promise: attestKeyItem failed, code: ${error.code}, msg: ${error.message}`);
            });
    } catch (error) {
        console.error(`promise: attestKeyItem input arg invalid, code: ${error.code}, msg: ${error.message}`);
    }
}
A
annie_wangli 已提交
662 663
```

A
Annie_wang 已提交
664
## huks.importWrappedKeyItem<sup>9+</sup>
A
annie_wangli 已提交
665

A
Annie_wang 已提交
666
importWrappedKeyItem(keyAlias: string, wrappingKeyAlias: string, options: HuksOptions, callback: AsyncCallback\<void>) : void
A
annie_wangli 已提交
667

A
Annie_wang 已提交
668
Imports a wrapped key. This API uses an asynchronous callback to return the result.
A
annie_wangli 已提交
669 670 671 672 673

**System capability**: SystemCapability.Security.Huks

**Parameters**

A
Annie_wang 已提交
674 675 676 677 678
| Name          | Type                       | Mandatory| Description                                         |
| ---------------- | --------------------------- | ---- | --------------------------------------------- |
| keyAlias         | string                      | Yes  | Alias of the wrapped key to import.             |
| wrappingKeyAlias | string                      | Yes  | Alias of the data used to unwrap the key imported.   |
| options          | [HuksOptions](#huksoptions) | Yes  | Tags required for the import and the wrapped key to import.|
A
Annie_wang 已提交
679
| callback         | AsyncCallback\<void>        | Yes  | Callback that returns no value.|
A
annie_wangli 已提交
680 681 682 683

**Example**

```js
A
Annie_wang 已提交
684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833
import huks from '@ohos.security.huks';

let exportWrappingKey;
let alias1 = "importAlias";
let alias2 = "wrappingKeyAlias";

async function TestGenFunc(alias, options) {
    try {
        await genKey(alias, options)
            .then((data) => {
                console.info(`callback: generateKeyItem success`);
            })
            .catch(error => {
                console.error(`callback: generateKeyItem failed, code: ${error.code}, msg: ${error.message}`);
            });
    } catch (error) {
        console.error(`callback: generateKeyItem input arg invalid, code: ${error.code}, msg: ${error.message}`);
    }
}

function genKey(alias, options) {
    return new Promise((resolve, reject) => {
        try {
            huks.generateKeyItem(alias, options, function (error, data) {
                if (error) {
                    reject(error);
                } else {
                    resolve(data);
                }
            });
        } catch (error) {
            throw(error);
        }
    });
}

async function TestExportFunc(alias, options) {
    try {
        await exportKey(alias, options)
            .then ((data) => {
                console.info(`callback: exportKeyItem success, data = ${JSON.stringify(data)}`);
                exportWrappingKey = data.outData;
            })
            .catch(error => {
                console.error(`callback: exportKeyItem failed, code: ${error.code}, msg: ${error.message}`);
            });
    } catch (error) {
        console.error(`callback: exportKeyItem input arg invalid, code: ${error.code}, msg: ${error.message}`);
    }
}

function exportKey(alias, options) : Promise<huks.HuksReturnResult> {
    return new Promise((resolve, reject) => {
        try {
            huks.exportKeyItem(alias, options, function (error, data) {
                if (error) {
                    reject(error);
                } else {
                    resolve(data);
                }
            });
        } catch (error) {
            throw(error);
        }
    });
}

async function TestImportWrappedFunc(alias, wrappingAlias, options) {
    try {
        await importWrappedKey(alias, wrappingAlias, options)
            .then ((data) => {
                console.info(`callback: importWrappedKeyItem success`);
            })
            .catch(error => {
                console.error(`callback: importWrappedKeyItem failed, code: ${error.code}, msg: ${error.message}`);
            });
    } catch (error) {
        console.error(`callback: importWrappedKeyItem input arg invalid, code: ${error.code}, msg: ${error.message}`);
    }
}

function importWrappedKey(alias, wrappingAlias, options) {
    return new Promise((resolve, reject) => {
        try {
            huks.importWrappedKeyItem(alias, wrappingAlias, options, function (error, data) {
                if (error) {
                    reject(error);
                } else {
                    resolve(data);
                }
            });
        } catch (error) {
            throw(error);
        }
    });
}

async function TestImportWrappedKeyFunc(
        alias,
        wrappingAlias,
        genOptions,
        importOptions
) {
    await TestGenFunc(wrappingAlias, genOptions);
    await TestExportFunc(wrappingAlias, genOptions);

    /*The following operations do not invoke the HUKS APIs, and the specific implementation is not provided here.
     * For example, import **keyA**.
     * 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**.
     * 2. Use **keyB_pri** and the public key obtained from **wrappingAlias** to negotiate the shared key **share_key**.
     * 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**.
     * 4. Use **share_key** to encrypt **kek** with AES-GCM. During the encryption, record **nonce2**, **aad2**, ciphertext **kek_enc**, and encrypted **tag2**.
     * 5. Generate the **importOptions.inData** field in the following format:
     * keyB_pub length (4 bytes) + keyB_pub + aad2 length (4 bytes) + aad2 +
     * nonce2 length (4 bytes) + nonce2 + tag2 length (4 bytes) + tag2 +
     * kek_enc length (4 bytes) + kek_enc + aad1 length (4 bytes) + aad1 +
     * nonce1 length (4 bytes) + nonce1 + tag1 length (4 bytes) + tag1 +
     * Memory occupied by the keyA length (4 bytes) + keyA length + keyA_enc length (4 bytes) + keyA_enc
     */
    let inputKey = new Uint8Array([0x02, 0x00, 0x00, 0x00]);
    importOptions.inData = inputKey;
    await TestImportWrappedFunc(alias, wrappingAlias, importOptions);
}

function makeGenerateOptions() {
    let properties = new Array();
    properties[0] = {
        tag: huks.HuksTag.HUKS_TAG_ALGORITHM,
        value: huks.HuksKeyAlg.HUKS_ALG_ECC
    };
    properties[1] = {
        tag: huks.HuksTag.HUKS_TAG_KEY_SIZE,
        value: huks.HuksKeySize.HUKS_ECC_KEY_SIZE_256
    };
    properties[2] = {
        tag: huks.HuksTag.HUKS_TAG_PURPOSE,
        value: huks.HuksKeyPurpose.HUKS_KEY_PURPOSE_UNWRAP
    };
    properties[3] = {
        tag: huks.HuksTag.HUKS_TAG_DIGEST,
        value: huks.HuksKeyDigest.HUKS_DIGEST_SHA256
    };
    properties[4] = {
        tag: huks.HuksTag.HUKS_TAG_IMPORT_KEY_TYPE,
        value: huks.HuksImportKeyType.HUKS_KEY_TYPE_KEY_PAIR,
    };
    let options = {
        properties: properties
    };
    return options;
A
annie_wangli 已提交
834
};
A
Annie_wang 已提交
835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877

function makeImportOptions() {
    let properties = new Array();
    properties[0] = {
        tag: huks.HuksTag.HUKS_TAG_ALGORITHM,
        value: huks.HuksKeyAlg.HUKS_ALG_AES
    };
    properties[1] = {
        tag: huks.HuksTag.HUKS_TAG_KEY_SIZE,
        value: huks.HuksKeySize.HUKS_AES_KEY_SIZE_256
    };
    properties[2] = {
        tag: huks.HuksTag.HUKS_TAG_PURPOSE,
        value: huks.HuksKeyPurpose.HUKS_KEY_PURPOSE_ENCRYPT | huks.HuksKeyPurpose.HUKS_KEY_PURPOSE_DECRYPT
    };
    properties[3] = {
        tag: huks.HuksTag.HUKS_TAG_BLOCK_MODE,
        value: huks.HuksCipherMode.HUKS_MODE_CBC
    };
    properties[4] = {
        tag: huks.HuksTag.HUKS_TAG_PADDING,
        value: huks.HuksKeyPadding.HUKS_PADDING_NONE
    };
    properties[5] = {
        tag: huks.HuksTag.HUKS_TAG_UNWRAP_ALGORITHM_SUITE,
        value: huks.HuksUnwrapSuite.HUKS_UNWRAP_SUITE_ECDH_AES_256_GCM_NOPADDING
    };
    let options = {
        properties: properties
    };
    return options;
};

function huksImportWrappedKey() {
    let genOptions = makeGenerateOptions();
    let importOptions = makeImportOptions();
    TestImportWrappedKeyFunc(
        alias1,
        alias2,
        genOptions,
        importOptions
    );
}
A
annie_wangli 已提交
878 879
```

A
Annie_wang 已提交
880
## huks.importWrappedKeyItem<sup>9+</sup>
A
annie_wangli 已提交
881

A
Annie_wang 已提交
882
importWrappedKeyItem(keyAlias: string, wrappingKeyAlias: string, options: HuksOptions) : Promise\<void>
A
annie_wangli 已提交
883

A
Annie_wang 已提交
884
Imports a wrapped key. This API uses a promise to return the result.
A
annie_wangli 已提交
885 886 887 888 889

**System capability**: SystemCapability.Security.Huks

**Parameters**

A
Annie_wang 已提交
890 891 892 893 894
| Name          | Type                       | Mandatory| Description                                         |
| ---------------- | --------------------------- | ---- | --------------------------------------------- |
| keyAlias         | string                      | Yes  | Alias of the wrapped key to import.             |
| wrappingKeyAlias | string                      | Yes  | Alias of the data used to unwrap the key imported.   |
| options          | [HuksOptions](#huksoptions) | Yes  | Tags required for the import and the wrapped key to import.|
A
annie_wangli 已提交
895 896 897 898

**Example**

```js
A
Annie_wang 已提交
899 900 901 902 903 904 905 906 907 908 909 910
/* The process is similar as if a callback is used, except the following:*/
async function TestImportWrappedFunc(alias, wrappingAlias, options) {
    try {
        await huks.importWrappedKeyItem(alias, wrappingAlias, options)
            .then ((data) => {
                console.info(`promise: importWrappedKeyItem success`);
            })
            .catch(error => {
                console.error(`promise: importWrappedKeyItem failed, code: ${error.code}, msg: ${error.message}`);
            });
    } catch (error) {
        console.error(`promise: importWrappedKeyItem input arg invalid, code: ${error.code}, msg: ${error.message}`);
A
Annie_wang 已提交
911
    }
A
Annie_wang 已提交
912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928
}
```

## huks.exportKeyItem<sup>9+</sup>

exportKeyItem(keyAlias: string, options: HuksOptions, callback: AsyncCallback\<HuksReturnResult>) : void

Exports a key. This API uses an asynchronous callback to return the result.

**System capability**: SystemCapability.Security.Huks

**Parameters**

| Name  | Type                                                | Mandatory| Description                                                        |
| -------- | ---------------------------------------------------- | ---- | ------------------------------------------------------------ |
| keyAlias | string                                               | Yes  | Key alias, which must be the same as the alias used when the key was generated.                |
| options  | [HuksOptions](#huksoptions)                          | Yes  | Empty object (leave this parameter empty).                                    |
A
Annie_wang 已提交
929
| callback | AsyncCallback<[HuksReturnResult](#huksreturnresult)> | 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. |
A
Annie_wang 已提交
930 931 932 933 934 935 936 937

**Example**

```js
/* Set options to emptyOptions. */
let keyAlias = 'keyAlias';
let emptyOptions = {
    properties: []
A
annie_wangli 已提交
938
};
A
Annie_wang 已提交
939 940 941 942 943 944 945 946 947 948 949
try {
    huks.exportKeyItem(keyAlias, emptyOptions, function (error, data) {
        if (error) {
            console.error(`callback: exportKeyItem failed, code: ${error.code}, msg: ${error.message}`);
        } else {
            console.info(`callback: exportKeyItem success, data = ${JSON.stringify(data)}`);
        }
    });
} catch (error) {
    console.error(`callback: exportKeyItem input arg invalid, code: ${error.code}, msg: ${error.message}`);
}
A
annie_wangli 已提交
950 951
```

A
Annie_wang 已提交
952
## huks.exportKeyItem<sup>9+</sup>
A
annie_wangli 已提交
953

A
Annie_wang 已提交
954
exportKeyItem(keyAlias: string, options: HuksOptions) : Promise\<HuksReturnResult>
A
annie_wangli 已提交
955

A
Annie_wang 已提交
956
Exports a key. This API uses a promise to return the result.
A
annie_wangli 已提交
957 958 959 960 961

**System capability**: SystemCapability.Security.Huks

**Parameters**

A
Annie_wang 已提交
962 963 964 965
| Name  | Type                       | Mandatory| Description                                        |
| -------- | --------------------------- | ---- | -------------------------------------------- |
| keyAlias | string                      | Yes  | Key alias, which must be the same as the alias used when the key was generated.|
| options  | [HuksOptions](#huksoptions) | Yes  | Empty object (leave this parameter empty).                    |
A
annie_wangli 已提交
966 967 968

**Return value**

A
Annie_wang 已提交
969 970
| Type                                          | Description                                                        |
| ---------------------------------------------- | ------------------------------------------------------------ |
A
Annie_wang 已提交
971
| Promise<[HuksReturnResult](#huksreturnresult)> | 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. |
A
annie_wangli 已提交
972 973 974 975

**Example**

```js
A
Annie_wang 已提交
976 977 978 979
/* Set options to emptyOptions. */
let keyAlias = 'keyAlias';
let emptyOptions = {
    properties: []
A
annie_wangli 已提交
980
};
A
Annie_wang 已提交
981 982 983 984 985 986 987 988 989 990 991
try {
    huks.exportKeyItem(keyAlias, emptyOptions)
        .then ((data) => {
            console.info(`promise: exportKeyItem success, data = ${JSON.stringify(data)}`);
        })
        .catch(error => {
            console.error(`promise: exportKeyItem failed, code: ${error.code}, msg: ${error.message}`);
        });
} catch (error) {
    console.error(`promise: exportKeyItem input arg invalid, code: ${error.code}, msg: ${error.message}`);
}
A
annie_wangli 已提交
992 993
```

A
Annie_wang 已提交
994
## huks.getKeyItemProperties<sup>9+</sup>
A
Annie_wang 已提交
995

A
Annie_wang 已提交
996
getKeyItemProperties(keyAlias: string, options: HuksOptions, callback: AsyncCallback\<HuksReturnResult>) : void
A
Annie_wang 已提交
997

A
Annie_wang 已提交
998
Obtains key properties. This API uses an asynchronous callback to return the result.
A
Annie_wang 已提交
999 1000 1001 1002 1003

**System capability**: SystemCapability.Security.Huks

**Parameters**

A
Annie_wang 已提交
1004 1005 1006 1007
| Name  | Type                                                | Mandatory| Description                                                        |
| -------- | ---------------------------------------------------- | ---- | ------------------------------------------------------------ |
| keyAlias | string                                               | Yes  | Key alias, which must be the same as the alias used when the key was generated.                |
| options  | [HuksOptions](#huksoptions)                          | Yes  | Empty object (leave this parameter empty).                                    |
A
Annie_wang 已提交
1008
| callback | AsyncCallback<[HuksReturnResult](#huksreturnresult)> | Yes  | Callback invoked to return the result. If the operation is successful, **errorCode** is **HUKS_SUCCESS**; otherwise, an error code is returned.|
A
Annie_wang 已提交
1009 1010 1011 1012

**Example**

```js
A
Annie_wang 已提交
1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027
/* Set options to emptyOptions. */
let keyAlias = 'keyAlias';
let emptyOptions = {
    properties: []
};
try {
    huks.getKeyItemProperties(keyAlias, emptyOptions, function (error, data) {
        if (error) {
            console.error(`callback: getKeyItemProperties failed, code: ${error.code}, msg: ${error.message}`);
        } else {
            console.info(`callback: getKeyItemProperties success, data = ${JSON.stringify(data)}`);
        }
    });
} catch (error) {
    console.error(`callback: getKeyItemProperties input arg invalid, code: ${error.code}, msg: ${error.message}`);
A
Annie_wang 已提交
1028
}
A
Annie_wang 已提交
1029
```
A
Annie_wang 已提交
1030

A
Annie_wang 已提交
1031
## huks.getKeyItemProperties<sup>9+</sup>
A
Annie_wang 已提交
1032

A
Annie_wang 已提交
1033
getKeyItemProperties(keyAlias: string, options: HuksOptions) : Promise\<HuksReturnResult>
A
Annie_wang 已提交
1034

A
Annie_wang 已提交
1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049
Obtains key properties. This API uses a promise to return the result.

**System capability**: SystemCapability.Security.Huks

**Parameters**

| Name  | Type                       | Mandatory| Description                                        |
| -------- | --------------------------- | ---- | -------------------------------------------- |
| keyAlias | string                      | Yes  | Key alias, which must be the same as the alias used when the key was generated.|
| options  | [HuksOptions](#huksoptions) | Yes  | Empty object (leave this parameter empty).                    |

**Return value**

| Type                                           | Description                                                        |
| ----------------------------------------------- | ------------------------------------------------------------ |
A
Annie_wang 已提交
1050
| Promise\<[HuksReturnResult](#huksreturnresult)> | 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. |
A
Annie_wang 已提交
1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069

**Example**

```js
/* Set options to emptyOptions. */
let keyAlias = 'keyAlias';
let emptyOptions = {
    properties: []
};
try {
    huks.getKeyItemProperties(keyAlias, emptyOptions)
        .then ((data) => {
            console.info(`promise: getKeyItemProperties success, data = ${JSON.stringify(data)}`);
        })
        .catch(error => {
            console.error(`promise: getKeyItemProperties failed, code: ${error.code}, msg: ${error.message}`);
        });
} catch (error) {
    console.error(`promise: getKeyItemProperties input arg invalid, code: ${error.code}, msg: ${error.message}`);
A
Annie_wang 已提交
1070
}
A
Annie_wang 已提交
1071
```
A
Annie_wang 已提交
1072

A
Annie_wang 已提交
1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086
## huks.isKeyItemExist<sup>9+</sup>

isKeyItemExist(keyAlias: string, options: HuksOptions, callback: AsyncCallback\<boolean>) : void

Checks whether a key exists. This API uses an asynchronous callback to return the result.

**System capability**: SystemCapability.Security.Huks

**Parameters**

| Name  | Type                       | Mandatory| Description                                   |
| -------- | --------------------------- | ---- | --------------------------------------- |
| keyAlias | string                      | Yes  | Alias of the key to check.                 |
| options  | [HuksOptions](#huksoptions) | Yes  | Empty object (leave this parameter empty).               |
A
Annie_wang 已提交
1087
| callback | AsyncCallback\<boolean>     | Yes  | Callback invoked to return the result. **TRUE** means that the key exists; **FALSE** means the opposite.|
A
Annie_wang 已提交
1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106

**Example**

```js
/* Set options to emptyOptions. */
let keyAlias = 'keyAlias';
let emptyOptions = {
    properties: []
};
try {
    huks.isKeyItemExist(keyAlias, emptyOptions, function (error, data) {
        if (error) {
            console.info(`callback: isKeyItemExist success, data = ${JSON.stringify(data)}`);
        } else {
            console.error(`callback: isKeyItemExist failed, code: ${error.code}, msg: ${error.message}`);
        }
    });
} catch (error) {
    console.error(`promise: isKeyItemExist input arg invalid, code: ${error.code}, msg: ${error.message}`);
A
Annie_wang 已提交
1107 1108 1109
}
```

A
Annie_wang 已提交
1110
## huks.isKeyItemExist<sup>9+</sup>
A
Annie_wang 已提交
1111

A
Annie_wang 已提交
1112
isKeyItemExist(keyAlias: string, options: HuksOptions) : Promise\<boolean>
A
Annie_wang 已提交
1113

A
Annie_wang 已提交
1114
Checks whether a key exists. This API uses a promise to return the result.
A
Annie_wang 已提交
1115 1116 1117 1118 1119

**System capability**: SystemCapability.Security.Huks

**Parameters**

A
Annie_wang 已提交
1120 1121 1122 1123
| Name  | Type                       | Mandatory| Description                    |
| -------- | --------------------------- | ---- | ------------------------ |
| keyAlias | string                      | Yes  | Alias of the key to check.  |
| options  | [HuksOptions](#huksoptions) | Yes  | Empty object (leave this parameter empty).|
A
Annie_wang 已提交
1124 1125 1126

**Return value**

A
Annie_wang 已提交
1127 1128
| Type             | Description                                   |
| ----------------- | --------------------------------------- |
A
Annie_wang 已提交
1129
| Promise\<boolean> | Promise used to return the result. **TRUE** means that the key exists; **FALSE** means the opposite.|
A
Annie_wang 已提交
1130 1131 1132 1133

**Example**

```js
A
Annie_wang 已提交
1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148
/* Set options to emptyOptions. */
let keyAlias = 'keyAlias';
let emptyOptions = {
    properties: []
};
try {
    huks.isKeyItemExist(keyAlias, emptyOptions)
        .then ((data) => {
            console.info(`promise: isKeyItemExist success, data = ${JSON.stringify(data)}`);
        })
        .catch(error => {
            console.error(`promise: isKeyItemExist failed, code: ${error.code}, msg: ${error.message}`);
        });
} catch (error) {
    console.error(`promise: isKeyItemExist input arg invalid, code: ${error.code}, msg: ${error.message}`);
A
Annie_wang 已提交
1149
}
A
Annie_wang 已提交
1150
```
A
Annie_wang 已提交
1151

A
Annie_wang 已提交
1152
## huks.initSession<sup>9+</sup>
A
Annie_wang 已提交
1153

A
Annie_wang 已提交
1154
initSession(keyAlias: string, options: HuksOptions, callback: AsyncCallback\<HuksSessionHandle>) : void
A
Annie_wang 已提交
1155

A
Annie_wang 已提交
1156
Initializes 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.
A
Annie_wang 已提交
1157

A
Annie_wang 已提交
1158
**System capability**: SystemCapability.Security.Huks
A
Annie_wang 已提交
1159

A
Annie_wang 已提交
1160
**Parameters**
A
Annie_wang 已提交
1161

A
Annie_wang 已提交
1162 1163 1164 1165 1166
| Name  | Type                                                   | Mandatory| Description                                                |
| -------- | ------------------------------------------------------- | ---- | ---------------------------------------------------- |
| keyAlias | string                                                  | Yes  | Alias of the target key.                                |
| options  | [HuksOptions](#huksoptions)                             | Yes  | Parameters used for initialization.                                |
| callback | AsyncCallback\<[HuksSessionHandle](#hukssessionhandle)> | Yes  | Callback invoked to return the key operation handle.|
A
Annie_wang 已提交
1167

A
Annie_wang 已提交
1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308

## huks.initSession<sup>9+</sup>

initSession(keyAlias: string, options: HuksOptions) : Promise\<HuksSessionHandle>

Initializes 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.

**System capability**: SystemCapability.Security.Huks

**Parameters**

| Name  | Type                                             | Mandatory| Description                                            |
| -------- | ------------------------------------------------- | ---- | ------------------------------------------------ |
| keyAlias | string                                            | Yes  | Alias of the target key.                            |
| options  | [HuksOptions](#huksoptions)                       | Yes  | Parameters used for initialization.                                  |

**Return value**

| Type                               | Description                                              |
| ----------------------------------- | -------------------------------------------------- |
| Promise\<[HuksSessionHandle](#hukssessionhandle)> | Promise used to return the key operation handle.|

## huks.updateSession<sup>9+</sup>

updateSession(handle: number, options: HuksOptions, callback: AsyncCallback\<HuksReturnResult>) : void

Updates 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.

**System capability**: SystemCapability.Security.Huks

**Parameters**

| Name  | Type                                                | Mandatory| Description                                        |
| -------- | ---------------------------------------------------- | ---- | -------------------------------------------- |
| handle   | number                                               | Yes  | Handle of the **Update** operation.                        |
| options  | [HuksOptions](#huksoptions)                          | Yes  | Parameters of the **Update** operation.                          |
| callback | AsyncCallback<[HuksReturnResult](#huksreturnresult)> | Yes  | Callback invoked to return the result.|


## huks.updateSession<sup>9+</sup>

updateSession(handle: number, options: HuksOptions, token: Uint8Array, callback: AsyncCallback\<HuksReturnResult>) : void

Updates 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.

**System capability**: SystemCapability.Security.Huks

**Parameters**

| Name  | Type                                                | Mandatory| Description                                        |
| -------- | ---------------------------------------------------- | ---- | -------------------------------------------- |
| handle   | number                                               | Yes  | Handle of the **Update** operation.                        |
| options  | [HuksOptions](#huksoptions)                          | Yes  | Parameters of the **Update** operation.                      |
| token    | Uint8Array                                           | Yes  | Token of the **Update** operation.                         |
| callback | AsyncCallback<[HuksReturnResult](#huksreturnresult)> | Yes  | Callback invoked to return the result.|

## huks.updateSession<sup>9+</sup>

updateSession(handle: number, options: HuksOptions, token?: Uint8Array) : Promise\<HuksReturnResult>

Updates the key operation data by segment. This API uses a promise to return the result. **huks.initSession**, **huks.updateSession**, and **huks.finishSession** must be used together.

**System capability**: SystemCapability.Security.Huks

**Parameters**

| Name | Type                                          | Mandatory| Description                                        |
| ------- | ---------------------------------------------- | ---- | -------------------------------------------- |
| handle  | number                                         | Yes  | Handle of the **Update** operation.                        |
| options | [HuksOptions](#huksoptions)                    | Yes  | Parameters of the **Update** operation.                      |
| token   | Uint8Array                                     | No  | Token of the **Update** operation.                         |

**Return value**

| Type                               | Description                                              |
| ----------------------------------- | -------------------------------------------------- |
| Promise<[HuksReturnResult](#huksreturnresult)> | Promise used to return the result.|

## huks.finishSession<sup>9+</sup>

finishSession(handle: number, options: HuksOptions, callback: AsyncCallback\<HuksReturnResult>) : void

Completes 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.

**System capability**: SystemCapability.Security.Huks

**Parameters**

| Name  | Type                                                | Mandatory| Description                                        |
| -------- | ---------------------------------------------------- | ---- | -------------------------------------------- |
| handle   | number                                               | Yes  | Handle of the **Finish** operation.                        |
| options  | [HuksOptions](#huksoptions)                          | Yes  | Parameters of the **Finish** operation.                          |
| token    | Uint8Array                                           | Yes  | Token for the **Finish** operation.                         |
| callback | AsyncCallback<[HuksReturnResult](#huksreturnresult)> | Yes  | Callback invoked to return the result.|

## huks.finishSession<sup>9+</sup>

finishSession(handle: number, options: HuksOptions, token: Uint8Array, callback: AsyncCallback\<HuksReturnResult>) : void

Completes 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.

**System capability**: SystemCapability.Security.Huks

**Parameters**

| Name  | Type                                                 | Mandatory| Description                                        |
| -------- | ----------------------------------------------------- | ---- | -------------------------------------------- |
| handle   | number                                                | Yes  | Handle of the **Finish** operation.                        |
| options  | [HuksOptions](#huksoptions)                           | Yes  | Parameters of the **Finish** operation.                          |
| token    | Uint8Array                                            | Yes  | Token for the **Finish** operation.                         |
| callback | AsyncCallback\<[HuksReturnResult](#huksreturnresult)> | Yes  | Callback invoked to return the result.|


## huks.finishSession<sup>9+</sup>

finishSession(handle: number, options: HuksOptions, token?: Uint8Array) : Promise\<HuksReturnResult>

Completes 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.

**System capability**: SystemCapability.Security.Huks

**Parameters**

| Name | Type                                           | Mandatory| Description                               |
| ------- | ----------------------------------------------- | ---- | ----------------------------------- |
| handle  | number                                          | Yes  | Handle of the **Finish** operation.               |
| options | [HuksOptions](#huksoptions)                     | Yes  | Parameters of the **Finish** operation.             |
| token   | Uint8Array                                      | No  | Token for the **Finish** operation.                |

**Return value**

| Type                               | Description                                              |
| ----------------------------------- | -------------------------------------------------- |
| Promise\<[HuksReturnResult](#huksreturnresult)> | Promise used to return the result.|


## huks.abortSession<sup>9+</sup>

abortSession(handle: number, options: HuksOptions, callback: AsyncCallback\<void>) : void

Aborts the use of the key. This API uses an asynchronous callback to return the result.
A
Annie_wang 已提交
1309 1310 1311 1312 1313

**System capability**: SystemCapability.Security.Huks

**Parameters**

A
Annie_wang 已提交
1314 1315 1316 1317
| Name  | Type                       | Mandatory| Description                                       |
| -------- | --------------------------- | ---- | ------------------------------------------- |
| handle   | number                      | Yes  | Handle of the **Abort** operation.                        |
| options  | [HuksOptions](#huksoptions) | Yes  | Parameters of the **Abort** operation.                      |
A
Annie_wang 已提交
1318
| callback | AsyncCallback\<void>        | Yes  | Callback that returns no value.|
A
Annie_wang 已提交
1319 1320 1321 1322

**Example**

```js
A
Annie_wang 已提交
1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336
/* huks.initSession, huks.updateSession, and huks.finishSession must be used together.
 * If an error occurs in any of huks.initSession, huks.updateSession,
 * and huks.finishSession operation,
 * huks.abortSession must be called to terminate the use of the key.
 *
 * The following uses the callback of an RSA1024 key as an example.
 */
function stringToUint8Array(str) {
    let arr = [];
    for (let i = 0, j = str.length; i < j; ++i) {
        arr.push(str.charCodeAt(i));
    }
    let tmpUint8Array = new Uint8Array(arr);
    return tmpUint8Array;
A
Annie_wang 已提交
1337 1338
}

A
Annie_wang 已提交
1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382
let keyAlias = "HuksDemoRSA";
let properties = new Array();
let options = {
    properties: properties,
    inData: new Uint8Array(0)
};
let handle;
async function generateKey() {
    properties[0] = {
        tag: huks.HuksTag.HUKS_TAG_ALGORITHM,
        value: huks.HuksKeyAlg.HUKS_ALG_RSA
    };
    properties[1] = {
        tag: huks.HuksTag.HUKS_TAG_KEY_SIZE,
        value: huks.HuksKeySize.HUKS_RSA_KEY_SIZE_1024
    };
    properties[2] = {
        tag: huks.HuksTag.HUKS_TAG_PURPOSE,
        value: huks.HuksKeyPurpose.HUKS_KEY_PURPOSE_ENCRYPT
    };
    properties[3] = {
        tag: huks.HuksTag.HUKS_TAG_PADDING,
        value: huks.HuksKeyPadding.HUKS_PADDING_PKCS1_V1_5
    };
    properties[4] = {
        tag: huks.HuksTag.HUKS_TAG_DIGEST,
        value: huks.HuksKeyDigest.HUKS_DIGEST_SHA256
    };
    properties[5] = {
        tag: huks.HuksTag.HUKS_TAG_BLOCK_MODE,
        value: huks.HuksCipherMode.HUKS_MODE_ECB,
    }

    try {
        await huks.generateKeyItem(keyAlias, options, function (error, data) {
            if (error) {
                console.error(`callback: generateKeyItem failed, code: ${error.code}, msg: ${error.message}`);
            } else {
                console.info(`callback: generateKeyItem success`);
            }
        });
    } catch (error) {
        console.error(`callback: generateKeyItem input arg invalid, code: ${error.code}, msg: ${error.message}`);
    }
A
Annie_wang 已提交
1383 1384
}

A
Annie_wang 已提交
1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398
async function huksInit() {
    console.log('enter huksInit');
    try {
        huks.initSession(keyAlias, options, function (error, data) {
            if (error) {
                console.error(`callback: initSession failed, code: ${error.code}, msg: ${error.message}`);
            } else {
                console.info(`callback: initSession success, data = ${JSON.stringify(data)}`);
                handle = data.handle;
            }
        });
    } catch (error) {
        console.error(`callback: initSession input arg invalid, code: ${error.code}, msg: ${error.message}`);
    }
A
Annie_wang 已提交
1399 1400
}

A
Annie_wang 已提交
1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414
async function huksUpdate() {
    console.log('enter huksUpdate');
    options.inData = stringToUint8Array("huksHmacTest");
    try {
        huks.updateSession(handle, options, function (error, data) {
            if (error) {
                console.error(`callback: updateSession failed, code: ${error.code}, msg: ${error.message}`);
            } else {
                console.info(`callback: updateSession success, data = ${JSON.stringify(data)}`);
            }
        });
    } catch (error) {
        console.error(`callback: updateSession input arg invalid, code: ${error.code}, msg: ${error.message}`);
    }
A
Annie_wang 已提交
1415 1416
}

A
Annie_wang 已提交
1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430
async function huksFinish() {
    console.log('enter huksFinish');
    options.inData = new Uint8Array(0);
    try {
        huks.finishSession(handle, options, function (error, data) {
            if (error) {
                console.error(`callback: finishSession failed, code: ${error.code}, msg: ${error.message}`);
            } else {
                console.info(`callback: finishSession success, data = ${JSON.stringify(data)}`);
            }
        });
    } catch (error) {
        console.error(`callback: finishSession input arg invalid, code: ${error.code}, msg: ${error.message}`);
    }
A
Annie_wang 已提交
1431 1432
}

A
Annie_wang 已提交
1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445
async function huksAbort() {
    console.log('enter huksAbort');
    try {
        huks.abortSession(handle, options, function (error, data) {
            if (error) {
                console.error(`callback: abortSession failed, code: ${error.code}, msg: ${error.message}`);
            } else {
                console.info(`callback: abortSession success`);
            }
        });
    } catch (error) {
        console.error(`callback: abortSession input arg invalid, code: ${error.code}, msg: ${error.message}`);
    }
A
Annie_wang 已提交
1446
}
A
Annie_wang 已提交
1447
```
A
Annie_wang 已提交
1448

A
Annie_wang 已提交
1449
## huks.abortSession<sup>9+</sup>
A
Annie_wang 已提交
1450

A
Annie_wang 已提交
1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467
abortSession(handle: number, options: HuksOptions) : Promise\<void>;

Aborts the use of the key. This API uses a promise to return the result.

**System capability**: SystemCapability.Security.Huks

**Parameters**

| Name | Type                       | Mandatory| Description                                       |
| ------- | --------------------------- | ---- | ------------------------------------------- |
| handle  | number                      | Yes  | Handle of the **Abort** operation.                        |
| options | [HuksOptions](#huksoptions) | Yes  | Parameters of the **Abort** operation.                      |

**Return value**

| Type                               | Description                                              |
| ----------------------------------- | -------------------------------------------------- |
A
Annie_wang 已提交
1468
| Promise\<void>             | Promise that returns no value.|
A
Annie_wang 已提交
1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486

**Example**

```js
/* huks.initSession, huks.updateSession, and huks.finishSession must be used together.
 * If an error occurs in any of huks.initSession, huks.updateSession,
 * and huks.finishSession operation,
 * huks.abortSession must be called to terminate the use of the key.
 *
 * The following uses the callback of an RSA1024 key as an example.
 */
function stringToUint8Array(str) {
    let arr = [];
    for (let i = 0, j = str.length; i < j; ++i) {
        arr.push(str.charCodeAt(i));
    }
    let tmpUint8Array = new Uint8Array(arr);
    return tmpUint8Array;
A
Annie_wang 已提交
1487 1488
}

A
Annie_wang 已提交
1489 1490 1491 1492 1493
let keyAlias = "HuksDemoRSA";
let properties = new Array();
let options = {
    properties: properties,
    inData: new Uint8Array(0)
A
Annie_wang 已提交
1494
};
A
Annie_wang 已提交
1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520
let handle;
async function generateKey() {
    properties[0] = {
        tag: huks.HuksTag.HUKS_TAG_ALGORITHM,
        value: huks.HuksKeyAlg.HUKS_ALG_RSA
    };
    properties[1] = {
        tag: huks.HuksTag.HUKS_TAG_KEY_SIZE,
        value: huks.HuksKeySize.HUKS_RSA_KEY_SIZE_1024
    };
    properties[2] = {
        tag: huks.HuksTag.HUKS_TAG_PURPOSE,
        value: huks.HuksKeyPurpose.HUKS_KEY_PURPOSE_ENCRYPT
    };
    properties[3] = {
        tag: huks.HuksTag.HUKS_TAG_PADDING,
        value: huks.HuksKeyPadding.HUKS_PADDING_PKCS1_V1_5
    };
    properties[4] = {
        tag: huks.HuksTag.HUKS_TAG_DIGEST,
        value: huks.HuksKeyDigest.HUKS_DIGEST_SHA256
    };
    properties[5] = {
        tag: huks.HuksTag.HUKS_TAG_BLOCK_MODE,
        value: huks.HuksCipherMode.HUKS_MODE_ECB,
    }
A
Annie_wang 已提交
1521

A
Annie_wang 已提交
1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958 1959 1960 1961 1962 1963 1964 1965 1966 1967 1968 1969 1970 1971 1972 1973 1974 1975 1976 1977 1978 1979 1980 1981 1982 1983 1984 1985 1986 1987 1988 1989 1990 1991 1992 1993 1994 1995
    try {
        await huks.generateKeyItem(keyAlias, options)
            .then((data) => {
                console.info(`promise: generateKeyItem success`);
            })
            .catch(error => {
                console.error(`promise: generateKeyItem failed, code: ${error.code}, msg: ${error.message}`);
            });
    } catch (error) {
        console.error(`promise: generateKeyItem input arg invalid, code: ${error.code}, msg: ${error.message}`);
    }
}

async function huksInit() {
    console.log('enter huksInit');
    try {
        await huks.initSession(keyAlias, options)
            .then ((data) => {
                console.info(`promise: initSession success, data = ${JSON.stringify(data)}`);
                    handle = data.handle;
            })
            .catch(error => {
                console.error(`promise: initSession key failed, code: ${error.code}, msg: ${error.message}`);
            });
    } catch (error) {
        console.error(`promise: initSession input arg invalid, code: ${error.code}, msg: ${error.message}`);
    }
}

async function huksUpdate() {
    console.log('enter huksUpdate');
    options.inData = stringToUint8Array("huksHmacTest");
    try {
        await huks.updateSession(handle, options)
            .then ((data) => {
                console.info(`promise: updateSession success, data = ${JSON.stringify(data)}`);
            })
            .catch(error => {
                console.error(`promise: updateSession failed, code: ${error.code}, msg: ${error.message}`);
            });
    } catch (error) {
        console.error(`promise: updateSession input arg invalid, code: ${error.code}, msg: ${error.message}`);
    }
}

async function huksFinish() {
    console.log('enter huksFinish');
    options.inData = new Uint8Array(0);
    try {
        await huks.finishSession(handle, options)
            .then ((data) => {
                console.info(`promise: finishSession success, data = ${JSON.stringify(data)}`);
            })
            .catch(error => {
                console.error(`promise: finishSession failed, code: ${error.code}, msg: ${error.message}`);
            });
    } catch (error) {
        console.error(`promise: finishSession input arg invalid, code: ${error.code}, msg: ${error.message}`);
    }
}

async function huksAbort() {
    console.log('enter huksAbort');
    try {
        await huks.abortSession(keyAlias, options)
            .then ((data) => {
                console.info(`promise: abortSession success`);
            })
            .catch(error => {
                console.error(`promise: abortSession failed, code: ${error.code}, msg: ${error.message}`);
            });
    } catch (error) {
        console.error(`promise: abortSession input arg invalid, code: ${error.code}, msg: ${error.message}`);
    }
}
```


## HuksExceptionErrCode<sup>9+</sup>

Enumerates the error codes.

For details about the error codes, see [KUKS Error Codes](../errorcodes/errorcode-huks.md).

**System capability**: SystemCapability.Security.Huks

| Name                                          | Description                       | Error Code  |
| ---------------------------------------------- | --------------------------- | -------- |
| HUKS_ERR_CODE_PERMISSION_FAIL                  | Permission verification failed.         | 201      |
| HUKS_ERR_CODE_ILLEGAL_ARGUMENT                 | Invalid parameters are detected.         | 401      |
| HUKS_ERR_CODE_NOT_SUPPORTED_API                | The API is not supported.              | 801      |
| HUKS_ERR_CODE_FEATURE_NOT_SUPPORTED            | The feature is not supported.        | 12000001 |
| HUKS_ERR_CODE_MISSING_CRYPTO_ALG_ARGUMENT      | Key algorithm parameters are missing.         | 12000002 |
| HUKS_ERR_CODE_INVALID_CRYPTO_ALG_ARGUMENT      | Invalid key algorithm parameters are detected.         | 12000003 |
| HUKS_ERR_CODE_FILE_OPERATION_FAIL              | The file operation failed.             | 12000004 |
| HUKS_ERR_CODE_COMMUNICATION_FAIL               | The communication failed.                 | 12000005 |
| HUKS_ERR_CODE_CRYPTO_FAIL                      | Failed to operate the algorithm library.           | 12000006 |
| HUKS_ERR_CODE_KEY_AUTH_PERMANENTLY_INVALIDATED | Failed to access the key because the key has expired.| 12000007 |
| HUKS_ERR_CODE_KEY_AUTH_VERIFY_FAILED           | Failed to access the key because the authentication has failed.| 12000008 |
| HUKS_ERR_CODE_KEY_AUTH_TIME_OUT                | Key access timed out.| 12000009 |
| HUKS_ERR_CODE_SESSION_LIMIT                    | The number of key operation sessions has reached the limit.   | 12000010 |
| HUKS_ERR_CODE_ITEM_NOT_EXIST                   | The target object does not exist.           | 12000011 |
| HUKS_ERR_CODE_EXTERNAL_ERROR                   | An external error occurs.                 | 12000012 |
| HUKS_ERR_CODE_CREDENTIAL_NOT_EXIST             | The credential does not exist.             | 12000013 |
| HUKS_ERR_CODE_INSUFFICIENT_MEMORY              | The memory is insufficient.                 | 12000014 |
| HUKS_ERR_CODE_CALL_SERVICE_FAILED              | Failed to call other system services.     | 12000015 |

## HuksKeyPurpose

Enumerates the key purposes.

**System capability**: SystemCapability.Security.Huks

| Name                    | Value  | Description                            |
| ------------------------ | ---- | -------------------------------- |
| HUKS_KEY_PURPOSE_ENCRYPT | 1    | Used to encrypt the plaintext.|
| HUKS_KEY_PURPOSE_DECRYPT | 2    | Used to decrypt the cipher text.|
| HUKS_KEY_PURPOSE_SIGN    | 4    | Used for signing.    |
| HUKS_KEY_PURPOSE_VERIFY  | 8    | Used to verify the signature.  |
| HUKS_KEY_PURPOSE_DERIVE  | 16   | Used to derive a key.          |
| HUKS_KEY_PURPOSE_WRAP    | 32   | Used for an encrypted export.          |
| HUKS_KEY_PURPOSE_UNWRAP  | 64   | Used for an encrypted import.              |
| HUKS_KEY_PURPOSE_MAC     | 128  | Used to generate a message authentication code (MAC). |
| HUKS_KEY_PURPOSE_AGREE   | 256  | Used for key agreement.      |

## HuksKeyDigest

Enumerates the digest algorithms.

**System capability**: SystemCapability.Security.Huks

| Name                  | Value  | Description                                    |
| ---------------------- | ---- | ---------------------------------------- |
| HUKS_DIGEST_NONE       | 0   | No digest algorithm|
| HUKS_DIGEST_MD5        | 1    | MD5|
| HUKS_DIGEST_SM3<sup>9+</sup> | 2 | SM3|
| HUKS_DIGEST_SHA1       | 10   | SHA-1|
| HUKS_DIGEST_SHA224 | 11   | SHA-224|
| HUKS_DIGEST_SHA256 | 12  | SHA-256|
| HUKS_DIGEST_SHA384  | 13  | SHA-384|
| HUKS_DIGEST_SHA512 | 14  | SHA-512|

## HuksKeyPadding

Enumerates the padding algorithms.

**System capability**: SystemCapability.Security.Huks

| Name                  | Value  | Description                                    |
| ---------------------- | ---- | ---------------------------------------- |
| HUKS_PADDING_NONE | 0    | No padding algorithm|
| HUKS_PADDING_OAEP | 1    | Optimal Asymmetric Encryption Padding (OAEP)|
| HUKS_PADDING_PSS | 2    | Probabilistic Signature Scheme (PSS)|
| HUKS_PADDING_PKCS1_V1_5 | 3    | Public Key Cryptography Standards (PKCS) #1 v1.5|
| HUKS_PADDING_PKCS5 | 4   | PKCS #5|
| HUKS_PADDING_PKCS7 | 5   | PKCS #7|

## HuksCipherMode

Enumerates the cipher modes.

**System capability**: SystemCapability.Security.Huks

| Name         | Value  | Description                 |
| ------------- | ---- | --------------------- |
| HUKS_MODE_ECB | 1    | Electronic Code Block (ECB) mode|
| HUKS_MODE_CBC | 2    | Cipher Block Chaining (CBC) mode|
| HUKS_MODE_CTR | 3    | Counter (CTR) mode|
| HUKS_MODE_OFB | 4    | Output Feedback (OFB) mode|
| HUKS_MODE_CCM | 31   | Counter with CBC-MAC (CCM) mode|
| HUKS_MODE_GCM | 32   | Galois/Counter (GCM) mode|

## HuksKeySize

Enumerates the key sizes.

**System capability**: SystemCapability.Security.Huks

| Name                              | Value  | Description                                      |
| ---------------------------------- | ---- | ------------------------------------------ |
| HUKS_RSA_KEY_SIZE_512              | 512  | Rivest-Shamir-Adleman (RSA) key of 512 bits       |
| HUKS_RSA_KEY_SIZE_768              | 768  | RSA key of 768 bits       |
| HUKS_RSA_KEY_SIZE_1024             | 1024 | RSA key of 1024 bits      |
| HUKS_RSA_KEY_SIZE_2048             | 2048 | RSA key of 2048 bits      |
| HUKS_RSA_KEY_SIZE_3072             | 3072 | RSA key of 3072 bits      |
| HUKS_RSA_KEY_SIZE_4096             | 4096 | RSA key of 4096 bits      |
| HUKS_ECC_KEY_SIZE_224              | 224  | Elliptic Curve Cryptography (ECC) key of 224 bits       |
| HUKS_ECC_KEY_SIZE_256              | 256  | ECC key of 256 bits       |
| HUKS_ECC_KEY_SIZE_384              | 384  | ECC key of 384 bits       |
| HUKS_ECC_KEY_SIZE_521              | 521  | ECC key of 521 bits       |
| HUKS_AES_KEY_SIZE_128              | 128  | Advanced Encryption Standard (AES) key of 128 bits       |
| HUKS_AES_KEY_SIZE_192              | 196  | AES key of 196 bits       |
| HUKS_AES_KEY_SIZE_256              | 256  | AES key of 256 bits       |
| HUKS_AES_KEY_SIZE_512              | 512  | AES key of 512 bits       |
| HUKS_CURVE25519_KEY_SIZE_256       | 256  | Curve25519 key of 256 bits|
| HUKS_DH_KEY_SIZE_2048              | 2048 | Diffie-Hellman (DH) key of 2048 bits       |
| HUKS_DH_KEY_SIZE_3072              | 3072 | DH key of 3072 bits       |
| HUKS_DH_KEY_SIZE_4096              | 4096 | DH key of 4096 bits       |
| HUKS_SM2_KEY_SIZE_256<sup>9+</sup> | 256  | ShangMi2 (SM2) key of 256 bits           |
| HUKS_SM4_KEY_SIZE_128<sup>9+</sup> | 128  | ShangMi4 (SM4) key of 128 bits           |

## HuksKeyAlg

Enumerates the key algorithms.

**System capability**: SystemCapability.Security.Huks

| Name                     | Value  | Description                 |
| ------------------------- | ---- | --------------------- |
| HUKS_ALG_RSA              | 1    | RSA    |
| HUKS_ALG_ECC              | 2    | ECC    |
| HUKS_ALG_DSA              | 3    | DSA    |
| HUKS_ALG_AES              | 20   | AES    |
| HUKS_ALG_HMAC             | 50   | HMAC   |
| HUKS_ALG_HKDF             | 51   | HKDF   |
| HUKS_ALG_PBKDF2           | 52   | PBKDF2 |
| HUKS_ALG_ECDH             | 100  | ECDH   |
| HUKS_ALG_X25519           | 101  | X25519  |
| HUKS_ALG_ED25519          | 102  | ED25519|
| HUKS_ALG_DH               | 103  | DH     |
| HUKS_ALG_SM2<sup>9+</sup> | 150  | SM2    |
| HUKS_ALG_SM3<sup>9+</sup> | 151  | SM3    |
| HUKS_ALG_SM4<sup>9+</sup> | 152  | SM4    |

## HuksKeyGenerateType

Enumerates the key generation types.

**System capability**: SystemCapability.Security.Huks

| Name                          | Value  | Description            |
| ------------------------------ | ---- | ---------------- |
| HUKS_KEY_GENERATE_TYPE_DEFAULT | 0    | Key generated by default.|
| HUKS_KEY_GENERATE_TYPE_DERIVE  | 1    | Derived key.|
| HUKS_KEY_GENERATE_TYPE_AGREE   | 2    | Key generated by agreement.|

## HuksKeyFlag

Enumerates the key generation modes.

**System capability**: SystemCapability.Security.Huks

| Name                      | Value  | Description                                |
| -------------------------- | ---- | ------------------------------------ |
| HUKS_KEY_FLAG_IMPORT_KEY   | 1    | Import a key using an API.    |
| HUKS_KEY_FLAG_GENERATE_KEY | 2    | Generate a key by using an API.    |
| HUKS_KEY_FLAG_AGREE_KEY    | 3    | Generate a key by using a key agreement API.|
| HUKS_KEY_FLAG_DERIVE_KEY   | 4    | Derive a key by using an API.|

## HuksKeyStorageType

Enumerates the key storage modes.

**System capability**: SystemCapability.Security.Huks

| Name                   | Value  | Description                          |
| ----------------------- | ---- | ------------------------------ |
| HUKS_STORAGE_TEMP       | 0    | The key is managed locally.    |
| HUKS_STORAGE_PERSISTENT | 1    | The key is managed by the HUKS service.|

## HuksSendType

Enumerates the tag transfer modes.

**System capability**: SystemCapability.Security.Huks

| Name                | Value  | Description             |
| -------------------- | ---- | ----------------- |
| HUKS_SEND_TYPE_ASYNC | 0    | The tag is sent asynchronously.|
| HUKS_SEND_TYPE_SYNC  | 1    | The tag is sent synchronously.|

## HuksUnwrapSuite<sup>9+</sup>

Enumerates the algorithm suites required for encrypted imports.

**System capability**: SystemCapability.Security.Huks

| Name                                          | Value  | Description                                                 |
| ---------------------------------------------- | ---- | ----------------------------------------------------- |
| HUKS_UNWRAP_SUITE_X25519_AES_256_GCM_NOPADDING | 1    | Use X25519 for key agreement and then use AES-256 GCM to encrypt the key.|
| HUKS_UNWRAP_SUITE_ECDH_AES_256_GCM_NOPADDING   | 2    | Use ECDH for key agreement and then use AES-256 GCM to encrypt the key.  |

## HuksImportKeyType<sup>9+</sup>

Enumerates the types of keys to import. By default, a public key is imported. This field is not required when a symmetric key is imported.

**System capability**: SystemCapability.Security.Huks

| Name                     | Value  | Description                          |
| ------------------------- | ---- | ------------------------------ |
| HUKS_KEY_TYPE_PUBLIC_KEY  | 0    | Public key    |
| HUKS_KEY_TYPE_PRIVATE_KEY | 1    | Private key    |
| HUKS_KEY_TYPE_KEY_PAIR    | 2    | Public and private key pair|

## HuksUserAuthType<sup>9+</sup>

Enumerates the user authentication types.

**System capability**: SystemCapability.Security.Huks

| Name                           | Value  | Description                     |
| ------------------------------- | ---- | ------------------------- |
| HUKS_USER_AUTH_TYPE_FINGERPRINT | 1    | Fingerprint authentication. |
| HUKS_USER_AUTH_TYPE_FACE        | 2    | Facial authentication.|
| HUKS_USER_AUTH_TYPE_PIN         | 4    | PIN authentication.|

## HuksAuthAccessType<sup>9+</sup>

Enumerates the access control types.

**System capability**: SystemCapability.Security.Huks

| Name                                   | Value  | Description                                            |
| --------------------------------------- | ---- | ------------------------------------------------ |
| HUKS_AUTH_ACCESS_INVALID_CLEAR_PASSWORD | 1    | The key becomes invalid after the password is cleared.      |
| HUKS_AUTH_ACCESS_INVALID_NEW_BIO_ENROLL | 2    | The key becomes invalid after a new biometric feature is added.|

## HuksChallengeType<sup>9+</sup>

Enumerates the types of the challenges generated when a key is used.

**System capability**: SystemCapability.Security.Huks

| Name                           | Value  | Description                          |
| ------------------------------- | ---- | ------------------------------ |
| HUKS_CHALLENGE_TYPE_NORMAL | 0    | Normal challenge, which is of 32 bytes by default.|
| HUKS_CHALLENGE_TYPE_CUSTOM        | 1    | Custom challenge, which supports only one authentication for multiple keys.|
| HUKS_CHALLENGE_TYPE_NONE         | 2    | Challenge is not required.|

## HuksChallengePosition<sup>9+</sup>

Enumerates the positions of the 8-byte valid value in a custom challenge generated.

**System capability**: SystemCapability.Security.Huks

| Name                           | Value  | Description                          |
| ------------------------------- | ---- | ------------------------------ |
| HUKS_CHALLENGE_POS_0 | 0    | Bytes 0 to 7.|
| HUKS_CHALLENGE_POS_1        | 1    | Bytes 8 to 15.|
| HUKS_CHALLENGE_POS_2         | 2    | Bytes 16 to 23.|
| HUKS_CHALLENGE_POS_3        | 3   | Bytes 24 to 31.|

## HuksSecureSignType<sup>9+</sup>

Defines the signature type of the key generated or imported.

**System capability**: SystemCapability.Security.Huks

| Name                          | Value  | Description                                                        |
| ------------------------------ | ---- | ------------------------------------------------------------ |
| 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.|

## HuksTagType

Enumerates the tag data types.

**System capability**: SystemCapability.Security.Huks

| Name                 | Value     | Description                                   |
| --------------------- | ------- | --------------------------------------- |
| HUKS_TAG_TYPE_INVALID | 0 << 28 | Invalid tag type.                    |
| HUKS_TAG_TYPE_INT     | 1 << 28 | Number of the int type. |
| HUKS_TAG_TYPE_UINT    | 2 << 28 | Number of the uint type.|
| HUKS_TAG_TYPE_ULONG   | 3 << 28 | BigInt.          |
| HUKS_TAG_TYPE_BOOL    | 4 << 28 | Boolean.         |
| HUKS_TAG_TYPE_BYTES   | 5 << 28 | Uint8Array.      |

## HuksTag

Enumerates the tags used to invoke parameters.

**System capability**: SystemCapability.Security.Huks

| Name                                        | Value                                      | Description                                  |
| -------------------------------------------- | ---------------------------------------- | -------------------------------------- |
| HUKS_TAG_INVALID                             | HuksTagType.HUKS_TAG_TYPE_INVALID \| 0   | Invalid tag.                       |
| HUKS_TAG_ALGORITHM                           | HUKS_TAG_TYPE_UINT \| 1                  | Algorithm.                       |
| HUKS_TAG_PURPOSE                             | HuksTagType.HUKS_TAG_TYPE_UINT \| 2      | Purpose of the key.                   |
| HUKS_TAG_KEY_SIZE                            | HuksTagType.HUKS_TAG_TYPE_UINT \| 3      | Key size.                   |
| HUKS_TAG_DIGEST                              | HuksTagType.HUKS_TAG_TYPE_UINT \| 4      | Digest algorithm.                   |
| HUKS_TAG_PADDING                             | HuksTagType.HUKS_TAG_TYPE_UINT \| 5      | Padding algorithm.                   |
| HUKS_TAG_BLOCK_MODE                          | HuksTagType.HUKS_TAG_TYPE_UINT \| 6      | Cipher mode.                   |
| HUKS_TAG_KEY_TYPE                            | HuksTagType.HUKS_TAG_TYPE_UINT \| 7      | Key type.                   |
| HUKS_TAG_ASSOCIATED_DATA                     | HuksTagType.HUKS_TAG_TYPE_BYTES \| 8     | Associated authentication data.           |
| HUKS_TAG_NONCE                               | HuksTagType.HUKS_TAG_TYPE_BYTES \| 9     | Field for key encryption and decryption.                |
| HUKS_TAG_IV                                  | HuksTagType.HUKS_TAG_TYPE_BYTES \| 10    | IV.                |
| HUKS_TAG_INFO                                | HuksTagType.HUKS_TAG_TYPE_BYTES \| 11    | Information generated during key derivation.                |
| HUKS_TAG_SALT                                | HuksTagType.HUKS_TAG_TYPE_BYTES \| 12    | Salt value used for key derivation.                |
| HUKS_TAG_PWD                                 | HuksTagType.HUKS_TAG_TYPE_BYTES \| 13    | Password used for key derivation.            |
| HUKS_TAG_ITERATION                           | HuksTagType.HUKS_TAG_TYPE_UINT \| 14     | Number of iterations for key derivation.            |
| HUKS_TAG_KEY_GENERATE_TYPE                   | HuksTagType.HUKS_TAG_TYPE_UINT \| 15     | Key generation type.               |
| HUKS_TAG_DERIVE_MAIN_KEY                     | HuksTagType.HUKS_TAG_TYPE_BYTES \| 16    | Main key for key derivation.              |
| HUKS_TAG_DERIVE_FACTOR                       | HuksTagType.HUKS_TAG_TYPE_BYTES \| 17    | Factor for key derivation.            |
| HUKS_TAG_DERIVE_ALG                          | HuksTagType.HUKS_TAG_TYPE_UINT \| 18     | Type of the algorithm used for key derivation.            |
| HUKS_TAG_AGREE_ALG                           | HuksTagType.HUKS_TAG_TYPE_UINT \| 19     | Type of the algorithm used for key agreement.            |
| HUKS_TAG_AGREE_PUBLIC_KEY_IS_KEY_ALIAS       | HuksTagType.HUKS_TAG_TYPE_BOOL \| 20     | Public key alias used in key agreement.            |
| HUKS_TAG_AGREE_PRIVATE_KEY_ALIAS             | HuksTagType.HUKS_TAG_TYPE_BYTES \| 21    | Private key alias used in key agreement.            |
| HUKS_TAG_AGREE_PUBLIC_KEY                    | HuksTagType.HUKS_TAG_TYPE_BYTES \| 22    | Public key used in key agreement.                |
| HUKS_TAG_KEY_ALIAS                           | HuksTagType.HUKS_TAG_TYPE_BYTES \| 23    | Key alias.                        |
| HUKS_TAG_DERIVE_KEY_SIZE                     | HuksTagType.HUKS_TAG_TYPE_UINT \| 24     | Size of the derived key.                  |
| HUKS_TAG_IMPORT_KEY_TYPE<sup>9+</sup>        | HuksTagType.HUKS_TAG_TYPE_UINT \| 25     | Type of the imported key.                    |
| HUKS_TAG_UNWRAP_ALGORITHM_SUITE<sup>9+</sup> | HuksTagType.HUKS_TAG_TYPE_UINT \| 26     | Algorithm suite required for encrypted imports.                |
| HUKS_TAG_ACTIVE_DATETIME                     | HuksTagType.HUKS_TAG_TYPE_ULONG \| 201   | Reserved.                                |
| HUKS_TAG_ORIGINATION_EXPIRE_DATETIME         | HuksTagType.HUKS_TAG_TYPE_ULONG \| 202   | Reserved.                                |
| HUKS_TAG_USAGE_EXPIRE_DATETIME               | HuksTagType.HUKS_TAG_TYPE_ULONG \| 203   | Reserved.                                |
| HUKS_TAG_CREATION_DATETIME                   | HuksTagType.HUKS_TAG_TYPE_ULONG \| 204   | Reserved.                                |
| HUKS_TAG_ALL_USERS                           | ksTagType.HUKS_TAG_TYPE_BOOL \| 301      | Reserved.                                |
| HUKS_TAG_USER_ID                             | HuksTagType.HUKS_TAG_TYPE_UINT \| 302    | Reserved.                                |
| HUKS_TAG_NO_AUTH_REQUIRED                    | HuksTagType.HUKS_TAG_TYPE_BOOL \| 303    | Reserved.                                |
| 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\**.| HKS_USER_AUTH_TYPE_FINGERPRINT |
| HUKS_TAG_AUTH_TIMEOUT                        | HuksTagType.HUKS_TAG_TYPE_UINT \| 305    | Reserved.                                |
| HUKS_TAG_AUTH_TOKEN                          | HuksTagType.HUKS_TAG_TYPE_BYTES \| 306   | Reserved.                                |
| 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).|
| HUKS_TAG_KEY_SECURE_SIGN_TYPE<sup>9+</sup> | HuksTagType.HUKS_TAG_TYPE_UINT \| 308 | Signature type of the key generated or imported.|
| 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).|
| 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).|
| HUKS_TAG_ATTESTATION_CHALLENGE               | HuksTagType.HUKS_TAG_TYPE_BYTES \| 501   | Challenge value used in the attestation.           |
| HUKS_TAG_ATTESTATION_APPLICATION_ID          | HuksTagType.HUKS_TAG_TYPE_BYTES \| 502   | Application ID used in the attestation.   |
| HUKS_TAG_ATTESTATION_ID_BRAND                | HuksTagType.HUKS_TAG_TYPE_BYTES \| 503   | Brand of the device.                     |
| HUKS_TAG_ATTESTATION_ID_DEVICE               | HuksTagType.HUKS_TAG_TYPE_BYTES \| 504   | ID of the device.                    |
| HUKS_TAG_ATTESTATION_ID_PRODUCT              | HuksTagType.HUKS_TAG_TYPE_BYTES \| 505   | Product name of the device.                   |
| HUKS_TAG_ATTESTATION_ID_SERIAL               | HuksTagType.HUKS_TAG_TYPE_BYTES \| 506   | SN of the device.                      |
| HUKS_TAG_ATTESTATION_ID_IMEI                 | HuksTagType.HUKS_TAG_TYPE_BYTES \| 507   | International mobile equipment identity (IMEI) of the device.                    |
| HUKS_TAG_ATTESTATION_ID_MEID                 | HuksTagType.HUKS_TAG_TYPE_BYTES \| 508   | Mobile equipment identity (MEID) of the device.                    |
| HUKS_TAG_ATTESTATION_ID_MANUFACTURER         | HuksTagType.HUKS_TAG_TYPE_BYTES \| 509   | Manufacturer of the device.                    |
| HUKS_TAG_ATTESTATION_ID_MODEL                | HuksTagType.HUKS_TAG_TYPE_BYTES \| 510   | Device model.                      |
| HUKS_TAG_ATTESTATION_ID_ALIAS                | HuksTagType.HUKS_TAG_TYPE_BYTES \| 511   | Key alias used in the attestation.         |
| HUKS_TAG_ATTESTATION_ID_SOCID                | HuksTagType.HUKS_TAG_TYPE_BYTES \| 512   | System-on-a-chip (SoCID) of the device.                     |
| HUKS_TAG_ATTESTATION_ID_UDID                 | HuksTagType.HUKS_TAG_TYPE_BYTES \| 513   | Unique device identifier (UDID) of the device.                      |
| HUKS_TAG_ATTESTATION_ID_SEC_LEVEL_INFO       | HuksTagType.HUKS_TAG_TYPE_BYTES \| 514   | Security level used in the attestation.         |
| HUKS_TAG_ATTESTATION_ID_VERSION_INFO         | HuksTagType.HUKS_TAG_TYPE_BYTES \| 515   | Version information used in the attestation.           |
| HUKS_TAG_IS_KEY_ALIAS                        | HuksTagType.HUKS_TAG_TYPE_BOOL \| 1001   | Whether to use the alias passed in during key generation.|
| HUKS_TAG_KEY_STORAGE_FLAG                    | HuksTagType.HUKS_TAG_TYPE_UINT \| 1002   | Key storage mode.               |
| HUKS_TAG_IS_ALLOWED_WRAP                     | HuksTagType.HUKS_TAG_TYPE_BOOL \| 1003   | Reserved.                                |
| HUKS_TAG_KEY_WRAP_TYPE                       | HuksTagType.HUKS_TAG_TYPE_UINT \| 1004   | Reserved.                                |
| HUKS_TAG_KEY_AUTH_ID                         | HuksTagType.HUKS_TAG_TYPE_BYTES \| 1005  | Reserved.                                |
| HUKS_TAG_KEY_ROLE                            | HuksTagType.HUKS_TAG_TYPE_UINT \| 1006   | Reserved.                                |
| HUKS_TAG_KEY_FLAG                            | HuksTagType.HUKS_TAG_TYPE_UINT \| 1007   | Flag of the key.                   |
| HUKS_TAG_IS_ASYNCHRONIZED                    | HuksTagType.HUKS_TAG_TYPE_UINT \| 1008   | Reserved.                                |
| HUKS_TAG_SECURE_KEY_ALIAS                    | HuksTagType.HUKS_TAG_TYPE_BOOL \| 1009   | Reserved.                                |
| HUKS_TAG_SECURE_KEY_UUID                     | HuksTagType.HUKS_TAG_TYPE_BYTES \| 1010  | Reserved.                                |
| HUKS_TAG_KEY_DOMAIN                          | HuksTagType.HUKS_TAG_TYPE_UINT \| 1011   | Reserved.                                |
| HUKS_TAG_PROCESS_NAME                        | HuksTagType.HUKS_TAG_TYPE_BYTES \| 10001 | Process name.                   |
| HUKS_TAG_PACKAGE_NAME                        | HuksTagType.HUKS_TAG_TYPE_BYTES \| 10002 | Reserved.                                |
| HUKS_TAG_ACCESS_TIME                         | HuksTagType.HUKS_TAG_TYPE_UINT \| 10003  | Reserved.                                |
| HUKS_TAG_USES_TIME                           | HuksTagType.HUKS_TAG_TYPE_UINT \| 10004  | Reserved.                                |
| HUKS_TAG_CRYPTO_CTX                          | HuksTagType.HUKS_TAG_TYPE_ULONG \| 10005 | Reserved.                                |
| HUKS_TAG_KEY                                 | HuksTagType.HUKS_TAG_TYPE_BYTES \| 10006 | Reserved.                                |
| HUKS_TAG_KEY_VERSION                         | HuksTagType.HUKS_TAG_TYPE_UINT \| 10007  | Key version.                   |
| HUKS_TAG_PAYLOAD_LEN                         | HuksTagType.HUKS_TAG_TYPE_UINT \| 10008  | Reserved.                                |
| HUKS_TAG_AE_TAG                              | HuksTagType.HUKS_TAG_TYPE_BYTES \| 10009 | Reserved.                                |
| HUKS_TAG_IS_KEY_HANDLE                       | HuksTagType.HUKS_TAG_TYPE_ULONG \| 10010 | Reserved.                                |
| HUKS_TAG_OS_VERSION                          | HuksTagType.HUKS_TAG_TYPE_UINT \| 10101  | OS version.               |
| HUKS_TAG_OS_PATCHLEVEL                       | HuksTagType.HUKS_TAG_TYPE_UINT \| 10102  | OS patch level.           |
| HUKS_TAG_SYMMETRIC_KEY_DATA                  | HuksTagType.HUKS_TAG_TYPE_BYTES \| 20001 | Reserved.                                |
| HUKS_TAG_ASYMMETRIC_PUBLIC_KEY_DATA          | HuksTagType.HUKS_TAG_TYPE_BYTES \| 20002 | Reserved.                                |
| HUKS_TAG_ASYMMETRIC_PRIVATE_KEY_DATA         | HuksTagType.HUKS_TAG_TYPE_BYTES \| 20003 | Reserved.                                |

## huks.generateKey<sup>(deprecated)</sup>

generateKey(keyAlias: string, options: HuksOptions, callback: AsyncCallback\<HuksResult>) : void

Generates a key. This API uses an asynchronous callback to return the result.

>  **NOTE**<br>This API is deprecated since API version 9. You are advised to use [huks.generateKeyItem<sup>9+</sup>](#huksgeneratekeyitem9).

**System capability**: SystemCapability.Security.Huks

**Parameters**

| Name  | Type                                     | Mandatory| Description                                                        |
| -------- | ----------------------------------------- | ---- | ------------------------------------------------------------ |
| keyAlias | string                                    | Yes  | Alias of the key.                                                       |
| options  | [HuksOptions](#huksoptions)               | Yes  | Tags required for generating the key.                                    |
A
Annie_wang 已提交
1996
| callback | AsyncCallback\<[HuksResult](#huksresult)> | 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.|
A
Annie_wang 已提交
1997 1998 1999 2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 2012 2013 2014 2015 2016 2017 2018 2019 2020 2021 2022 2023 2024 2025 2026 2027 2028 2029 2030 2031 2032 2033 2034 2035 2036 2037 2038 2039 2040 2041 2042 2043 2044 2045 2046 2047 2048 2049 2050 2051 2052

**Example**

```js
/* Generate an RSA key of 512 bits. */
let keyAlias = 'keyAlias';
let properties = new Array();
properties[0] = {
  tag: huks.HuksTag.HUKS_TAG_ALGORITHM,
  value: huks.HuksKeyAlg.HUKS_ALG_RSA
};
properties[1] = {
  tag: huks.HuksTag.HUKS_TAG_KEY_SIZE,
  value: huks.HuksKeySize.HUKS_RSA_KEY_SIZE_512
};
properties[2] = {
  tag: huks.HuksTag.HUKS_TAG_PURPOSE,
  value:
huks.HuksKeyPurpose.HUKS_KEY_PURPOSE_ENCRYPT |
huks.HuksKeyPurpose.HUKS_KEY_PURPOSE_DECRYPT
};
properties[3] = {
  tag: huks.HuksTag.HUKS_TAG_PADDING,
  value: huks.HuksKeyPadding.HUKS_PADDING_OAEP
};
properties[4] = {
  tag: huks.HuksTag.HUKS_TAG_DIGEST,
  value: huks.HuksKeyDigest.HUKS_DIGEST_SHA256
};
let options = {
  properties: properties
};
huks.generateKey(keyAlias, options, function (err, data){}); 
```

## huks.generateKey<sup>(deprecated)</sup>

generateKey(keyAlias: string, options: HuksOptions) : Promise\<HuksResult>

Generates a key. This API uses a promise to return the result.

>  **NOTE**<br>This API is deprecated since API version 9. You are advised to use [huks.generateKeyItem<sup>9+</sup>](#huksgeneratekeyitem9-1).

**System capability**: SystemCapability.Security.Huks

**Parameters**

| Name  | Type                       | Mandatory| Description                    |
| -------- | --------------------------- | ---- | ------------------------ |
| keyAlias | string                      | Yes  | Alias of the key.              |
| options  | [HuksOptions](#huksoptions) | Yes  | Tags required for generating the key.|

**Return value**

| Type                               | Description                                              |
| ----------------------------------- | -------------------------------------------------- |
A
Annie_wang 已提交
2053
| Promise\<[HuksResult](#huksresult)> | Promise used to return the result. If the operation is successful, **HUKS_SUCCESS** is returned; otherwise, an error code is returned.|
A
Annie_wang 已提交
2054 2055 2056 2057 2058 2059 2060 2061 2062 2063 2064 2065 2066 2067 2068 2069 2070 2071 2072 2073 2074 2075 2076 2077 2078 2079 2080 2081 2082 2083 2084 2085 2086 2087 2088 2089 2090 2091 2092 2093 2094 2095 2096 2097 2098 2099 2100 2101

**Example**

```js
/* Generate an ECC key of 256 bits. */
let keyAlias = 'keyAlias';
let properties = new Array();
properties[0] = {
  tag: huks.HuksTag.HUKS_TAG_ALGORITHM,
  value: huks.HuksKeyAlg.HUKS_ALG_ECC
};
properties[1] = {
  tag: huks.HuksTag.HUKS_TAG_KEY_SIZE,
  value: huks.HuksKeySize.HUKS_ECC_KEY_SIZE_256
};
properties[2] = {
  tag: huks.HuksTag.HUKS_TAG_PURPOSE,
  value:
huks.HuksKeyPurpose.HUKS_KEY_PURPOSE_SIGN |
huks.HuksKeyPurpose.HUKS_KEY_PURPOSE_VERIFY
};
properties[3] = {
  tag: huks.HuksTag.HUKS_TAG_DIGEST,
  value: huks.HuksKeyDigest.HUKS_DIGEST_SHA256
};
let options = {
  properties: properties
};
let result = huks.generateKey(keyAlias, options);
```


## huks.deleteKey<sup>(deprecated)</sup>

deleteKey(keyAlias: string, options: HuksOptions, callback: AsyncCallback\<HuksResult>) : void

Deletes a key. This API uses an asynchronous callback to return the result.

>  **NOTE**<br>This API is deprecated since API version 9. You are advised to use [huks.deleteKeyItem<sup>9+</sup>](#huksdeletekeyitem9).

**System capability**: SystemCapability.Security.Huks

**Parameters**

| Name  | Type                                     | Mandatory| Description                                              |
| -------- | ----------------------------------------- | ---- | -------------------------------------------------- |
| keyAlias | string                                    | Yes  | Key alias passed in when the key was generated.               |
| options  | [HuksOptions](#huksoptions)               | Yes  | Empty object (leave this parameter empty).                          |
A
Annie_wang 已提交
2102
| callback | AsyncCallback\<[HuksResult](#huksresult)> | Yes  | Callback invoked to return the result. If the operation is successful, **HUKS_SUCCESS** is returned; otherwise, an error code is returned.|
A
Annie_wang 已提交
2103 2104 2105 2106 2107 2108 2109 2110 2111 2112 2113 2114 2115 2116 2117 2118 2119 2120 2121 2122 2123 2124 2125 2126 2127 2128 2129 2130 2131 2132 2133 2134 2135

**Example**

```js
/* Set options to emptyOptions. */
let keyAlias = 'keyAlias';
let emptyOptions = {
  properties: []
};
huks.deleteKey(keyAlias, emptyOptions, function (err, data) {});
```

## huks.deleteKey<sup>(deprecated)</sup>

deleteKey(keyAlias: string, options: HuksOptions) : Promise\<HuksResult>

Deletes a key. This API uses a promise to return the result.

>  **NOTE**<br>This API is deprecated since API version 9. You are advised to use [huks.deleteKeyItem<sup>9+</sup>](#huksdeletekeyitem9-1).

**System capability**: SystemCapability.Security.Huks

**Parameters**

| Name  | Type       | Mandatory| Description                                                 |
| -------- | ----------- | ---- | ----------------------------------------------------- |
| keyAlias | string      | Yes  | Key alias passed in when the key was generated.|
| options | [HuksOptions](#huksoptions) | Yes  | Empty object (leave this parameter empty).|

**Return value**

| Type                               | Description                                              |
| ----------------------------------- | -------------------------------------------------- |
A
Annie_wang 已提交
2136
| Promise\<[HuksResult](#huksresult)> | Promise used to return the result. If the operation is successful, **HUKS_SUCCESS** is returned; otherwise, an error code is returned.|
A
Annie_wang 已提交
2137 2138 2139 2140 2141 2142 2143 2144 2145 2146 2147 2148 2149 2150 2151 2152 2153 2154 2155 2156 2157 2158 2159 2160 2161 2162 2163 2164 2165

**Example**

```js
/* Set options to emptyOptions. */
let keyAlias = 'keyAlias';
let emptyOptions = {
  properties: []
};
let result = huks.deleteKey(keyAlias, emptyOptions);
```


## huks.importKey<sup>(deprecated)</sup>

importKey(keyAlias: string, options: HuksOptions, callback: AsyncCallback\<HuksResult>) : void

Imports a key in plaintext. This API uses an asynchronous callback to return the result.

>  **NOTE**<br>This API is deprecated since API version 9. You are advised to use [huks.importKeyItem<sup>9+</sup>](#huksimportkeyitem9).

**System capability**: SystemCapability.Security.Huks

**Parameters**

| Name  | Type                    | Mandatory| Description                                             |
| -------- | ------------------------ | ---- | ------------------------------------------------- |
| keyAlias | string                   | Yes  | Alias of the key.|
| options  | [HuksOptions](#huksoptions) | Yes  | Tags required for the import and key to import.|
A
Annie_wang 已提交
2166
| callback | AsyncCallback\<[HuksResult](#huksresult)> | Yes  | Callback invoked to return the result. If the operation is successful, **HUKS_SUCCESS** is returned; otherwise, an error code is returned.|
A
Annie_wang 已提交
2167 2168 2169 2170 2171 2172 2173 2174 2175 2176 2177 2178 2179 2180 2181 2182 2183 2184 2185 2186 2187 2188

**Example**

```js
/* Import an AES key of 256 bits. */
let plainTextSize32 = makeRandomArr(32);
function makeRandomArr(size) {
    let arr = new Uint8Array(size);
    for (let i = 0; i < size; i++) {
        arr[i] = Math.floor(Math.random() * 10);
    }
    return arr;
};
let keyAlias = 'keyAlias';
let properties = new Array();
properties[0] = {
  tag: huks.HuksTag.HUKS_TAG_ALGORITHM,
  value: huks.HuksKeyAlg.HUKS_ALG_AES
};
properties[1] = {
  tag: huks.HuksTag.HUKS_TAG_KEY_SIZE,
  value: huks.HuksKeySize.HUKS_AES_KEY_SIZE_256
A
Annie_wang 已提交
2189
};
A
Annie_wang 已提交
2190 2191 2192 2193 2194 2195 2196 2197 2198 2199 2200 2201 2202 2203 2204 2205 2206 2207
properties[2] = {
  tag: huks.HuksTag.HUKS_TAG_PURPOSE,
  value:
huks.HuksKeyPurpose.HUKS_KEY_PURPOSE_ENCRYPT | huks.HuksKeyPurpose.HUKS_KEY_PURPOSE_DECRYPT
};
properties[3] = {
  tag: huks.HuksTag.HUKS_TAG_PADDING,
  value:huks.HuksKeyPadding.HUKS_PADDING_PKCS7
};
properties[4] = {
  tag: huks.HuksTag.HUKS_TAG_BLOCK_MODE,
  value: huks.HuksCipherMode.HUKS_MODE_ECB
};
let options = {
  properties: properties,
  inData: plainTextSize32
};
huks.importKey(keyAlias, options, function (err, data){});
A
Annie_wang 已提交
2208 2209
```

A
Annie_wang 已提交
2210
## huks.importKey<sup>(deprecated)</sup>
A
Annie_wang 已提交
2211

A
Annie_wang 已提交
2212
importKey(keyAlias: string, options: HuksOptions) : Promise\<HuksResult>
A
Annie_wang 已提交
2213

A
Annie_wang 已提交
2214 2215 2216
Imports a key in plaintext. This API uses a promise to return the result.

>  **NOTE**<br>This API is deprecated since API version 9. You are advised to use [huks.importKeyItem<sup>9+</sup>](#huksimportkeyitem9-1).
A
Annie_wang 已提交
2217 2218 2219 2220 2221

**System capability**: SystemCapability.Security.Huks

**Parameters**

A
Annie_wang 已提交
2222 2223 2224 2225
| Name  | Type       | Mandatory| Description                                |
| -------- | ----------- | ---- | ------------------------------------ |
| keyAlias | string      | Yes  | Alias of the key.|
| options  | [HuksOptions](#huksoptions) | Yes  | Tags required for the import and key to import.|
A
Annie_wang 已提交
2226 2227 2228 2229 2230

**Return value**

| Type                               | Description                                              |
| ----------------------------------- | -------------------------------------------------- |
A
Annie_wang 已提交
2231
| Promise\<[HuksResult](#huksresult)> | Promise used to return the result. If the operation is successful, **HUKS_SUCCESS** is returned; otherwise, an error code is returned.|
A
Annie_wang 已提交
2232 2233 2234 2235

**Example**

```js
A
Annie_wang 已提交
2236 2237 2238 2239 2240 2241 2242 2243 2244 2245 2246 2247 2248 2249 2250 2251 2252 2253 2254 2255 2256 2257 2258 2259 2260 2261 2262 2263 2264 2265 2266 2267 2268 2269 2270 2271 2272 2273 2274
/* Import an AES key of 128 bits. */
let plainTextSize32 = makeRandomArr(32);

function makeRandomArr(size) {
    let arr = new Uint8Array(size);
    for (let i = 0; i < size; i++) {
        arr[i] = Math.floor(Math.random() * 10);
    }
    return arr;
};

/* Step 1 Generate a key. */
let keyAlias = 'keyAlias';
let properties = new Array();
properties[0] = {
  tag: huks.HuksTag.HUKS_TAG_ALGORITHM,
  value: huks.HuksKeyAlg.HUKS_ALG_AES
};
properties[1] = {
  tag: huks.HuksTag.HUKS_TAG_KEY_SIZE,
  value: huks.HuksKeySize.HUKS_AES_KEY_SIZE_128
};
properties[2] = {
  tag: huks.HuksTag.HUKS_TAG_PURPOSE,
  value: huks.HuksKeyPurpose.HUKS_KEY_PURPOSE_ENCRYPT | huks.HuksKeyPurpose.HUKS_KEY_PURPOSE_DECRYPT
};
properties[3] = {
  tag: huks.HuksTag.HUKS_TAG_PADDING,
  value:huks.HuksKeyPadding.HUKS_PADDING_PKCS7
};
properties[4] = {
  tag: huks.HuksTag.HUKS_TAG_BLOCK_MODE,
  value: huks.HuksCipherMode.HUKS_MODE_ECB
};
let huksoptions = {
  properties: properties,
  inData: plainTextSize32
};
let result = huks.importKey(keyAlias, huksoptions);
A
Annie_wang 已提交
2275 2276
```

A
Annie_wang 已提交
2277 2278

## huks.exportKey<sup>(deprecated)</sup>
A
annie_wangli 已提交
2279 2280 2281

exportKey(keyAlias: string, options: HuksOptions, callback: AsyncCallback\<HuksResult>) : void

A
Annie_wang 已提交
2282
Exports a key. This API uses an asynchronous callback to return the result.
A
annie_wangli 已提交
2283

A
Annie_wang 已提交
2284 2285
>  **NOTE**<br>This API is deprecated since API version 9. You are advised to use [huks.exportKeyItem<sup>9+</sup>](#huksexportkeyitem9).

A
annie_wangli 已提交
2286 2287 2288 2289 2290 2291 2292 2293
**System capability**: SystemCapability.Security.Huks

**Parameters**

| Name  | Type                                     | Mandatory| Description                                                        |
| -------- | ----------------------------------------- | ---- | ------------------------------------------------------------ |
| keyAlias | string                                    | Yes  | Key alias, which must be the same as the alias used when the key was generated.                |
| options  | [HuksOptions](#huksoptions)               | Yes  | Empty object (leave this parameter empty).                                    |
A
Annie_wang 已提交
2294
| callback | AsyncCallback\<[HuksResult](#huksresult)> | 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.|
A
annie_wangli 已提交
2295 2296 2297 2298

**Example**

```js
A
Annie_wang 已提交
2299
/* Set options to emptyOptions. */
A
Annie_wang 已提交
2300 2301
let keyAlias = 'keyAlias';
let emptyOptions = {
A
annie_wangli 已提交
2302 2303 2304 2305 2306
  properties: []
};
huks.exportKey(keyAlias, emptyOptions, function (err, data){});
```

A
Annie_wang 已提交
2307
## huks.exportKey<sup>(deprecated)</sup>
A
annie_wangli 已提交
2308 2309 2310

exportKey(keyAlias: string, options: HuksOptions) : Promise\<HuksResult>

A
Annie_wang 已提交
2311
Exports a key. This API uses a promise to return the result.
A
annie_wangli 已提交
2312

A
Annie_wang 已提交
2313 2314
>  **NOTE**<br>This API is deprecated since API version 9. You are advised to use [huks.exportKeyItem<sup>9+</sup>](#huksexportkeyitem9-1).

A
annie_wangli 已提交
2315 2316 2317 2318 2319 2320
**System capability**: SystemCapability.Security.Huks

**Parameters**

| Name  | Type       | Mandatory| Description                                                        |
| -------- | ----------- | ---- | ------------------------------------------------------------ |
A
Annie_wang 已提交
2321 2322
| keyAlias | string      | Yes  | Key alias, which must be the same as the alias used when the key was generated.|
| options  | [HuksOptions](#huksoptions) | Yes  | Empty object (leave this parameter empty).|
A
annie_wangli 已提交
2323 2324 2325 2326 2327

**Return value**

| Type                               | Description                                                        |
| ----------------------------------- | ------------------------------------------------------------ |
A
Annie_wang 已提交
2328
| Promise\<[HuksResult](#huksresult)> | 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. |
A
annie_wangli 已提交
2329 2330 2331 2332

**Example**

```js
A
Annie_wang 已提交
2333
/* Set options to emptyOptions. */
A
Annie_wang 已提交
2334 2335
let keyAlias = 'keyAlias';
let emptyOptions = {
A
annie_wangli 已提交
2336 2337
  properties: []
};
A
Annie_wang 已提交
2338
let result = huks.exportKey(keyAlias, emptyOptions);
A
annie_wangli 已提交
2339 2340
```

A
Annie_wang 已提交
2341 2342

## huks.getKeyProperties<sup>(deprecated)</sup>
A
annie_wangli 已提交
2343 2344 2345

getKeyProperties(keyAlias: string, options: HuksOptions, callback: AsyncCallback\<HuksResult>) : void

A
Annie_wang 已提交
2346
Obtains key properties. This API uses an asynchronous callback to return the result.
A
annie_wangli 已提交
2347

A
Annie_wang 已提交
2348 2349
>  **NOTE**<br>This API is deprecated since API version 9. You are advised to use [huks.getKeyItemProperties<sup>9+</sup>](#huksgetkeyitemproperties9).

A
annie_wangli 已提交
2350 2351 2352 2353 2354 2355 2356 2357
**System capability**: SystemCapability.Security.Huks

**Parameters**

| Name  | Type                                     | Mandatory| Description                                                        |
| -------- | ----------------------------------------- | ---- | ------------------------------------------------------------ |
| keyAlias | string                                    | Yes  | Key alias, which must be the same as the alias used when the key was generated.                |
| options  | [HuksOptions](#huksoptions)               | Yes  | Empty object (leave this parameter empty).                                    |
A
Annie_wang 已提交
2358
| callback | AsyncCallback\<[HuksResult](#huksresult)> | Yes  | Callback invoked to return the result. If the operation is successful, **errorCode** is **HUKS_SUCCESS**; otherwise, an error code is returned.|
A
annie_wangli 已提交
2359 2360 2361 2362

**Example**

```js
A
Annie_wang 已提交
2363
/* Set options to emptyOptions. */
A
Annie_wang 已提交
2364 2365
let keyAlias = 'keyAlias';
let emptyOptions = {
A
annie_wangli 已提交
2366 2367 2368 2369 2370
  properties: []
};
huks.getKeyProperties(keyAlias, emptyOptions, function (err, data){});
```

A
Annie_wang 已提交
2371
## huks.getKeyProperties<sup>(deprecated)</sup>
A
annie_wangli 已提交
2372 2373 2374

getKeyProperties(keyAlias: string, options: HuksOptions) : Promise\<HuksResult>

A
Annie_wang 已提交
2375
Obtains key properties. This API uses a promise to return the result.
A
annie_wangli 已提交
2376

A
Annie_wang 已提交
2377 2378
>  **NOTE**<br>This API is deprecated since API version 9. You are advised to use [huks.getKeyItemProperties<sup>9+</sup>](#huksgetkeyitemproperties9-1).

A
annie_wangli 已提交
2379 2380 2381 2382 2383 2384
**System capability**: SystemCapability.Security.Huks

**Parameters**

| Name  | Type       | Mandatory| Description                                                        |
| -------- | ----------- | ---- | ------------------------------------------------------------ |
A
Annie_wang 已提交
2385 2386
| keyAlias | string      | Yes  | Key alias, which must be the same as the alias used when the key was generated.|
| options  | [HuksOptions](#huksoptions) | Yes  | Empty object (leave this parameter empty).|
A
annie_wangli 已提交
2387 2388 2389 2390 2391

**Return value**

| Type              | Description                                                        |
| ------------------ | ------------------------------------------------------------ |
A
Annie_wang 已提交
2392
| 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. |
A
annie_wangli 已提交
2393 2394 2395 2396

**Example**

```js
A
Annie_wang 已提交
2397
/* Set options to emptyOptions. */
A
Annie_wang 已提交
2398 2399
let keyAlias = 'keyAlias';
let emptyOptions = {
A
annie_wangli 已提交
2400 2401
  properties: []
};
A
Annie_wang 已提交
2402
let result = huks.getKeyProperties(keyAlias, emptyOptions);
A
annie_wangli 已提交
2403 2404
```

A
Annie_wang 已提交
2405 2406

## huks.isKeyExist<sup>(deprecated)</sup>
A
annie_wangli 已提交
2407 2408 2409

isKeyExist(keyAlias: string, options: HuksOptions, callback: AsyncCallback\<boolean>) : void

A
Annie_wang 已提交
2410
Checks whether a key exists. This API uses an asynchronous callback to return the result.
A
annie_wangli 已提交
2411

A
Annie_wang 已提交
2412 2413
>  **NOTE**<br>This API is deprecated since API version 9. You are advised to use [huks.isKeyItemExist<sup>9+</sup>](#huksiskeyitemexist9).

A
annie_wangli 已提交
2414 2415 2416 2417 2418 2419
**System capability**: SystemCapability.Security.Huks

**Parameters**

| Name  | Type                  | Mandatory| Description                                 |
| -------- | ---------------------- | ---- | ------------------------------------- |
A
Annie_wang 已提交
2420 2421
| keyAlias | string                 | Yes  | Alias of the key to check.|
| options  | [HuksOptions](#huksoptions) | Yes  | Empty object (leave this parameter empty).|
A
Annie_wang 已提交
2422
| callback | AsyncCallback\<boolean> | Yes  | Callback invoked to return the result. **TRUE** means that the key exists; **FALSE** means the opposite.|
A
annie_wangli 已提交
2423 2424 2425 2426

**Example**

```js
A
Annie_wang 已提交
2427
/* Set options to emptyOptions. */
A
Annie_wang 已提交
2428 2429
let keyAlias = 'keyAlias';
let emptyOptions = {
A
annie_wangli 已提交
2430 2431 2432 2433 2434
  properties: []
};
huks.isKeyExist(keyAlias, emptyOptions, function (err, data){});
```

A
Annie_wang 已提交
2435
## huks.isKeyExist<sup>(deprecated)</sup>
A
annie_wangli 已提交
2436 2437 2438

isKeyExist(keyAlias: string, options: HuksOptions) : Promise\<boolean>

A
Annie_wang 已提交
2439
Checks whether a key exists. This API uses a promise to return the result.
A
annie_wangli 已提交
2440

A
Annie_wang 已提交
2441 2442
>  **NOTE**<br>This API is deprecated since API version 9. You are advised to use [huks.isKeyItemExist<sup>9+</sup>](#huksiskeyitemexist9-1).

A
annie_wangli 已提交
2443 2444 2445 2446 2447 2448
**System capability**: SystemCapability.Security.Huks

**Parameters**

| Name  | Type       | Mandatory| Description                            |
| -------- | ----------- | ---- | -------------------------------- |
A
Annie_wang 已提交
2449 2450
| keyAlias | string      | Yes  | Alias of the key to check.|
| options  | [HuksOptions](#huksoptions) | Yes  | Empty object (leave this parameter empty).|
A
annie_wangli 已提交
2451 2452 2453 2454 2455

**Return value**

| Type             | Description                                   |
| ----------------- | --------------------------------------- |
A
Annie_wang 已提交
2456
| Promise\<boolean> | Promise used to return the result. **TRUE** means that the key exists; **FALSE** means the opposite.|
A
annie_wangli 已提交
2457 2458 2459 2460

**Example**

```js
A
Annie_wang 已提交
2461
/* Set options to emptyOptions. */
A
Annie_wang 已提交
2462 2463
let keyAlias = 'keyAlias';
let emptyOptions = {
A
annie_wangli 已提交
2464 2465
  properties: []
};
A
Annie_wang 已提交
2466
let result = huks.isKeyExist(keyAlias, emptyOptions);
A
annie_wangli 已提交
2467 2468
```

A
Annie_wang 已提交
2469
## huks.init<sup>(deprecated)</sup>
A
annie_wangli 已提交
2470 2471 2472

init(keyAlias: string, options: HuksOptions, callback: AsyncCallback\<HuksHandle>) : void

A
Annie_wang 已提交
2473 2474 2475
Initializes 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.

>  **NOTE**<br>This API is deprecated since API version 9. You are advised to use [huks.initSession<sup>9+</sup>](#huksinitsession9-1).
A
annie_wangli 已提交
2476 2477 2478 2479 2480 2481 2482

**System capability**: SystemCapability.Security.Huks

**Parameters**

| Name  | Type                  | Mandatory| Description                                 |
| -------- | ---------------------- | ---- | ------------------------------------- |
A
Annie_wang 已提交
2483 2484
| keyAlias | string                 | Yes  | Alias of the target key.|
| options  | [HuksOptions](#huksoptions) | Yes  | Parameters used for initialization.|
A
Annie_wang 已提交
2485
| callback | AsyncCallback\<[HuksHandle](#hukshandle)> | Yes  | Callback invoked to return the key operation handle.|
A
annie_wangli 已提交
2486 2487


A
Annie_wang 已提交
2488
## huks.init<sup>(deprecated)</sup>
A
annie_wangli 已提交
2489 2490 2491

init(keyAlias: string, options: HuksOptions) : Promise\<HuksHandle>

A
Annie_wang 已提交
2492 2493 2494
Initializes 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.

>  **NOTE**<br>This API is deprecated since API version 9. You are advised to use [huks.initSession<sup>9+</sup>](#huksinitsession9-1).
A
annie_wangli 已提交
2495 2496 2497 2498 2499 2500 2501

**System capability**: SystemCapability.Security.Huks

**Parameters**

| Name  | Type                  | Mandatory| Description                                 |
| -------- | ---------------------- | ---- | ------------------------------------- |
A
Annie_wang 已提交
2502 2503
| keyAlias | string                 | Yes  | Alias of the target key.|
| options  | [HuksOptions](#huksoptions) | Yes  | Parameters used for initialization.|
A
annie_wangli 已提交
2504

A
Annie_wang 已提交
2505
**Return value**
A
annie_wangli 已提交
2506

A
Annie_wang 已提交
2507 2508 2509
| Type                               | Description                                              |
| ----------------------------------- | -------------------------------------------------- |
| Promise\<[HuksHandle](#hukshandle)> | Promise used to return the key operation handle.|
A
annie_wangli 已提交
2510 2511


A
Annie_wang 已提交
2512
## huks.update<sup>(deprecated)</sup>
A
annie_wangli 已提交
2513

A
Annie_wang 已提交
2514 2515
update(handle: number, options: HuksOptions, callback: AsyncCallback\<HuksResult>) : void

A
Annie_wang 已提交
2516 2517 2518
Updates 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.

>  **NOTE**<br>This API is deprecated since API version 9. You are advised to use [huks.updateSession<sup>9+</sup>](#huksupdatesession9).
A
Annie_wang 已提交
2519 2520 2521 2522 2523 2524 2525 2526 2527

**System capability**: SystemCapability.Security.Huks

**Parameters**

| Name  | Type                                     | Mandatory| Description                                        |
| -------- | ----------------------------------------- | ---- | -------------------------------------------- |
| handle   | number                                    | Yes  | Handle of the **Update** operation.                        |
| options  | [HuksOptions](#huksoptions)               | Yes  | Parameters of the **Update** operation.                          |
A
Annie_wang 已提交
2528
| callback | AsyncCallback\<[HuksResult](#huksresult)> | Yes  | Callback invoked to return the result.|
A
Annie_wang 已提交
2529

A
Annie_wang 已提交
2530
## huks.update<sup>(deprecated)</sup>
A
Annie_wang 已提交
2531

A
Annie_wang 已提交
2532
update(handle: number, options: HuksOptions,  token: Uint8Array,  callback: AsyncCallback\<HuksResult>) : void
A
Annie_wang 已提交
2533

A
Annie_wang 已提交
2534
Updates 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.
A
Annie_wang 已提交
2535

A
Annie_wang 已提交
2536
>  **NOTE**<br>This API is deprecated since API version 9. You are advised to use [huks.updateSession<sup>9+</sup>](#huksupdatesession9-1).
A
Annie_wang 已提交
2537 2538

**System capability**: SystemCapability.Security.Huks
A
annie_wangli 已提交
2539

A
Annie_wang 已提交
2540 2541 2542 2543 2544
**Parameters**

| Name  | Type                                     | Mandatory| Description                                        |
| -------- | ----------------------------------------- | ---- | -------------------------------------------- |
| handle   | number                                    | Yes  | Handle of the **Update** operation.                        |
A
Annie_wang 已提交
2545
| token    | Uint8Array                                | No  | Token of the **Update** operation.                         |
A
Annie_wang 已提交
2546
| options  | [HuksOptions](#huksoptions)               | Yes  | Parameters of the **Update** operation.                      |
A
Annie_wang 已提交
2547
| callback | AsyncCallback\<[HuksResult](#huksresult)> | Yes  | Callback invoked to return the result.|
A
Annie_wang 已提交
2548

A
Annie_wang 已提交
2549
## huks.update<sup>(deprecated)</sup>
A
Annie_wang 已提交
2550 2551 2552

update(handle: number, options: HuksOptions, token?: Uint8Array) : Promise\<HuksResult>

A
Annie_wang 已提交
2553 2554 2555
Updates 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.

>  **NOTE**<br>This API is deprecated since API version 9. You are advised to use [huks.updateSession<sup>9+</sup>](#huksupdatesession9-2).
A
Annie_wang 已提交
2556 2557 2558 2559 2560 2561 2562 2563 2564

**System capability**: SystemCapability.Security.Huks

**Parameters**

| Name | Type                               | Mandatory| Description                                        |
| ------- | ----------------------------------- | ---- | -------------------------------------------- |
| handle  | number                              | Yes  | Handle of the **Update** operation.                        |
| token   | Uint8Array                          | No  | Token of the **Update** operation.                         |
A
Annie_wang 已提交
2565
| options | [HuksOptions](#huksoptions)         | Yes  | Parameters of the **Update** operation.                      |
A
annie_wangli 已提交
2566

A
Annie_wang 已提交
2567 2568 2569 2570 2571 2572 2573 2574
**Return value**

| Type                               | Description                                              |
| ----------------------------------- | -------------------------------------------------- |
| Promise\<[HuksResult](#huksresult)> | Promise used to return the result.|


## huks.finish<sup>(deprecated)</sup>
A
annie_wangli 已提交
2575 2576 2577

finish(handle: number, options: HuksOptions, callback: AsyncCallback\<HuksResult>) : void

A
Annie_wang 已提交
2578 2579 2580
Completes 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.

>  **NOTE**<br>This API is deprecated since API version 9. You are advised to use [huks.finishSession<sup>9+</sup>](#huksfinishsession9).
A
annie_wangli 已提交
2581 2582 2583 2584 2585 2586 2587

**System capability**: SystemCapability.Security.Huks

**Parameters**

| Name  | Type                  | Mandatory| Description                                 |
| -------- | ---------------------- | ---- | ------------------------------------- |
A
Annie_wang 已提交
2588 2589
| handle | number           | Yes  | Handle of the **Finish** operation.|
| options  | [HuksOptions](#huksoptions) | Yes  | Parameters of the **Finish** operation.|
A
Annie_wang 已提交
2590
| callback | AsyncCallback\<[HuksResult](#huksresult)> | Yes| Callback invoked to return the result.|
A
annie_wangli 已提交
2591 2592


A
Annie_wang 已提交
2593
## huks.finish<sup>(deprecated)</sup>
A
annie_wangli 已提交
2594 2595 2596

finish(handle: number, options: HuksOptions) : Promise\<HuksResult>

A
Annie_wang 已提交
2597 2598 2599
Completes 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.

>  **NOTE**<br>This API is deprecated since API version 9. You are advised to use [huks.finishSession<sup>9+</sup>](#huksfinishsession9-1).
A
annie_wangli 已提交
2600 2601 2602 2603 2604 2605 2606

**System capability**: SystemCapability.Security.Huks

**Parameters**

| Name  | Type                  | Mandatory| Description                                 |
| -------- | ---------------------- | ---- | ------------------------------------- |
A
Annie_wang 已提交
2607 2608
| handle | number           | Yes  | Handle of the **Finish** operation.|
| options  | [HuksOptions](#huksoptions) | Yes  | Parameters of the **Finish** operation.|
A
Annie_wang 已提交
2609

A
Annie_wang 已提交
2610
**Return value**
A
Annie_wang 已提交
2611

A
Annie_wang 已提交
2612 2613 2614
| Type                               | Description                                              |
| ----------------------------------- | -------------------------------------------------- |
| Promise\<[HuksResult](#huksresult)> | Promise used to return the result.|
A
annie_wangli 已提交
2615 2616


A
Annie_wang 已提交
2617
## huks.abort<sup>(deprecated)</sup>
A
annie_wangli 已提交
2618 2619 2620

abort(handle: number, options: HuksOptions, callback: AsyncCallback\<HuksResult>) : void

A
Annie_wang 已提交
2621
Aborts the use of the key. This API uses an asynchronous callback to return the result.
A
annie_wangli 已提交
2622

A
Annie_wang 已提交
2623 2624
>  **NOTE**<br>This API is deprecated since API version 9. You are advised to use [huks.abortSession<sup>9+</sup>](#huksabortsession9).

A
annie_wangli 已提交
2625 2626 2627 2628 2629 2630
**System capability**: SystemCapability.Security.Huks

**Parameters**

| Name  | Type                  | Mandatory| Description                                 |
| -------- | ---------------------- | ---- | ------------------------------------- |
A
Annie_wang 已提交
2631 2632
| handle | number           | Yes  | Handle of the **Abort** operation.|
| options  | [HuksOptions](#huksoptions) | Yes  | Parameters of the **Abort** operation.|
A
Annie_wang 已提交
2633
| callback | AsyncCallback\<[HuksResult](#huksresult)> | Yes| Callback invoked to return the result.|
A
annie_wangli 已提交
2634 2635 2636 2637

**Example**

```js
A
Annie_wang 已提交
2638 2639 2640 2641 2642
/* huks.init, huks.update, and huks.finish must be used together.
 * If an error occurs in any of them, huks.abort must be called to terminate the use of the key.
 *
 * The following uses the callback of an RSA 1024-bit key as an example.
 */
A
Annie_wang 已提交
2643 2644 2645
let keyalias = "HuksDemoRSA";
let properties = new Array();
let options = {
A
Annie_wang 已提交
2646 2647 2648
  properties: properties,
  inData: new Uint8Array(0)
};
A
Annie_wang 已提交
2649 2650
let handle;
let resultMessage = "";
A
Annie_wang 已提交
2651 2652 2653 2654 2655 2656 2657 2658 2659 2660 2661 2662 2663 2664 2665 2666 2667 2668 2669 2670 2671
async function generateKey() {
  properties[0] = {
    tag: huks.HuksTag.HUKS_TAG_ALGORITHM,
    value: huks.HuksKeyAlg.HUKS_ALG_RSA
  };
  properties[1] = {
    tag: huks.HuksTag.HUKS_TAG_KEY_SIZE,
    value: huks.HuksKeySize.HUKS_RSA_KEY_SIZE_1024
  };
  properties[2] = {
    tag: huks.HuksTag.HUKS_TAG_PURPOSE,
    value: huks.HuksKeyPurpose.HUKS_KEY_PURPOSE_ENCRYPT
  };
  properties[3] = {
    tag: huks.HuksTag.HUKS_TAG_PADDING,
    value: huks.HuksKeyPadding.HUKS_PADDING_OAEP
  };
  properties[4] = {
    tag: huks.HuksTag.HUKS_TAG_DIGEST,
    value: huks.HuksKeyDigest.HUKS_DIGEST_SHA256
  };
A
Annie_wang 已提交
2672
  huks.generateKey(keyalias, options);
A
Annie_wang 已提交
2673 2674
}
function stringToUint8Array(str) {
A
Annie_wang 已提交
2675 2676
  let arr = [];
  for (let i = 0, j = str.length; i < j; ++i) {
A
Annie_wang 已提交
2677 2678
    arr.push(str.charCodeAt(i));
  }
A
Annie_wang 已提交
2679
  let tmpUint8Array = new Uint8Array(arr);
A
Annie_wang 已提交
2680 2681 2682
  return tmpUint8Array;
}
async function huksInit() {
A
Annie_wang 已提交
2683
  await huks.init(keyalias, options).then((data) => {
A
Annie_wang 已提交
2684
    console.log(`test init data: ${JSON.stringify(data)}`);
A
Annie_wang 已提交
2685
    handle = data.handle;
A
Annie_wang 已提交
2686 2687 2688 2689 2690 2691 2692 2693 2694 2695 2696 2697 2698 2699 2700 2701 2702 2703 2704 2705 2706 2707 2708 2709 2710 2711 2712 2713 2714 2715 2716 2717 2718 2719 2720 2721
  }).catch((err) => {
    console.log("test init err information: " + JSON.stringify(err))
  })
}
async function huksUpdate() {
    options.inData = stringToUint8Array("huksHmacTest");
    await huks.update(handle, options).then((data) => {
      if (data.errorCode === 0) {
        resultMessage += "update success!";
      } else {
        resultMessage += "update fail!";
      }
    });
    console.log(resultMessage);
}
function huksFinish() {
  options.inData = stringToUint8Array("HuksDemoHMAC");
  huks.finish(handle, options).then((data) => {
    if (data.errorCode === 0) {
      resultMessage = "finish success!";
    } else {
      resultMessage = "finish fail errorCode: " + data.errorCode;
    }
  }).catch((err) => {
    resultMessage = "Failed to complete the key operation. catch errorMessage:" + JSON.stringify(err)
  });
  console.log(resultMessage);
}
async function huksAbort() {
  huks.abort(handle, options).then((data) => {
    if (data.errorCode === 0) {
      resultMessage = "abort success!";
    } else {
      resultMessage = "abort fail errorCode: " + data.errorCode;
    }
  }).catch((err) => {
A
Annie_wang 已提交
2722
    resultMessage = "Failed to abort the use of the key. catch errorMessage:" + JSON.stringify(err)
A
Annie_wang 已提交
2723 2724 2725
  });
  console.log(resultMessage);
}
A
annie_wangli 已提交
2726 2727
```

A
Annie_wang 已提交
2728
## huks.abort<sup>(deprecated)</sup>
A
annie_wangli 已提交
2729 2730 2731

abort(handle: number, options: HuksOptions) : Promise\<HuksResult>;

A
Annie_wang 已提交
2732
Aborts the use of the key. This API uses a promise to return the result.
A
annie_wangli 已提交
2733

A
Annie_wang 已提交
2734 2735
>  **NOTE**<br>This API is deprecated since API version 9. You are advised to use [huks.abortSession<sup>9+</sup>](#huksabortsession9-1).

A
annie_wangli 已提交
2736 2737 2738 2739 2740 2741
**System capability**: SystemCapability.Security.Huks

**Parameters**

| Name  | Type                  | Mandatory| Description                                 |
| -------- | ---------------------- | ---- | ------------------------------------- |
A
Annie_wang 已提交
2742 2743
| handle | number           | Yes  | Handle of the **Abort** operation.|
| options  | [HuksOptions](#huksoptions) | Yes  | Parameters of the **Abort** operation.|
A
Annie_wang 已提交
2744 2745 2746 2747 2748 2749

**Return value**

| Type                               | Description                                              |
| ----------------------------------- | -------------------------------------------------- |
| Promise\<[HuksResult](#huksresult)> | Promise used to return the result.|
A
annie_wangli 已提交
2750 2751 2752 2753

**Example**

```js
A
Annie_wang 已提交
2754 2755 2756 2757 2758
/* huks.init, huks.update, and huks.finish must be used together.
 * If an error occurs in any of them, huks.abort must be called to terminate the use of the key.
 *
 * The following uses the promise of an RSA 1024-bit key as an example.
 */
A
Annie_wang 已提交
2759 2760 2761
let keyalias = "HuksDemoRSA";
let properties = new Array();
let options = {
A
Annie_wang 已提交
2762 2763 2764
  properties: properties,
  inData: new Uint8Array(0)
};
A
Annie_wang 已提交
2765 2766
let handle;
let resultMessage = "";
A
Annie_wang 已提交
2767
function stringToUint8Array(str) {
A
Annie_wang 已提交
2768 2769
  let arr = [];
  for (let i = 0, j = str.length; i < j; ++i) {
A
Annie_wang 已提交
2770 2771
    arr.push(str.charCodeAt(i));
  }
A
Annie_wang 已提交
2772
  let tmpUint8Array = new Uint8Array(arr);
A
Annie_wang 已提交
2773 2774 2775 2776 2777 2778 2779 2780 2781 2782 2783 2784 2785 2786 2787 2788 2789 2790 2791 2792 2793 2794 2795 2796
  return tmpUint8Array;
}

async function generateKey() {
  properties[0] = {
    tag: huks.HuksTag.HUKS_TAG_ALGORITHM,
    value: huks.HuksKeyAlg.HUKS_ALG_RSA
  };
  properties[1] = {
    tag: huks.HuksTag.HUKS_TAG_KEY_SIZE,
    value: huks.HuksKeySize.HUKS_RSA_KEY_SIZE_1024
  };
  properties[2] = {
    tag: huks.HuksTag.HUKS_TAG_PURPOSE,
    value: huks.HuksKeyPurpose.HUKS_KEY_PURPOSE_ENCRYPT
  };
  properties[3] = {
    tag: huks.HuksTag.HUKS_TAG_PADDING,
    value: huks.HuksKeyPadding.HUKS_PADDING_OAEP
  };
  properties[4] = {
    tag: huks.HuksTag.HUKS_TAG_DIGEST,
    value: huks.HuksKeyDigest.HUKS_DIGEST_SHA256
  };
A
Annie_wang 已提交
2797
  huks.generateKey(keyalias, options, function (err, data) { });
A
Annie_wang 已提交
2798 2799 2800
}
async function huksInit() {
  return new Promise((resolve, reject) => {
A
Annie_wang 已提交
2801
    huks.init(keyalias, options, async function (err, data) {
A
Annie_wang 已提交
2802
      if (data.errorCode === 0) {
A
Annie_wang 已提交
2803
        resultMessage = "init success!"
A
Annie_wang 已提交
2804
        handle = data.handle;
A
Annie_wang 已提交
2805 2806 2807 2808 2809 2810 2811 2812 2813 2814 2815 2816 2817 2818 2819 2820 2821 2822 2823
      } else {
        resultMessage = "init fail errorCode: " + data.errorCode
      }
    });
  });
}

async function huksUpdate() {
    options.inData = stringToUint8Array("huksHmacTest");
    new Promise((resolve, reject) => {
      huks.update(handle, options, function (err, data) {
        if (data.errorCode === 0) {
          resultMessage += "update success!";
        } else {
          resultMessage += "update fail!";
        }
      });
    });
    console.log(resultMessage);
A
Annie_wang 已提交
2824

A
Annie_wang 已提交
2825 2826 2827 2828 2829 2830 2831 2832 2833 2834 2835 2836 2837 2838 2839 2840 2841 2842 2843 2844 2845 2846 2847
}

async function huksFinish() {
  options.inData = stringToUint8Array("0");
  new Promise((resolve, reject) => {
    huks.finish(handle, options, function (err, data) {
      if (data.errorCode === 0) {
        resultMessage = "finish success!";
      } else {
        resultMessage =  "finish fail errorCode: " + data.errorCode;
      }
    });
  });
}

function huksAbort() {
  new Promise((resolve, reject) => {
    huks.abort(handle, options, function (err, data) {
      console.log(`Huks_Demo hmac huksAbort1 data ${JSON.stringify(data)}`);
      console.log(`Huks_Demo hmac huksAbort1 err ${JSON.stringify(err)}`);
    });
  });
}
A
annie_wangli 已提交
2848 2849 2850
```


A
Annie_wang 已提交
2851
## HuksHandle<sup>(deprecated)</sup>
A
annie_wangli 已提交
2852 2853 2854 2855 2856

Defines the HUKS handle structure.

**System capability**: SystemCapability.Security.Huks

A
Annie_wang 已提交
2857
| Name    | Type            | Mandatory| Description    |
A
annie_wangli 已提交
2858
| ---------- | ---------------- | ---- | -------- |
A
Annie_wang 已提交
2859 2860
| errorCode  | number           | Yes  | Error code.|
| handle    | number       | Yes| Value of the handle.|
A
Annie_wang 已提交
2861
| token | Uint8Array | No| Challenge obtained after the [init](#huksinit) operation.|
A
annie_wangli 已提交
2862 2863


A
Annie_wang 已提交
2864
## HuksResult<sup>(deprecated)</sup>
A
annie_wangli 已提交
2865 2866 2867 2868 2869 2870 2871

Defines the **HuksResult** structure.

**System capability**: SystemCapability.Security.Huks



A
Annie_wang 已提交
2872 2873 2874 2875 2876 2877
| Name    | Type                           | Mandatory| Description            |
| ---------- | ------------------------------- | ---- | ---------------- |
| errorCode  | number                          | Yes  | Error code.    |
| outData    | Uint8Array                      | No  | Output data.  |
| properties | Array\<[HuksParam](#huksparam)> | No  | Property information.  |
| certChains | Array\<string>                  | No  | Certificate chain information.|
A
Annie_wang 已提交
2878 2879 2880 2881 2882 2883 2884 2885 2886 2887 2888 2889 2890 2891 2892 2893 2894 2895 2896 2897 2898 2899 2900 2901 2902 2903 2904 2905 2906 2907 2908 2909 2910 2911 2912 2913 2914 2915 2916 2917 2918 2919 2920 2921 2922 2923 2924 2925 2926 2927 2928 2929 2930 2931 2932 2933 2934 2935 2936 2937 2938 2939 2940 2941 2942 2943 2944 2945 2946 2947 2948 2949 2950 2951 2952 2953 2954 2955 2956 2957 2958 2959 2960 2961


## HuksErrorCode<sup>(deprecated)</sup>

Enumerates the error codes.

**System capability**: SystemCapability.Security.Huks

| Name                      | Value   | Description|
| -------------------------- | ----- | ---- |
| HUKS_SUCCESS | 0     |Success.|
| HUKS_FAILURE | -1    |Failure.|
| HUKS_ERROR_BAD_STATE | -2    |Incorrect state.|
| HUKS_ERROR_INVALID_ARGUMENT | -3    |Invalid argument.|
| HUKS_ERROR_NOT_SUPPORTED | -4    |Not supported.|
| HUKS_ERROR_NO_PERMISSION | -5    |No permission.|
| HUKS_ERROR_INSUFFICIENT_DATA | -6    |Insufficient data.|
| HUKS_ERROR_BUFFER_TOO_SMALL | -7    |Insufficient buffer.|
| HUKS_ERROR_INSUFFICIENT_MEMORY | -8    |Insufficient memory.|
| HUKS_ERROR_COMMUNICATION_FAILURE | -9    |Communication failure.|
| HUKS_ERROR_STORAGE_FAILURE | -10   |Insufficient storage space.|
| HUKS_ERROR_HARDWARE_FAILURE | -11   |Hardware fault.|
| HUKS_ERROR_ALREADY_EXISTS | -12   |The object already exists.|
| HUKS_ERROR_NOT_EXIST | -13   |The object does not exist.|
| HUKS_ERROR_NULL_POINTER | -14   |Null pointer.|
| HUKS_ERROR_FILE_SIZE_FAIL | -15   |Incorrect file size.|
| HUKS_ERROR_READ_FILE_FAIL | -16   |Failed to read the file.|
| HUKS_ERROR_INVALID_PUBLIC_KEY | -17   |Invalid public key.|
| HUKS_ERROR_INVALID_PRIVATE_KEY | -18   |Invalid private key.|
| HUKS_ERROR_INVALID_KEY_INFO | -19   |Invalid key information.|
| HUKS_ERROR_HASH_NOT_EQUAL | -20   |The hash values are not equal.|
| HUKS_ERROR_MALLOC_FAIL | -21   |MALLOC failed.|
| HUKS_ERROR_WRITE_FILE_FAIL | -22   |Failed to write the file.|
| HUKS_ERROR_REMOVE_FILE_FAIL | -23   |Failed to delete the file.|
| HUKS_ERROR_OPEN_FILE_FAIL | -24   |Failed to open the file.|
| HUKS_ERROR_CLOSE_FILE_FAIL | -25   |Failed to close the file.|
| HUKS_ERROR_MAKE_DIR_FAIL | -26   |Failed to create the directory.|
| HUKS_ERROR_INVALID_KEY_FILE | -27   |Invalid key file.|
| HUKS_ERROR_IPC_MSG_FAIL | -28   |Incorrect IPC information.|
| HUKS_ERROR_REQUEST_OVERFLOWS | -29   |Request overflows.|
| HUKS_ERROR_PARAM_NOT_EXIST | -30   |The parameter does not exist.|
| HUKS_ERROR_CRYPTO_ENGINE_ERROR | -31   |CRYPTO ENGINE error.|
| HUKS_ERROR_COMMUNICATION_TIMEOUT | -32   |Communication timed out.|
| HUKS_ERROR_IPC_INIT_FAIL | -33   |IPC initialization failed.|
| HUKS_ERROR_IPC_DLOPEN_FAIL | -34   |IPC DLOPEN failed.|
| HUKS_ERROR_EFUSE_READ_FAIL | -35   |Failed to read eFUSE.|
| HUKS_ERROR_NEW_ROOT_KEY_MATERIAL_EXIST | -36   |New root key material exists.|
| HUKS_ERROR_UPDATE_ROOT_KEY_MATERIAL_FAIL | -37   |Failed to update the root key material.|
| HUKS_ERROR_VERIFICATION_FAILED | -38   |Failed to verify the certificate chain.|
| HUKS_ERROR_GET_USERIAM_SECINFO_FAILED<sup>9+</sup> | -40 |Failed to obtain the security attribute information of the user.|
| HUKS_ERROR_GET_USERIAM_AUTHINFO_FAILED<sup>9+</sup> | -41 |Failed to obtain the authentication information of the user.|
| HUKS_ERROR_USER_AUTH_TYPE_NOT_SUPPORT<sup>9+</sup> | -42 |The access control of the current authentication type is not supported.|
| HUKS_ERROR_KEY_AUTH_FAILED<sup>9+</sup> | -43 |The access control authentication has failed.|
| HUKS_ERROR_DEVICE_NO_CREDENTIAL<sup>9+</sup> | -44 |No credential has been enrolled for the device.|
| HUKS_ERROR_CHECK_GET_ALG_FAIL | -100  |Failed to obtain the ALG. |
| HUKS_ERROR_CHECK_GET_KEY_SIZE_FAIL | -101  |Failed to obtain the key size.|
| HUKS_ERROR_CHECK_GET_PADDING_FAIL | -102  |Failed to obtain the padding algorithm.|
| HUKS_ERROR_CHECK_GET_PURPOSE_FAIL | -103  |Failed to obtain the key purpose.|
| HUKS_ERROR_CHECK_GET_DIGEST_FAIL | -104  |Failed to obtain the digest algorithm.|
| HUKS_ERROR_CHECK_GET_MODE_FAIL | -105  |Failed to obtain the cipher mode.|
| HUKS_ERROR_CHECK_GET_NONCE_FAIL | -106  |Failed to obtain the nonce.|
| HUKS_ERROR_CHECK_GET_AAD_FAIL | -107  |Failed to obtain the AAD.|
| HUKS_ERROR_CHECK_GET_IV_FAIL | -108  |Failed to obtain the initialization vector (IV).|
| HUKS_ERROR_CHECK_GET_AE_TAG_FAIL | -109  |Failed to obtain the AE flag.|
| HUKS_ERROR_CHECK_GET_SALT_FAIL | -110  |Failed to obtain the salt value.|
| HUKS_ERROR_CHECK_GET_ITERATION_FAIL | -111  |Failed to obtain the number of iterations.|
| HUKS_ERROR_INVALID_ALGORITHM | -112  |Invalid algorithm.|
| HUKS_ERROR_INVALID_KEY_SIZE | -113  |Invalid key size.|
| HUKS_ERROR_INVALID_PADDING | -114  |Invalid padding algorithm.|
| HUKS_ERROR_INVALID_PURPOSE | -115  |Invalid key purpose.|
| HUKS_ERROR_INVALID_MODE | -116  |Invalid cipher mode.|
| HUKS_ERROR_INVALID_DIGEST | -117  |Invalid digest algorithm.|
| HUKS_ERROR_INVALID_SIGNATURE_SIZE | -118  |Invalid signature size.|
| HUKS_ERROR_INVALID_IV | -119  |Invalid IV.|
| HUKS_ERROR_INVALID_AAD | -120  |Invalid AAD.|
| HUKS_ERROR_INVALID_NONCE | -121  |Invalid nonce.|
| HUKS_ERROR_INVALID_AE_TAG | -122  |Invalid AE tag.|
| HUKS_ERROR_INVALID_SALT | -123  |Invalid salt value.|
| HUKS_ERROR_INVALID_ITERATION | -124  |Invalid iteration count.|
| HUKS_ERROR_INVALID_OPERATION | -125  |Invalid operation.|
| HUKS_ERROR_INVALID_WRAPPED_FORMAT<sup>9+</sup> | -126 |Incorrect format of the wrapped key being imported.|
| HUKS_ERROR_INVALID_USAGE_OF_KEY<sup>9+</sup> | -127 |Incorrect purpose of the wrapped key being imported.|
| HUKS_ERROR_INTERNAL_ERROR | -999  |Internal error.|
| HUKS_ERROR_UNKNOWN_ERROR | -1000 |Unknown error.|