目录

Setting the Digital Shield Password

Use Cases

When activating the digital shield service for the first time, a user needs to set a dedicated password on the Trusted User Interface (TUI). The password will be used for security verification during transaction authentication.

Constraints

  1. In versions earlier than 6.1.1(24), this function is supported only on mobile phones. In 6.1.1(24) and later versions, this function is supported on PCs/2-in-1 devices and tablets with the TUI capability. You can call the checkConfirmUITextFormat API to check whether a device has the TUI capability.
  2. When an unsupported device calls the service APIs of the Digital Shield service, error code 1019100016 is returned.

Service Process

Enabling the Digital Shield service requires the collaboration of the app server, app client, Universal Keystore Kit, and Device Security Kit. The process is as follows:

  1. The app server sends a request to the app client to enable the Digital Shield service.
  2. Querying whether the device supports the TUI capability: The app client sends a request to Device Security Kit to check whether the device supports the TUI capability. Device Security Kit returns the query result.
  3. Querying the highest security level supported by the system for enabling the Digital Shield service: The app client queries Device Security Kit again for the highest security level supported by the system for enabling the Digital Shield service. Device Security Kit returns the query result.
  4. Generating a session signing key: The app client uses the key alias to request Universal Keystore Kit to generate a session key. Universal Keystore Kit returns the key generation result.
  5. Initializing a signing session: The app client sends an "init session" request to Universal Keystore Kit. Universal Keystore Kit returns the session handle and challenge.
  6. The app client sends a request to Device Security Kit to enable the digital shield. Device Security Kit sets the shield password and returns the enabling result (including authToken and authID).
  7. Completing the update/finish signature operation: The app client sends the obtained authToken and data to be signed to Universal Keystore Kit to initiate the signing operation. Universal Keystore Kit returns the signing information.
  8. Binding the digital shield: The app server receives the signature information returned by the app client and completes the signature verification. After the signature verification is successful, the app server binds the user account to the authID and anonymous authID corresponding to the digital shield.

API Description

For details about the APIs and their usage, see API Reference.

API Description
checkConfirmUITextFormat(text: string): Promise<TextCheckResult> Checks whether the content to be displayed on the TUI can be completely displayed in a single line, which can indirectly determine whether the device has the TUI capability.
getSecurityLevel(authID?: bigint): Promise<SecurityLevel> Obtains the highest security level supported by the system for enabling the Digital Shield service or the security level corresponding to a specified digital shield.
enableTrustedAuthentication(challenge: Uint8Array, pwdInfo: PasswordInfo, label: TUILable): Promise<AuthInfo> Creates a digital shield password.

