openharmony 鸿蒙 js-apis-huksExternalCrypto

2026-08-25 浏览 (1)

@ohos.security.huksExternalCrypto (外部密钥管理)

模块提供外部密钥管理扩展功能的注册与注销,PIN码认证与认证状态获取等。

说明

本模块首批接口从API version 22开始支持。后续版本的新增接口,采用上角标单独标记接口的起始版本。

导入模块

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

HuksExternalCryptoTagType

表示外部加密数据类型的枚举。

系统能力: SystemCapability.Security.Huks.CryptoExtension

名称说明
HUKS_EXT_CRYPTO_TAG_TYPE_INT1 << 28表示TAG的值为整数类型。
HUKS_EXT_CRYPTO_TAG_TYPE_BYTES5 << 28表示TAG的值为字节数组。

HuksExternalCryptoTag

表示调用参数的Tag。

系统能力: SystemCapability.Security.Huks.CryptoExtension

名称说明
HUKS_EXT_CRYPTO_TAG_UKEY_PINHuksExternalCryptoTagType.HUKS_EXT_CRYPTO_TAG_TYPE_BYTES |200001表示PIN码的TAG。
HUKS_EXT_CRYPTO_TAG_ABILITY_NAMEHuksExternalCryptoTagType.HUKS_EXT_CRYPTO_TAG_TYPE_BYTES |200002表示CryptoExtensionAbility的名称。
HUKS_EXT_CRYPTO_TAG_EXTRA_DATAHuksExternalCryptoTagType.HUKS_EXT_CRYPTO_TAG_TYPE_BYTES |200003外部数据,在通用查询场景,表示返回的数据。
HUKS_EXT_CRYPTO_TAG_UIDHuksExternalCryptoTagType.HUKS_EXT_CRYPTO_TAG_TYPE_INT |200004表示调用方的uid。
HUKS_EXT_CRYPTO_TAG_PURPOSEHuksExternalCryptoTagType.HUKS_EXT_CRYPTO_TAG_TYPE_INT |200005表示证书链对应密钥的使用类型,具体类型详见CertificatePurpose定义
HUKS_EXT_CRYPTO_TAG_RESOURCE_INFOHuksExternalCryptoTagType.HUKS_EXT_CRYPTO_TAG_TYPE_BYTES |200007表示获取资源ID所需的信息,格式和内容由厂商自定义。
起始版本: 26.0.0
HUKS_EXT_CRYPTO_TAG_ABILITY_INFOHuksExternalCryptoTagType.HUKS_EXT_CRYPTO_TAG_TYPE_BYTES |200008表示密钥管理扩展自定义PIN码弹窗相关Ability列表信息,在注册密钥管理扩展时,同步注册,详见provider注册示例。注册了自定义弹窗,则在PIN码认证时允许拉起自定义弹窗,进行PIN码认证等操作。
HUKS_EXT_CRYPTO_TAG_ABILITY_NAME中的JSON列表由多个JSON对象组成,每个JSON对象包含两个字段:AbilityName和index。字段应遵循以下要求:
1.AbilityName:长度范围为1~128字节。
2.index:其值为resourceId,最大长度为512字节。允许单个CryptoExtension下该字段为空,为空时传输空字符串,该字段不允许重复。在搜索时优先匹配index对应的UIExtensionAbility,当不存在时返回index为空的UIExtensionAbility。
起始版本:26.0.0
模型约束:此接口仅可在Stage模型下使用。
HUKS_EXT_CRYPTO_TAG_BUNDLE_NAMEHuksExternalCryptoTagType.HUKS_EXT_CRYPTO_TAG_TYPE_BYTES |200009表示CryptoExtensionAbility所属的HAP Bundle名称。
起始版本: 26.0.0

HuksExternalCryptoParam

表示调用接口使用的param数组的类型。

系统能力: SystemCapability.Security.Huks.CryptoExtension

