js-apis-huks.md 126.7 KB
Newer Older
A
Annie_wang 已提交
1
# @ohos.security.huks (HUKS)
A
annie_wangli 已提交
2

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
> **NOTE**
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
| Name   | Type      | Mandatory| Description                                                |
| --------- | ---------- | ---- | ---------------------------------------------------- |
| handle    | number     | Yes  | Value of the handle.                                      |
A
Annie_wang 已提交
47
| challenge | Uint8Array | No  | Challenge obtained after the [initSession](#huksinitsession9) 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
| Name  | Type                       | Mandatory| Description                                         |
| -------- | --------------------------- | ---- | --------------------------------------------- |
| keyAlias | string                      | Yes  | Alias of the key.                                        |
A
Annie_wang 已提交
77
| options  | [HuksOptions](#huksoptions) | Yes  | Tags required for generating the key. The algorithm, key purpose, and key length are mandatory.|
A
Annie_wang 已提交
78
| callback | AsyncCallback\<void>        | Yes  | Callback invoked to return the result. If no error is captured, the key is successfully generated. In this case, the API does not return the key content because the key is always protected in a TEE. If an error is captured, an exception occurs in the generation process.|
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. Because the key is always protected in an trusted environment (such as a TEE), the promise does not return the key content. It returns only the information indicating whether the API is successfully called.
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
| Name  | Type                       | Mandatory| Description                    |
| -------- | --------------------------- | ---- | ------------------------ |
| keyAlias | string                      | Yes  | Alias of the key.              |
A
Annie_wang 已提交
133
| options  | [HuksOptions](#huksoptions) | Yes  | Tags required for generating the key. The algorithm, key purpose, and key length are mandatory.|
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 invoked to return the result. If the operation is successful, no **err** value is returned; otherwise, an error code is returned.|
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
| Name  | Type                       | Mandatory| Description                                         |
| -------- | --------------------------- | ---- | --------------------------------------------- |
| keyAlias | string                      | Yes  | Alias of the key.                                   |
A
Annie_wang 已提交
291
| options  | [HuksOptions](#huksoptions) | Yes  | Tags required for the import and key to import. The algorithm, key purpose, and key length are mandatory.|
A
Annie_wang 已提交
292
| callback | AsyncCallback\<void>        | Yes  | Callback invoked to return the result. If the operation is successful, no **err** value is returned; otherwise, an error code is returned.|
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
| Name  | Type                       | Mandatory| Description                               |
| -------- | --------------------------- | ---- | ----------------------------------- |
| keyAlias | string                      | Yes  | Alias of the key.                         |
A
Annie_wang 已提交
359
| options  | [HuksOptions](#huksoptions) | Yes  | Tags required for the import and key to import. The algorithm, key purpose, and key length are mandatory.|
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
| 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_wang 已提交
429
| callback | AsyncCallback<[HuksReturnResult](#huksreturnresult9)> | Yes  | Callback invoked to return the result. If the operation is successful, no **err** value is returned; otherwise, an error code is returned.|
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](#huksreturnresult9)> | 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
| 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.   |
A
Annie_wang 已提交
678
| options          | [HuksOptions](#huksoptions) | Yes  | Tags required for the import and the wrapped key to import. The algorithm, key purpose, and key length are mandatory.|
A
Annie_wang 已提交
679
| callback         | AsyncCallback\<void>        | Yes  | Callback invoked to return the result. If the operation is successful, no **err** value is returned; otherwise, an error code is returned.|
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
| 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.   |
A
Annie_wang 已提交
894
| options          | [HuksOptions](#huksoptions) | Yes  | Tags required for the import and the wrapped key to import. The algorithm, key purpose, and key length are mandatory.|
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](#huksreturnresult9)> | Yes  | Callback invoked to return the result. If the operation is successful, no **err** value is returned; otherwise, an error code is returned. **outData** contains the public key exported.|
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](#huksreturnresult9)> | Promise used to return the result. If the operation is successful, no **err** value is returned and **outData** contains the public key exported. If the operation fails, an error code is returned. |
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](#huksreturnresult9)> | Yes  | Callback invoked to return the result. If the operation is successful, no **err** value is returned and **properties** contains the parameters required for generating the key. If the operation fails, an error code is returned. |
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](#huksreturnresult9)> | Promise used to return the result. If the operation is successful, no **err** value is returned and **properties** contains the parameters required for generating the key. If the operation fails, an error code is returned. |
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. If the key exists, **data** is **true**. If the key does not exist, **error** is the error code.|
A
Annie_wang 已提交
1088 1089 1090 1091 1092 1093 1094 1095 1096

**Example**

```js
/* Set options to emptyOptions. */
let keyAlias = 'keyAlias';
let emptyOptions = {
    properties: []
};
A
Annie_wang 已提交
1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109
huks.isKeyItemExist(keyAlias, emptyOptions, function (error, data) {
    if (data) {
      promptAction.showToast({
        message: "keyAlias: " + keyAlias +"is existed! ",
        duration: 2500,
      })
    } else {
      promptAction.showToast({
        message: "find key failed, error code: " + error.code + " error msg: " + error.message,
        duration: 2500,
      })
    }
});
A
Annie_wang 已提交
1110 1111
```

A
Annie_wang 已提交
1112
## huks.isKeyItemExist<sup>9+</sup>
A
Annie_wang 已提交
1113

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

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

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

**Parameters**

A
Annie_wang 已提交
1122 1123 1124 1125
| 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 已提交
1126 1127 1128

**Return value**

A
Annie_wang 已提交
1129 1130
| Type             | Description                                   |
| ----------------- | --------------------------------------- |
A
Annie_wang 已提交
1131
| Promise\<boolean> | Promise used to return the result. If the key exists, then() performs subsequent operations. If the key does not exist, error() performs the related service operations.|
A
Annie_wang 已提交
1132 1133 1134 1135

**Example**

```js
A
Annie_wang 已提交
1136 1137 1138 1139 1140
/* Set options to emptyOptions. */
let keyAlias = 'keyAlias';
let emptyOptions = {
    properties: []
};
A
Annie_wang 已提交
1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151
await huks.isKeyItemExist(keyAlias, emptyOptions).then((data) => {
    promptAction.showToast({
      message: "keyAlias: " + keyAlias +"is existed! ",
      duration: 500,
    })
  }).catch((err)=>{
    promptAction.showToast({
      message: "find key failed, error code: " + err.code + " error message: " + err.message,
      duration: 6500,
    })
  })
A
Annie_wang 已提交
1152
```
A
Annie_wang 已提交
1153

A
Annie_wang 已提交
1154
## huks.initSession<sup>9+</sup>
A
Annie_wang 已提交
1155

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

A
Annie_wang 已提交
1158
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 已提交
1159

A
Annie_wang 已提交
1160
**System capability**: SystemCapability.Security.Huks
A
Annie_wang 已提交
1161

A
Annie_wang 已提交
1162
**Parameters**
A
Annie_wang 已提交
1163

A
Annie_wang 已提交
1164 1165
| Name  | Type                                                   | Mandatory| Description                                                |
| -------- | ------------------------------------------------------- | ---- | ---------------------------------------------------- |
A
Annie_wang 已提交
1166 1167 1168
| keyAlias | string                                                  | Yes  | Alias of the key involved in the **initSession** operation.                                |
| options  | [HuksOptions](#huksoptions)                             | Yes  | Parameter set used for the **initSession** operation.                                |
| callback | AsyncCallback\<[HuksSessionHandle](#hukssessionhandle9)> | Yes  | Callback invoked to return a session handle for subsequent operations.|
A
Annie_wang 已提交
1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181

## 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                                            |
| -------- | ------------------------------------------------- | ---- | ------------------------------------------------ |
A
Annie_wang 已提交
1182 1183
| keyAlias | string                                            | Yes  | Alias of the key involved in the **initSession** operation.                            |
| options  | [HuksOptions](#huksoptions)                       | Yes  | Parameter set used for the **initSession** operation.                                  |
A
Annie_wang 已提交
1184 1185 1186 1187 1188

**Return value**

| Type                               | Description                                              |
| ----------------------------------- | -------------------------------------------------- |
A
Annie_wang 已提交
1189
| Promise\<[HuksSessionHandle](#hukssessionhandle9)> | Promise used to return a session handle for subsequent operations.|
A
Annie_wang 已提交
1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202

## 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                                        |
| -------- | ---------------------------------------------------- | ---- | -------------------------------------------- |
A
Annie_wang 已提交
1203 1204 1205
| handle   | number                                               | Yes  | Handle for the **updateSession** operation.                        |
| options  | [HuksOptions](#huksoptions)                          | Yes  | Parameter set used for the **updateSession** operation.                          |
| callback | AsyncCallback<[HuksReturnResult](#huksreturnresult9)> | Yes  | Callback invoked to return the **updateSession** operation result.|
A
Annie_wang 已提交
1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219


## 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                                        |
| -------- | ---------------------------------------------------- | ---- | -------------------------------------------- |
A
Annie_wang 已提交
1220 1221 1222 1223
| handle   | number                                               | Yes  | Handle for the **updateSession** operation.                        |
| options  | [HuksOptions](#huksoptions)                          | Yes  | Parameter set used for the **updateSession** operation.                      |
| token    | Uint8Array                                           | Yes  | Token of the **updateSession** operation.                         |
| callback | AsyncCallback<[HuksReturnResult](#huksreturnresult9)> | Yes  | Callback invoked to return the **updateSession** operation result.|
A
Annie_wang 已提交
1224 1225 1226 1227 1228

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

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

A
Annie_wang 已提交
1229
Updates the key operation by segment. This API uses a promise to return the result. **huks.initSession**, **huks.updateSession**, and **huks.finishSession** must be used together.
A
Annie_wang 已提交
1230 1231 1232 1233 1234 1235 1236

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

**Parameters**

| Name | Type                                          | Mandatory| Description                                        |
| ------- | ---------------------------------------------- | ---- | -------------------------------------------- |
A
Annie_wang 已提交
1237 1238 1239
| handle  | number                                         | Yes  | Handle for the **updateSession** operation.                        |
| options | [HuksOptions](#huksoptions)                    | Yes  | Parameter set used for the **updateSession** operation.                      |
| token   | Uint8Array                                     | No  | Token of the **updateSession** operation.                         |
A
Annie_wang 已提交
1240 1241 1242 1243 1244

**Return value**

| Type                               | Description                                              |
| ----------------------------------- | -------------------------------------------------- |
A
Annie_wang 已提交
1245
| Promise<[HuksReturnResult](#huksreturnresult9)> | Promise used to return the **updateSession** operation result.|
A
Annie_wang 已提交
1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258

## 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                                        |
| -------- | ---------------------------------------------------- | ---- | -------------------------------------------- |
A
Annie_wang 已提交
1259 1260 1261
| handle   | number                                               | Yes  | Handle for the **finishSession** operation.                        |
| options  | [HuksOptions](#huksoptions)                          | Yes  | Parameter set used for the **finishSession** operation.                          |
| token    | Uint8Array                                           | Yes  | Token of the **finishSession** operation.                         |
A
Annie_wang 已提交
1262
| callback | AsyncCallback<[HuksReturnResult](#huksreturnresult9)> | Yes  | Callback invoked to return the **finishSession** operation result.|
A
Annie_wang 已提交
1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275

## 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                                        |
| -------- | ----------------------------------------------------- | ---- | -------------------------------------------- |
A
Annie_wang 已提交
1276 1277 1278
| handle   | number                                                | Yes  | Handle for the **finishSession** operation.                        |
| options  | [HuksOptions](#huksoptions)                           | Yes  | Parameter set used for the **finishSession** operation.                          |
| token    | Uint8Array                                            | Yes  | Token of the **finishSession** operation.                         |
A
Annie_wang 已提交
1279
| callback | AsyncCallback\<[HuksReturnResult](#huksreturnresult9)> | Yes  | Callback invoked to return the **finishSession** operation result.|
A
Annie_wang 已提交
1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292

## 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                               |
| ------- | ----------------------------------------------- | ---- | ----------------------------------- |
A
Annie_wang 已提交
1293 1294 1295
| handle  | number                                          | Yes  | Handle for the **finishSession** operation.               |
| options | [HuksOptions](#huksoptions)                     | Yes  | Parameter set used for the **finishSession** operation.             |
| token   | Uint8Array                                      | No  | Token of the **finishSession** operation.                |
A
Annie_wang 已提交
1296 1297 1298 1299 1300

**Return value**

| Type                               | Description                                              |
| ----------------------------------- | -------------------------------------------------- |
A
Annie_wang 已提交
1301
| Promise\<[HuksReturnResult](#huksreturnresult9)> | Promise used to return the result.|
A
Annie_wang 已提交
1302 1303 1304 1305 1306

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

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

A
Annie_wang 已提交
1307
Aborts a key operation. This API uses an asynchronous callback to return the result.
A
Annie_wang 已提交
1308 1309 1310 1311 1312

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

**Parameters**

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

**Example**

```js
A
Annie_wang 已提交
1322 1323
/* huks.initSession, huks.updateSession, and huks.finishSession must be used together.
 * If an error occurs in any of huks.initSession, huks.updateSession,
A
Annie_wang 已提交
1324
 * and huks.finishSession operations,
A
Annie_wang 已提交
1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335
 * 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 已提交
1336 1337
}

A
Annie_wang 已提交
1338 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
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 已提交
1382 1383
}

A
Annie_wang 已提交
1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397
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 已提交
1398 1399
}

A
Annie_wang 已提交
1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413
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 已提交
1414 1415
}

A
Annie_wang 已提交
1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429
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 已提交
1430 1431
}

A
Annie_wang 已提交
1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444
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 已提交
1445
}
A
Annie_wang 已提交
1446
```
A
Annie_wang 已提交
1447

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

A
Annie_wang 已提交
1450 1451
abortSession(handle: number, options: HuksOptions) : Promise\<void>;

A
Annie_wang 已提交
1452
Aborts a key operation. This API uses a promise to return the result.
A
Annie_wang 已提交
1453 1454 1455 1456 1457 1458 1459

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

**Parameters**

| Name | Type                       | Mandatory| Description                                       |
| ------- | --------------------------- | ---- | ------------------------------------------- |
A
Annie_wang 已提交
1460 1461
| handle  | number                      | Yes  | Handle for the **abortSession** operation.                        |
| options | [HuksOptions](#huksoptions) | Yes  | Parameter set used for the **abortSession** operation.                      |
A
Annie_wang 已提交
1462 1463 1464 1465 1466

**Return value**

| Type                               | Description                                              |
| ----------------------------------- | -------------------------------------------------- |
A
Annie_wang 已提交
1467
| Promise\<void>             | Promise used to return the **abortSession** operation result.|
A
Annie_wang 已提交
1468 1469 1470 1471 1472 1473

**Example**

```js
/* huks.initSession, huks.updateSession, and huks.finishSession must be used together.
 * If an error occurs in any of huks.initSession, huks.updateSession,
A
Annie_wang 已提交
1474
 * and huks.finishSession operations,
A
Annie_wang 已提交
1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485
 * 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 已提交
1486 1487
}

A
Annie_wang 已提交
1488 1489 1490 1491 1492
let keyAlias = "HuksDemoRSA";
let properties = new Array();
let options = {
    properties: properties,
    inData: new Uint8Array(0)
A
Annie_wang 已提交
1493
};
A
Annie_wang 已提交
1494 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
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 已提交
1520

A
Annie_wang 已提交
1521 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
    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 {
A
Annie_wang 已提交
1585
        await huks.abortSession(handle, options)
A
Annie_wang 已提交
1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606
            .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

A
Annie_wang 已提交
1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626
| Name                                          | Value|  Description                       |
| ---------------------------------------------- | -------- |--------------------------- |
| HUKS_ERR_CODE_PERMISSION_FAIL                  | 201      | Permission verification failed.         |
| HUKS_ERR_CODE_ILLEGAL_ARGUMENT                 | 401      | Invalid parameters are detected.         |
| HUKS_ERR_CODE_NOT_SUPPORTED_API                | 801      | The API is not supported.              |
| HUKS_ERR_CODE_FEATURE_NOT_SUPPORTED            | 12000001 | The feature is not supported.        |
| HUKS_ERR_CODE_MISSING_CRYPTO_ALG_ARGUMENT      | 12000002 | Key algorithm parameters are missing.         |
| HUKS_ERR_CODE_INVALID_CRYPTO_ALG_ARGUMENT      | 12000003 | Invalid key algorithm parameters are detected.         |
| HUKS_ERR_CODE_FILE_OPERATION_FAIL              | 12000004 | The file operation failed.             |
| HUKS_ERR_CODE_COMMUNICATION_FAIL               | 12000005 | The communication failed.                 |
| HUKS_ERR_CODE_CRYPTO_FAIL                      | 12000006 | Failed to operate the algorithm library.           |
| HUKS_ERR_CODE_KEY_AUTH_PERMANENTLY_INVALIDATED | 12000007 | Failed to access the key because the key has expired.|
| HUKS_ERR_CODE_KEY_AUTH_VERIFY_FAILED           | 12000008 | Failed to access the key because the authentication has failed.|
| HUKS_ERR_CODE_KEY_AUTH_TIME_OUT                | 12000009 | Key access timed out.|
| HUKS_ERR_CODE_SESSION_LIMIT                    | 12000010 | The number of key operation sessions has reached the limit.   |
| HUKS_ERR_CODE_ITEM_NOT_EXIST                   | 12000011 | The target object does not exist.           |
| HUKS_ERR_CODE_EXTERNAL_ERROR                   | 12000012 | An external error occurs.                 |
| HUKS_ERR_CODE_CREDENTIAL_NOT_EXIST             | 12000013 | The credential does not exist.             |
| HUKS_ERR_CODE_INSUFFICIENT_MEMORY              | 12000014 | The memory is insufficient.                 |
| HUKS_ERR_CODE_CALL_SERVICE_FAILED              | 12000015 | Failed to call other system services.     |
A
Annie_wang 已提交
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

## 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       |
A
Annie_wang 已提交
1712
| HUKS_AES_KEY_SIZE_192              | 192  | AES key of 192 bits       |
A
Annie_wang 已提交
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
| 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>

A
Annie_wang 已提交
1794
Enumerates the algorithm suites used for importing an encrypted key.
A
Annie_wang 已提交
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

**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                     |
| ------------------------------- | ---- | ------------------------- |
A
Annie_wang 已提交
1823 1824 1825
| HUKS_USER_AUTH_TYPE_FINGERPRINT | 1 << 0 | Fingerprint authentication. |
| HUKS_USER_AUTH_TYPE_FACE        | 1 << 1 | Facial authentication.|
| HUKS_USER_AUTH_TYPE_PIN         | 1 << 2  | PIN authentication.|
A
Annie_wang 已提交
1826 1827 1828 1829 1830 1831 1832 1833 1834

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

Enumerates the access control types.

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

| Name                                   | Value  | Description                                            |
| --------------------------------------- | ---- | ------------------------------------------------ |
A
Annie_wang 已提交
1835 1836
| HUKS_AUTH_ACCESS_INVALID_CLEAR_PASSWORD | 1 << 0 | The key becomes invalid after the password is cleared.      |
| HUKS_AUTH_ACCESS_INVALID_NEW_BIO_ENROLL | 1 << 1 | The key becomes invalid after a new biometric feature is added.|
A
Annie_wang 已提交
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

## 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

A
Annie_wang 已提交
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
| Name                                        | Value                                      | Description                                  |
| -------------------------------------------- | ---------------------------------------- | -------------------------------------- |
| HUKS_TAG_INVALID                             | HuksTagType.HUKS_TAG_TYPE_INVALID \| 0   | Invalid tag.                       |
| HUKS_TAG_ALGORITHM                           | HuksTagType.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<sup>(deprecated)</sup>                 | HuksTagType.HUKS_TAG_TYPE_ULONG \| 201   | Parameter originally reserved for certificate management. It is deprecated because certificate management is no longer implemented in this module.                                |
| HUKS_TAG_ORIGINATION_EXPIRE_DATETIME<sup>(deprecated)</sup>         | HuksTagType.HUKS_TAG_TYPE_ULONG \| 202   | Parameter originally reserved for certificate management. It is deprecated because certificate management is no longer implemented in this module.                                |
| HUKS_TAG_USAGE_EXPIRE_DATETIME<sup>(deprecated)</sup>               | HuksTagType.HUKS_TAG_TYPE_ULONG \| 203   | Parameter originally reserved for certificate management. It is deprecated because certificate management is no longer implemented in this module.                                |
| HUKS_TAG_CREATION_DATETIME<sup>(deprecated)</sup>       | HuksTagType.HUKS_TAG_TYPE_ULONG \| 204   | Parameter originally reserved for certificate management. It is deprecated because certificate management is no longer implemented in this module.                        |
| HUKS_TAG_ALL_USERS                           | HuksTagType.HUKS_TAG_TYPE_BOOL \| 301      | Reserved.                                |
| HUKS_TAG_USER_ID                             | HuksTagType.HUKS_TAG_TYPE_UINT \| 302    | ID of the user to which the key belongs.                                |
| 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    | Timeout period of an authentication token.                                |
| HUKS_TAG_AUTH_TOKEN                          | HuksTagType.HUKS_TAG_TYPE_BYTES \| 306   | Used to pass in the authentication token.                                |
| 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 | Used to pass in the AEAD in GCM mode.                                |
| 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.                                |
A
Annie_wang 已提交
1978 1979 1980 1981 1982 1983 1984

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

A
Annie_wang 已提交
1985
> **NOTE**<br>This API is deprecated since API version 9. You are advised to use [huks.generateKeyItem<sup>9+</sup>](#huksgeneratekeyitem9).
A
Annie_wang 已提交
1986 1987 1988 1989 1990 1991 1992 1993 1994

**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 已提交
1995
| callback | AsyncCallback\<[HuksResult](#huksresultdeprecated)> | Yes  | Callback invoked to return the result. If the operation is successful, **HUKS_SUCCESS** is returned; otherwise, an error code defined in **HuksResult** is returned.|
A
Annie_wang 已提交
1996 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

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

A
Annie_wang 已提交
2037
> **NOTE**<br>This API is deprecated since API version 9. You are advised to use [huks.generateKeyItem<sup>9+</sup>](#huksgeneratekeyitem9-1).
A
Annie_wang 已提交
2038 2039 2040 2041 2042 2043 2044 2045 2046 2047 2048 2049 2050 2051

**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 已提交
2052
| Promise\<[HuksResult](#huksresultdeprecated)> | Promise used to return the result. If the operation is successful, **HUKS_SUCCESS** is returned; otherwise, an error code is returned.|
A
Annie_wang 已提交
2053 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

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

A
Annie_wang 已提交
2090
> **NOTE**<br>This API is deprecated since API version 9. You are advised to use [huks.deleteKeyItem<sup>9+</sup>](#huksdeletekeyitem9).
A
Annie_wang 已提交
2091 2092 2093 2094 2095 2096 2097 2098 2099

**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 已提交
2100
| callback | AsyncCallback\<[HuksResult](#huksresultdeprecated)> | Yes  | Callback invoked to return the result. If the operation is successful, **HUKS_SUCCESS** is returned; otherwise, an error code is returned.|
A
Annie_wang 已提交
2101 2102 2103 2104 2105 2106 2107 2108 2109 2110 2111 2112 2113 2114 2115 2116 2117 2118

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

A
Annie_wang 已提交
2119
> **NOTE**<br>This API is deprecated since API version 9. You are advised to use [huks.deleteKeyItem<sup>9+</sup>](#huksdeletekeyitem9-1).
A
Annie_wang 已提交
2120 2121 2122 2123 2124 2125 2126 2127 2128 2129 2130 2131 2132 2133

**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 已提交
2134
| Promise\<[HuksResult](#huksresultdeprecated)> | Promise used to return the result. If the operation is successful, **HUKS_SUCCESS** is returned; otherwise, an error code is returned.|
A
Annie_wang 已提交
2135 2136 2137 2138 2139 2140 2141 2142 2143 2144 2145 2146 2147 2148 2149 2150 2151 2152

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

A
Annie_wang 已提交
2153
> **NOTE**<br>This API is deprecated since API version 9. You are advised to use [huks.importKeyItem<sup>9+</sup>](#huksimportkeyitem9).
A
Annie_wang 已提交
2154 2155 2156 2157 2158 2159 2160 2161 2162

**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 已提交
2163
| callback | AsyncCallback\<[HuksResult](#huksresultdeprecated)> | Yes  | Callback invoked to return the result. If the operation is successful, **HUKS_SUCCESS** is returned; otherwise, an error code is returned.|
A
Annie_wang 已提交
2164 2165 2166 2167 2168 2169 2170 2171 2172 2173 2174 2175 2176 2177 2178 2179 2180 2181 2182 2183 2184 2185

**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 已提交
2186
};
A
Annie_wang 已提交
2187 2188 2189 2190 2191 2192 2193 2194 2195 2196 2197 2198 2199 2200 2201 2202 2203 2204
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 已提交
2205 2206
```

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

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

A
Annie_wang 已提交
2211 2212
Imports a key in plaintext. This API uses a promise to return the result.

A
Annie_wang 已提交
2213
> **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 已提交
2214 2215 2216 2217 2218

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

**Parameters**

A
Annie_wang 已提交
2219 2220 2221 2222
| 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 已提交
2223 2224 2225 2226 2227

**Return value**

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

**Example**

```js
A
Annie_wang 已提交
2233 2234 2235 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
/* 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 已提交
2272 2273
```

A
Annie_wang 已提交
2274
## huks.exportKey<sup>(deprecated)</sup>
A
annie_wangli 已提交
2275 2276 2277

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

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

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

A
annie_wangli 已提交
2282 2283 2284 2285 2286 2287 2288 2289
**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 已提交
2290
| callback | AsyncCallback\<[HuksResult](#huksresultdeprecated)> | Yes  | Callback invoked to return the result. If the operation is successful, **HUKS_SUCCESS** is returned and **outData** contains the public key exported. If the operation fails, an error code is returned.|
A
annie_wangli 已提交
2291 2292 2293 2294

**Example**

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

A
Annie_wang 已提交
2303
## huks.exportKey<sup>(deprecated)</sup>
A
annie_wangli 已提交
2304 2305 2306

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

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

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

A
annie_wangli 已提交
2311 2312 2313 2314 2315 2316
**System capability**: SystemCapability.Security.Huks

**Parameters**

| Name  | Type       | Mandatory| Description                                                        |
| -------- | ----------- | ---- | ------------------------------------------------------------ |
A
Annie_wang 已提交
2317 2318
| 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 已提交
2319 2320 2321 2322 2323

**Return value**

| Type                               | Description                                                        |
| ----------------------------------- | ------------------------------------------------------------ |
A
Annie_wang 已提交
2324
| Promise\<[HuksResult](#huksresultdeprecated)> | Promise used to return the result. If the operation is successful, **HUKS_SUCCESS** is returned and **outData** contains the public key exported. If the operation fails, an error code is returned.|
A
annie_wangli 已提交
2325 2326 2327 2328

**Example**

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

A
Annie_wang 已提交
2337
## huks.getKeyProperties<sup>(deprecated)</sup>
A
annie_wangli 已提交
2338 2339 2340

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

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

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

A
annie_wangli 已提交
2345 2346 2347 2348 2349 2350 2351 2352
**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 已提交
2353
| callback | AsyncCallback\<[HuksResult](#huksresultdeprecated)> | Yes  | Callback invoked to return the result. If the operation is successful, **errorCode** is **HUKS_SUCCESS**; otherwise, an error code is returned.|
A
annie_wangli 已提交
2354 2355 2356 2357

**Example**

```js
A
Annie_wang 已提交
2358
/* Set options to emptyOptions. */
A
Annie_wang 已提交
2359 2360
let keyAlias = 'keyAlias';
let emptyOptions = {
A
annie_wangli 已提交
2361 2362 2363 2364 2365
  properties: []
};
huks.getKeyProperties(keyAlias, emptyOptions, function (err, data){});
```

A
Annie_wang 已提交
2366
## huks.getKeyProperties<sup>(deprecated)</sup>
A
annie_wangli 已提交
2367 2368 2369

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

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

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

A
annie_wangli 已提交
2374 2375 2376 2377 2378 2379
**System capability**: SystemCapability.Security.Huks

**Parameters**

| Name  | Type       | Mandatory| Description                                                        |
| -------- | ----------- | ---- | ------------------------------------------------------------ |
A
Annie_wang 已提交
2380 2381
| 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 已提交
2382 2383 2384 2385 2386

**Return value**

| Type              | Description                                                        |
| ------------------ | ------------------------------------------------------------ |
A
Annie_wang 已提交
2387
| 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 已提交
2388 2389 2390 2391

**Example**

```js
A
Annie_wang 已提交
2392
/* Set options to emptyOptions. */
A
Annie_wang 已提交
2393 2394
let keyAlias = 'keyAlias';
let emptyOptions = {
A
annie_wangli 已提交
2395 2396
  properties: []
};
A
Annie_wang 已提交
2397
let result = huks.getKeyProperties(keyAlias, emptyOptions);
A
annie_wangli 已提交
2398 2399
```

A
Annie_wang 已提交
2400
## huks.isKeyExist<sup>(deprecated)</sup>
A
annie_wangli 已提交
2401 2402 2403

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

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

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

A
annie_wangli 已提交
2408 2409 2410 2411 2412 2413
**System capability**: SystemCapability.Security.Huks

**Parameters**

| Name  | Type                  | Mandatory| Description                                 |
| -------- | ---------------------- | ---- | ------------------------------------- |
A
Annie_wang 已提交
2414 2415
| keyAlias | string                 | Yes  | Alias of the key to check.|
| options  | [HuksOptions](#huksoptions) | Yes  | Empty object (leave this parameter empty).|
A
Annie_wang 已提交
2416
| callback | AsyncCallback\<boolean> | Yes  | Callback invoked to return the result. The value **TRUE** means that the key exists; **FALSE** means the opposite.|
A
annie_wangli 已提交
2417 2418 2419 2420

**Example**

```js
A
Annie_wang 已提交
2421
/* Set options to emptyOptions. */
A
Annie_wang 已提交
2422 2423
let keyAlias = 'keyAlias';
let emptyOptions = {
A
annie_wangli 已提交
2424 2425 2426 2427 2428
  properties: []
};
huks.isKeyExist(keyAlias, emptyOptions, function (err, data){});
```

A
Annie_wang 已提交
2429
## huks.isKeyExist<sup>(deprecated)</sup>
A
annie_wangli 已提交
2430 2431 2432

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

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

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

A
annie_wangli 已提交
2437 2438 2439 2440 2441 2442
**System capability**: SystemCapability.Security.Huks

**Parameters**

| Name  | Type       | Mandatory| Description                            |
| -------- | ----------- | ---- | -------------------------------- |
A
Annie_wang 已提交
2443 2444
| keyAlias | string      | Yes  | Alias of the key to check.|
| options  | [HuksOptions](#huksoptions) | Yes  | Empty object (leave this parameter empty).|
A
annie_wangli 已提交
2445 2446 2447 2448 2449

**Return value**

| Type             | Description                                   |
| ----------------- | --------------------------------------- |
A
Annie_wang 已提交
2450
| Promise\<boolean> | Promise used to return the result. The value **TRUE** means that the key exists; **FALSE** means the opposite.|
A
annie_wangli 已提交
2451 2452 2453 2454

**Example**

```js
A
Annie_wang 已提交
2455
/* Set options to emptyOptions. */
A
Annie_wang 已提交
2456 2457
let keyAlias = 'keyAlias';
let emptyOptions = {
A
annie_wangli 已提交
2458 2459
  properties: []
};
A
Annie_wang 已提交
2460
let result = huks.isKeyExist(keyAlias, emptyOptions);
A
annie_wangli 已提交
2461 2462
```

A
Annie_wang 已提交
2463
## huks.init<sup>(deprecated)</sup>
A
annie_wangli 已提交
2464 2465 2466

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

A
Annie_wang 已提交
2467 2468
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.

A
Annie_wang 已提交
2469
> **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 已提交
2470 2471 2472 2473 2474 2475 2476

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

**Parameters**

| Name  | Type                  | Mandatory| Description                                 |
| -------- | ---------------------- | ---- | ------------------------------------- |
A
Annie_wang 已提交
2477
| keyAlias | string                 | Yes  | Alias of the target key.|
A
Annie_wang 已提交
2478 2479
| options  | [HuksOptions](#huksoptions) | Yes  | Parameter set used for the **init** operation.|
| callback | AsyncCallback\<[HuksHandle](#hukshandledeprecated)> | Yes  | Callback invoked to return a session handle for subsequent operations.|
A
annie_wangli 已提交
2480

A
Annie_wang 已提交
2481
## huks.init<sup>(deprecated)</sup>
A
annie_wangli 已提交
2482 2483 2484

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

A
Annie_wang 已提交
2485 2486
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.

A
Annie_wang 已提交
2487
> **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 已提交
2488 2489 2490 2491 2492 2493 2494

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

**Parameters**

| Name  | Type                  | Mandatory| Description                                 |
| -------- | ---------------------- | ---- | ------------------------------------- |
A
Annie_wang 已提交
2495
| keyAlias | string                 | Yes  | Alias of the target key.|
A
Annie_wang 已提交
2496
| options  | [HuksOptions](#huksoptions) | Yes  | Parameter set used for the **init** operation.|
A
annie_wangli 已提交
2497

A
Annie_wang 已提交
2498
**Return value**
A
annie_wangli 已提交
2499

A
Annie_wang 已提交
2500 2501
| Type                               | Description                                              |
| ----------------------------------- | -------------------------------------------------- |
A
Annie_wang 已提交
2502
| Promise\<[HuksHandle](#hukshandledeprecated)> | Promise used to return a session handle for subsequent operations.|
A
annie_wangli 已提交
2503

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

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

A
Annie_wang 已提交
2508 2509
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 已提交
2510
> **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 已提交
2511 2512

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

A
Annie_wang 已提交
2514 2515 2516 2517
**Parameters**

| Name  | Type                                     | Mandatory| Description                                        |
| -------- | ----------------------------------------- | ---- | -------------------------------------------- |
A
Annie_wang 已提交
2518 2519 2520
| handle   | number                                    | Yes  | Handle for the **update** operation.                        |
| token    | Uint8Array                                | No  | Token of the **update** operation.                         |
| options  | [HuksOptions](#huksoptions)               | Yes  | Parameter set used for the **update** operation.                      |
A
Annie_wang 已提交
2521
| callback | AsyncCallback\<[HuksResult](#huksresultdeprecated)> | Yes  | Callback invoked to return the **update** operation result.|
A
Annie_wang 已提交
2522

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

A
Annie_wang 已提交
2525
update(handle: number, token?: Uint8Array, options: HuksOptions) : Promise\<HuksResult>;
A
Annie_wang 已提交
2526

A
Annie_wang 已提交
2527 2528
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.

A
Annie_wang 已提交
2529
> **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 已提交
2530 2531 2532 2533 2534 2535 2536

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

**Parameters**

| Name | Type                               | Mandatory| Description                                        |
| ------- | ----------------------------------- | ---- | -------------------------------------------- |
A
Annie_wang 已提交
2537 2538 2539
| handle  | number                              | Yes  | Handle for the **update** operation.                        |
| token   | Uint8Array                          | No  | Token of the **update** operation.                         |
| options | [HuksOptions](#huksoptions)         | Yes  | Parameter set used for the **update** operation.                      |
A
annie_wangli 已提交
2540

A
Annie_wang 已提交
2541 2542 2543 2544
**Return value**

| Type                               | Description                                              |
| ----------------------------------- | -------------------------------------------------- |
A
Annie_wang 已提交
2545
| Promise\<[HuksResult](#huksresultdeprecated)> | Promise used to return the **update** operation result.|
A
Annie_wang 已提交
2546 2547

## huks.finish<sup>(deprecated)</sup>
A
annie_wangli 已提交
2548 2549 2550

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

A
Annie_wang 已提交
2551 2552
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.

A
Annie_wang 已提交
2553
> **NOTE**<br>This API is deprecated since API version 9. You are advised to use [huks.finishSession<sup>9+</sup>](#huksfinishsession9).
A
annie_wangli 已提交
2554 2555 2556 2557 2558 2559 2560

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

**Parameters**

| Name  | Type                  | Mandatory| Description                                 |
| -------- | ---------------------- | ---- | ------------------------------------- |
A
Annie_wang 已提交
2561 2562 2563
| handle | number           | Yes  | Handle for the **finish** operation.|
| options  | [HuksOptions](#huksoptions) | Yes  | Parameter set used for the **finish** operation.|
| callback | AsyncCallback\<[HuksResult](#huksresultdeprecated)> | Yes| Callback invoked to return the **finish** operation result.|
A
annie_wangli 已提交
2564

A
Annie_wang 已提交
2565
## huks.finish<sup>(deprecated)</sup>
A
annie_wangli 已提交
2566 2567 2568

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

A
Annie_wang 已提交
2569 2570
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.

A
Annie_wang 已提交
2571
> **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 已提交
2572 2573 2574 2575 2576 2577 2578

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

**Parameters**

| Name  | Type                  | Mandatory| Description                                 |
| -------- | ---------------------- | ---- | ------------------------------------- |
A
Annie_wang 已提交
2579 2580
| handle | number           | Yes  | Handle for the **finish** operation.|
| options  | [HuksOptions](#huksoptions) | Yes  | Parameter set used for the **finish** operation.|
A
Annie_wang 已提交
2581

A
Annie_wang 已提交
2582
**Return value**
A
Annie_wang 已提交
2583

A
Annie_wang 已提交
2584 2585
| Type                               | Description                                              |
| ----------------------------------- | -------------------------------------------------- |
A
Annie_wang 已提交
2586
| Promise\<[HuksResult](#huksresultdeprecated)> | Promise used to return the result.|
A
annie_wangli 已提交
2587

A
Annie_wang 已提交
2588
## huks.abort<sup>(deprecated)</sup>
A
annie_wangli 已提交
2589 2590 2591

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

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

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

A
annie_wangli 已提交
2596 2597 2598 2599 2600 2601
**System capability**: SystemCapability.Security.Huks

**Parameters**

| Name  | Type                  | Mandatory| Description                                 |
| -------- | ---------------------- | ---- | ------------------------------------- |
A
Annie_wang 已提交
2602 2603
| handle | number           | Yes  | Handle for the **abort** operation.|
| options  | [HuksOptions](#huksoptions) | Yes  | Parameter set used for the **abort** operation.|
A
Annie_wang 已提交
2604
| callback | AsyncCallback\<[HuksResult](#huksresultdeprecated)> | Yes| Callback invoked to return the **abort** operation result.|
A
annie_wangli 已提交
2605 2606 2607 2608

**Example**

```js
A
Annie_wang 已提交
2609 2610 2611
/* 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.
 *
A
Annie_wang 已提交
2612
 * The following uses the callback of an RSA 1024 key as an example.
A
Annie_wang 已提交
2613
 */
A
Annie_wang 已提交
2614 2615 2616
let keyalias = "HuksDemoRSA";
let properties = new Array();
let options = {
A
Annie_wang 已提交
2617 2618 2619
  properties: properties,
  inData: new Uint8Array(0)
};
A
Annie_wang 已提交
2620 2621
let handle;
let resultMessage = "";
A
Annie_wang 已提交
2622 2623 2624 2625 2626 2627 2628 2629 2630 2631 2632 2633 2634 2635 2636 2637 2638 2639 2640 2641 2642
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 已提交
2643
  huks.generateKey(keyalias, options);
A
Annie_wang 已提交
2644 2645
}
function stringToUint8Array(str) {
A
Annie_wang 已提交
2646 2647
  let arr = [];
  for (let i = 0, j = str.length; i < j; ++i) {
A
Annie_wang 已提交
2648 2649
    arr.push(str.charCodeAt(i));
  }
A
Annie_wang 已提交
2650
  let tmpUint8Array = new Uint8Array(arr);
A
Annie_wang 已提交
2651 2652 2653
  return tmpUint8Array;
}
async function huksInit() {
A
Annie_wang 已提交
2654
  await huks.init(keyalias, options).then((data) => {
A
Annie_wang 已提交
2655
    console.log(`test init data: ${JSON.stringify(data)}`);
A
Annie_wang 已提交
2656
    handle = data.handle;
A
Annie_wang 已提交
2657 2658 2659 2660 2661 2662 2663 2664 2665 2666 2667 2668 2669 2670 2671 2672 2673 2674 2675 2676 2677 2678 2679 2680 2681 2682 2683 2684 2685 2686 2687 2688 2689 2690 2691 2692
  }).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 已提交
2693
    resultMessage = "Failed to abort the use of the key. catch errorMessage:" + JSON.stringify(err)
A
Annie_wang 已提交
2694 2695 2696
  });
  console.log(resultMessage);
}
A
annie_wangli 已提交
2697 2698
```

A
Annie_wang 已提交
2699
## huks.abort<sup>(deprecated)</sup>
A
annie_wangli 已提交
2700 2701 2702

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

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

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

A
annie_wangli 已提交
2707 2708 2709 2710 2711 2712
**System capability**: SystemCapability.Security.Huks

**Parameters**

| Name  | Type                  | Mandatory| Description                                 |
| -------- | ---------------------- | ---- | ------------------------------------- |
A
Annie_wang 已提交
2713 2714
| handle | number           | Yes  | Handle for the **abort** operation.|
| options  | [HuksOptions](#huksoptions) | Yes  | Parameter set used for the **abort** operation.|
A
Annie_wang 已提交
2715 2716 2717 2718 2719

**Return value**

| Type                               | Description                                              |
| ----------------------------------- | -------------------------------------------------- |
A
Annie_wang 已提交
2720
| Promise\<[HuksResult](#huksresultdeprecated)> | Promise used to return the **abort** operation result.|
A
annie_wangli 已提交
2721 2722 2723 2724

**Example**

```js
A
Annie_wang 已提交
2725 2726 2727 2728 2729
/* 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 已提交
2730 2731 2732
let keyalias = "HuksDemoRSA";
let properties = new Array();
let options = {
A
Annie_wang 已提交
2733 2734 2735
  properties: properties,
  inData: new Uint8Array(0)
};
A
Annie_wang 已提交
2736 2737
let handle;
let resultMessage = "";
A
Annie_wang 已提交
2738
function stringToUint8Array(str) {
A
Annie_wang 已提交
2739 2740
  let arr = [];
  for (let i = 0, j = str.length; i < j; ++i) {
A
Annie_wang 已提交
2741 2742
    arr.push(str.charCodeAt(i));
  }
A
Annie_wang 已提交
2743
  let tmpUint8Array = new Uint8Array(arr);
A
Annie_wang 已提交
2744 2745 2746 2747 2748 2749 2750 2751 2752 2753 2754 2755 2756 2757 2758 2759 2760 2761 2762 2763 2764 2765 2766 2767
  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 已提交
2768
  huks.generateKey(keyalias, options, function (err, data) { });
A
Annie_wang 已提交
2769 2770 2771
}
async function huksInit() {
  return new Promise((resolve, reject) => {
A
Annie_wang 已提交
2772
    huks.init(keyalias, options, async function (err, data) {
A
Annie_wang 已提交
2773
      if (data.errorCode === 0) {
A
Annie_wang 已提交
2774
        resultMessage = "init success!"
A
Annie_wang 已提交
2775
        handle = data.handle;
A
Annie_wang 已提交
2776 2777 2778 2779 2780 2781 2782 2783 2784 2785 2786 2787 2788 2789 2790 2791 2792 2793 2794
      } 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 已提交
2795

A
Annie_wang 已提交
2796 2797 2798 2799 2800 2801 2802 2803 2804 2805 2806 2807 2808 2809 2810 2811 2812 2813 2814 2815 2816 2817 2818
}

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 已提交
2819 2820
```

A
Annie_wang 已提交
2821
## HuksHandle<sup>(deprecated)</sup>
A
annie_wangli 已提交
2822 2823 2824 2825

Defines the HUKS handle structure.

**System capability**: SystemCapability.Security.Huks
A
Annie_wang 已提交
2826
> **NOTE**<br>This API is deprecated since API version 9. You are advised to use [HuksSessionHandle<sup>9+</sup>](#hukssessionhandle9).
A
annie_wangli 已提交
2827

A
Annie_wang 已提交
2828
| Name    | Type            | Mandatory| Description    |
A
annie_wangli 已提交
2829
| ---------- | ---------------- | ---- | -------- |
A
Annie_wang 已提交
2830 2831
| errorCode  | number           | Yes  | Error code.|
| handle    | number       | Yes| Value of the handle.|
A
Annie_wang 已提交
2832
| token | Uint8Array | No| Challenge obtained after the [init](#huksinitdeprecated) operation.|
A
annie_wangli 已提交
2833

A
Annie_wang 已提交
2834
## HuksResult<sup>(deprecated)</sup>
A
annie_wangli 已提交
2835 2836 2837 2838 2839

Defines the **HuksResult** structure.

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

A
Annie_wang 已提交
2840 2841
> **NOTE**<br>This API is deprecated since API version 9. You are advised to use [HuksReturnResult<sup>9+</sup>](#huksreturnresult9).

A
Annie_wang 已提交
2842 2843 2844 2845 2846 2847
| 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 已提交
2848 2849 2850 2851 2852 2853 2854


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

Enumerates the error codes.

**System capability**: SystemCapability.Security.Huks
A
Annie_wang 已提交
2855
> **NOTE**<br>This API is deprecated since API version 9. You are advised to use HuksExceptionErrCode<sup>9+</sup>](#huksexceptionerrcode9).
A
Annie_wang 已提交
2856 2857 2858 2859 2860 2861 2862 2863 2864 2865 2866 2867 2868 2869 2870 2871 2872 2873 2874 2875 2876 2877 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

| 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_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_INTERNAL_ERROR | -999  |Internal error.|
| HUKS_ERROR_UNKNOWN_ERROR | -1000 |Unknown error.|