Development Procedure

  1. Import required modules.

    import { resourceManager } from '@kit.LocalizationKit'
    import { huks } from '@kit.UniversalKeystoreKit';
    import { BusinessError } from '@kit.BasicServicesKit';
    import { trustedAuthentication } from '@kit.DeviceSecurityKit';
    import { cryptoFramework } from '@kit.CryptoArchitectureKit';
    import { hilog } from '@kit.PerformanceAnalysisKit';
    import { common } from '@kit.AbilityKit';
  2. Call the checkConfirmUITextFormat API to check whether the device has the TUI capability.

    async isSupportTUI():Promise<boolean> {
      if (canIUse('SystemCapability.Security.TrustedAuthentication')) {
        let text = 'a'; // Any short string.
        try {
          const result = await trustedAuthentication.checkConfirmUITextFormat(text);
          if (result.result == 0) {
            return true;
          }
        } catch (error) {
          hilog.error(DOMAIN, 'testTag', 'The trusted authentication feature is not enabled.');
          return false;
        }
      }
      return false;
    }
  3. Call the getSecurityLevel API to obtain the highest security level supported by the system for enabling the Digital Shield service. This level is used to specify the security level for generating keys and enabling the Digital Shield service.

    async getSystemSecurityLevel(): Promise<trustedAuthentication.SecurityLevel> {
      try {
        const securityLevel = await trustedAuthentication.getSecurityLevel();
        hilog.info(0x0000, 'testTag', `The current system supports enabling the highest security level for the digital shield is: ${securityLevel}`);
        return securityLevel;
      } catch (error) {
        hilog.error(0x0000, 'testTag', 'get system securityLevel failed: %{public}d %{public}s',
          (error as BusinessError).code, (error as BusinessError).message);
        throw new Error('get system securityLevel failed: ' + (error as BusinessError).message);
      }
    }
  4. Use the specified session key alias and key property set to generate a key. For details, see generating a key of the key management service.

    1. When specifying options for the key authentication type tag: huks.HuksTag.HUKS_TAG_USER_AUTH_TYPE in the key property set during key creation, you must include huks.HuksUserAuthType.HUKS_USER_AUTH_TYPE_TUI_PIN. Other options (such as face or fingerprint) can be customized based on service requirements.
    2. If you want to retain the key after the app is uninstalled and continue to use it after the app is reinstalled, you need to use the encrypted key export/import function and set HUKS_TAG_IS_ALLOWED_WRAP to allow the key to be exported when generating the key.
    3. When using the SE-level digital shield, you also need to specify the key level as SE. You only need to apply for the ohos.permission.ACCESS_SE_KEY permission, add the huks.HuksTag.HUKS_TAG_KEY_SECURITY_LEVEL tag, and set the tag value to huks.HuksKeySecurityLevel.HUKS_KEY_SECURITY_LEVEL_SE when generating or importing the key. You do not need to specify the key level when using the key. The usage specifications of SE-level keys are different from those of TEE-level keys. For details, see SE-Level Key Specifications.
     async TestGenKeyForTuiPinSign(): Promise<void> {
       let properties: Array<huks.HuksParam> = [{
         tag: huks.HuksTag.HUKS_TAG_ALGORITHM,
         value: huks.HuksKeyAlg.HUKS_ALG_ECC
       }, {
         tag: huks.HuksTag.HUKS_TAG_PURPOSE,
         value: huks.HuksKeyPurpose.HUKS_KEY_PURPOSE_SIGN | huks.HuksKeyPurpose.HUKS_KEY_PURPOSE_VERIFY
       }, {
         tag: huks.HuksTag.HUKS_TAG_KEY_SIZE,
         value: huks.HuksKeySize.HUKS_ECC_KEY_SIZE_256
       }, {
         tag: huks.HuksTag.HUKS_TAG_DIGEST,
         value: huks.HuksKeyDigest.HUKS_DIGEST_SHA256
       }, {
         tag: huks.HuksTag.HUKS_TAG_KEY_AUTH_PURPOSE,
         value: huks.HuksKeyPurpose.HUKS_KEY_PURPOSE_SIGN
       },
       // Specify the key authentication type: TUI_PIN/fingerprint/face.
       {
         tag: huks.HuksTag.HUKS_TAG_USER_AUTH_TYPE,
         value: huks.HuksUserAuthType.HUKS_USER_AUTH_TYPE_TUI_PIN | huks.HuksUserAuthType.HUKS_USER_AUTH_TYPE_FINGERPRINT |
         huks.HuksUserAuthType.HUKS_USER_AUTH_TYPE_FACE
       },
       // Specify the key-based security authorization type (expiration type). The authorization becomes invalid after a new biometric feature (fingerprint) is enrolled.
       {
         tag: huks.HuksTag.HUKS_TAG_KEY_AUTH_ACCESS_TYPE,
         value: huks.HuksAuthAccessType.HUKS_AUTH_ACCESS_ALWAYS_VALID
       },
       // Use the default challenge type.
       {
         tag: huks.HuksTag.HUKS_TAG_CHALLENGE_TYPE,
         value: huks.HuksChallengeType.HUKS_CHALLENGE_TYPE_NORMAL
       },
       /* Allow the key to be exported for future key backup scenarios. */
       {
         tag: huks.HuksTag.HUKS_TAG_IS_ALLOWED_WRAP,
         value: true
       }];
       let huksOptions: huks.HuksOptions = {
         properties: properties,
         inData: new Uint8Array(new Array())
       }
       await publicGenKeyFunc(KEY_ALIAS, huksOptions);
     }
  5. Initialize the signing session. For details, see Signing and Signature Verification provided by the key management service.

  6. Call the password setting API to initiate a digital shield password creation request.

    The security level of the digital shield must be the same as that of the key generated in step 4. Select the security level based on the highest security level obtained in step 3.

    • To enable the digital shield at the SE level, you need to generate a key at the SE security level in step 4. When calling enableTrustedAuthentication, set the securityLevel field in PasswordInfo to trustedAuthentication.SecurityLevel.SECURITY_LEVEL_SE.
    • If the digital shield at the SE level is enabled on a device that does not support the SE security level, error code 801 is returned.
    • In a private space, only the TEE-level digital shield can be enabled.
    • If the SE chip is faulty due to hardware aging or other reasons, the corresponding API call returns error code 1019100023. In this case, you can disable the digital shield, generate a TEE-level key, and enable the digital shield at the TEE level based on service requirements.
    async SetPwd(challenge: Uint8Array, assetName: string): Promise<trustedAuthentication.AuthInfo> {
      try {
        const passwordInfo: trustedAuthentication.PasswordInfo = {
          pwdType: trustedAuthentication.PasswordType.PASSWORD_TYPE_DIGITAL,
          pwdMaxLength: 10,
          pwdMinLength: 6,
          maxAuthFailCount: 6
        };
        const context = AppStorage.get('context') as Context;
        const buffer: ArrayBuffer = await CryptoUtils.ImportImage(); // Obtain the app logo image to be displayed on the TUI.
        const label: trustedAuthentication.TUILable = {
          image: buffer,
          title: context.resourceManager.getStringSync($r('app.string.OpenShield').id)
        }
        const authInfo = await trustedAuthentication.enableTrustedAuthentication(challenge, passwordInfo, label);
        let assetLabel = assetName + 'label';
        AssetUtils.AddDataToAssetStore(CryptoUtils.bigIntToUint8Array(authInfo.authID), assetName, assetLabel);
        hilog.info(0x0000, 'testTag', 'Open Shield Success: ', authInfo.authID, authInfo.authToken.length,
          authInfo.authToken);
        return authInfo;
      } catch (error) {
        hilog.error(0x0000, 'testTag', 'Open Shield Fail: ', error);
        throw new Error('Open Shield Fail: ' + (error as BusinessError).message);
      }
    }
  7. Sign the authentication using the authToken obtained in step 6 and end the session (initSession has been completed in step 5) by referring to Signing and Signature Verification provided by the key management service.

    • To ensure end-to-end security in the digital shield signing scenario, the app server must process authentication information parsed from authToken during signature verification. Therefore, the signature type that carries authentication information must be selected during signing (HUKS_KEY_PURPOSE_SIGN and HUKS_TAG_KEY_SECURE_SIGN_TYPE which is set to HUKS_SECURE_SIGN_WITH_AUTHINFO). This type of signature automatically prefixes 41-byte authentication information before the original data to be signed before the signing operation.
    • The overall structure of the returned signature data is as follows: 41-byte authentication information + original data signature value. You need to send the complete signature data (including the prefixed 41-byte authentication information) to the app server for signature verification.
    • When parsing the signature data, the app server needs to split the prefixed 41-byte authentication information and signature value from the signature data based on the preceding offset relationship, and perform signature verification on the signature value. After the signature verification is successful, the app server can extract fields such as anonymous AuthId from the authentication information to associate the user account with the authID and anonymous AuthId corresponding to the digital shield (step 8 in the service process).
    • The meaning and parsing method of the 41-byte authentication information are the same as those in Signature with Authentication Information.
    • The following table describes the overall structure of the signature data.
    Data Segment Field Offset (Byte) Length (Byte) Description
    Authentication information Version 0 4 Authentication information version.
    Authentication information User authentication type 4 4 User authentication mode used for authentication, such as TUI_PIN, face, and fingerprint.
    Authentication information Anonymous AuthId 8 32 Anonymous AuthId of the digital shield, which is used to bind an account on the server.
    Authentication information Data hash verification required or not 40 1 Whether data hash verification is performed on the original data. If anti-tamper protection for TUI display content is involved, the value 1 indicates that verification is required.
    Signature Signature value of the original data. 41 - Signature value generated for the original data to be signed (including the prefixed authentication information).