名称类型只读可选说明
tagHuksExternalCryptoTag参数标签,用于区分参数。
valueboolean|number|bigint|Uint8Array标签对应值。

HuksExternalPinAuthState

表示Ukey PIN码管理的状态值的枚举。

系统能力: SystemCapability.Security.Huks.CryptoExtension

名称说明
HUKS_EXT_CRYPTO_PIN_NO_AUTH0Ukey PIN未认证。
HUKS_EXT_CRYPTO_PIN_AUTH_SUCCEEDED1Ukey PIN认证成功。
HUKS_EXT_CRYPTO_PIN_LOCKED2Ukey PIN已锁定。

huksExternalCrypto.registerProvider

registerProvider(providerName: string, params: Array<HuksExternalCryptoParam>): Promise<void>

注册指定的外部provider。使用Promise异步回调。

若需使用自定义PIN码弹窗,在注册provider时需要同步注册UIExtensionAbility,注意事项如下:

  1. 自定义ability通过UIExtensionAbility扩展实现。

  2. 注册的UIExtensionAbility可以通过证书管理kit提供的openUKeyAuthDialog接口统一拉起。

  3. 系统拉起自定义弹窗时会通过want接口向开发者传递以下参数:

    • Action:string参数类型,在拉起自定义弹窗时want传输的Action为"UkeyPINAuth"。
    • appUid:number参数类型,通过want.parameters传输。"appUid"字段为应用id,开发者可以通过该字段完成应用隔离。
    • keyUri:string参数类型其值为resourceId,通过want.parameters传输,表示Ukey证书的索引。
  4. 开发者实现UIExtensionAbility时,应用需根据指定场景返回对应的错误码:

    • 用户取消操作时,返回-1001。
    • keyUri指定的证书/密钥不存在时,返回-1008。
    • 参数格式错误时,返回-1014。
    • 其余失败场景返回错误码-1000,成功时返回0。

需要权限: ohos.permission.CRYPTO_EXTENSION_REGISTER

系统能力: SystemCapability.Security.Huks.CryptoExtension

参数:

参数名类型必填说明
providerNamestringprovider名称,最大长度为128。建议包含厂商信息,全局唯一,不要包含个人联系方式等敏感数据。
最多支持注册10个provider。
paramsArray<HuksExternalCryptoParam>操作时需传入的参数,必选TAG:HUKS_EXT_CRYPTO_TAG_ABILITY_NAME,表示ability的名字,根据业务自己内部定义按照实际填写。
从API版本26.0.0开始,可选TAG:HUKS_EXT_CRYPTO_TAG_ABILITY_INFO,以JSON列表的形式传入PIN码认证自定义弹窗UIExtensionAbility的名字以及包名。

返回值:

类型说明
Promise<void>Promise对象,无返回结果。

错误码:

以下错误码的详细介绍请参见通用错误码HUKS错误码

错误码ID错误信息
201check permission failed.
801api is not supported.
12000002the ability name param is missing.
12000005IPC communication failed.
12000014memory is insufficient.
12000018the input parameter is invalid.
12000019the provider is already registered.
12000020an error occurred in the dependent module.
12000025the number of providers exceeds the limit.

示例:

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

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

const providerName = "testProviderName";
const extProperties: Array<huksExternalCrypto.HuksExternalCryptoParam> = [
  {
    tag: huksExternalCrypto.HuksExternalCryptoTag.HUKS_EXT_CRYPTO_TAG_ABILITY_NAME,
    value: StringToUint8Array("CryptoExtension")
  }
];
huksExternalCrypto.registerProvider(providerName, extProperties)
    .then((data) => {
        console.info(`promise: registerProvider success`);
    });

huksExternalCrypto.unregisterProvider

unregisterProvider(providerName: string, params?: Array<HuksExternalCryptoParam>): Promise<void>

注销指定的外部provider。使用Promise异步回调。

需要权限: ohos.permission.CRYPTO_EXTENSION_REGISTER

