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

A
Annie_wang 已提交
3
> ![icon-note.gif](public_sys-resources/icon-note.gif) **NOTE**<br>
4
>
A
annie_wangli 已提交
5 6
> 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.

A
Annie_wang 已提交
7
The **KUKS** module provides KeyStore (KS) capabilities for applications, including key management and key cryptography operations.
A
Annie_wang 已提交
8
The keys managed by OpenHarmony Universal KeyStore (HUKS) can be imported by applications or generated by calling the HUKS APIs.
A
annie_wangli 已提交
9 10 11 12 13 14 15 16

## Modules to Import

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

A
Annie_wang 已提交
17
Enumerates the error codes.
A
annie_wangli 已提交
18 19 20 21 22

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

| Name                      | Value   | Description|
| -------------------------- | ----- | ---- |
A
Annie_wang 已提交
23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61
| 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   |Storage failure.|
| 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.|
A
Annie_wang 已提交
62 63 64 65 66
| HUKS_ERROR_GET_USERIAM_SECINFO_FAILED<sup>9+</sup> | -40 |Failed to obtain the security attribute information of the current user.|
| HUKS_ERROR_GET_USERIAM_AUTHINFO_FAILED<sup>9+</sup> | -41 |Failed to obtain the authentication information of the current user.|
| HUKS_ERROR_USER_AUTH_TYPE_NOT_SUPPORT<sup>9+</sup> | -42 |The access control of the current authentication type is not supported.|
| HUKS_ERROR_KEY_AUTH_FAILED<sup>9+</sup> | -43 |The access control authentication has failed.|
| HUKS_ERROR_DEVICE_NO_CREDENTIAL<sup>9+</sup> | -44 |No credential has been enrolled for the device.|
A
annie_wangli 已提交
67
| HUKS_ERROR_CHECK_GET_ALG_FAIL | -100  |Failed to check whether the ALG is obtained. |
A
Annie_wang 已提交
68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96
| HUKS_ERROR_CHECK_GET_KEY_SIZE_FAIL | -101  |Failed to check whether the key size is obtained.|
| HUKS_ERROR_CHECK_GET_PADDING_FAIL | -102  |Failed to check whether padding is obtained.|
| HUKS_ERROR_CHECK_GET_PURPOSE_FAIL | -103  |Failed to check whether the purpose is obtained.|
| HUKS_ERROR_CHECK_GET_DIGEST_FAIL | -104  |Failed to check whether digest is obtained.|
| HUKS_ERROR_CHECK_GET_MODE_FAIL | -105  |Failed to check whether the mode is obtained.|
| HUKS_ERROR_CHECK_GET_NONCE_FAIL | -106  |Failed to check whether the nonce is obtained.|
| HUKS_ERROR_CHECK_GET_AAD_FAIL | -107  |Failed to check whether the AAD is obtained.|
| HUKS_ERROR_CHECK_GET_IV_FAIL | -108  |Failed to check whether the initialization vector (IV) is obtained.|
| HUKS_ERROR_CHECK_GET_AE_TAG_FAIL | -109  |Failed to check whether the AE flag is obtained.|
| HUKS_ERROR_CHECK_GET_SALT_FAIL | -110  |Failed to check whether the SALT is obtained.|
| HUKS_ERROR_CHECK_GET_ITERATION_FAIL | -111  |Failed to check whether the iteration is obtained.|
| HUKS_ERROR_INVALID_ALGORITHM | -112  |Invalid algorithm.|
| HUKS_ERROR_INVALID_KEY_SIZE | -113  |Invalid key size.|
| HUKS_ERROR_INVALID_PADDING | -114  |Invalid padding.|
| HUKS_ERROR_INVALID_PURPOSE | -115  |Invalid purpose.|
| HUKS_ERROR_INVALID_MODE | -116  |Invalid mode.|
| HUKS_ERROR_INVALID_DIGEST | -117  |Invalid digest.|
| 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.|
| HUKS_ERROR_INVALID_ITERATION | -124  |Invalid iteration.|
| HUKS_ERROR_INVALID_OPERATION | -125  |Invalid operation.|
| HUKS_ERROR_INVALID_WRAPPED_FORMAT<sup>9+</sup> | -126 |Incorrect format of the wrapped key being imported.|
| HUKS_ERROR_INVALID_USAGE_OF_KEY<sup>9+</sup> | -127 |Incorrect purpose of the wrapped key being imported.|
| HUKS_ERROR_INTERNAL_ERROR | -999  |Internal error.|
| HUKS_ERROR_UNKNOWN_ERROR | -1000 |Unknown error.|
A
annie_wangli 已提交
97 98 99 100


## HuksKeyPurpose

A
Annie_wang 已提交
101
Enumerates the key purposes.
A
annie_wangli 已提交
102 103 104

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

A
annie_wangli 已提交
105 106
| Name                    | Value  | Description                            |
| ------------------------ | ---- | -------------------------------- |
A
Annie_wang 已提交
107
| HUKS_KEY_PURPOSE_ENCRYPT | 1    | Used to encrypt plaintext.|
A
Annie_wang 已提交
108
| HUKS_KEY_PURPOSE_DECRYPT | 2    | Used to decrypt the cipher text.|
A
Annie_wang 已提交
109
| HUKS_KEY_PURPOSE_SIGN    | 4    | Used to sign data.    |
110 111
| HUKS_KEY_PURPOSE_VERIFY  | 8    | Used to verify the signed data.  |
| HUKS_KEY_PURPOSE_DERIVE  | 16   | Used to derive a key.          |
A
Annie_wang 已提交
112 113
| HUKS_KEY_PURPOSE_WRAP    | 32   | Used to wrap a key.          |
| HUKS_KEY_PURPOSE_UNWRAP  | 64   | Used to unwrap a key.              |
114 115
| HUKS_KEY_PURPOSE_MAC     | 128  | Used to generate a message authentication code (MAC). |
| HUKS_KEY_PURPOSE_AGREE   | 256  | Used for key agreement.      |
A
annie_wangli 已提交
116 117 118 119 120 121 122 123 124

## HuksKeyDigest

Enumerates the digest algorithms.

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

| Name                  | Value  | Description                                    |
| ---------------------- | ---- | ---------------------------------------- |
A
Annie_wang 已提交
125 126 127 128 129 130 131 132
| HUKS_DIGEST_NONE       | 0   | No digest algorithm|
| HUKS_DIGEST_MD5        | 1    | MD5|
| HUKS_DIGEST_SM3<sup>9+</sup> | 2 | SM3|
| HUKS_DIGEST_SHA1       | 10   | SHA1|
| HUKS_DIGEST_SHA224 | 11   | SHA-224|
| HUKS_DIGEST_SHA256 | 12  | SHA-256|
| HUKS_DIGEST_SHA384  | 13  | SHA-384|
| HUKS_DIGEST_SHA512 | 14  | SHA-512|
A
annie_wangli 已提交
133 134 135 136 137 138 139 140 141

## HuksKeyPadding

Enumerates the padding algorithms.

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

| Name                  | Value  | Description                                    |
| ---------------------- | ---- | ---------------------------------------- |
A
Annie_wang 已提交
142 143 144 145 146
| 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    | PKCS1_V1_5|
| HUKS_PADDING_PKCS5 | 4   | Public Key Cryptography Standards (PKCS) #5|
A
Annie_wang 已提交
147
| HUKS_PADDING_PKCS7 | 5   | PKCS #7|
A
annie_wangli 已提交
148 149 150 151 152 153 154 155 156

## HuksCipherMode

Enumerates the cipher modes.

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

| Name         | Value  | Description                 |
| ------------- | ---- | --------------------- |
A
Annie_wang 已提交
157
| HUKS_MODE_ECB | 1    | Electronic Code bLock (ECB) mode|
A
Annie_wang 已提交
158 159 160 161 162
| 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|
A
annie_wangli 已提交
163 164 165

## HuksKeySize

A
Annie_wang 已提交
166
Enumerates the key sizes.
A
annie_wangli 已提交
167 168 169

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

A
Annie_wang 已提交
170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185
| 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  | 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  | AES key of 128 bits       |
| HUKS_AES_KEY_SIZE_192              | 196  | AES key of 196 bits       |
| HUKS_AES_KEY_SIZE_256              | 256  | AES key of 256 bits       |
| HUKS_AES_KEY_SIZE_512              | 512  | AES key of 512 bits       |
A
Annie_wang 已提交
186
| HUKS_CURVE25519_KEY_SIZE_256       | 256  | Curve25519 key of 256 bits|
A
Annie_wang 已提交
187 188 189 190 191
| HUKS_DH_KEY_SIZE_2048              | 2048 | 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  | SM2 key of 256 bits           |
| HUKS_SM4_KEY_SIZE_128<sup>9+</sup> | 128  | SM4 key of 128 bits           |
A
annie_wangli 已提交
192 193 194