Specification Differences Between SE- and TEE-Level Keys

Since API version 26.0.0, the Digital Shield service supports the activation of the Digital Shield at the SE security level. Before activation, you need to generate an SE-level key. Unlike TEE-level keys, SE keys are generated and used in an independent security chip with higher security protection. To use an SE key, you need to explicitly specify the key security level.

[h2]Constraints

[h2]Supported APIs and Specifications

SE-level keys support the following HUKS APIs:

The SE security level needs to be specified only when a key is generated, imported in security mode, or imported in encryption mode. For other key-related APIs, the SE security level does not need to be specified.

API Specifications Description
Key generation (generateKeyItem) Only the SM2 and SM4 algorithms are supported. The SE security level must be specified. A group key is supported.
Key deletion (deleteKeyItem) - The SE security level does not need to be specified.
Key query (getKeyItemProperties) - The SE security level does not need to be specified.
Public key export (exportKeyItem) - The SE security level does not need to be specified.
Key import in secure mode (importWrappedKeyItem) Only the digital envelope mode (HUKS_UNWRAP_SUITE_SM2_SM4_ECB_NOPADDING) is supported. The security level of the key encryption key (KEK) must match that of the key to be imported.
Key export and import in encryption mode (wrapKeyItem/unwrapKeyItem) - The security level of the key for encrypted export must match that of the key for encrypted import.
Key usage initSession/updateSession/finishSession/abortSession For details, see SM2 and SM4 algorithm specifications. Only encryption, decryption, and signature verification are supported. The SE security level does not need to be specified.
Key attestation (anonAttestKeyItem) Only anonymous attestation is supported. The SE security level does not need to be specified.

SM2 Algorithm Specifications