系统能力: SystemCapability.Security.Huks.CryptoExtension

参数:

参数名类型必填说明
providerNamestringprovider名称,最大长度为128。建议包含厂商信息,全局唯一,不要包含个人联系方式等敏感数据。如果provider注册了多个扩展能力,则该provider下的扩展能力都会被注销。
paramsArray<HuksExternalCryptoParam>操作时需传入的参数。
可以在param参数中指定HUKS_EXT_CRYPTO_TAG_ABILITY_NAME,将根据“包名 + providerName + abilityName”注销对应的cryptoExtensionAbility。
如果未在params参数中指定HUKS_EXT_CRYPTO_TAG_ABILITY_NAME,或者未传入params参数,则注销对应的providerName下的所有Provider。

返回值:

类型说明
Promise<void>Promise对象,无返回结果。

错误码:

以下错误码的详细介绍请参见通用错误码HUKS错误码

错误码ID错误信息
201check permission failed.
801api is not supported.
12000005IPC communication failed.
12000011the provider is not found.
12000012Device environment or input parameter is abnormal. This may happen for several reasons, such as the model already being unloaded.
12000014memory is insufficient.
12000018the input parameter is invalid.

示例:

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

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

const providerName = "testProviderName";
const extProperties: Array<huksExternalCrypto.HuksExternalCryptoParam> = [
  {
    tag: huksExternalCrypto.HuksExternalCryptoTag.HUKS_EXT_CRYPTO_TAG_ABILITY_NAME,
    value: StringToUint8Array("CryptoExtension")
  }
];
huksExternalCrypto.unregisterProvider(providerName, extProperties)
    .then((data) => {
        console.info(`promise: unregisterProvider success`);
    });

huksExternalCrypto.getUkeyPinAuthState

getUkeyPinAuthState(resourceId: string, params?: Array<HuksExternalCryptoParam>): Promise<HuksExternalPinAuthState>

获取PIN码认证状态。使用Promise异步回调。

系统能力: SystemCapability.Security.Huks.CryptoExtension

参数:

参数名类型必填说明
resourceIdstring资源ID,可通过导出证书的接口获取,其结果中附带资源ID。
paramsArray<HuksExternalCryptoParam>操作的属性。非系统应用传入HUKS_EXT_CRYPTO_TAG_UID是非法参数。

返回值:

类型说明
Promise<HuksExternalPinAuthState>Promise对象,返回认证结果。
HUKS_EXT_CRYPTO_PIN_NO_AUTH 表示未认证;HUKS_EXT_CRYPTO_PIN_AUTH_SUCCEEDED 表示认证成功;HUKS_EXT_CRYPTO_PIN_LOCKED 表示PIN被锁定。

错误码:

以下错误码的详细介绍请参见通用错误码HUKS错误码

错误码ID错误信息
801api is not supported.
12000005IPC communication failed.
12000006the Ukey driver operation failed.
12000011queried entity does not exist. This may happen because the resource ID has not been opened.
12000012Device environment or input parameter is abnormal. This error may occur if the process function is not found, or due to other issues.
12000014memory is insufficient.
12000018the input parameter is invalid.
12000020the provider operation failed.
12000024the provider or Ukey is busy.

示例:

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

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

const testResourceId = "{\"providerName\":\"testProviderName\", \"bundleName\":\"com.example.cryptoapplication\", \"abilityName\":\"CryptoExtension\",\"index\":{\"key\":\"testKey\"}}";
const extProperties: Array<huksExternalCrypto.HuksExternalCryptoParam> = [];
huksExternalCrypto.getUkeyPinAuthState(testResourceId, extProperties)
    .then((data) => {
      console.info(`promise: getUkeyPinAuthState success, data: ${data}`);
    });

huksExternalCrypto.getProperty

getProperty(resourceId: string, propertyId: string, params?: Array<HuksExternalCryptoParam>): Promise<Array<HuksExternalCryptoParam>>