## HuksKeyAlg

A
Annie_wang 已提交
195
Enumerates the key algorithms.
A
annie_wangli 已提交
196 197 198

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

A
Annie_wang 已提交
199 200 201 202 203 204 205 206 207 208
| 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   |
A
Annie_wang 已提交
209 210
| HUKS_ALG_X25519           | 101  | X25519  |
| HUKS_ALG_ED25519          | 102  | ED25519|
A
Annie_wang 已提交
211 212 213 214
| 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    |
A
annie_wangli 已提交
215 216 217 218 219 220 221 222 223

## HuksKeyGenerateType

Enumerates the key generation types.

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

| Name                          | Value  | Description            |
| ------------------------------ | ---- | ---------------- |
A
Annie_wang 已提交
224 225 226
| 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.|
A
annie_wangli 已提交
227 228 229 230 231 232 233 234 235

## HuksKeyFlag

Enumerates the key generation modes.

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

| Name                      | Value  | Description                                |
| -------------------------- | ---- | ------------------------------------ |
A
Annie_wang 已提交
236 237 238 239
| HUKS_KEY_FLAG_IMPORT_KEY   | 1    | The key is imported by using an API.    |
| HUKS_KEY_FLAG_GENERATE_KEY | 2    | The key is generated by using an API.    |
| HUKS_KEY_FLAG_AGREE_KEY    | 3    | The key is generated by using a key agreement API.|
| HUKS_KEY_FLAG_DERIVE_KEY   | 4    | The key is derived by using an API.|
A
annie_wangli 已提交
240 241 242 243 244 245 246 247 248 249

## HuksKeyStorageType

Enumerates the key storage modes.

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

| Name                   | Value  | Description                          |
| ----------------------- | ---- | ------------------------------ |
| HUKS_STORAGE_TEMP       | 0    | The key is managed locally.    |
A
Annie_wang 已提交
250
| HUKS_STORAGE_PERSISTENT | 1    | The key is managed by the HUKS service.|
A
annie_wangli 已提交
251 252 253 254 255 256 257 258 259

## HuksSendType

Enumerates the tag transfer modes.

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

| Name                | Value  | Description             |
| -------------------- | ---- | ----------------- |
A
Annie_wang 已提交
260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275
| HUKS_SEND_TYPE_ASYNC | 0    | The tag is sent asynchronously.|
| HUKS_SEND_TYPE_SYNC  | 1    | The tag is sent synchronously.|

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

Enumerates the algorithm suites used when a wrapped key is imported.

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

A
Annie_wang 已提交
276
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.
A
Annie_wang 已提交
277 278 279 280 281 282 283

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

| Name                     | Value  | Description                          |
| ------------------------- | ---- | ------------------------------ |
| HUKS_KEY_TYPE_PUBLIC_KEY  | 0    | Public key    |
| HUKS_KEY_TYPE_PRIVATE_KEY | 1    | Private key    |
A
Annie_wang 已提交
284
| HUKS_KEY_TYPE_KEY_PAIR    | 2    | Public and private key pair|
A
annie_wangli 已提交
285

A
Annie_wang 已提交
286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343
## HuksUserAuthType<sup>9+</sup>

Enumerates the user authentication types.

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

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

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

Enumerates access control types.

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

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

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

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

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

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

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

Enumerates the positions of the 8-byte custom challenges.

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

| Name                           | Value  | Description                          |
| ------------------------------- | ---- | ------------------------------ |
| HUKS_CHALLENGE_POS_0 | 0    | Bytes 0 to 7 indicate the valid challenge of the key.|
| HUKS_CHALLENGE_POS_1        | 1    | Bytes 8 to 15 indicate the valid challenge of the key.|
| HUKS_CHALLENGE_POS_2         | 2    | Bytes 16 to 23 indicate the valid challenge of the key.|
| HUKS_CHALLENGE_POS_3        | 3   | Bytes 24 to 31 indicate the valid challenge of the key.|

## 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 to sign data, the data will be added with the authentication information and then be signed.|

A
annie_wangli 已提交
344 345 346 347 348 349 350
## HuksTagType

Enumerates the tag data types.

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


A
annie_wangli 已提交
351 352
| Name                 | Value     | Description                                   |
| --------------------- | ------- | --------------------------------------- |
A
Annie_wang 已提交
353 354 355 356 357 358
| 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.      |
A
annie_wangli 已提交
359 360 361 362 363 364 365

## HuksTag

Enumerates the tags used to invoke parameters.

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