Algorithm Key Length Purpose MD Algorithm Padding Mode Data Length
SM2 256 Signature and signature verification SM3 NoPadding Input data ≤ 512 bytes
SM2 256 Signature and signature verification NoDigest NoPadding Input data = 32 bytes
SM2 256 Encryption and decryption SM3 NoPadding Total data size ≤ 128 bytes

SM4 Algorithm Specifications

Algorithm Key Length Purpose Padding Mode Block Cipher Mode Data Length
SM4 128 Encryption and decryption PKCS7 ECB Single segment ≤ 256 bytes
SM4 128 Encryption and decryption PKCS7 CBC Single segment ≤ 256 bytes
SM4 128 Encryption and decryption NoPadding CTR Single segment ≤ 256 bytes
SM4 128 Encryption and decryption NoPadding CBC Single segment ≤ 256 bytes

SE-level keys do not support the AES, RSA, or ECC algorithm. The CFB and OFB modes of SM4 are not supported.

[h2]Sample Code

Key Generation

When the generateKeyItem API is called to generate an SE-level key, the security level needs to be specified by using HUKS_TAG_KEY_SECURITY_LEVEL.

import { huks } from '@kit.UniversalKeystoreKit';

let keyAlias = 'se_sm2_sign_key';

let properties: huks.HuksParam[] = [
  { tag: huks.HuksTag.HUKS_TAG_ALGORITHM, value: huks.HuksKeyAlg.HUKS_ALG_SM2 },
  { tag: huks.HuksTag.HUKS_TAG_KEY_SIZE, value: huks.HuksKeySize.HUKS_SM2_KEY_SIZE_256 },
  { tag: huks.HuksTag.HUKS_TAG_PURPOSE, value: huks.HuksKeyPurpose.HUKS_KEY_PURPOSE_SIGN | huks.HuksKeyPurpose.HUKS_KEY_PURPOSE_VERIFY },
  { tag: huks.HuksTag.HUKS_TAG_DIGEST, value: huks.HuksKeyDigest.HUKS_DIGEST_SM3 },
  { tag: huks.HuksTag.HUKS_TAG_KEY_SECURITY_LEVEL, value: huks.HuksKeySecurityLevel.HUKS_KEY_SECURITY_LEVEL_SE },
  { tag: huks.HuksTag.HUKS_TAG_USER_AUTH_TYPE, value: huks.HuksUserAuthType.HUKS_USER_AUTH_TYPE_TUI_PIN },
  { tag: huks.HuksTag.HUKS_TAG_KEY_AUTH_ACCESS_TYPE, value: huks.HuksAuthAccessType.HUKS_AUTH_ACCESS_ALWAYS_VALID },
  { tag: huks.HuksTag.HUKS_TAG_CHALLENGE_TYPE, value: huks.HuksChallengeType.HUKS_CHALLENGE_TYPE_NORMAL },
];

async function testGenerateKey() {
  try {
    await huks.generateKeyItem(keyAlias, { properties: properties });
    console.info('promise: generateKeyItem success');
  } catch (error) {
    console.error('promise: generateKeyItem failed, error: ' + error);
  }
}

Key Deletion

When the deleteKeyItem API is called to delete an SE-level key, the security level parameter does not need to be specified.

import { huks } from '@kit.UniversalKeystoreKit';

let keyAlias = 'se_sm2_sign_key';

let properties: huks.HuksParam[] = [
  { tag: huks.HuksTag.HUKS_TAG_ALGORITHM, value: huks.HuksKeyAlg.HUKS_ALG_SM2 },
  { tag: huks.HuksTag.HUKS_TAG_KEY_SIZE, value: huks.HuksKeySize.HUKS_SM2_KEY_SIZE_256 },
  { tag: huks.HuksTag.HUKS_TAG_PURPOSE, value: huks.HuksKeyPurpose.HUKS_KEY_PURPOSE_SIGN | huks.HuksKeyPurpose.HUKS_KEY_PURPOSE_VERIFY },
  { tag: huks.HuksTag.HUKS_TAG_DIGEST, value: huks.HuksKeyDigest.HUKS_DIGEST_SM3 },
  { tag: huks.HuksTag.HUKS_TAG_KEY_SECURITY_LEVEL, value: huks.HuksKeySecurityLevel.HUKS_KEY_SECURITY_LEVEL_SE },
  { tag: huks.HuksTag.HUKS_TAG_USER_AUTH_TYPE, value: huks.HuksUserAuthType.HUKS_USER_AUTH_TYPE_TUI_PIN },
  { tag: huks.HuksTag.HUKS_TAG_KEY_AUTH_ACCESS_TYPE, value: huks.HuksAuthAccessType.HUKS_AUTH_ACCESS_ALWAYS_VALID },
  { tag: huks.HuksTag.HUKS_TAG_CHALLENGE_TYPE, value: huks.HuksChallengeType.HUKS_CHALLENGE_TYPE_NORMAL },
];