调用此接口获取属性值并返回结果。使用Promise异步回调。

propertyId表示查询属性的ID信息,当前仅支持GMT 0016-2023中定义的SKF接口名作为属性ID,支持的ID包括如下:

  • SKF_EnumDev
  • SKF_GetDevInfo
  • SKF_EnumApplication
  • SKF_EnumContainer

模型约束: 此接口仅可在Stage模型下使用。

系统能力: SystemCapability.Security.Huks.CryptoExtension

参数:

参数名类型必填说明
resourceIdstring资源ID,可通过导出证书的接口获取,该接口的返回结果中附带resourceId。
propertyIdstring查找操作的属性名称,是GMT 0016-2023中定义的SKF接口名,应用开发者需要针对接口名进行适配。
paramsArray<HuksExternalCryptoParam>需要传递给Extension Ability的输入参数。非系统应用传入HUKS_EXT_CRYPTO_TAG_UID是非法参数。

返回值:

类型说明
Promise<Array<HuksExternalCryptoParam>>Promise对象,返回调用接口的结果。当调用成功时,返回结果为HuksExternalCryptoParam类型的数组,包含要查询的属性。

错误码:

以下错误码的详细介绍请参见通用错误码HUKS错误码

错误码ID错误信息
801API is not supported.
12000005IPC communication failed.
12000006If the Ukey driver operation failed. Possible causes: 1. Error reported when the provider accesses the SKF interface of Ukey.
12000011If the cached resource ID is not found.
12000012Device environment or input parameter is abnormal. This error may occur if the process function is not found, or due to other issues.
12000014If the memory is insufficient.
12000018Input parameter is invalid. Possible causes: 1. The resourceId or propertyId length is invalid. 2. The params contains invalid tags or invalid value types.
12000020If the provider operation failed. Possible causes: 1. The provider experienced an internal processing error.
12000021The Ukey PIN is locked.
12000023The Ukey PIN is not authenticated.
12000024If the provider or Ukey is busy.

示例:

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

const testResourceId = JSON.stringify({
  providerName: "testProviderName",
  bundleName: "com.example.cryptoapplication",
  abilityName: "CryptoExtension",
  index: {
    key: "testKey"
  } as ESObject
});

let propertyId = "SKF_EnumDev";
const extProperties: Array<huksExternalCrypto.HuksExternalCryptoParam> = [];

console.info(`promise: await huksExternalCrypto getProperty`);
async function testFunction() : Promise<void>
{
  try {
    await huksExternalCrypto.getProperty(testResourceId, propertyId, extProperties)
      .then((data) => {
        console.info(`promise: getProperty success, data: ` + JSON.stringify(data));
      });
  } catch (error) {
    console.error(`promise: getProperty failed, errCode : ${error.code}, errMsg : ${error.message}`);
  }
}

huksExternalCrypto.clearUkeyPinAuthState

clearUkeyPinAuthState(resourceId: string): Promise<void>

清除指定资源ID的PIN码认证状态。使用Promise异步回调。

起始版本: 26.0.0

模型约束: 此接口仅可在Stage模型下使用。

系统能力: SystemCapability.Security.Huks.CryptoExtension

参数:

参数名类型必填说明
resourceIdstring资源ID。

返回值:

类型说明
Promise<void>Promise对象,无返回结果。

错误码:

以下错误码的详细介绍请参见通用错误码HUKS错误码

错误码ID错误信息
801API is not supported.
12000005IPC communication failed.
12000006Failed to call the UKey driver interface. Please check the UKey connection and driver status.
12000011The cached resource ID not found.
12000012Device environment or input parameters are abnormal. This may occur if the process function is null, or due to other issues.
12000014The memory is insufficient.
12000018The input parameters are invalid. Possible causes: 1. The resourceId length is invalid.
12000020The provider operation failed. This means an error occurred in the crypto extension before calling the UKey driver interface.
12000024The provider or UKey is busy.

