diff --git a/en/application-dev/reference/apis/js-apis-huks.md b/en/application-dev/reference/apis/js-apis-huks.md index 1811193f0a4fee41e8f3ec23d0705ab24e0b43a1..cad81d4e80c3303859274b2b79c3258bf8d2556c 100644 --- a/en/application-dev/reference/apis/js-apis-huks.md +++ b/en/application-dev/reference/apis/js-apis-huks.md @@ -75,7 +75,7 @@ Generates a key. This API uses an asynchronous callback to return the result. | -------- | --------------------------- | ---- | --------------------------------------------- | | keyAlias | string | Yes | Alias of the key. | | options | [HuksOptions](#huksoptions) | Yes | Tags required for generating the key. The algorithm, key purpose, and key length are mandatory.| -| callback | AsyncCallback\ | Yes | Callback that returns no value.| +| callback | AsyncCallback\ | Yes | Callback invoked to return the result. If the operation fails, **err** is returned.| **Example** @@ -186,7 +186,7 @@ Deletes a key. This API uses an asynchronous callback to return the result. | -------- | --------------------------- | ---- | --------------------------------------------- | | keyAlias | string | Yes | Key alias passed in when the key was generated. | | options | [HuksOptions](#huksoptions) | Yes | Empty object (leave this parameter empty). | -| callback | AsyncCallback\ | Yes | Callback that returns no value.| +| callback | AsyncCallback\ | Yes | Callback invoked to return the result. If the operation fails, **err** is returned.| **Example** @@ -289,7 +289,7 @@ Imports a key in plaintext. This API uses an asynchronous callback to return the | -------- | --------------------------- | ---- | --------------------------------------------- | | keyAlias | string | Yes | Alias of the key. | | options | [HuksOptions](#huksoptions) | Yes | Tags required for the import and key to import. The algorithm, key purpose, and key length are mandatory.| -| callback | AsyncCallback\ | Yes | Callback that returns no value.| +| callback | AsyncCallback\ | Yes | Callback invoked to return the result. If the operation fails, **err** is returned.| **Example** @@ -426,7 +426,7 @@ Obtains the certificate used to verify a key. This API uses an asynchronous call | -------- | ---------------------------------------------------- | ---- | --------------------------------------------- | | keyAlias | string | Yes | Alias of the key. The certificate to be obtained stores the key. | | options | [HuksOptions](#huksoptions) | Yes | Parameters and data required for obtaining the certificate. | -| callback | AsyncCallback<[HuksReturnResult](#huksreturnresult9)> | Yes | Callback invoked to return the result. If the operation is successful, no **err** value is returned; otherwise, an error code is returned.| +| callback | AsyncCallback<[HuksReturnResult](#huksreturnresult9)> | Yes | Callback invoked to return the result. If the operation fails, **err** is returned.| **Example** @@ -553,7 +553,7 @@ Obtains the certificate used to verify a key. This API uses a promise to return | Type | Description | | ---------------------------------------------- | --------------------------------------------- | -| Promise<[HuksReturnResult](#huksreturnresult9)> | Promise used to return the result. If the operation is successful, no **err** value is returned; otherwise, an error code is returned.| +| Promise<[HuksReturnResult](#huksreturnresult9)> | Promise used to return the result. If the operation fails, **err** is returned.| **Example** @@ -676,7 +676,7 @@ Imports a wrapped key. This API uses an asynchronous callback to return the resu | 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. The algorithm, key purpose, and key length are mandatory.| -| callback | AsyncCallback\ | Yes | Callback that returns no value.| +| callback | AsyncCallback\ | Yes | Callback invoked to return the result. If the operation fails, **err** is returned.| **Example** @@ -1097,9 +1097,9 @@ let emptyOptions = { try { huks.isKeyItemExist(keyAlias, emptyOptions, function (error, data) { if (error) { - console.info(`callback: isKeyItemExist success, data = ${JSON.stringify(data)}`); - } else { console.error(`callback: isKeyItemExist failed, code: ${error.code}, msg: ${error.message}`); + } else { + console.info(`callback: isKeyItemExist success, data = ${JSON.stringify(data)}`); } }); } catch (error) { @@ -1312,7 +1312,7 @@ Aborts the use of the key. This API uses an asynchronous callback to return the | -------- | --------------------------- | ---- | ------------------------------------------- | | handle | number | Yes | Handle of the **Abort** operation. | | options | [HuksOptions](#huksoptions) | Yes | Parameters of the **Abort** operation. | -| callback | AsyncCallback\ | Yes | Callback that returns no value.| +| callback | AsyncCallback\ | Yes | Callback invoked to return the result. If the operation fails, **err** is returned.| **Example** @@ -1580,7 +1580,7 @@ async function huksFinish() { async function huksAbort() { console.log('enter huksAbort'); try { - await huks.abortSession(keyAlias, options) + await huks.abortSession(handle, options) .then ((data) => { console.info(`promise: abortSession success`); }) @@ -1602,26 +1602,26 @@ For details about the error codes, see [KUKS Error Codes](../errorcodes/errorcod **System capability**: SystemCapability.Security.Huks -| Name | Value| Description | -| ---------------------------------------------- | -------- |--------------------------- | -| HUKS_ERR_CODE_PERMISSION_FAIL | 201 | Permission verification failed. | -| HUKS_ERR_CODE_ILLEGAL_ARGUMENT | 401 | Invalid parameters are detected. | -| HUKS_ERR_CODE_NOT_SUPPORTED_API | 801 | The API is not supported. | -| HUKS_ERR_CODE_FEATURE_NOT_SUPPORTED | 12000001 | The feature is not supported. | -| HUKS_ERR_CODE_MISSING_CRYPTO_ALG_ARGUMENT | 12000002 | Key algorithm parameters are missing. | -| HUKS_ERR_CODE_INVALID_CRYPTO_ALG_ARGUMENT | 12000003 | Invalid key algorithm parameters are detected. | -| HUKS_ERR_CODE_FILE_OPERATION_FAIL | 12000004 | The file operation failed. | -| HUKS_ERR_CODE_COMMUNICATION_FAIL | 12000005 | The communication failed. | -| HUKS_ERR_CODE_CRYPTO_FAIL | 12000006 | Failed to operate the algorithm library. | -| HUKS_ERR_CODE_KEY_AUTH_PERMANENTLY_INVALIDATED | 12000007 | Failed to access the key because the key has expired.| -| HUKS_ERR_CODE_KEY_AUTH_VERIFY_FAILED | 12000008 | Failed to access the key because the authentication has failed.| -| HUKS_ERR_CODE_KEY_AUTH_TIME_OUT | 12000009 | Key access timed out.| -| HUKS_ERR_CODE_SESSION_LIMIT | 12000010 | The number of key operation sessions has reached the limit. | -| HUKS_ERR_CODE_ITEM_NOT_EXIST | 12000011 | The target object does not exist. | -| HUKS_ERR_CODE_EXTERNAL_ERROR | 12000012 | An external error occurs. | -| HUKS_ERR_CODE_CREDENTIAL_NOT_EXIST | 12000013 | The credential does not exist. | -| HUKS_ERR_CODE_INSUFFICIENT_MEMORY | 12000014 | The memory is insufficient. | -| HUKS_ERR_CODE_CALL_SERVICE_FAILED | 12000015 | Failed to call other system services. | +| Name | Value| Description | +| ---------------------------------------------- | -------- |--------------------------- | +| HUKS_ERR_CODE_PERMISSION_FAIL | 201 | Permission verification failed. | +| HUKS_ERR_CODE_ILLEGAL_ARGUMENT | 401 | Invalid parameters are detected. | +| HUKS_ERR_CODE_NOT_SUPPORTED_API | 801 | The API is not supported. | +| HUKS_ERR_CODE_FEATURE_NOT_SUPPORTED | 12000001 | The feature is not supported. | +| HUKS_ERR_CODE_MISSING_CRYPTO_ALG_ARGUMENT | 12000002 | Key algorithm parameters are missing. | +| HUKS_ERR_CODE_INVALID_CRYPTO_ALG_ARGUMENT | 12000003 | Invalid key algorithm parameters are detected. | +| HUKS_ERR_CODE_FILE_OPERATION_FAIL | 12000004 | The file operation failed. | +| HUKS_ERR_CODE_COMMUNICATION_FAIL | 12000005 | The communication failed. | +| HUKS_ERR_CODE_CRYPTO_FAIL | 12000006 | Failed to operate the algorithm library. | +| HUKS_ERR_CODE_KEY_AUTH_PERMANENTLY_INVALIDATED | 12000007 | Failed to access the key because the key has expired.| +| HUKS_ERR_CODE_KEY_AUTH_VERIFY_FAILED | 12000008 | Failed to access the key because the authentication has failed.| +| HUKS_ERR_CODE_KEY_AUTH_TIME_OUT | 12000009 | Key access timed out.| +| HUKS_ERR_CODE_SESSION_LIMIT | 12000010 | The number of key operation sessions has reached the limit. | +| HUKS_ERR_CODE_ITEM_NOT_EXIST | 12000011 | The target object does not exist. | +| HUKS_ERR_CODE_EXTERNAL_ERROR | 12000012 | An external error occurs. | +| HUKS_ERR_CODE_CREDENTIAL_NOT_EXIST | 12000013 | The credential does not exist. | +| HUKS_ERR_CODE_INSUFFICIENT_MEMORY | 12000014 | The memory is insufficient. | +| HUKS_ERR_CODE_CALL_SERVICE_FAILED | 12000015 | Failed to call other system services. | ## HuksKeyPurpose @@ -1789,7 +1789,7 @@ Enumerates the tag transfer modes. ## HuksUnwrapSuite9+ -Enumerates the algorithm suites required for encrypted imports. +Enumerates the algorithm suites used for importing an encrypted key. **System capability**: SystemCapability.Security.Huks diff --git a/en/application-dev/security/figures/huks_import_wrapped_key.png b/en/application-dev/security/figures/huks_import_wrapped_key.png index 8ab098ace4f24884fa754acfc66f70b3df4b6162..f798f0c9cf93117ee47e4ba68c5024528fabb4f2 100644 Binary files a/en/application-dev/security/figures/huks_import_wrapped_key.png and b/en/application-dev/security/figures/huks_import_wrapped_key.png differ diff --git a/en/application-dev/security/figures/huks_key_user_auth_work_flow.png b/en/application-dev/security/figures/huks_key_user_auth_work_flow.png index 476279901c0600132f6311c7b4ab316c5319da5f..d41b45a427c9a441bdb2e383f48e640d5fe8f387 100644 Binary files a/en/application-dev/security/figures/huks_key_user_auth_work_flow.png and b/en/application-dev/security/figures/huks_key_user_auth_work_flow.png differ diff --git a/en/application-dev/security/huks-guidelines.md b/en/application-dev/security/huks-guidelines.md index bae3fd15ece4cbe1ceac8b56dfec1f62723d04f4..59a9bc546ad1db93e6568f1a13d0dcfc8ece4876 100644 --- a/en/application-dev/security/huks-guidelines.md +++ b/en/application-dev/security/huks-guidelines.md @@ -3,25 +3,23 @@ ## Key Generation -The HUKS provides the capability of randomly generating keys for services. For a key generated by the HUKS, its plaintext will never be exposed outside throughout the lifecycle. This ensures that no one can access the plaintext of the key. Even the service that generates the key can call APIs provided by the HUKS to perform key operations and obtain the operation result, rather than accessing the key. +The HUKS provides the capability of randomly generating keys for services. For a key generated by the HUKS, the plaintext will never be exposed outside throughout the lifecycle. No one can access the plaintext of the key. Even the service, for which the key is generated, can call APIs provided by the HUKS to perform operations on the key and obtain the operation result, but not access the key. **How to Develop** -Use [huks.generateKeyItem(keyAlias,options,callback)](../reference/apis/js-apis-huks.md#huksgeneratekeyitem9) to generate a key. You need to pass in the key alias in **keyAlias**, a key attribute set in **options**, and **callback** to result the result asynchronously. For details about the APIs, see [HUKS](../reference/apis/js-apis-huks.md). - +Use [huks.generateKeyItem(keyAlias,options,callback)](../reference/apis/js-apis-huks.md#huksgeneratekeyitem9) to generate a key. You need to pass in the key alias in **keyAlias**, key attributes in **options**, and **callback** to return the result asynchronously. For details about the APIs, see [HUKS](../reference/apis/js-apis-huks.md). +Procedure: 1. Determine the key alias. -2. Initialize the key attributes.
Use [HuksParam](../reference/apis/js-apis-huks.md#huksparam) to encapsulate key attributes. Use a **HuksParam** array to assign values to the **properties** field of [HuksOptions](../reference/apis/js-apis-huks.md#huksoptions). The parameters [HuksKeyAlg](../reference/apis/js-apis-huks.md#hukskeyalg), [HuksKeySize](../reference/apis/js-apis-huks.md#hukskeysize), and [HuksKeyPurpose](../reference/apis/js-apis-huks.md#hukskeypurpose) are mandatory. +2. Initialize the key attributes.
Use [HuksParam](../reference/apis/js-apis-huks.md#huksparam) to encapsulate key attributes and use a **HuksParam** array to assign values to the **properties** field of [HuksOptions](../reference/apis/js-apis-huks.md#huksoptions). The parameters [HuksKeyAlg](../reference/apis/js-apis-huks.md#hukskeyalg), [HuksKeySize](../reference/apis/js-apis-huks.md#hukskeysize), and [HuksKeyPurpose](../reference/apis/js-apis-huks.md#hukskeypurpose) are mandatory. 3. Pass in the key alias and key parameter set to generate a key. - - > **NOTE** > > The key alias cannot exceed 64 bytes. -**Sample code** +**Sample Code** ```ts /* @@ -30,7 +28,7 @@ Use [huks.generateKeyItem(keyAlias,options,callback)](../reference/apis/js-apis- import huks from '@ohos.security.huks'; /* - * Determine the key alias and encapsulate the key attribute set. + * Determine the key alias and encapsulate the key attributes. */ let keyAlias = 'dh_key'; let properties = new Array(); @@ -96,7 +94,7 @@ async function TestGenKey() { ``` ## Key Import -If the key is generated outside the HUKS (for example, generated through key agreement or by a server), the application can import the key to the HUKS for management. The HUKS supports import of keys in plaintext. However, if keys are imported in plaintext, the keys are exposed in the REE memory. This operation applies to lightweight devices or security-insensitive services. For security-sensitive services, use the secure import provided by the HUKS. Secure import allows the keys generate keys by services to be transferred to the HUKS through an end-to-end encrypted transmission channel. +A key generated outside the HUKS (for example, generated through key agreement or by a server) can be imported to the HUKS for management. The HUKS supports import of keys in plaintext. However, if a key is imported in plaintext, the key is exposed in the REE memory. This operation applies to lightweight devices or security-insensitive services. For security-sensitive services, use the secure import provided by the HUKS. Secure import allows the keys generated for services to be transferred to the HUKS through an end-to-end encrypted transmission channel. Once a key is imported to the HUKS, its plaintext will not be exposed outside the HUKS throughout the lifecycle of the key. @@ -105,16 +103,16 @@ Once a key is imported to the HUKS, its plaintext will not be exposed outside th ### Importing a Key in Plaintext -Use [huks.importKeyItem(keyAlias,options,callback)](../reference/apis/js-apis-huks.md#huksimportkeyitem9) to import a key in plaintext. You need to pass in the key alias in **keyAlias**, key material and attribute set in **options**, and **callback** to return the result asynchronously. For details about the APIs, see [HUKS](../reference/apis/js-apis-huks.md). +Use [huks.importKeyItem(keyAlias,options,callback)](../reference/apis/js-apis-huks.md#huksimportkeyitem9) to import a key in plaintext. You need to pass in the key alias in **keyAlias**, key material and attributes in **options**, and **callback** to return the result asynchronously. For details about the APIs, see [HUKS](../reference/apis/js-apis-huks.md). 1. Determine the key alias. -2. Encapsulate the key material and key attribute set.
The key material must comply with [HUKS key material formats](./huks-appendix.md#key-material-formats). The **inData** value of [HuksOptions](../reference/apis/js-apis-huks.md#huksoptions) must be in the Uint8Array form. Encapsulate key attributes in [HuksParam](../reference/apis/js-apis-huks.md#huksparam), and use a **HuksParam** array to assign values to the **properties** field. The key attribute set must contain [HuksKeyAlg](../reference/apis/js-apis-huks.md#hukskeyalg), [HuksKeySize](../reference/apis/js-apis-huks.md#hukskeysize), and [HuksKeyPurpose](../reference/apis/js-apis-huks.md#hukskeypurpose). +2. Encapsulate the key material and key attributes.
The key material must comply with [HUKS key material formats](./huks-appendix.md#key-material-formats). The **inData** value of [HuksOptions](../reference/apis/js-apis-huks.md#huksoptions) must be in the Uint8Array format. Encapsulate key attributes in [HuksParam](../reference/apis/js-apis-huks.md#huksparam), and use a **HuksParam** array to assign values to the **properties** field. The key attributes must contain [HuksKeyAlg](../reference/apis/js-apis-huks.md#hukskeyalg), [HuksKeySize](../reference/apis/js-apis-huks.md#hukskeysize), and [HuksKeyPurpose](../reference/apis/js-apis-huks.md#hukskeypurpose). 3. Import the key. -**Sample code** +**Sample Code** ```ts /* @@ -133,7 +131,7 @@ let plainTextSize32 = new Uint8Array([ let keyAlias = 'AES256Alias_sample'; /* - * Encapsulate the key attribute set and key material. + * Encapsulate the key attributes and key material. */ let properties = new Array(); properties[0] = { @@ -174,7 +172,7 @@ try { Check whether the key exists. If yes, the key is imported successfully. -**Sample code** +**Sample Code** ```ts import huks from '@ohos.security.huks'; @@ -207,13 +205,11 @@ try { } ``` -### Importing a Wrapped Key - -Compared with import of plaintext, secure import has complex key material and operations. The following figure illustrates the development process of secure import. - +### Importing a Key Securely +Compared with import of plaintext, secure import involves complex key material and operations. The following figure illustrates the basic development process of secure import. -**Figure 2** Development process of secure import +**Figure 1** Secure import process ![huks_import_wrapped_key](figures/huks_import_wrapped_key.png) @@ -223,39 +219,36 @@ Compared with import of plaintext, secure import has complex key material and op **Available APIs** You need to use the APIs for generating a key, exporting a public key, importing a wrapped key, and deleting a key in sequence. - -**Table 1** APIs for secure import - | API | Description | | -------------------------------------- | ----------------------------| |generateKeyItem(keyAlias: string, options: HuksOptions, callback: AsyncCallback\) : void| Generates a key.| -|exportKeyItem(keyAlias: string, options: HuksOptions, callback: AsyncCallback\) : void| Exports the public key of a key pair.| -|importWrappedKeyItem(keyAlias: string, wrappingKeyAlias: string, options: HuksOptions, callback: AsyncCallback\) : void|Imports a wrapped key.| -|deleteKeyItem(keyAlias: string, options: HuksOptions, callback: AsyncCallback\) : void|Deletes a key.| +|exportKeyItem(keyAlias: string, options: HuksOptions, callback: AsyncCallback) : void| Exports the public key of a key pair.| +|importWrappedKeyItem(keyAlias: string, wrappingKeyAlias: string, options: HuksOptions, callback: AsyncCallback) : void|Imports an wrapped key.| +|deleteKeyItem(keyAlias: string, options: HuksOptions, callback: AsyncCallback) : void|Deletes a key.| ->**NOTE**
The public key plaintext material returned by **exportKeyItem()** is encapsulated in X.509 format, and the key material to be imported by **importWrappedKeyItem()** must be encapsulated in **LengthData-Data** format. Specifically, the application needs to apply for a Uint8Array and encapsulate the Uint8Array in the sequence listed in the following table. +>**NOTE**
The public key plaintext material returned by **exportKeyItem()** is encapsulated in X.509 format, and the key material to be imported by **importWrappedKeyItem()** must be encapsulated in **LengthData-Data** format. Specifically, the application needs to request a Uint8Array and encapsulate the Uint8Array in the sequence listed in the following table. **Table 2** Format of the wrapped key material -| Content| Public Key Length (Lpk2)| Public Key pk2| k2 AAD2 Length LAAD2| k2 Encryption Parameter AAD2| k2 Nonce2 Length LNonce2| k2 Encryption Parameter Nonce2| +| Content| Public Key Length (Lpk2)| Public Key (pk2) | k2 AAD Length (LAAD2) | k2 AAD (AAD2) | k2 Nonce Length (LNonce2) | k2 Nonce (Nonce2) | | :--: |:----:|:----: |:----: | :----: | :----:|:----:| |Length| 4 bytes|Lpk2 bytes| 4 bytes| LAAD2 bytes| 4 bytes| LNonce2 bytes| -| Content| k2 AEAD2 Length LAEAD2| k2 Encryption Parameter AEAD2| k3 Ciphertext Length Lk3_enc| k3 Ciphertext k3_enc| k3 AAD3 Length LAAD3| k3 Encryption Parameter AAD3| +| Content| k2 AEAD Length (LAEAD2) | k2 AEAD (AEAD2) | k3 Ciphertext Length (Lk3_enc) | k3 Ciphertext (k3_enc) | k3 AAD Length (LAAD3) | k3 AAD (AAD3) | |Length| 4 bytes|LAEAD2 bytes| 4 bytes| Lk3_enc bytes| 4 bytes| LAAD3 bytes| -| Content| k3 Nonce3 Length LNonce3| k3 Encryption Parameter Nonce3| k3 AEAD3 Length LAEAD3| k3 Encryption Parameter AEAD3| Length of **k1'_size** Lk1'_size| Key Plaintext Material Length k1'_size| +| Content| k3 Nonce Length (LNonce3) | k3 Nonce (Nonce3) | k3 AEAD Length (LAEAD3) | k3 AEAD (AEAD3) | Length of **k1'_size** (Lk1'_size) | Key Plaintext Material Length (k1'_size) | |Length| 4 bytes|LNonce3 bytes| 4 bytes| LAEAD3 bytes| 4 bytes| Lk1'_size bytes| -|Content|k1' Ciphertext Length Lk1'_enc| k1' ciphertext k1'_enc| | | | | +|Content|k1' Ciphertext Length (Lk1'_enc)| k1' ciphertext (k1'_enc) | | | | | |Length| 4 bytes|Lk1'_enc bytes| | | | | **How to Develop** -The following example provides the development involving HUKS APIs (using the ECDH key agreement suite). The operations performed by the service are not included. -1. Convert the key material to the HUKS format. -2. Generate a wrapping key (a key used for secure import). +The following example presents the development involving HUKS APIs (using the ECDH key agreement suite). The operations performed by the service are not included. +1. Convert the key material into the HUKS format. +2. Generate a key for secure import. 3. Export the public key material. -4. Wrap the key material to be imported. -5. Import the wrapped key material. -6. Delete the wrapping key. +4. Encapsulate (encrypt) the key material to be imported. +5. Import the encapsulated key material. +6. Delete the key used for secure import. **Sample code** @@ -293,9 +286,9 @@ let inputEccPair = new Uint8Array([ ]); /* - * Encapsulate the key attribute set. + * Encapsulate the key attributes. */ -// Attribute set for the wrapping key. +// Attributes for the key used for secure import. let properties = new Array(); properties[0] = { tag: huks.HuksTag.HUKS_TAG_ALGORITHM, @@ -392,7 +385,7 @@ async function publicExportKeyFunc(keyAlias:string, huksOptions:huks.HuksOptions } } -// Generate a wrapping key (the key is imported here). +// Generate a key used for secure import (the key is imported here). function importKeyItem(keyAlias:string, huksOptions:huks.HuksOptions, throwObject) { return new Promise((resolve, reject) => { try { @@ -468,7 +461,7 @@ function importWrappedKeyItem(keyAlias:string, wrappingKeyAlias:string, huksOpti }); } -// Delete the wrapping key. +// Delete the key used for secure import. function deleteKeyItem(keyAlias:string, huksOptions:huks.HuksOptions, throwObject) { return new Promise((resolve, reject) => { try { @@ -509,12 +502,12 @@ async function publicDeleteKeyFunc(keyAlias:string, huksOptions:huks.HuksOptions async function ImportWrappedKeyNormalTest() { console.info(`enter ImportWrapKey test`); /* - * Generate a wrapping key (the key is imported here). + * Generate a key for secure import (the key is imported here). */ await publicImportKeyFunc(wrapAlias, huksOptions); /* - * Export the public key material of the wrapping key. + * Export the public key material of the key used for secure import. */ await publicExportKeyFunc(wrapAlias, huksOptions); @@ -524,11 +517,11 @@ async function ImportWrappedKeyNormalTest() { /* Encapsulate the key material to be imported. * Create the importOptions.inData field in the following format: - * pk2 length (4 bytes) + pk2 data + AAD2 length (4 bytes) + AAD2 data + - * Nonce2 length (4 bytes) + Nonce2 data + AEAD2 length (4 bytes) + AEAD2 data + - * k3 ciphertext length (4 bytes) + k3 data + AAD3 length (4 bytes) + AAD3 data + - * Nonce3 length (4 bytes) +Nonce3 data + AEAD3 length (4 bytes) + AEAD3 data + - * k1'_size length (4 bytes) + k1'_size + k1'_enc length (4 bytes) + k1'_enc data + * pk2 length (4 bytes) + pk2 + AAD2 length (4 bytes) + AAD2 + + * Nonce2 length (4 bytes) + Nonce2 + AEAD2 length (4 bytes) + AEAD2 + + * k3 ciphertext length (4 bytes) + k3 ciphertext + AAD3 length (4 bytes) + AAD3 + + * Nonce3 length (4 bytes) +Nonce3 + AEAD3 length (4 bytes) + AEAD3 + + * k1'_size length (4 bytes) + k1'_size + k1'_enc length (4 bytes) + k1'_enc */ let inputKey = new Uint8Array([ 0x5b, 0x00, 0x00, 0x00, // ECC-P-256 public key length (DER format defined in X.509): 91 @@ -581,14 +574,14 @@ async function ImportWrappedKeyNormalTest() { importOptions.inData = inputKey; /* - * Import the wrapped key material. + * Import the encapsulated key material. */ await publicImportWrappedKey(importAlias, wrapAlias, importOptions); /* - * Delete the wrapping key. + * Delete the key used for secure import. */ - await publicDeleteKeyFunc(wrapAlias, huksOptions); + await publicDeleteKeyFunc(wrapAlias, huksOptions); } ``` @@ -596,13 +589,13 @@ async function ImportWrappedKeyNormalTest() { Check whether the key exists. If yes, the key is imported successfully. -**Sample code** +**Sample Code** ```ts import huks from '@ohos.security.huks'; /* - * Determine the key alias and encapsulate the key attribute set. + * Determine the key alias and encapsulate the key attributes. */ let keyAlias = 'importAlias'; let isKeyExist; @@ -642,7 +635,7 @@ To ensure data confidentiality and integrity, you may need to encrypt or decrypt **General Development Process** The HUKS operates data based on key sessions. The general process is as follows: -1. (Mandatory) Use [huks.initSession()](../reference/apis/js-apis-huks.md#huksinitsession9) to initialize a key session.
You need to pass in the key alias and key operation parameters to initialize a key session, and obtain the session handle. The key operation parameters must contain the parameters required by the cipher algorithm, including the cipher algorithm, key size, key purpose, working mode, padding mode, hash mode, IV, nonce, and AAD. If access control is set for the key, other parameters are required. For details, see [Key Access Control](#key-access-control). +1. (Mandatory) Use [huks.initSession()](../reference/apis/js-apis-huks.md#huksinitsession9) to initialize a key session.
You need to pass in the key alias and key operation parameters to initialize a key session, and obtain a session handle. The key operation parameters must contain the parameters required by the cipher algorithm, including the cipher algorithm, key size, key purpose, working mode, padding mode, hash mode, IV, nonce, and AAD. If access control is set for the key, other parameters are required. For details, see [Key Access Control](#key-access-control). 2. (Optional) Use [huks.updateSession()](../reference/apis/js-apis-huks.md#huksupdatesession9) to pass in data by segment.
Perform this step only if the data exceeds 100 KB or the cipher algorithm requires operations by data segment. Otherwise, skip this step. 3. (Mandatory) Use [huks.finishSession()](../reference/apis/js-apis-huks.md#huksfinishsession9) to finalize the key session operation.
Pass in the last data segment and perform the key session operation. If an error occurs during the process or the data passed in is not required, use [huks.abortSession()](../reference/apis/js-apis-huks.md#huksabortsession9) to abort the session. @@ -654,7 +647,7 @@ The HUKS operates data based on key sessions. The general process is as follows: import huks from '@ohos.security.huks'; /* - * Determine the key alias and encapsulate the key attribute set. + * Determine the key alias and encapsulate the key attributes. */ let srcKeyAlias = 'sm4_Key'; let IV = '0000000000000000'; @@ -979,11 +972,13 @@ async function testSm4Cipher() { import huks from '@ohos.security.huks'; /* - * Determine the key alias and encapsulate the key attribute set. + * Determine the key alias and encapsulate the key attributes. */ let generateKeyAlias = 'sm2_Key'; let importKeyAlias = 'importKeyAlias'; -let signVerifyInData = 'signVerifyInDataForTest'; +let signVerifyInData1 = 'signVerifyInDataForTestFirstText'; +let signVerifyInData2 = 'signVerifyInDataForTestSecondText'; +let signVerifyInData = [signVerifyInData1, signVerifyInData2]; let handle; let exportKey; let finishOutData; @@ -1340,9 +1335,10 @@ async function testSm2SignVerify() { await publicInitFunc(generateKeyAlias, signOptions); signHandle = handle; - signOptions.inData = StringToUint8Array(signVerifyInData) - await publicUpdateFunc(signHandle, signOptions); - + for (var index = 0; index < signVerifyInData.length; index++) { + signOptions.inData = StringToUint8Array(signVerifyInData[index]); + await publicUpdateFunc(signHandle, signOptions); + } signOptions.inData = new Uint8Array(new Array()); await publicFinishFunc(signHandle, signOptions); signFinishOutData = finishOutData; @@ -1359,10 +1355,10 @@ async function testSm2SignVerify() { await publicInitFunc(importKeyAlias, verifyOptions); verifyHandle = handle; - - verifyOptions.inData = StringToUint8Array(signVerifyInData) - await publicUpdateFunc(verifyHandle, verifyOptions); - + for (var index = 0; index < signVerifyInData.length; index++) { + verifyOptions.inData = StringToUint8Array(signVerifyInData[index]); + await publicUpdateFunc(verifyHandle, verifyOptions); + } verifyOptions.inData = signFinishOutData; await publicFinishFunc(verifyHandle, verifyOptions); @@ -1379,7 +1375,7 @@ async function testSm2SignVerify() { import huks from '@ohos.security.huks'; /* - * Determine the key alias and encapsulate the key attribute set. + * Determine the key alias and encapsulate the key attributes. */ let srcKeyAliasFirst = "AgreeX25519KeyFirstAlias"; let srcKeyAliasSecond = "AgreeX25519KeySecondAlias"; @@ -1743,7 +1739,7 @@ async function testAgree() { import huks from '@ohos.security.huks'; /* - * Determine the key alias and encapsulate the key attribute set. + * Determine the key alias and encapsulate the key attributes. */ let srcKeyAlias = "hkdf_Key"; let deriveHkdfInData = "deriveHkdfTestIndata"; @@ -2064,83 +2060,69 @@ The HUKS also restricts the key usage. For example, the AES keys can only be use When generating or importing a key, you can enable user identity authentication for the key use. You can specify a subset of credentials (lock screen password, fingerprint, and face) for user identity authentication. After a key is generated or imported, unauthorized key access can be prevented even if the application process is attacked. Key access control applies to security-sensitive scenarios, such as password-free login, password-free payment, and automatic password filling. -In addition to user identity authentication, the authorized key access type (key expiration condition) must be either of the following types: -- Invalidate the key when the screen lock password is cleared.
This type takes effect only when a screen lock password has been set. If the screen lock password is cleared, the key becomes invalid permanently. The key will not be invalidated if the screen lock password is modified. Use this type for user-related data protection or access based on screen lock passwords. -- Invalidate the key when new biometric enrollments are added.
This type takes effect only when at least one biometric feature (such as fingerprint) has been enrolled. The key becomes invalid permanently once a new biometric feature is enrolled. The key will not be invalidated if the biometric feature is deleted. You can use this type for scenarios, such as password-free login or payment. +In addition to user identity authentication, the HUKS provides the following modes ([HuksAuthAccessType](../reference/apis/js-apis-huks.md#huksauthaccesstype9)) for automatically invalidating a key: +- Invalidate the key when the screen lock password is cleared.
This mode takes effect only when a screen lock password has been set. If the screen lock password is cleared, the key becomes invalid permanently. The key will not be invalidated if the screen lock password is modified. This mode applies to user-related data protection and access based on screen lock passwords. +- Invalidate the key when new biometric enrollments are added.
This mode takes effect only when at least one biometric feature (such as fingerprint) has been enrolled. The key becomes invalid permanently once a new biometric feature is enrolled. The key will not be invalidated if the biometric feature is deleted. This mode applies to scenarios, such as password-free login or payment. -To ensure the validity of the user authentication result, the HUKS supports challenge value verification. Before user identity authentication, obtain the challenge (in the [HuksSessionHandle](../reference/apis/js-apis-huks.md#hukssessionhandle9) returned by [huks.initSession()](../reference/apis/js-apis-huks.md#huksinitsession9)) from the HUKS and pass in the challenge in [userIAM_userAuth.getAuthInstance](../reference/apis/js-apis-useriam-userauth.md#authinstance9). The challenge value of the authentication token is then verified during key operations. +To ensure the validity of the user authentication result, the HUKS supports challenge verification. Before user identity authentication, obtain the challenge (in [HuksSessionHandle](../reference/apis/js-apis-huks.md#hukssessionhandle9) returned by [huks.initSession()](../reference/apis/js-apis-huks.md#huksinitsession9)) from the HUKS and pass in the challenge in [userIAM_userAuth.getAuthInstance](../reference/apis/js-apis-useriam-userauth.md#authinstance9). The challenge of the authentication token is then verified during key operations. **How to Develop** -If secondary user identity authentication is enabled for a key, initialize the key session and obtain the challenge value. Then, pass the challenge value to **userIAM_userAuth.getAuthInstance()** for user identity authentication. After the authentication is successful, an authentication token is obtained. The authentication token can be used to perform key operations. +If secondary user identity authentication is enabled for a key, initialize the key session and obtain the challenge. Then, pass the challenge to **userIAM_userAuth.getAuthInstance()** for user identity authentication. After the authentication is successful, an authentication token is obtained. The authentication token can be used to perform key operations. ![huks_key_user_auth_work_flow](./figures/huks_key_user_auth_work_flow.png) **Available APIs** -1. [HuksUserAuthType](../reference/apis/js-apis-huks.md#huksuserauthtype9), [HuksAuthAccessType](../reference/apis/js-apis-huks.md#huksauthaccesstype9), and [HuksChallengeType](../reference/apis/js-apis-huks.md#hukschallengetype9) in the key attribute set are mandatory for key generation/import. - - **Table 3** User authentication types - - | Name | Value | Description | - | ------------------------------- |---|------------------------ | - | HUKS_USER_AUTH_TYPE_FINGERPRINT |0x0001 | Fingerprint authentication. | - | HUKS_USER_AUTH_TYPE_FACE |0x0002 | Facial authentication.| - | HUKS_USER_AUTH_TYPE_PIN |0x0004 | PIN authentication. | - - > **NOTE** - > - > You can specify any or a combination of the three authentication types. - - - **Table 4** Secure access types - - | Name | Value | Description | - | --------------------------------------- | ---- | ------------------------------------------------ | - | HUKS_AUTH_ACCESS_INVALID_CLEAR_PASSWORD | 1 | Invalidates the key after the screen lock password is cleared. | - | HUKS_AUTH_ACCESS_INVALID_NEW_BIO_ENROLL | 2 | Invalidates the key after a biometric enrollment is added. The user authentication types must include the biometric authentication.| - - > **NOTE** - > - > **HUKS_AUTH_ACCESS_INVALID_CLEAR_PASSWORD** and **HUKS_AUTH_ACCESS_INVALID_NEW_BIO_ENROLL** are mutually exclusive. - - **Table 5** Challenge types - - | Name | Value | Description | - | ------------------------------- | ---- | ------------------------------ | - | HUKS_CHALLENGE_TYPE_NORMAL | 0 | Normal challenge, which requires an independent user authentication for each use of the key.| - | HUKS_CHALLENGE_TYPE_CUSTOM | 1 | Custom challenge, which supports only one user authentication for multiple keys.| - | HUKS_CHALLENGE_TYPE_NONE | 2 | No challenge is required during user authentication.| - - > **NOTICE** - > - > The three challenge types are mutually exclusive. - > - > If the challenge type is **HUKS_CHALLENGE_TYPE_NONE**, no challenge is required. However, the key can be accessed only within a specified time period (set by **HUKS_TAG_AUTH_TIMEOUT**) after a successful authentication. The maximum value of **HUKS_TAG_AUTH_TIMEOUT** is 60 seconds. - - -2. To use a key, initialize the key session, and determine whether a challenge is required based on the challenge type specified when the key is generated or imported. - - **Table 6** APIs for using a key - - | API | Description | - |-------------- | ------------------------------------ | - | initSession(keyAlias: string, options: HuksOptions, callback: AsyncCallback\) : void |Initializes the key session and obtains the challenge value.| - | updateSession(handle: number, options: HuksOptions, token: Uint8Array, callback: AsyncCallback\) : void| Operates data by segment and passes the authentication token.| - | finishSession(handle: number, options: HuksOptions, token: Uint8Array, callback: AsyncCallback\) : void | Finalizes the key session.| - - +When a key is generated or imported, [HuksUserAuthType](../reference/apis/js-apis-huks.md#huksuserauthtype9), [HuksAuthAccessType](../reference/apis/js-apis-huks.md#huksauthaccesstype9), and [HuksChallengeType](../reference/apis/js-apis-huks.md#hukschallengetype9) in the key attributes are mandatory. + +**Table 3** User authentication types + +| Name | Value | Description | +| ------------------------------- |---|------------------------ | +| HUKS_USER_AUTH_TYPE_FINGERPRINT |0x0001 | Fingerprint authentication.
Fingerprint authentication, facial authentication, and PIN authentication can be enabled at the same time. | +| HUKS_USER_AUTH_TYPE_FACE |0x0002 | Facial authentication.
Fingerprint authentication, facial authentication, and PIN authentication can be enabled at the same time. | +| HUKS_USER_AUTH_TYPE_PIN |0x0004 | PIN authentication.
Fingerprint authentication, facial authentication, and PIN authentication can be enabled at the same time. | + +**Table 4** Secure access types +| Name | Value | Description | +| --------------------------------------- | ---- | ------------------------------------------------ | +| HUKS_AUTH_ACCESS_INVALID_CLEAR_PASSWORD | 1 | Invalidate the key after the screen lock password is cleared. | +| HUKS_AUTH_ACCESS_INVALID_NEW_BIO_ENROLL | 2 | Invalidate the key after a biometric enrollment is added. The user authentication types must include the biometric authentication. | + +**Table 5** Challenge types + +| Name | Value | Description | +| ------------------------------- | ---- | ------------------------------ | +| HUKS_CHALLENGE_TYPE_NORMAL | 0 | Normal challenge, which requires an independent user authentication for each use of the key.| +| HUKS_CHALLENGE_TYPE_CUSTOM | 1 | Custom challenge, which supports only one user authentication for multiple keys.| +| HUKS_CHALLENGE_TYPE_NONE | 2 | No challenge is required during user authentication.| + +> **NOTICE** +> +> - The three challenge types are mutually exclusive. +> - If the challenge type is **HUKS_CHALLENGE_TYPE_NONE**, no challenge is required. However, the key can be accessed within a specified time period (set by **HUKS_TAG_AUTH_TIMEOUT**) after a successful authentication. The maximum value of **HUKS_TAG_AUTH_TIMEOUT** is 60 seconds. + +To use a key, initialize the key session and determine whether a challenge is required based on the challenge type specified when the key is generated or imported. + +**Table 6** APIs for using a key + +| API | Description | +| -------------------------------------- | ----------------------------| +|initSession(keyAlias: string, options: HuksOptions, callback: AsyncCallback\) : void| Initializes a key session and obtains the challenge. | +|updateSession(handle: number, options: HuksOptions, token: Uint8Array, callback: AsyncCallback\) : void| Operates data by segment and passes the authentication token.| +|finishSession(handle: number, options: HuksOptions, token: Uint8Array, callback: AsyncCallback\) : void| Finalizes the key session operation. | + + **How to Develop** - 1. Generate a key and specify user authentication attributes. - ```ts import huks from '@ohos.security.huks'; /* - * Determine the key alias and encapsulate the key attribute set. + * Determine the key alias and encapsulate the key attributes. */ let keyAlias = 'dh_key_fingerprint_access'; let properties = new Array(); @@ -2236,7 +2218,7 @@ import huks from '@ohos.security.huks'; import userIAM_userAuth from '@ohos.userIAM.userAuth'; /* - * Determine the key alias and encapsulate the key attribute set. + * Determine the key alias and encapsulate the key attributes. */ let srcKeyAlias = 'sm4_key_fingerprint_access'; let handle; @@ -2359,7 +2341,7 @@ async function testInitAndAuthFinger() { import huks from '@ohos.security.huks'; /* - * Determine the key alias and encapsulate the key attribute set. + * Determine the key alias and encapsulate the key attributes. */ let srcKeyAlias = 'sm4_key_fingerprint_access'; let IV = '1234567890123456'; @@ -2511,7 +2493,8 @@ The HUKS provides attestation for the public keys of asymmetric key pairs. The H **Available APIs** -**Table 7** APIs for key attestation +**Table 7** API for key attestation + | API | Description | | -------------------------------------- | ----------------------------| |attestKeyItem(keyAlias: string, options: HuksOptions, callback: AsyncCallback\) : void| Attests a key.| @@ -2525,7 +2508,7 @@ The HUKS provides attestation for the public keys of asymmetric key pairs. The H import huks from '@ohos.security.huks'; /* - * Determine the key alias and encapsulate the key attribute set. + * Determine the key alias and encapsulate the key attributes. */ let keyAliasString = "key attest"; let aliasString = keyAliasString;