async function testDeleteKey() {
  try {
    await huks.generateKeyItem(keyAlias, { properties: properties });
    console.info('promise: generateKeyItem success');

    await huks.deleteKeyItem(keyAlias, { properties: [] });
    console.info('promise: deleteKeyItem success');
  } catch (error) {
    console.error('promise: deleteKeyItem failed, error: ' + error);
  }
}

Key Query

When the getKeyItemProperties API is called to query the properties of an SE-level key, the security level parameter does not need to be specified.

import { huks } from '@kit.UniversalKeystoreKit';

let keyAlias = 'se_sm2_sign_key';

let properties: huks.HuksParam[] = [
  { tag: huks.HuksTag.HUKS_TAG_ALGORITHM, value: huks.HuksKeyAlg.HUKS_ALG_SM2 },
  { tag: huks.HuksTag.HUKS_TAG_KEY_SIZE, value: huks.HuksKeySize.HUKS_SM2_KEY_SIZE_256 },
  { tag: huks.HuksTag.HUKS_TAG_PURPOSE, value: huks.HuksKeyPurpose.HUKS_KEY_PURPOSE_SIGN | huks.HuksKeyPurpose.HUKS_KEY_PURPOSE_VERIFY },
  { tag: huks.HuksTag.HUKS_TAG_DIGEST, value: huks.HuksKeyDigest.HUKS_DIGEST_SM3 },
  { tag: huks.HuksTag.HUKS_TAG_KEY_SECURITY_LEVEL, value: huks.HuksKeySecurityLevel.HUKS_KEY_SECURITY_LEVEL_SE },
  { tag: huks.HuksTag.HUKS_TAG_USER_AUTH_TYPE, value: huks.HuksUserAuthType.HUKS_USER_AUTH_TYPE_TUI_PIN },
  { tag: huks.HuksTag.HUKS_TAG_KEY_AUTH_ACCESS_TYPE, value: huks.HuksAuthAccessType.HUKS_AUTH_ACCESS_ALWAYS_VALID },
  { tag: huks.HuksTag.HUKS_TAG_CHALLENGE_TYPE, value: huks.HuksChallengeType.HUKS_CHALLENGE_TYPE_NORMAL },
];

async function testGetKeyProperties() {
  try {
    await huks.generateKeyItem(keyAlias, { properties: properties });
    console.info('promise: generateKeyItem success');

    let result = await huks.getKeyItemProperties(keyAlias, { properties: [] });
    console.info('promise: getKeyItemProperties success');
  } catch (error) {
    console.error('promise: getKeyItemProperties failed, error: ' + error);
  }
}

Public Key Export

When the exportKeyItem is used to export an SE-level public key, the security level parameter does not need to be specified.

import { huks } from '@kit.UniversalKeystoreKit';

let keyAlias = 'se_sm2_sign_key';

let properties: huks.HuksParam[] = [
  { tag: huks.HuksTag.HUKS_TAG_ALGORITHM, value: huks.HuksKeyAlg.HUKS_ALG_SM2 },
  { tag: huks.HuksTag.HUKS_TAG_KEY_SIZE, value: huks.HuksKeySize.HUKS_SM2_KEY_SIZE_256 },
  { tag: huks.HuksTag.HUKS_TAG_PURPOSE, value: huks.HuksKeyPurpose.HUKS_KEY_PURPOSE_SIGN | huks.HuksKeyPurpose.HUKS_KEY_PURPOSE_VERIFY },
  { tag: huks.HuksTag.HUKS_TAG_DIGEST, value: huks.HuksKeyDigest.HUKS_DIGEST_SM3 },
  { tag: huks.HuksTag.HUKS_TAG_KEY_SECURITY_LEVEL, value: huks.HuksKeySecurityLevel.HUKS_KEY_SECURITY_LEVEL_SE },
  { tag: huks.HuksTag.HUKS_TAG_USER_AUTH_TYPE, value: huks.HuksUserAuthType.HUKS_USER_AUTH_TYPE_TUI_PIN },
  { tag: huks.HuksTag.HUKS_TAG_KEY_AUTH_ACCESS_TYPE, value: huks.HuksAuthAccessType.HUKS_AUTH_ACCESS_ALWAYS_VALID },
  { tag: huks.HuksTag.HUKS_TAG_CHALLENGE_TYPE, value: huks.HuksChallengeType.HUKS_CHALLENGE_TYPE_NORMAL },
];