示例:

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

const testResourceId = JSON.stringify({
  providerName: "testProviderName",
  bundleName: "com.example.cryptoapplication",
  abilityName: "CryptoExtension",
  index: {
    key: "testKey"
  } as ESObject
});

huksExternalCrypto.clearUkeyPinAuthState(testResourceId)
    .then(() => {
      console.info('promise: clearUkeyPinAuthState success.');
    });

huksExternalCrypto.getResourceId

getResourceId(providerName: string, params: HuksExternalCryptoParam[]): Promise<string>

获取密钥扩展能力的资源ID。使用Promise异步回调。

起始版本: 26.0.0

模型约束: 此接口仅可在Stage模型下使用。

系统能力: SystemCapability.Security.Huks.CryptoExtension

参数:

参数名类型必填说明
providerNamestring提供者名称,建议包含厂商信息,全局唯一,长度最大为128字节。
paramsArray<HuksExternalCryptoParam>获取资源ID所需的属性参数。必选TAG包括:HUKS_EXT_CRYPTO_TAG_ABILITY_NAMEHUKS_EXT_CRYPTO_TAG_BUNDLE_NAMEHUKS_EXT_CRYPTO_TAG_RESOURCE_INFO

返回值:

类型说明
Promise<string>Promise对象,返回资源ID。

错误码:

以下错误码的详细介绍请参见通用错误码HUKS错误码

错误码ID错误信息
801API is not supported.
12000002The ability name or bundle name parameter is missing.
12000005IPC communication failed.
12000011The cached resource ID not found.
12000012Device environment or input parameters are abnormal. This may occur if the process function is null, or due to other issues.
12000014The memory is insufficient.
12000018The input parameters are invalid. Possible causes: 1. The params contains invalid tags or invalid value types.
12000020The provider operation failed.
12000024The provider or UKey is busy.

示例:

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

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

const providerName = "testProviderName";
const abilityName = "CryptoExtension";
const bundleName = "com.example.cryptoapplication";
// 资源信息,格式和内容由厂商自定义
const resourceInfo = "vendor_defined_resource_info";

const extProperties: Array<huksExternalCrypto.HuksExternalCryptoParam> = [
  {
    tag: huksExternalCrypto.HuksExternalCryptoTag.HUKS_EXT_CRYPTO_TAG_ABILITY_NAME,
    value: StringToUint8Array(abilityName)
  },
  {
    tag: huksExternalCrypto.HuksExternalCryptoTag.HUKS_EXT_CRYPTO_TAG_BUNDLE_NAME,
    value: StringToUint8Array(bundleName)
  },
  {
    tag: huksExternalCrypto.HuksExternalCryptoTag.HUKS_EXT_CRYPTO_TAG_RESOURCE_INFO,
    value: StringToUint8Array(resourceInfo)
  }
];

huksExternalCrypto.getResourceId(providerName, extProperties)
    .then((resourceId) => {
      console.info(`promise: getResourceId success, resourceId: ${resourceId}`);
    });

huksExternalCrypto.openResource

openResource(resourceId: string, params?: HuksExternalCryptoParam[]): Promise<void>

打开指定资源ID的资源。使用Promise异步回调。

说明:

打开的资源必须使用closeResource关闭。

起始版本: 26.0.0

模型约束: 此接口仅可在Stage模型下使用。

系统能力: SystemCapability.Security.Huks.CryptoExtension

参数:

参数名类型必填说明
resourceIdstring资源ID。可通过证书选择接口获取keyUri作为resourceId,或通过getResourceId获取外部密钥管理扩展的资源ID。
paramsArray<HuksExternalCryptoParam>需要传递给Extension Ability的输入参数。不传入时,不向Extension Ability传递额外参数。

返回值:

类型说明
Promise<void>Promise对象,无返回结果。

错误码:

以下错误码的详细介绍请参见通用错误码HUKS错误码