A
Annie_wang 已提交
366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386
| Name                                        | Value                                      | Description                                  |
| -------------------------------------------- | ---------------------------------------- | -------------------------------------- |
| HUKS_TAG_INVALID                             | HuksTagType.HUKS_TAG_TYPE_INVALID \| 0   | Invalid tag.                       |
| HUKS_TAG_ALGORITHM                           | HUKS_TAG_TYPE_UINT \| 1                  | Algorithm.                       |
| HUKS_TAG_PURPOSE                             | HuksTagType.HUKS_TAG_TYPE_UINT \| 2      | Purpose of a 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.            |
A
Annie_wang 已提交
387 388
| 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.            |
A
Annie_wang 已提交
389 390 391 392 393 394 395 396 397 398 399 400 401
| 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 used when a wrapped key is imported.                |
| HUKS_TAG_ACTIVE_DATETIME                     | HuksTagType.HUKS_TAG_TYPE_ULONG \| 201   | Reserved.                                |
| HUKS_TAG_ORIGINATION_EXPIRE_DATETIME         | HuksTagType.HUKS_TAG_TYPE_ULONG \| 202   | Reserved.                                |
| HUKS_TAG_USAGE_EXPIRE_DATETIME               | HuksTagType.HUKS_TAG_TYPE_ULONG \| 203   | Reserved.                                |
| HUKS_TAG_CREATION_DATETIME                   | HuksTagType.HUKS_TAG_TYPE_ULONG \| 204   | Reserved.                                |
| HUKS_TAG_ALL_USERS                           | ksTagType.HUKS_TAG_TYPE_BOOL \| 301      | Reserved.                                |
| HUKS_TAG_USER_ID                             | HuksTagType.HUKS_TAG_TYPE_UINT \| 302    | Reserved.                                |
| HUKS_TAG_NO_AUTH_REQUIRED                    | HuksTagType.HUKS_TAG_TYPE_BOOL \| 303    | Reserved.                                |
A
Annie_wang 已提交
402
| 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 |
A
Annie_wang 已提交
403 404
| HUKS_TAG_AUTH_TIMEOUT                        | HuksTagType.HUKS_TAG_TYPE_UINT \| 305    | Reserved.                                |
| HUKS_TAG_AUTH_TOKEN                          | HuksTagType.HUKS_TAG_TYPE_BYTES \| 306   | Reserved.                                |
A
Annie_wang 已提交
405 406 407 408
| 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-bypte custom challenge. For details, see [HuksChallengePosition](#hukschallengeposition9).|
A
Annie_wang 已提交
409 410
| 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.   |
A
Annie_wang 已提交
411
| HUKS_TAG_ATTESTATION_ID_BRAND                | HuksTagType.HUKS_TAG_TYPE_BYTES \| 503   | Brand of the device.                     |
A
Annie_wang 已提交
412 413
| HUKS_TAG_ATTESTATION_ID_DEVICE               | HuksTagType.HUKS_TAG_TYPE_BYTES \| 504   | Device ID.                    |
| HUKS_TAG_ATTESTATION_ID_PRODUCT              | HuksTagType.HUKS_TAG_TYPE_BYTES \| 505   | Product name of the device.                   |
A
Annie_wang 已提交
414 415 416 417 418 419 420 421
| HUKS_TAG_ATTESTATION_ID_SERIAL               | HuksTagType.HUKS_TAG_TYPE_BYTES \| 506   | Device SN.                      |
| HUKS_TAG_ATTESTATION_ID_IMEI                 | HuksTagType.HUKS_TAG_TYPE_BYTES \| 507   | Device IMEI.                    |
| HUKS_TAG_ATTESTATION_ID_MEID                 | HuksTagType.HUKS_TAG_TYPE_BYTES \| 508   | Device MEID.                    |
| HUKS_TAG_ATTESTATION_ID_MANUFACTURER         | HuksTagType.HUKS_TAG_TYPE_BYTES \| 509   | Device manufacturer.                    |
| 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   | Device SOCID.                     |
| HUKS_TAG_ATTESTATION_ID_UDID                 | HuksTagType.HUKS_TAG_TYPE_BYTES \| 513   | Device UDID.                      |
A
Annie_wang 已提交
422
| HUKS_TAG_ATTESTATION_ID_SEC_LEVEL_INFO       | HuksTagType.HUKS_TAG_TYPE_BYTES \| 514   | Security credential used in the attestation.         |
A
Annie_wang 已提交
423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449
| HUKS_TAG_ATTESTATION_ID_VERSION_INFO         | HuksTagType.HUKS_TAG_TYPE_BYTES \| 515   | Version information used in the attestation.           |
| HUKS_TAG_IS_KEY_ALIAS                        | HuksTagType.HUKS_TAG_TYPE_BOOL \| 1001   | Whether to use the alias passed in during key generation.|
| HUKS_TAG_KEY_STORAGE_FLAG                    | HuksTagType.HUKS_TAG_TYPE_UINT \| 1002   | Key storage mode.               |
| HUKS_TAG_IS_ALLOWED_WRAP                     | HuksTagType.HUKS_TAG_TYPE_BOOL \| 1003   | Reserved.                                |
| HUKS_TAG_KEY_WRAP_TYPE                       | HuksTagType.HUKS_TAG_TYPE_UINT \| 1004   | Reserved.                                |
| HUKS_TAG_KEY_AUTH_ID                         | HuksTagType.HUKS_TAG_TYPE_BYTES \| 1005  | Reserved.                                |
| HUKS_TAG_KEY_ROLE                            | HuksTagType.HUKS_TAG_TYPE_UINT \| 1006   | Reserved.                                |
| HUKS_TAG_KEY_FLAG                            | HuksTagType.HUKS_TAG_TYPE_UINT \| 1007   | Flag of the key.                   |
| HUKS_TAG_IS_ASYNCHRONIZED                    | HuksTagType.HUKS_TAG_TYPE_UINT \| 1008   | Reserved.                                |
| HUKS_TAG_SECURE_KEY_ALIAS                    | HuksTagType.HUKS_TAG_TYPE_BOOL \| 1009   | Reserved.                                |
| HUKS_TAG_SECURE_KEY_UUID                     | HuksTagType.HUKS_TAG_TYPE_BYTES \| 1010  | Reserved.                                |
| HUKS_TAG_KEY_DOMAIN                          | HuksTagType.HUKS_TAG_TYPE_UINT \| 1011   | Reserved.                                |
| HUKS_TAG_PROCESS_NAME                        | HuksTagType.HUKS_TAG_TYPE_BYTES \| 10001 | Process name.                   |
| HUKS_TAG_PACKAGE_NAME                        | HuksTagType.HUKS_TAG_TYPE_BYTES \| 10002 | Reserved.                                |
| HUKS_TAG_ACCESS_TIME                         | HuksTagType.HUKS_TAG_TYPE_UINT \| 10003  | Reserved.                                |
| HUKS_TAG_USES_TIME                           | HuksTagType.HUKS_TAG_TYPE_UINT \| 10004  | Reserved.                                |
| HUKS_TAG_CRYPTO_CTX                          | HuksTagType.HUKS_TAG_TYPE_ULONG \| 10005 | Reserved.                                |
| HUKS_TAG_KEY                                 | HuksTagType.HUKS_TAG_TYPE_BYTES \| 10006 | Reserved.                                |
| HUKS_TAG_KEY_VERSION                         | HuksTagType.HUKS_TAG_TYPE_UINT \| 10007  | Key version.                   |
| HUKS_TAG_PAYLOAD_LEN                         | HuksTagType.HUKS_TAG_TYPE_UINT \| 10008  | Reserved.                                |
| HUKS_TAG_AE_TAG                              | HuksTagType.HUKS_TAG_TYPE_BYTES \| 10009 | Reserved.                                |
| HUKS_TAG_IS_KEY_HANDLE                       | HuksTagType.HUKS_TAG_TYPE_ULONG \| 10010 | Reserved.                                |
| HUKS_TAG_OS_VERSION                          | HuksTagType.HUKS_TAG_TYPE_UINT \| 10101  | OS version.               |
| HUKS_TAG_OS_PATCHLEVEL                       | HuksTagType.HUKS_TAG_TYPE_UINT \| 10102  | OS patch level.           |
| HUKS_TAG_SYMMETRIC_KEY_DATA                  | HuksTagType.HUKS_TAG_TYPE_BYTES \| 20001 | Reserved.                                |
| HUKS_TAG_ASYMMETRIC_PUBLIC_KEY_DATA          | HuksTagType.HUKS_TAG_TYPE_BYTES \| 20002 | Reserved.                                |
| HUKS_TAG_ASYMMETRIC_PRIVATE_KEY_DATA         | HuksTagType.HUKS_TAG_TYPE_BYTES \| 20003 | Reserved.                                |
A
annie_wangli 已提交
450 451 452 453 454

## huks.generateKey

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

A
Annie_wang 已提交
455
Generates a key. This API uses an asynchronous callback to return the result.
A
annie_wangli 已提交
456 457 458 459 460 461 462 463 464

**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 已提交
465
| callback | AsyncCallback\<[HuksResult](#huksresult)> | Yes  | Callback used to return the result. If the operation is successful, **HUKS_SUCCESS** will be returned. If the operation fails, an error code defined in **HuksResult** will be returned.|
A
annie_wangli 已提交
466 467 468 469

**Example**

```js
A
Annie_wang 已提交
470 471
/* Generate an RSA key of 512 bits. */
var keyAlias = 'keyAlias';
A
annie_wangli 已提交
472 473 474
var properties = new Array();
properties[0] = {
  tag: huks.HuksTag.HUKS_TAG_ALGORITHM,
A
Annie_wang 已提交
475
  value: huks.HuksKeyAlg.HUKS_ALG_RSA
A
annie_wangli 已提交
476 477 478 479 480 481 482
};
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,
A
Annie_wang 已提交
483 484 485
  value:
huks.HuksKeyPurpose.HUKS_KEY_PURPOSE_ENCRYPT |
huks.HuksKeyPurpose.HUKS_KEY_PURPOSE_DECRYPT
A
annie_wangli 已提交
486 487 488
};
properties[3] = {
  tag: huks.HuksTag.HUKS_TAG_PADDING,
A
Annie_wang 已提交
489
  value: huks.HuksKeyPadding.HUKS_PADDING_OAEP
A
annie_wangli 已提交
490 491 492
};
properties[4] = {
  tag: huks.HuksTag.HUKS_TAG_DIGEST,
A
Annie_wang 已提交
493
  value: huks.HuksKeyDigest.HUKS_DIGEST_SHA256
A
annie_wangli 已提交
494 495 496 497
};
var options = {
  properties: properties
};
A
Annie_wang 已提交
498
huks.generateKey(keyAlias, options, function (err, data){}); 
A
annie_wangli 已提交
499 500 501 502 503 504
```

## huks.generateKey

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

A
Annie_wang 已提交
505
Generates a key. This API uses a promise to return the result asynchronously.
A
annie_wangli 已提交
506 507 508 509 510 511 512 513

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

**Parameters**

| Name  | Type                       | Mandatory| Description                    |
| -------- | --------------------------- | ---- | ------------------------ |
| keyAlias | string                      | Yes  | Alias of the key.              |
A
Annie_wang 已提交
514
| options  | [HuksOptions](#huksoptions) | Yes  | Tags required for generating the key.|
A
annie_wangli 已提交
515 516 517 518 519

**Return value**

| Type                               | Description                                              |
| ----------------------------------- | -------------------------------------------------- |
A
Annie_wang 已提交
520
| Promise\<[HuksResult](#huksresult)> | Promise used to return the result. If the operation is successful, **HUKS_SUCCESS** will be returned. If the operation fails, an error code will be returned.|
A
annie_wangli 已提交
521 522 523 524

**Example**

```js
A
Annie_wang 已提交
525 526
/* Generate an ECC key of 256 bits. */
var keyAlias = 'keyAlias';
A
annie_wangli 已提交
527 528 529
var properties = new Array();
properties[0] = {
  tag: huks.HuksTag.HUKS_TAG_ALGORITHM,
A
Annie_wang 已提交
530
  value: huks.HuksKeyAlg.HUKS_ALG_ECC
A
annie_wangli 已提交
531 532 533
};
properties[1] = {
  tag: huks.HuksTag.HUKS_TAG_KEY_SIZE,
A
Annie_wang 已提交
534
  value: huks.HuksKeySize.HUKS_ECC_KEY_SIZE_256
A
annie_wangli 已提交
535 536 537
};
properties[2] = {
  tag: huks.HuksTag.HUKS_TAG_PURPOSE,
A
Annie_wang 已提交
538 539 540
  value:
huks.HuksKeyPurpose.HUKS_KEY_PURPOSE_SIGN |
huks.HuksKeyPurpose.HUKS_KEY_PURPOSE_VERIFY
A
annie_wangli 已提交
541 542 543
};
properties[3] = {
  tag: huks.HuksTag.HUKS_TAG_DIGEST,
A
Annie_wang 已提交
544
  value: huks.HuksKeyDigest.HUKS_DIGEST_SHA256
A
annie_wangli 已提交
545 546 547 548
};
var options = {
  properties: properties
};
A
Annie_wang 已提交
549
var result = huks.generateKey(keyAlias, options);
A
annie_wangli 已提交
550 551 552 553 554 555
```

## huks.deleteKey

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

A
Annie_wang 已提交
556
Deletes a key. This API uses an asynchronous callback to return the result.
A
annie_wangli 已提交
557 558 559 560 561 562 563 564 565

**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 已提交
566
| callback | AsyncCallback\<[HuksResult](#huksresult)> | Yes  | Callback used to return the result. If the operation is successful, **HUKS_SUCCESS** will be returned. If the operation fails, an error code will be returned.|
A
annie_wangli 已提交
567 568 569 570

**Example**

```js
A
Annie_wang 已提交
571 572
/* Set options to emptyOptions. */
var keyAlias = 'keyAlias';
A
annie_wangli 已提交
573 574 575
var emptyOptions = {
  properties: []
};
A
Annie_wang 已提交
576
huks.deleteKey(keyAlias, emptyOptions, function (err, data) {});
A
annie_wangli 已提交
577 578 579 580 581 582
```

## huks.deleteKey

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

A
Annie_wang 已提交
583
Deletes a key. This API uses a promise to return the result asynchronously.
A
annie_wangli 已提交
584 585 586 587 588 589 590

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

**Parameters**

| Name  | Type       | Mandatory| Description                                                 |
| -------- | ----------- | ---- | ----------------------------------------------------- |
A
Annie_wang 已提交
591 592
| keyAlias | string      | Yes  | Key alias passed in when the key was generated.|
| options | [HuksOptions](#huksoptions) | Yes  | Empty object (leave this parameter empty).|
A
annie_wangli 已提交
593 594 595 596 597

**Return value**

| Type                               | Description                                              |
| ----------------------------------- | -------------------------------------------------- |
A
Annie_wang 已提交
598
| Promise\<[HuksResult](#huksresult)> | Promise used to return the result. If the operation is successful, **HUKS_SUCCESS** will be returned. If the operation fails, an error code will be returned.|
A
annie_wangli 已提交
599 600 601 602

**Example**

```js
A
Annie_wang 已提交
603 604
/* Set options to emptyOptions. */
var keyAlias = 'keyAlias';
A
annie_wangli 已提交
605 606 607
var emptyOptions = {
  properties: []
};
A
Annie_wang 已提交
608
var result = huks.deleteKey(keyAlias, emptyOptions);
A
annie_wangli 已提交
609 610 611 612 613 614 615 616 617 618 619 620 621 622
```

## huks.getSdkVersion

getSdkVersion(options: HuksOptions) : string

Obtains the SDK version of the current system.

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

**Parameters**

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

**Return value**

A
annie_wangli 已提交
627 628
| Type  | Description         |
| ------ | ------------- |
A
Annie_wang 已提交
629
| string | SDK version obtained.|
A
annie_wangli 已提交
630 631 632 633

**Example**

```js
A
Annie_wang 已提交
634
/* Set options to emptyOptions. */
A
annie_wangli 已提交
635 636 637 638 639 640 641 642 643 644
var emptyOptions = {
  properties: []
};
var result = huks.getSdkVersion(emptyOptions);
```

## huks.importKey

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

A
Annie_wang 已提交
645
Imports a key in plaintext. This API uses an asynchronous callback to return the result.
A
annie_wangli 已提交
646 647 648 649 650 651 652

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

**Parameters**

| Name  | Type                    | Mandatory| Description                                             |
| -------- | ------------------------ | ---- | ------------------------------------------------- |
A
Annie_wang 已提交
653 654 655
| keyAlias | string                   | Yes  | Alias of the key to import.|
| options  | [HuksOptions](#huksoptions) | Yes  | Tags required for the import and key to import.|
| callback | AsyncCallback\<[HuksResult](#huksresult)> | Yes  | Callback used to return the result. If the operation is successful, **HUKS_SUCCESS** will be returned. If the operation fails, an error code will be returned.|
A
annie_wangli 已提交
656 657 658 659

**Example**

```js
A
Annie_wang 已提交
660 661 662 663 664 665 666 667 668
/* Import an AES key of 256 bits. */
var plainTextSize32 = makeRandomArr(32);
function makeRandomArr(size) {
    var arr = new Uint8Array(size);
    for (var i = 0; i < size; i++) {
        arr[i] = Math.floor(Math.random() * 10);
    }
    return arr;
};
A
annie_wangli 已提交
669 670 671 672
var keyAlias = 'keyAlias';
var properties = new Array();
properties[0] = {
  tag: huks.HuksTag.HUKS_TAG_ALGORITHM,
A
Annie_wang 已提交
673
  value: huks.HuksKeyAlg.HUKS_ALG_AES
A
annie_wangli 已提交
674 675 676
};
properties[1] = {
  tag: huks.HuksTag.HUKS_TAG_KEY_SIZE,
A
Annie_wang 已提交
677
  value: huks.HuksKeySize.HUKS_AES_KEY_SIZE_256
A
annie_wangli 已提交
678 679 680
};
properties[2] = {
  tag: huks.HuksTag.HUKS_TAG_PURPOSE,
A
Annie_wang 已提交
681 682
  value:
huks.HuksKeyPurpose.HUKS_KEY_PURPOSE_ENCRYPT | huks.HuksKeyPurpose.HUKS_KEY_PURPOSE_DECRYPT
A
annie_wangli 已提交
683 684 685
};
properties[3] = {
  tag: huks.HuksTag.HUKS_TAG_PADDING,
A
Annie_wang 已提交
686
  value:huks.HuksKeyPadding.HUKS_PADDING_PKCS7
A
annie_wangli 已提交
687 688
};
properties[4] = {
A
Annie_wang 已提交
689 690
  tag: huks.HuksTag.HUKS_TAG_BLOCK_MODE,
  value: huks.HuksCipherMode.HUKS_MODE_ECB
A
annie_wangli 已提交
691 692 693
};
var options = {
  properties: properties,
A
Annie_wang 已提交
694
  inData: plainTextSize32
A
annie_wangli 已提交
695 696 697 698 699 700 701 702
};
huks.importKey(keyAlias, options, function (err, data){});
```

## huks.importKey

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

A
Annie_wang 已提交
703
Imports a key in plaintext. This API uses a promise to return the result asynchronously.
A
annie_wangli 已提交
704 705 706 707 708 709 710

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

**Parameters**

| Name  | Type       | Mandatory| Description                                |
| -------- | ----------- | ---- | ------------------------------------ |
A
Annie_wang 已提交
711 712
| keyAlias | string      | Yes  | Alias of the key to import.|
| options  | [HuksOptions](#huksoptions) | Yes  | Tags required for the import and key to import.|
A
annie_wangli 已提交
713 714 715 716 717

**Return value**

| Type                               | Description                                              |
| ----------------------------------- | -------------------------------------------------- |
A
Annie_wang 已提交
718
| Promise\<[HuksResult](#huksresult)> | Promise used to return the result. If the operation is successful, **HUKS_SUCCESS** will be returned. If the operation fails, an error code will be returned.|
A
annie_wangli 已提交
719 720 721 722

**Example**

```js
A
Annie_wang 已提交
723 724 725 726 727 728 729 730 731 732 733 734
/* Import an AES key of 128 bits. */
var plainTextSize32 = makeRandomArr(32);

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

/* Step 1 Generate a key. */
A
annie_wangli 已提交
735 736 737 738
var keyAlias = 'keyAlias';
var properties = new Array();
properties[0] = {
  tag: huks.HuksTag.HUKS_TAG_ALGORITHM,
A
Annie_wang 已提交
739
  value: huks.HuksKeyAlg.HUKS_ALG_AES
A
annie_wangli 已提交
740 741 742
};
properties[1] = {
  tag: huks.HuksTag.HUKS_TAG_KEY_SIZE,
A
Annie_wang 已提交
743
  value: huks.HuksKeySize.HUKS_AES_KEY_SIZE_128
A
annie_wangli 已提交
744 745 746
};
properties[2] = {
  tag: huks.HuksTag.HUKS_TAG_PURPOSE,
A
Annie_wang 已提交
747
  value: huks.HuksKeyPurpose.HUKS_KEY_PURPOSE_ENCRYPT | huks.HuksKeyPurpose.HUKS_KEY_PURPOSE_DECRYPT
A
annie_wangli 已提交
748 749 750
};
properties[3] = {
  tag: huks.HuksTag.HUKS_TAG_PADDING,
A
Annie_wang 已提交
751
  value:huks.HuksKeyPadding.HUKS_PADDING_PKCS7
A
annie_wangli 已提交
752 753
};
properties[4] = {
A
Annie_wang 已提交
754 755
  tag: huks.HuksTag.HUKS_TAG_BLOCK_MODE,
  value: huks.HuksCipherMode.HUKS_MODE_ECB
A
annie_wangli 已提交
756
};
A
Annie_wang 已提交
757
var huksoptions = {
A
annie_wangli 已提交
758
  properties: properties,
A
Annie_wang 已提交
759
  inData: plainTextSize32
A
annie_wangli 已提交
760
};
A
Annie_wang 已提交
761
var result = huks.importKey(keyAlias, huksoptions);
A
annie_wangli 已提交
762 763
```

A
Annie_wang 已提交
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 834 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 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901
## huks.attestkey<sup>9+</sup>

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

Obtains the certificate used to verify 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  | Alias of the key. The certificate to be obtained stores the key.   |
| options          | [HuksOptions](#huksoptions)               | Yes  | Parameters and data required for obtaining the certificate.     |
| callback         | AsyncCallback\<[HuksResult](#huksresult)> | Yes  | Callback used to return the result. If the operation is successful, **HUKS_SUCCESS** will be returned. If the operation fails, an error code will be returned.|

**Example**

```js
let securityLevel = stringToUint8Array('sec_level');
let challenge = stringToUint8Array('challenge_data');
let versionInfo = stringToUint8Array('version_info');
let keyAliasString = "key attest";

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

function printLog(...data) {
  console.error(data.toString());
}

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
  };
  generateKey(aliasString);
  setTimeout(()=>huks.attestKey(aliasString, options, function (err, data) {
    printLog(`key attest result : ${JSON.stringify(data)}`);
  }), 1000);
}
```

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

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

Obtains the certificate used to verify a key. This API uses a promise to return the result.

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

**Parameters**

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

**Return value**

| Type                               | Description                                              |
| ----------------------------------- | -------------------------------------------------- |
| Promise\<[HuksResult](#huksresult)> | Promise used to return the result. If the operation is successful, **HUKS_SUCCESS** will be returned. If the operation fails, an error code will be returned.|

**Example**

```js
let securityLevel = stringToUint8Array('sec_level');
let challenge = stringToUint8Array('challenge_data');
let versionInfo = stringToUint8Array('version_info');
let keyAliasString = "key attest";

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

function printLog(...data) {
  console.error(data.toString());
}

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
  };
  generateKey(aliasString);
  let result = await huks.exportKey(attestKey, options);
  printLog(`key attest result : ${result.errorCode}`);
}
```

A
Annie_wang 已提交
902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008
## huks.importWrappedKey<sup>9+</sup>

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

Imports a wrapped key. 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 wrapped key to import.                  |
| wrappingKeyAlias | string                                    | Yes  | Alias of the data used to unwrap the key imported.        |
| options          | [HuksOptions](#huksoptions)               | Yes  | Tags required for the import and the wrapped key to import.     |
| callback         | AsyncCallback\<[HuksResult](#huksresult)> | Yes  | Callback used to return the result. If the operation is successful, **HUKS_SUCCESS** will be returned. If the operation fails, an error code will be returned.|

**Example**

```js
var exportWrappingKey;
var alias1 = "importAlias";
var alias2 = "wrappingKeyAlias";

async function TestGenFunc(alias, options) {
  await genKey(alias, options)
    .then((data) => {
      console.log(`test genKey data: ${JSON.stringify(data)}`);
    })
    .catch((err) => {
      console.log('test genKey err information: ' + JSON.stringify(err));
    });
}

function genKey(alias, options) {
  return new Promise((resolve, reject) => {
    huks.generateKey(alias, options, function (err, data) {
      console.log(`test genKey data: ${JSON.stringify(data)}`);
      if (err.code !== 0) {
        console.log('test genKey err information: ' + JSON.stringify(err));
        reject(err);
      } else {
        resolve(data);
      }
    });
  });
}

async function TestExportFunc(alias, options) {
  await exportKey(alias, options)
    .then((data) => {
      console.log(`test exportKey data: ${JSON.stringify(data)}`);
    })
    .catch((err) => {
      console.log('test exportKey err information: ' + JSON.stringify(err));
    });
}

function exportKey(alias, options) {
  return new Promise((resolve, reject) => {
    huks.exportKey(alias, options, function (err, data) {
      console.log(`test exportKey data: ${JSON.stringify(data)}`);
      if (err.code !== 0) {
        console.log('test exportKey err information: ' + JSON.stringify(err));
        reject(err);
      } else {
        exportWrappingKey = data.outData;
        resolve(data);
      }
    });
  });
}

async function TestImportWrappedFunc(alias, wrappingAlias, options) {
  await importWrappedKey(alias, wrappingAlias, options)
    .then((data) => {
      console.log(`TestImportWrappedFunc data: ${JSON.stringify(data)}`);
    })
    .catch((err) => {
      console.log('test importWrappedKey err information: ' + JSON.stringify(err));
    });
}

function importWrappedKey(alias, wrappingAlias, options) {
  return new Promise((resolve, reject) => {
    huks.importWrappedKey(alias, wrappingAlias, options, function (err, data) {
      console.log(`importWrappedKey data: ${JSON.stringify(data)}`);
      if (err.code !== 0) {
        console.log('importWrappedKey err information: ' + JSON.stringify(err));
        reject(err);
      } else {
        resolve(data);
      }
    });
  });
}

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.
A
Annie_wang 已提交
1009 1010 1011 1012 1013 1014
     * 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:
A
Annie_wang 已提交
1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125
     * 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
     */
    var inputKey = new Uint8Array([0x02, 0x00, 0x00, 0x00]);
    importOptions.inData = inputKey;
    await TestImportWrappedFunc(alias, wrappingAlias, importOptions);
}

function makeGenerateOptions() {
  var 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
  };
  var options = {
    properties: properties
  };
  return options;
};

function makeImportOptions() {
  var 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_UNWRAP_ALGORITHM_SUITE,
    value: huks.HuksUnwrapSuite.HUKS_UNWRAP_SUITE_ECDH_AES_256_GCM_NOPADDING
  };
  var options = {
    properties: properties
  };
  return options;
};

function huksImportWrappedKey() {
  var genOptions = makeGenerateOptions();
  var importOptions = makeImportOptions();
  TestImportWrappedKeyFunc(
    alias1,
    alias2,
    genOptions,
    importOptions
  );
}
```

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

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

Imports a wrapped key. This API uses a promise to return the result asynchronously.

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

**Parameters**

| Name          | Type                       | Mandatory| Description                                         |
| ---------------- | --------------------------- | ---- | --------------------------------------------- |
| keyAlias         | string                      | Yes  | Alias of the wrapped key to import.             |
| wrappingKeyAlias | string                      | Yes  | Alias of the data used to unwrap the key imported.   |
| options          | [HuksOptions](#huksoptions) | Yes  | Tags required for the import and the wrapped key to import.|

**Return value**

| Type                               | Description                                              |
| ----------------------------------- | -------------------------------------------------- |
| Promise\<[HuksResult](#huksresult)> | Promise used to return the result. If the operation is successful, **HUKS_SUCCESS** will be returned. If the operation fails, an error code will be returned.|

**Example**

```js
/* The process is similar as if a callback is used, except the following:*/
async function TestImportWrappedFunc(alias, wrappingAlias, options) {
  var result = await huks.importWrappedKey(alias, wrappingAlias, options);
  if (result.errorCode === 0) {
    console.log('test importWrappedKey success');
  } else {
    console.log('test importWrappedKey fail');
  }
}
```

A
annie_wangli 已提交
1126 1127 1128 1129
## huks.exportKey

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

A
Annie_wang 已提交
1130
Exports a key. This API uses an asynchronous callback to return the result.
A
annie_wangli 已提交
1131 1132 1133 1134 1135 1136 1137 1138 1139

**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 已提交
1140
| callback | AsyncCallback\<[HuksResult](#huksresult)> | Yes  | Callback used to return the result. If the operation is successful, **HUKS_SUCCESS** will be returned. If the operation fails, an error code will be returned. **outData** contains the public key exported.|
A
annie_wangli 已提交
1141 1142 1143 1144

**Example**

```js
A
Annie_wang 已提交
1145
/* Set options to emptyOptions. */
A
annie_wangli 已提交
1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156
var keyAlias = 'keyAlias';
var emptyOptions = {
  properties: []
};
huks.exportKey(keyAlias, emptyOptions, function (err, data){});
```

## huks.exportKey

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

A
Annie_wang 已提交
1157
Exports a key. This API uses a promise to return the result asynchronously.
A
annie_wangli 已提交
1158 1159 1160 1161 1162 1163 1164

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

**Parameters**

| Name  | Type       | Mandatory| Description                                                        |
| -------- | ----------- | ---- | ------------------------------------------------------------ |
A
Annie_wang 已提交
1165 1166
| 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 已提交
1167 1168 1169 1170 1171

**Return value**

| Type                               | Description                                                        |
| ----------------------------------- | ------------------------------------------------------------ |
A
Annie_wang 已提交
1172
| Promise\<[HuksResult](#huksresult)> | Promise used to return the result. If the operation is successful, **HUKS_SUCCESS** will be returned. If the operation fails, an error code will be returned. **outData** contains the public key exported.|
A
annie_wangli 已提交
1173 1174 1175 1176

**Example**

```js
A
Annie_wang 已提交
1177
/* Set options to emptyOptions. */
A
annie_wangli 已提交
1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188
var keyAlias = 'keyAlias';
var emptyOptions = {
  properties: []
};
var result = huks.exportKey(keyAlias, emptyOptions);
```

## huks.getKeyProperties

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

A
Annie_wang 已提交
1189
Obtains key properties. This API uses an asynchronous callback to return the result.
A
annie_wangli 已提交
1190 1191 1192 1193 1194 1195 1196 1197 1198

**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 已提交
1199
| callback | AsyncCallback\<[HuksResult](#huksresult)> | Yes  | Callback used to return the result. If the operation is successful, **errorCode** is **HUKS_SUCCESS**; otherwise, an error code will be returned.|
A
annie_wangli 已提交
1200 1201 1202 1203

**Example**

```js
A
Annie_wang 已提交
1204
/* Set options to emptyOptions. */
A
annie_wangli 已提交
1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215
var keyAlias = 'keyAlias';
var emptyOptions = {
  properties: []
};
huks.getKeyProperties(keyAlias, emptyOptions, function (err, data){});
```

## huks.getKeyProperties

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

A
Annie_wang 已提交
1216
Obtains key properties. This API uses a promise to return the result asynchronously.
A
annie_wangli 已提交
1217 1218 1219 1220 1221 1222 1223

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

**Parameters**

| Name  | Type       | Mandatory| Description                                                        |
| -------- | ----------- | ---- | ------------------------------------------------------------ |
A
Annie_wang 已提交
1224 1225
| 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 已提交
1226 1227 1228 1229 1230

**Return value**

| Type              | Description                                                        |
| ------------------ | ------------------------------------------------------------ |
A
Annie_wang 已提交
1231
| Promise\<[HuksResult](#huksoptions)> | Promise used to return the result. If the operation is successful, **errorCode** is **HUKS_SUCCESS**; otherwise, an error code will be returned. **properties** returns the parameters required for generating the key.|
A
annie_wangli 已提交
1232 1233 1234 1235

**Example**

```js
A
Annie_wang 已提交
1236
/* Set options to emptyOptions. */
A
annie_wangli 已提交
1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247
var keyAlias = 'keyAlias';
var emptyOptions = {
  properties: []
};
var result = huks.getKeyProperties(keyAlias, emptyOptions);
```

## huks.isKeyExist

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

A
Annie_wang 已提交
1248
Checks whether a key exists. This API uses an asynchronous callback to return the result.
A
annie_wangli 已提交
1249 1250 1251 1252 1253 1254 1255

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

**Parameters**

| Name  | Type                  | Mandatory| Description                                 |
| -------- | ---------------------- | ---- | ------------------------------------- |
A
Annie_wang 已提交
1256 1257 1258
| keyAlias | string                 | Yes  | Alias of the key to check.|
| options  | [HuksOptions](#huksoptions) | Yes  | Empty object (leave this parameter empty).|
| callback | AsyncCallback\<boolean> | Yes  | Callback used to return the result. **TRUE** means that the key exists; **FALSE** means the opposite.|
A
annie_wangli 已提交
1259 1260 1261 1262

**Example**

```js
A
Annie_wang 已提交
1263
/* Set options to emptyOptions. */
A
annie_wangli 已提交
1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274
var keyAlias = 'keyAlias';
var emptyOptions = {
  properties: []
};
huks.isKeyExist(keyAlias, emptyOptions, function (err, data){});
```

## huks.isKeyExist

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

A
Annie_wang 已提交
1275
Checks whether a key exists. This API uses a promise to return the result asynchronously.
A
annie_wangli 已提交
1276 1277 1278 1279 1280 1281 1282

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

**Parameters**

| Name  | Type       | Mandatory| Description                            |
| -------- | ----------- | ---- | -------------------------------- |
A
Annie_wang 已提交
1283 1284
| keyAlias | string      | Yes  | Alias of the key to check.|
| options  | [HuksOptions](#huksoptions) | Yes  | Empty object (leave this parameter empty).|
A
annie_wangli 已提交
1285 1286 1287 1288 1289

**Return value**

| Type             | Description                                   |
| ----------------- | --------------------------------------- |
A
Annie_wang 已提交
1290
| Promise\<boolean> | Promise used to return the result. **TRUE** means that the key exists; **FALSE** means the opposite.|
A
annie_wangli 已提交
1291 1292 1293 1294

**Example**

```js
A
Annie_wang 已提交
1295
/* Set options to emptyOptions. */
A
annie_wangli 已提交
1296 1297 1298 1299 1300 1301 1302 1303
var keyAlias = 'keyAlias';
var emptyOptions = {
  properties: []
};
var result = huks.isKeyExist(keyAlias, emptyOptions);
```


A
Annie_wang 已提交
1304

A
annie_wangli 已提交
1305 1306 1307 1308
## huks.init

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

A
Annie_wang 已提交
1309
Initializes a key. This API uses an asynchronous callback to return the result.
A
annie_wangli 已提交
1310 1311 1312 1313 1314 1315 1316

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

**Parameters**

| Name  | Type                  | Mandatory| Description                                 |
| -------- | ---------------------- | ---- | ------------------------------------- |
A
Annie_wang 已提交
1317 1318 1319
| keyAlias | string                 | Yes  | Alias of the target key.|
| options  | [HuksOptions](#huksoptions) | Yes  | Parameters used for initialization.|
| callback | AsyncCallback\<[HuksHandle](#hukshandle)> | Yes  | Callback used to return the handle of the initialization operation.|
A
annie_wangli 已提交
1320 1321 1322 1323 1324 1325


## huks.init

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

A
Annie_wang 已提交
1326
Initializes a key. This API uses a promise to return the result asynchronously.
A
annie_wangli 已提交
1327 1328 1329 1330 1331 1332 1333

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

**Parameters**

| Name  | Type                  | Mandatory| Description                                 |
| -------- | ---------------------- | ---- | ------------------------------------- |
A
Annie_wang 已提交
1334 1335 1336
| keyAlias | string                 | Yes  | Alias of the target key.|
| options  | [HuksOptions](#huksoptions) | Yes  | Parameters used for initialization.|
| promise | Promise\<[HuksHandle](#hukshandle)> | Yes  | Promise used to return the handle of the initialization operation.|
A
annie_wangli 已提交
1337 1338


A
Annie_wang 已提交
1339
## huks.update<sup>(deprecated)</sup>
A
annie_wangli 已提交
1340 1341 1342

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

A
Annie_wang 已提交
1343
Updates a key. This API uses an asynchronous callback to return the result.
A
annie_wangli 已提交
1344

A
Annie_wang 已提交
1345 1346
>  **NOTE**<br>This API is discarded since API version 9. You are advised to use [huks.update<sup>9+</sup>].

A
annie_wangli 已提交
1347 1348 1349 1350
**System capability**: SystemCapability.Security.Huks

**Parameters**

A
Annie_wang 已提交
1351 1352 1353 1354 1355 1356
| Name  | Type                                     | Mandatory| Description                                        |
| -------- | ----------------------------------------- | ---- | -------------------------------------------- |
| handle   | number                                    | Yes  | Handle of the **Update** operation.                        |
| token    | Uint8Array                                | No  | Token of the **Update** operation.                         |
| options  | [HuksOptions](#huksoptions)               | Yes  | Parameters of the **Update** operation.                      |
| callback | AsyncCallback\<[HuksResult](#huksresult)> | Yes  | Callback used to return the operation result.|
A
annie_wangli 已提交
1357

A
Annie_wang 已提交
1358
## huks.update<sup>(deprecated)</sup>
A
annie_wangli 已提交
1359 1360 1361

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

A
Annie_wang 已提交
1362
Updates a key. This API uses a promise to return the result asynchronously.
A
annie_wangli 已提交
1363

A
Annie_wang 已提交
1364 1365
>  **NOTE**<br>This API is discarded since API version 9. You are advised to use [huks.update<sup>9+</sup>](#huksupdate9).

A
annie_wangli 已提交
1366 1367 1368 1369
**System capability**: SystemCapability.Security.Huks

**Parameters**

A
Annie_wang 已提交
1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400
| Name | Type                               | Mandatory| Description                                        |
| ------- | ----------------------------------- | ---- | -------------------------------------------- |
| handle  | number                              | Yes  | Handle of the **Update** operation.                        |
| token   | Uint8Array                          | No  | Token of the **Update** operation.                         |
| options | [HuksOptions](#huksoptions)         | Yes  | Parameters of the **Update** operation.                      |
| promise | Promise\<[HuksResult](#huksresult)> | Yes  | Callback used to return the operation result.|

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

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

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

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

**Parameters**

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


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

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

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

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

A
Annie_wang 已提交
1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426
**Parameters**

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

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

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

Updates a key. This API uses a promise to return the result asynchronously.

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

**Parameters**

| Name | Type                               | Mandatory| Description                                        |
| ------- | ----------------------------------- | ---- | -------------------------------------------- |
| handle  | number                              | Yes  | Handle of the **Update** operation.                        |
| options | [HuksOptions](#huksoptions)         | Yes  | Parameters of the **Update** operation.                      |
| token   | Uint8Array                          | No  | Token of the **Update** operation.                         |
| promise | Promise\<[HuksResult](#huksresult)> | Yes  | Promise used to return the operation result.|
A
annie_wangli 已提交
1427 1428 1429 1430 1431

## huks.finish

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

A
Annie_wang 已提交
1432
Completes the key operation and releases resources. This API uses an asynchronous callback to return the result.
A
annie_wangli 已提交
1433 1434 1435 1436 1437 1438 1439

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

**Parameters**

| Name  | Type                  | Mandatory| Description                                 |
| -------- | ---------------------- | ---- | ------------------------------------- |
A
Annie_wang 已提交
1440 1441 1442
| handle | number           | Yes  | Handle of the **Finish** operation.|
| options  | [HuksOptions](#huksoptions) | Yes  | Parameters of the **Finish** operation.|
| callback | AsyncCallback\<[HuksResult](#huksresult)> | Yes| Callback used to return the operation result.|
A
annie_wangli 已提交
1443 1444 1445 1446 1447 1448


## huks.finish

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

A
Annie_wang 已提交
1449
Completes the key operation and releases resources. This API uses a promise to return the result asynchronously.
A
annie_wangli 已提交
1450 1451 1452 1453 1454 1455 1456

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

**Parameters**

| Name  | Type                  | Mandatory| Description                                 |
| -------- | ---------------------- | ---- | ------------------------------------- |
A
Annie_wang 已提交
1457 1458
| handle | number           | Yes  | Handle of the **Finish** operation.|
| options  | [HuksOptions](#huksoptions) | Yes  | Parameters of the **Finish** operation.|
A
Annie_wang 已提交
1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487
| promise | Promise\<[HuksResult](#huksresult)> | Yes| Promise used to return the operation result.|

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

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

Completes the key operation and releases resources. This API uses an asynchronous callback to return the result.

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

**Parameters**

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


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

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

Completes the key operation and releases resources. This API uses a promise to return the result asynchronously.

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

**Parameters**
A
annie_wangli 已提交
1488

A
Annie_wang 已提交
1489 1490 1491 1492 1493 1494
| Name | Type                               | Mandatory| Description                               |
| ------- | ----------------------------------- | ---- | ----------------------------------- |
| handle  | number                              | Yes  | Handle of the **Finish** operation.               |
| options | [HuksOptions](#huksoptions)         | Yes  | Parameters of the **Finish** operation.             |
| token   | Uint8Array                          | No  | Token for the **Finish** operation.                |
| promise | Promise\<[HuksResult](#huksresult)> | Yes  | Promise used to return the operation result.|
A
annie_wangli 已提交
1495 1496 1497 1498 1499

## huks.abort

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

A
Annie_wang 已提交
1500
Aborts the use of the key. This API uses an asynchronous callback to return the result.
A
annie_wangli 已提交
1501 1502 1503 1504 1505 1506 1507

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

**Parameters**

| Name  | Type                  | Mandatory| Description                                 |
| -------- | ---------------------- | ---- | ------------------------------------- |
A
Annie_wang 已提交
1508 1509 1510
| handle | number           | Yes  | Handle of the **Abort** operation.|
| options  | [HuksOptions](#huksoptions) | Yes  | Parameters of the **Abort** operation.|
| callback | AsyncCallback\<[HuksResult](#huksresult)> | Yes| Callback used to return the operation result.|
A
annie_wangli 已提交
1511 1512 1513 1514

**Example**

```js
A
Annie_wang 已提交
1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532
/* huks.init, huks.update, and huks.finish must be used together.
 * If an error occurs in any of them, huks.abort must be called to terminate the use of the key.
 *
 * The following uses the callback of an RSA 1024-bit key as an example.
 */
import router from '@system.router';
import huks from '@ohos.security.huks';

async function routePage() {
  let options = {
    uri: 'pages/second'
  }
  try {
    await router.push(options)
  } catch (err) {
    console.error(`fail callback, code: ${err.code}, msg: ${err.msg}`)
  }
}
A
Annie_wang 已提交
1533
var keyalias = "HuksDemoRSA";
A
annie_wangli 已提交
1534 1535
var properties = new Array();
var options = {
A
Annie_wang 已提交
1536 1537 1538
  properties: properties,
  inData: new Uint8Array(0)
};
A
Annie_wang 已提交
1539
var handle;
A
Annie_wang 已提交
1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561
var resultMessage = "";
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 已提交
1562
  huks.generateKey(keyalias, options);
A
Annie_wang 已提交
1563 1564 1565 1566 1567 1568 1569 1570 1571 1572
}
function stringToUint8Array(str) {
  var arr = [];
  for (var i = 0, j = str.length; i < j; ++i) {
    arr.push(str.charCodeAt(i));
  }
  var tmpUint8Array = new Uint8Array(arr);
  return tmpUint8Array;
}
async function huksInit() {
A
Annie_wang 已提交
1573
  await huks.init(keyalias, options).then((data) => {
A
Annie_wang 已提交
1574
    console.log(`test init data: ${JSON.stringify(data)}`);
A
Annie_wang 已提交
1575
    handle = data.handle;
A
Annie_wang 已提交
1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611
  }).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 已提交
1612
    resultMessage = "Failed to abort the use of the key. catch errorMessage:" + JSON.stringify(err)
A
Annie_wang 已提交
1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653
  });
  console.log(resultMessage);
}

@Entry
@Component
struct Index {
  build() {
    Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) {
      Text('Hello World')
        .fontSize(50)
        .fontWeight(FontWeight.Bold)
      Button() {
        Text('Tocallback')
          .fontSize(25)
          .fontWeight(FontWeight.Bold)
      }.type(ButtonType.Capsule)
      .margin({
        top: 20
      })
      .width('50%')
      .height('10%')
      .backgroundColor('#0D9FFB')
      .onClick(() => {
        routePage()
      })
      Button() {
        Text('generateKey')
          .fontSize(25)
          .fontWeight(FontWeight.Bold)
      }.type(ButtonType.Capsule)
      .margin({
        top: 20
      })
      .width('50%')
      .height('10%')
      .backgroundColor('#0D9FFB')
      .onClick(() => {
        generateKey()
      })
      Button() {
A
Annie_wang 已提交
1654
        Text('Init')
A
Annie_wang 已提交
1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667
          .fontSize(25)
          .fontWeight(FontWeight.Bold)
      }.type(ButtonType.Capsule)
      .margin({
        top: 20
      })
      .width('50%')
      .height('10%')
      .backgroundColor('#0D9FFB')
      .onClick(() => {
        huksInit()
      })
      Button() {
A
Annie_wang 已提交
1668
        Text('Update')
A
Annie_wang 已提交
1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681
          .fontSize(25)
          .fontWeight(FontWeight.Bold)
      }.type(ButtonType.Capsule)
      .margin({
        top: 20
      })
      .width('50%')
      .height('10%')
      .backgroundColor('#0D9FFB')
      .onClick(() => {
        huksUpdate()
      })
      Button() {
A
Annie_wang 已提交
1682
        Text('Finish')
A
Annie_wang 已提交
1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695
          .fontSize(25)
          .fontWeight(FontWeight.Bold)
      }.type(ButtonType.Capsule)
      .margin({
        top: 20
      })
      .width('50%')
      .height('10%')
      .backgroundColor('#0D9FFB')
      .onClick(() => {
        huksFinish()
      })
      Button() {
A
Annie_wang 已提交
1696
        Text('Abort')
A
Annie_wang 已提交
1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713
          .fontSize(25)
          .fontWeight(FontWeight.Bold)
      }.type(ButtonType.Capsule)
      .margin({
        top: 20
      })
      .width('50%')
      .height('10%')
      .backgroundColor('#0D9FFB')
      .onClick(() => {
        huksAbort()
      })
    }
    .width('100%')
    .height('100%')
  }
}
A
annie_wangli 已提交
1714 1715 1716 1717 1718 1719
```

## huks.abort

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

A
Annie_wang 已提交
1720
Aborts the use of the key. This API uses a promise to return the result asynchronously.
A
annie_wangli 已提交
1721 1722 1723 1724 1725 1726 1727

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

**Parameters**

| Name  | Type                  | Mandatory| Description                                 |
| -------- | ---------------------- | ---- | ------------------------------------- |
A
Annie_wang 已提交
1728 1729 1730
| handle | number           | Yes  | Handle of the **Abort** operation.|
| options  | [HuksOptions](#huksoptions) | Yes  | Parameters of the **Abort** operation.|
| promise | Promise\<[HuksResult](#huksresult)> | Yes| Promise used to return the operation result.|
A
annie_wangli 已提交
1731 1732 1733 1734

**Example**

```js
A
Annie_wang 已提交
1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753
/* 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.
 */
import router from '@system.router';
import huks from '@ohos.security.huks';

async function routePage() {
  let options = {
    uri: 'pages/second'
  }
  try {
    await router.push(options)
  } catch (err) {
    console.error(`fail callback, code: ${err.code}, msg: ${err.msg}`)
  }
}

A
Annie_wang 已提交
1754
var keyalias = "HuksDemoRSA";
A
annie_wangli 已提交
1755 1756
var properties = new Array();
var options = {
A
Annie_wang 已提交
1757 1758 1759
  properties: properties,
  inData: new Uint8Array(0)
};
A
Annie_wang 已提交
1760
var handle;
A
Annie_wang 已提交
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
var resultMessage = "";
function stringToUint8Array(str) {
  var arr = [];
  for (var i = 0, j = str.length; i < j; ++i) {
    arr.push(str.charCodeAt(i));
  }
  var tmpUint8Array = new Uint8Array(arr);
  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 已提交
1792
  huks.generateKey(keyalias, options, function (err, data) { });
A
Annie_wang 已提交
1793 1794 1795
}
async function huksInit() {
  return new Promise((resolve, reject) => {
A
Annie_wang 已提交
1796
    huks.init(keyalias, options, async function (err, data) {
A
Annie_wang 已提交
1797 1798
      if (data.errorCode === 0) {
        resultMessage = "Initialization successful!"
A
Annie_wang 已提交
1799
        handle = data.handle;
A
Annie_wang 已提交
1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818
      } 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 已提交
1819

A
Annie_wang 已提交
1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879
}

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)}`);
    });
  });
}
@Entry
@Component
struct Index {
  build() {
    Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) {
      Text('Hello World')
        .fontSize(50)
        .fontWeight(FontWeight.Bold)
      Button() {
        Text('to Promise')
          .fontSize(20)
          .fontWeight(FontWeight.Bold)
      }.type(ButtonType.Capsule)
      .margin({
        top: 20
      })
      .width('50%')
      .height('10%')
      .backgroundColor('#0D9FFB')
      .onClick(() => {
        router.back()
      })
      Button() {
        Text('generateKey')
          .fontSize(25)
          .fontWeight(FontWeight.Bold)
      }.type(ButtonType.Capsule)
      .margin({
        top: 20
      })
      .width('50%')
      .height('10%')
      .backgroundColor('#0D9FFB')
      .onClick(() => {
        generateKey()
      })
      Button() {
A
Annie_wang 已提交
1880
        Text('Init')
A
Annie_wang 已提交
1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893
          .fontSize(25)
          .fontWeight(FontWeight.Bold)
      }.type(ButtonType.Capsule)
      .margin({
        top: 20
      })
      .width('50%')
      .height('10%')
      .backgroundColor('#0D9FFB')
      .onClick(() => {
        huksInit()
      })
      Button() {
A
Annie_wang 已提交
1894
        Text('Update')
A
Annie_wang 已提交
1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907
          .fontSize(25)
          .fontWeight(FontWeight.Bold)
      }.type(ButtonType.Capsule)
      .margin({
        top: 20
      })
      .width('50%')
      .height('10%')
      .backgroundColor('#0D9FFB')
      .onClick(() => {
        huksUpdate()
      })
      Button() {
A
Annie_wang 已提交
1908
        Text('Finish')
A
Annie_wang 已提交
1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921
          .fontSize(25)
          .fontWeight(FontWeight.Bold)
      }.type(ButtonType.Capsule)
      .margin({
        top: 20
      })
      .width('50%')
      .height('10%')
      .backgroundColor('#0D9FFB')
      .onClick(() => {
        huksFinish()
      })
      Button() {
A
Annie_wang 已提交
1922
        Text('Abort')
A
Annie_wang 已提交
1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939
          .fontSize(25)
          .fontWeight(FontWeight.Bold)
      }.type(ButtonType.Capsule)
      .margin({
        top: 20
      })
      .width('50%')
      .height('10%')
      .backgroundColor('#0D9FFB')
      .onClick(() => {
        huksAbort()
      })
    }
    .width('100%')
    .height('100%')
  }
}
A
annie_wangli 已提交
1940 1941 1942 1943 1944 1945 1946 1947
```

## HuksParam

Defines the **param** in the **properties** array of **options** used in the APIs.

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

A
Annie_wang 已提交
1948 1949 1950
| Name| Type                               | Mandatory| Description        |
| ------ | ----------------------------------- | ---- | ------------ |
| tag    | [HuksTag](#hukstag)                 | Yes  | Tag.      |
A
Annie_wang 已提交
1951
| value  | boolean\|number\|bigint\|Uint8Array | Yes  | Value of the tag.|
A
annie_wangli 已提交
1952 1953 1954 1955 1956 1957 1958 1959 1960

## HuksOptions

Defines the **options** used in the APIs. 

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

| Name    | Type             | Mandatory| Description                    |
| ---------- | ----------------- | ---- | ------------------------ |
A
Annie_wang 已提交
1961
| properties | Array\<[HuksParam](#huksparam)> | No  | Array used to hold **HuksParam**.|
A
annie_wangli 已提交
1962 1963 1964 1965 1966 1967 1968 1969
| inData     | Uint8Array        | No  | Input data.              |

## HuksHandle

Defines the HUKS handle structure.

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

A
Annie_wang 已提交
1970
| Name    | Type            | Mandatory| Description    |
A
annie_wangli 已提交
1971
| ---------- | ---------------- | ---- | -------- |
A
Annie_wang 已提交
1972 1973
| errorCode  | number           | Yes  | Error code.|
| handle    | number       | Yes| Value of the handle.|
A
Annie_wang 已提交
1974
| token | Uint8Array | No| Challenge information obtained after the [init](#huksinit) operation.|
A
annie_wangli 已提交
1975 1976 1977 1978 1979 1980 1981 1982 1983 1984


## HuksResult

Defines the **HuksResult** structure.

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



A
Annie_wang 已提交
1985 1986 1987 1988 1989 1990
| 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.|