async function testExportKey() {
  try {
    await huks.generateKeyItem(keyAlias, { properties: properties });
    console.info('promise: generateKeyItem success');

    let exportResult = await huks.exportKeyItem(keyAlias, { properties: [] });
    let pubKeyData: Uint8Array = exportResult.outData as Uint8Array;
    console.info('promise: exportKeyItem success, length: ' + pubKeyData.length);
  } catch (error) {
    console.error('promise: exportKeyItem failed, error: ' + error);
  }
}

Key Import in Security Mode

When the importWrappedKeyItem API is called to import an SE-level key in secure mode using the digital envelope format, the security level of the KEK must match that of the key to be imported. For details, see Key Import Using Digital Envelope (ArkTS).

import { huks } from '@kit.UniversalKeystoreKit';
import { cryptoFramework } from '@kit.CryptoArchitectureKit';

// Convert int to Uint8Array.
function intToUint8Array(value: number): Uint8Array {
  let buffer: ArrayBuffer = new ArrayBuffer(4);
  let view: DataView = new DataView(buffer);
  view.setUint32(0, value, true);
  return new Uint8Array(buffer);
}

// Concatenate multiple Uint8Array objects.
function concatUint8Arrays(arrays: Uint8Array[]): Uint8Array {
  let totalLength: number = 0;
  for (let i = 0; i < arrays.length; i++) {
    totalLength += arrays[i].length;
  }
  let result: Uint8Array = new Uint8Array(totalLength);
  let offset: number = 0;
  for (let i = 0; i < arrays.length; i++) {
    result.set(arrays[i], offset);
    offset += arrays[i].length;
  }
  return result;
}

// Encrypt with the SM2 KEK public key using the cryptoFramework. This encryption mode is only an example. In practice, the encryption should be performed in a secure environment.
async function encryptSm2WithCryptoFramework(kekAlias: string, plainData: Uint8Array): Promise<Uint8Array> {
  let exportResult: huks.HuksReturnResult = await huks.exportKeyItem(kekAlias, { properties: [] });
  let pubKeyData: Uint8Array = exportResult.outData as Uint8Array;
  let keyGenerator: cryptoFramework.AsyKeyGenerator = cryptoFramework.createAsyKeyGenerator('SM2_256');
  let pubKeyBlob: cryptoFramework.DataBlob = { data: pubKeyData };
  let keyPair: cryptoFramework.KeyPair = await keyGenerator.convertKey(pubKeyBlob, null);
  let cipher: cryptoFramework.Cipher = cryptoFramework.createCipher('SM2_256|SM3');
  await cipher.init(cryptoFramework.CryptoMode.ENCRYPT_MODE, keyPair.pubKey, null);
  let inputBlob: cryptoFramework.DataBlob = { data: plainData };
  let outputBlob: cryptoFramework.DataBlob = await cipher.doFinal(inputBlob);
  return outputBlob.data;
}

// Use SM4-ECB to encrypt a key material.
async function encryptSm4EcbWithCryptoFramework(transportKey: Uint8Array, plainData: Uint8Array): Promise<Uint8Array> {
  let symKeyGenerator: cryptoFramework.SymKeyGenerator = cryptoFramework.createSymKeyGenerator('SM4_128');
  let keyBlob: cryptoFramework.DataBlob = { data: transportKey };
  let symKey: cryptoFramework.SymKey = await symKeyGenerator.convertKey(keyBlob);
  let cipher: cryptoFramework.Cipher = cryptoFramework.createCipher('SM4_128|ECB|NoPadding');
  await cipher.init(cryptoFramework.CryptoMode.ENCRYPT_MODE, symKey, null);
  let inputBlob: cryptoFramework.DataBlob = { data: plainData };
  let outputBlob: cryptoFramework.DataBlob = await cipher.doFinal(inputBlob);
  return outputBlob.data;
}