错误码ID错误信息
801API is not supported.
12000005IPC communication failed.
12000006Failed to call the UKey driver interface. Please check the UKey connection and driver status.
12000011The cached resource ID is not found. This may happen because the resource ID has not been opened.
12000012Device environment or input parameters are abnormal. This error may occur if the process function is not found, or due to other issues.
12000014The memory is insufficient.
12000017The resource with the resource ID is already open.
12000018Input parameters are invalid. Possible causes: 1. The resourceId length is invalid. 2. The parameters contain invalid tags or invalid value types.
12000020The provider operation failed. This means an error occurred in the crypto extension before calling the UKey driver interface.
12000024The provider or UKey is busy.
12000025The opened resources exceed the limit.

示例:

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

const testResourceId = JSON.stringify({
  providerName: "testProviderName",
  bundleName: "com.example.cryptoapplication",
  abilityName: "CryptoExtension",
  index: {
    key: "testKey"
  } as ESObject
});

huksExternalCrypto.openResource(testResourceId)
    .then(() => {
      console.info('promise: openResource success.');
    });

huksExternalCrypto.closeResource

closeResource(resourceId: string, params?: HuksExternalCryptoParam[]): Promise<void>

关闭指定资源ID的资源。使用Promise异步回调。

该接口会回调onClearUkeyPinAuthState清理该资源关联的PIN认证状态,以及会回调onFinishSession清理该资源关联的会话handle。

起始版本: 26.0.0

模型约束: 此接口仅可在Stage模型下使用。

系统能力: SystemCapability.Security.Huks.CryptoExtension

参数:

参数名类型必填说明
resourceIdstring资源ID。可通过证书选择接口获取keyUri作为resourceId,或通过getResourceId获取外部密钥管理扩展的资源ID。
paramsArray<HuksExternalCryptoParam>需要传递给Extension Ability的输入参数。不传入时,不向Extension Ability传递额外参数。

返回值:

类型说明
Promise<void>Promise对象,无返回结果。

错误码:

以下错误码的详细介绍请参见通用错误码HUKS错误码

错误码ID错误信息
801API is not supported.
12000005IPC communication failed.
12000006Failed to call the UKey driver interface. Please check the UKey connection and driver status.
12000012Device environment or input parameters are abnormal. This error may occur if the process function is not found, or due to other issues.
12000014The memory is insufficient.
12000018Input parameters are invalid. Possible causes: 1. The resourceId length is invalid. 2. The parameters contain invalid tags or invalid value types.
12000020The provider operation failed. This means an error occurred in the crypto extension before calling the UKey driver interface.
12000024The provider or UKey is busy.

示例:

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

const testResourceId = JSON.stringify({
  providerName: "testProviderName",
  bundleName: "com.example.cryptoapplication",
  abilityName: "CryptoExtension",
  index: {
    key: "testKey"
  } as ESObject
});

huksExternalCrypto.closeResource(testResourceId)
    .then(() => {
      console.info('promise: closeResource success.');
    });

你可能感兴趣的鸿蒙文章

openharmony 鸿蒙 js-apis-huksExternalCrypto-sys

openharmony 鸿蒙 capi-hukstypeapi-oh-huks-keymaterialrsa

openharmony 鸿蒙 capi-hukstypeapi-oh-huks-result

openharmony 鸿蒙 capi-native-huks-type-h

openharmony 鸿蒙 js-apis-CryptoExtensionAbility

openharmony 鸿蒙 capi-hukstypeapi-oh-huks-pubkeyinfo

openharmony 鸿蒙 capi-hukstypeapi-oh-huks-certchain

openharmony 鸿蒙 capi-hukstypeapi-oh-huks-keymaterialdsa

openharmony 鸿蒙 Readme-CN

openharmony 鸿蒙 capi-hukstypeapi

  • 所属分类: 后端技术
  • 本文标签: 软件 鸿蒙
  • 版权声明: 本文链接 https://seaxiang.com/blog/3N3LzWqL