async function testImportSm2Key() {
  // Generate a KEK.
  let kekAlias = 'kek_sm2_sign';
  let kekProps: huks.HuksParam[] = [
    { tag: huks.HuksTag.HUKS_TAG_ALGORITHM, value: huks.HuksKeyAlg.HUKS_ALG_SM2 },
    { tag: huks.HuksTag.HUKS_TAG_KEY_SIZE, value: huks.HuksKeySize.HUKS_SM2_KEY_SIZE_256 },
    { tag: huks.HuksTag.HUKS_TAG_PURPOSE, value: huks.HuksKeyPurpose.HUKS_KEY_PURPOSE_ENCRYPT | huks.HuksKeyPurpose.HUKS_KEY_PURPOSE_DECRYPT },
    { tag: huks.HuksTag.HUKS_TAG_DIGEST, value: huks.HuksKeyDigest.HUKS_DIGEST_SM3 },
    { tag: huks.HuksTag.HUKS_TAG_PADDING, value: huks.HuksKeyPadding.HUKS_PADDING_NONE },
    { tag: huks.HuksTag.HUKS_TAG_KEY_SECURITY_LEVEL, value: huks.HuksKeySecurityLevel.HUKS_KEY_SECURITY_LEVEL_SE },
    { tag: huks.HuksTag.HUKS_TAG_USER_AUTH_TYPE, value: huks.HuksUserAuthType.HUKS_USER_AUTH_TYPE_TUI_PIN },
    { tag: huks.HuksTag.HUKS_TAG_KEY_AUTH_ACCESS_TYPE, value: huks.HuksAuthAccessType.HUKS_AUTH_ACCESS_ALWAYS_VALID },
    { tag: huks.HuksTag.HUKS_TAG_CHALLENGE_TYPE, value: huks.HuksChallengeType.HUKS_CHALLENGE_TYPE_NORMAL },
  ];
  await huks.generateKeyItem(kekAlias, { properties: kekProps });

  // Encrypt the key material and construct the data to be imported.
  let sm2PubKey: Uint8Array = new Uint8Array([0x30, 0x59, 0x30, 0x13, 0x06, 0x07, 0x2a, 0x86, 0x48, 0xce,
    0x3d, 0x02, 0x01, 0x06, 0x08, 0x2a, 0x81, 0x1c, 0xcf, 0x55, 0x01, 0x82, 0x2d, 0x03, 0x42, 0x00,
    0x04, 0x38, 0x9e, 0xd3, 0x95, 0xb7, 0x98, 0xdf, 0x60, 0xbf, 0x5a, 0x14, 0x71, 0x45, 0x2b, 0xd6,
    0xb7, 0x35, 0x1c, 0xd1, 0x38, 0x7a, 0x11, 0x98, 0x8a, 0x28, 0xd1, 0x37, 0x9b, 0x75, 0x12, 0xd8,
    0x06, 0x42, 0xc2, 0xbf, 0x3b, 0x52, 0x18, 0x6e, 0x9c, 0x41, 0x2d, 0x77, 0xc0, 0xa1, 0x6d, 0x9e,
    0x08, 0x9d, 0x4e, 0x16, 0x62, 0x57, 0x97, 0x56, 0x10, 0xd4, 0x7b, 0x3a, 0x5f, 0x96, 0xf6, 0x8c,
    0x19]);
  let sm2PrivKey: Uint8Array = new Uint8Array([0xa7, 0xde, 0x26, 0xf9, 0xe8, 0xad, 0xe8, 0x9b, 0x5a, 0x37,
    0xca, 0x5b, 0x70, 0x18, 0x18, 0xe0, 0x68, 0x04, 0xa9, 0x8b, 0x94, 0x9c, 0xcd, 0x86, 0x90, 0x22,
    0x9f, 0x17, 0xfd, 0xc4, 0x9c, 0x51]);

  let rand: cryptoFramework.Random = cryptoFramework.createRandom();
  let transportKeyBlob: cryptoFramework.DataBlob = await rand.generateRandom(16);
  let transportKey: Uint8Array = transportKeyBlob.data;
  let encTransportKey: Uint8Array = await encryptSm2WithCryptoFramework(kekAlias, transportKey);
  let encKeyData: Uint8Array = await encryptSm4EcbWithCryptoFramework(transportKey, sm2PrivKey);

  let importData: Uint8Array = concatUint8Arrays([
    intToUint8Array(encTransportKey.length), encTransportKey,
    intToUint8Array(encKeyData.length), encKeyData,
  ]);

  // Import the digital envelope.
  let importAlias = 'imported_sm2_sign';
  let importProps: huks.HuksParam[] = [
    { tag: huks.HuksTag.HUKS_TAG_ALGORITHM, value: huks.HuksKeyAlg.HUKS_ALG_SM2 },
    { tag: huks.HuksTag.HUKS_TAG_KEY_SIZE, value: huks.HuksKeySize.HUKS_SM2_KEY_SIZE_256 },
    { tag: huks.HuksTag.HUKS_TAG_PURPOSE, value: huks.HuksKeyPurpose.HUKS_KEY_PURPOSE_SIGN | huks.HuksKeyPurpose.HUKS_KEY_PURPOSE_VERIFY },
    { tag: huks.HuksTag.HUKS_TAG_PADDING, value: huks.HuksKeyPadding.HUKS_PADDING_NONE },
    { tag: huks.HuksTag.HUKS_TAG_DIGEST, value: huks.HuksKeyDigest.HUKS_DIGEST_SM3 },
    { tag: huks.HuksTag.HUKS_TAG_UNWRAP_ALGORITHM_SUITE, value: huks.HuksUnwrapSuite.HUKS_UNWRAP_SUITE_SM2_SM4_ECB_NOPADDING },
    { tag: huks.HuksTag.HUKS_TAG_IMPORT_KEY_TYPE, value: huks.HuksImportKeyType.HUKS_KEY_TYPE_KEY_PAIR },
    { tag: huks.HuksTag.HUKS_TAG_ASYMMETRIC_PUBLIC_KEY_DATA, value: sm2PubKey },
    { tag: huks.HuksTag.HUKS_TAG_KEY_SECURITY_LEVEL, value: huks.HuksKeySecurityLevel.HUKS_KEY_SECURITY_LEVEL_SE },
    { tag: huks.HuksTag.HUKS_TAG_USER_AUTH_TYPE, value: huks.HuksUserAuthType.HUKS_USER_AUTH_TYPE_TUI_PIN },
    { tag: huks.HuksTag.HUKS_TAG_KEY_AUTH_ACCESS_TYPE, value: huks.HuksAuthAccessType.HUKS_AUTH_ACCESS_ALWAYS_VALID },
    { tag: huks.HuksTag.HUKS_TAG_CHALLENGE_TYPE, value: huks.HuksChallengeType.HUKS_CHALLENGE_TYPE_NORMAL },
  ];

  try {
    let importOptions: huks.HuksOptions = { properties: importProps, inData: importData };
    await huks.importWrappedKeyItem(importAlias, kekAlias, importOptions);
    console.info('promise: importWrappedKeyItem success');
  } catch (error) {
    console.error('promise: importWrappedKeyItem failed, error: ' + error);
  }
}

Key Export and Import in Encryption Mode

When the wrapKeyItem API is called to export an SE-level key in encryption mode, you do not need to specify the security level parameter. When the unwrapKeyItem API is called to import an SE-level key in encryption mode, the security level must be the same as that when the key is generated.

import { huks } from '@kit.UniversalKeystoreKit';

let keyAlias = 'se_wrap_key';

let properties: huks.HuksParam[] = [
  { tag: huks.HuksTag.HUKS_TAG_ALGORITHM, value: huks.HuksKeyAlg.HUKS_ALG_SM4 },
  { tag: huks.HuksTag.HUKS_TAG_KEY_SIZE, value: huks.HuksKeySize.HUKS_SM4_KEY_SIZE_128 },
  { tag: huks.HuksTag.HUKS_TAG_PURPOSE, value: huks.HuksKeyPurpose.HUKS_KEY_PURPOSE_ENCRYPT | huks.HuksKeyPurpose.HUKS_KEY_PURPOSE_DECRYPT },
  { tag: huks.HuksTag.HUKS_TAG_PADDING, value: huks.HuksKeyPadding.HUKS_PADDING_PKCS7 },
  { tag: huks.HuksTag.HUKS_TAG_BLOCK_MODE, value: huks.HuksCipherMode.HUKS_MODE_CBC },
  { tag: huks.HuksTag.HUKS_TAG_KEY_SECURITY_LEVEL, value: huks.HuksKeySecurityLevel.HUKS_KEY_SECURITY_LEVEL_SE },
  { tag: huks.HuksTag.HUKS_TAG_USER_AUTH_TYPE, value: huks.HuksUserAuthType.HUKS_USER_AUTH_TYPE_TUI_PIN },
  { tag: huks.HuksTag.HUKS_TAG_KEY_AUTH_ACCESS_TYPE, value: huks.HuksAuthAccessType.HUKS_AUTH_ACCESS_ALWAYS_VALID },
  { tag: huks.HuksTag.HUKS_TAG_CHALLENGE_TYPE, value: huks.HuksChallengeType.HUKS_CHALLENGE_TYPE_NORMAL },
  { tag: huks.HuksTag.HUKS_TAG_IS_ALLOWED_WRAP, value: true },
];

let wrapKeyProperties: huks.HuksParam[] = [
  { tag: huks.HuksTag.HUKS_TAG_KEY_WRAP_TYPE, value: huks.HuksKeyWrapType.HUKS_KEY_WRAP_TYPE_HUK_BASED },
];

let wrapKeyOptions: huks.HuksOptions = {
  properties: wrapKeyProperties,
};

let wrappedData: Uint8Array;

async function testWrapKey() {
  try {
    // Generate a key.
    await huks.generateKeyItem(keyAlias, { properties: properties });
    console.info('promise: generateKeyItem success');

    // Export the key in encryption mode.
    let wrapResult = await huks.wrapKeyItem(keyAlias, wrapKeyOptions);
    wrappedData = wrapResult.outData as Uint8Array;
    console.info('promise: wrapKeyItem success, length: ' + wrappedData.length);

    // Import the key in encryption mode.
    await huks.unwrapKeyItem(keyAlias, wrapKeyOptions, wrappedData);
    console.info('promise: unwrapKeyItem success');
  } catch (error) {
    console.error('promise: wrap/unwrap failed, error: ' + error);
  }
}