harmony 鸿蒙@ohos.security.huks (通用密钥库系统)

2022-08-09 浏览 (1189)

@ohos.security.huks (通用密钥库系统)

向应用提供密钥库能力,包括密钥管理及密钥的密码学操作等功能。 HUKS所管理的密钥可以由应用导入或者由应用调用HUKS接口生成。

说明

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

导入模块

import huks from '@ohos.security.huks'

HuksParam

调用接口使用的options中的properties数组中的param。

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

名称类型必填说明
tagHuksTag标签。
valueboolean|number|bigint|Uint8Array标签对应值。

HuksOptions

调用接口使用的options。

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

名称类型必填说明
propertiesArray<HuksParam>属性,用于存HuksParam的数组。
inDataUint8Array输入数据。

HuksSessionHandle9+

huks Handle结构体。

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

名称类型必填说明
handlenumber表示handle值。
challengeUint8Array表示initSession操作之后获取到的challenge信息。

HuksReturnResult9+

调用接口返回的result。

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

名称类型必填说明
outDataUint8Array表示输出数据。
propertiesArray<HuksParam>表示属性信息。
certChainsArray<string>表示证书链数据。

huks.generateKeyItem9+

generateKeyItem(keyAlias: string, options: HuksOptions, callback: AsyncCallback<void>) : void

生成密钥,使用Callback回调异步返回结果。

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

参数:

参数名类型必填说明
keyAliasstring别名。
optionsHuksOptions用于存放生成key所需TAG。其中密钥使用的算法、密钥用途、密钥长度为必选参数。
callbackAsyncCallback<void>回调函数。未捕获error时代表用户指定别名的密钥生成成功,基于密钥不出TEE原则,此接口不会返回密钥材料内容,若捕获error,则为生成阶段出现异常。

错误码:

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

错误码ID错误信息
401argument is invalid.
801api is not supported.
12000001algorithm mode is not supported.
12000002algorithm param is missing.
12000003algorithm param is invalid.
12000004operating file failed.
12000005IPC communication failed.
12000006error occured in crypto engine.
12000012external error.
12000013queried credential does not exist.
12000014memory is insufficient.
12000015call service failed.

示例:

import huks from '@ohos.security.huks';
/* 以生成ECC256密钥为例 */
class HuksProperties {
    tag: huks.HuksTag = huks.HuksTag.HUKS_TAG_ALGORITHM
    value: huks.HuksKeyAlg|huks.HuksKeySize|huks.HuksKeyPurpose|huks.HuksKeyDigest = huks.HuksKeyAlg.HUKS_ALG_ECC
}
let keyAlias: string = 'keyAlias';
let properties: HuksProperties[] = [
    {
        tag: huks.HuksTag.HUKS_TAG_ALGORITHM,
        value: huks.HuksKeyAlg.HUKS_ALG_ECC
    },
    {
        tag: huks.HuksTag.HUKS_TAG_KEY_SIZE,
        value: huks.HuksKeySize.HUKS_ECC_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_SHA256
    },
];
let options: huks.HuksOptions = {
    properties: properties
};
try {
    huks.generateKeyItem(keyAlias, options, (error, data) => {
        if (error) {
            console.error(`callback: generateKeyItem failed`);
        } else {
            console.info(`callback: generateKeyItem key success`);
        }
    });
} catch (error) {
    console.error(`callback: generateKeyItem input arg invalid`);
}

huks.generateKeyItem9+

generateKeyItem(keyAlias: string, options: HuksOptions) : Promise<void>

生成密钥,使用Promise方式异步返回结果。基于密钥不出TEE原则,通过promise不会返回密钥材料内容,只用于表示此次调用是否成功。

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

参数:

参数名类型必填说明
keyAliasstring密钥别名。
optionsHuksOptions用于存放生成key所需TAG。其中密钥使用的算法、密钥用途、密钥长度为必选参数。

错误码:

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

错误码ID错误信息
401argument is invalid.
801api is not supported.
12000001algorithm mode is not supported.
12000002algorithm param is missing.
12000003algorithm param is invalid.
12000004operating file failed.
12000005IPC communication failed.
12000006error occured in crypto engine.
12000012external error.
12000013queried credential does not exist.
12000014memory is insufficient.
12000015call service failed.

示例:

/* 以生成ECC256密钥为例 */
import huks from '@ohos.security.huks';
import { BusinessError } from '@ohos.base';
class HuksProperties {
    tag: huks.HuksTag = huks.HuksTag.HUKS_TAG_ALGORITHM
    value: huks.HuksKeyAlg|huks.HuksKeySize|huks.HuksKeyPurpose|huks.HuksKeyDigest = huks.HuksKeyAlg.HUKS_ALG_ECC
}
let keyAlias = 'keyAlias';
let properties: HuksProperties[] = [
    {
        tag: huks.HuksTag.HUKS_TAG_ALGORITHM,
        value: huks.HuksKeyAlg.HUKS_ALG_ECC
    },
    {
        tag: huks.HuksTag.HUKS_TAG_KEY_SIZE,
        value: huks.HuksKeySize.HUKS_ECC_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_SHA256
    },
];
let options: huks.HuksOptions = {
    properties: properties
};
try {
    huks.generateKeyItem(keyAlias, options)
        .then((data) => {
            console.info(`promise: generateKeyItem success`);
        })
        .catch((error: BusinessError) => {
            console.error(`promise: generateKeyItem failed`);
        });
} catch (error) {
    console.error(`promise: generateKeyItem input arg invalid`);
}

huks.deleteKeyItem9+

deleteKeyItem(keyAlias: string, options: HuksOptions, callback: AsyncCallback<void>) : void

删除密钥,使用Callback回调异步返回结果。

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

参数:

参数名类型必填说明
keyAliasstring密钥别名,应为生成key时传入的别名。
optionsHuksOptions空对象(此处传空即可)。
callbackAsyncCallback<void>回调函数。不返回err值时表示接口使用成功,其他时为错误。

错误码:

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

错误码ID错误信息
401argument is invalid.
801api is not supported.
12000004operating file failed.
12000005IPC communication failed.
12000011queried entity does not exist.
12000012external error.
12000014memory is insufficient.

示例:

import huks from '@ohos.security.huks';
/* 此处options选择emptyOptions传空 */
let keyAlias = 'keyAlias';
let emptyOptions: huks.HuksOptions = {
    properties: []
};
try {
    huks.deleteKeyItem(keyAlias, emptyOptions, (error, data) => {
        if (error) {
            console.error(`callback: deleteKeyItem failed`);
        } else {
            console.info(`callback: deleteKeyItem key success`);
        }
    });
} catch (error) {
    console.error(`callback: deleteKeyItem input arg invalid`);
}

huks.deleteKeyItem9+

deleteKeyItem(keyAlias: string, options: HuksOptions) : Promise<void>

删除密钥,使用Promise方式异步返回结果。

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

参数:

参数名类型必填说明
keyAliasstring密钥别名,应为生成key时传入的别名。
optionsHuksOptions空对象(此处传空即可)。

错误码:

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

错误码ID错误信息
401argument is invalid.
801api is not supported.
12000004operating file failed.
12000005IPC communication failed.
12000011queried entity does not exist.
12000012external error.
12000014memory is insufficient.

示例:

import huks from '@ohos.security.huks';
import { BusinessError } from '@ohos.base';
/* 此处options选择emptyOptions传空 */
let keyAlias = 'keyAlias';
let emptyOptions: huks.HuksOptions = {
    properties: []
};
try {
    huks.deleteKeyItem(keyAlias, emptyOptions)
        .then ((data) => {
            console.info(`promise: deleteKeyItem key success`);
        })
        .catch((error: BusinessError) => {
            console.error(`promise: deleteKeyItem failed`);
        });
} catch (error) {
    console.error(`promise: deleteKeyItem input arg invalid`);
}

huks.getSdkVersion

getSdkVersion(options: HuksOptions) : string

获取当前系统sdk版本。

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

参数:

参数名类型必填说明
optionsHuksOptions空对象,用于存放sdk版本。

返回值:

类型说明
string返回sdk版本。

示例:

import huks from '@ohos.security.huks';
/* 此处options选择emptyOptions传空 */
let emptyOptions: huks.HuksOptions = {
    properties: []
};
let result = huks.getSdkVersion(emptyOptions);

huks.importKeyItem9+

importKeyItem(keyAlias: string, options: HuksOptions, callback: AsyncCallback<void>) : void

导入明文密钥,使用Callback方式回调异步返回结果 。

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

参数:

参数名类型必填说明
keyAliasstring密钥别名。
optionsHuksOptions用于导入时所需TAG和需要导入的密钥。其中密钥使用的算法、密钥用途、密钥长度为必选参数。
callbackAsyncCallback<void>回调函数。不返回err值时表示接口使用成功,其他时为错误。

错误码:

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

错误码ID错误信息
401argument is invalid.
801api is not supported.
12000001algorithm mode is not supported.
12000002algorithm param is missing.
12000003algorithm param is invalid.
12000004operating file failed.
12000005IPC communication failed.
12000006error occured in crypto engine.
12000011queried entity does not exist.
12000012external error.
12000013queried credential does not exist.
12000014memory is insufficient.
12000015call service failed.

示例:

import huks from '@ohos.security.huks';
/* 以导入AES256密钥为例 */
class HuksProperties {
    tag: huks.HuksTag = huks.HuksTag.HUKS_TAG_ALGORITHM
    value: huks.HuksKeyAlg|huks.HuksKeySize|huks.HuksKeyPurpose|huks.HuksKeyPadding|
    huks.HuksCipherMode = huks.HuksKeyAlg.HUKS_ALG_ECC
}
let plainTextSize32 = makeRandomArr(32);
function makeRandomArr(size: number) {
    let arr = new Uint8Array(size);
    for (let i = 0; i < size; i++) {
        arr[i] = Math.floor(Math.random() * 10);
    }
    return arr;
};
let keyAlias = 'keyAlias';
let properties: HuksProperties[] = [
    {
        tag: huks.HuksTag.HUKS_TAG_ALGORITHM,
        value: huks.HuksKeyAlg.HUKS_ALG_AES
    },
    {
        tag: huks.HuksTag.HUKS_TAG_KEY_SIZE,
        value: huks.HuksKeySize.HUKS_AES_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_PADDING,
        value: huks.HuksKeyPadding.HUKS_PADDING_PKCS7
    },
    {
        tag: huks.HuksTag.HUKS_TAG_BLOCK_MODE,
        value: huks.HuksCipherMode.HUKS_MODE_ECB
    }
];
let options: huks.HuksOptions = {
    properties: properties,
    inData: plainTextSize32
};
try {
    huks.importKeyItem(keyAlias, options, (error, data) => {
        if (error) {
            console.error(`callback: importKeyItem failed`);
        } else {
            console.info(`callback: importKeyItem success`);
        }
    });
} catch (error) {
    console.error(`callback: importKeyItem input arg invalid`);
}

huks.importKeyItem9+

importKeyItem(keyAlias: string, options: HuksOptions) : Promise<void>

导入明文密钥,使用Promise方式异步返回结果。

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

参数:

参数名类型必填说明
keyAliasstring密钥别名。
optionsHuksOptions用于导入时所需TAG和需要导入的密钥。其中密钥使用的算法、密钥用途、密钥长度为必选参数。

错误码:

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

错误码ID错误信息
401argument is invalid.
801api is not supported.
12000001algorithm mode is not supported.
12000002algorithm param is missing.
12000003algorithm param is invalid.
12000004operating file failed.
12000005IPC communication failed.
12000006error occured in crypto engine.
12000011queried entity does not exist.
12000012external error.
12000013queried credential does not exist.
12000014memory is insufficient.
12000015call service failed.

示例:

import huks from '@ohos.security.huks';
import { BusinessError } from '@ohos.base';
/* 以导入AES128为例 */
class HuksProperties {
    tag: huks.HuksTag = huks.HuksTag.HUKS_TAG_ALGORITHM
    value: huks.HuksKeyAlg|huks.HuksKeySize|huks.HuksKeyPurpose|huks.HuksKeyPadding|
    huks.HuksCipherMode = huks.HuksKeyAlg.HUKS_ALG_ECC
}
let plainTextSize32 = makeRandomArr(32);
function makeRandomArr(size: number) {
    let arr = new Uint8Array(size);
    for (let i = 0; i < size; i++) {
        arr[i] = Math.floor(Math.random() * 10);
    }
    return arr;
};
/*第一步:生成密钥*/
let keyAlias = 'keyAlias';
let properties: HuksProperties[] = [
    {
        tag: huks.HuksTag.HUKS_TAG_ALGORITHM,
        value: huks.HuksKeyAlg.HUKS_ALG_AES
    },
    {
        tag: huks.HuksTag.HUKS_TAG_KEY_SIZE,
        value: huks.HuksKeySize.HUKS_AES_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_PADDING,
        value: huks.HuksKeyPadding.HUKS_PADDING_PKCS7
    },
    {
        tag: huks.HuksTag.HUKS_TAG_BLOCK_MODE,
        value: huks.HuksCipherMode.HUKS_MODE_ECB
    }
];
let huksoptions: huks.HuksOptions = {
    properties: properties,
    inData: plainTextSize32
};
try {
    huks.importKeyItem(keyAlias, huksoptions)
        .then((data) => {
            console.info(`promise: importKeyItem success`);
        })
        .catch((error: BusinessError) => {
            console.error(`promise: importKeyItem failed`);
        });
} catch (error) {
    console.error(`promise: importKeyItem input arg invalid`);
}

huks.attestKeyItem9+

attestKeyItem(keyAlias: string, options: HuksOptions, callback: AsyncCallback<HuksReturnResult>) : void

获取密钥证书,使用Callback方式回调异步返回结果 。

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

参数:

参数名类型必填说明
keyAliasstring密钥别名,存放待获取证书密钥的别名。
optionsHuksOptions用于获取证书时指定所需参数与数据。
callbackAsyncCallback<HuksReturnResult>回调函数。不返回err值时表示接口使用成功,其他时为错误。

错误码:

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

错误码ID错误信息
201check permission failed.
401argument is invalid.
801api is not supported.
12000001algorithm mode is not supported.
12000002algorithm param is missing.
12000003algorithm param is invalid.
12000004operating file failed.
12000005IPC communication failed.
12000006error occured in crypto engine.
12000011queried entity does not exist.
12000012external error.
12000014memory is insufficient.

示例:

import huks from '@ohos.security.huks';
class HuksProperties {
    tag: huks.HuksTag = huks.HuksTag.HUKS_TAG_ALGORITHM
    value: huks.HuksKeyAlg|huks.HuksKeySize|huks.HuksKeyPurpose|huks.HuksKeyDigest|
    huks.HuksKeyStorageType|huks.HuksKeyPadding|huks.HuksKeyGenerateType|
    huks.HuksCipherMode|Uint8Array = huks.HuksKeyAlg.HUKS_ALG_ECC
}
let securityLevel = stringToUint8Array('sec_level');
let challenge = stringToUint8Array('challenge_data');
let versionInfo = stringToUint8Array('version_info');
let keyAliasString = "key attest";
function stringToUint8Array(str: string) {
    let arr: number[] = [];
    for (let i = 0, j = str.length; i < j; ++i) {
        arr.push(str.charCodeAt(i));
    }
    let tmpUint8Array = new Uint8Array(arr);
    return tmpUint8Array;
}

async function generateKeyThenattestKey(alias: string) {
    let aliasString = keyAliasString;
    let aliasUint8 = stringToUint8Array(aliasString);
    let generateProperties: HuksProperties[] = [
        {
            tag: huks.HuksTag.HUKS_TAG_ALGORITHM,
            value: huks.HuksKeyAlg.HUKS_ALG_RSA
        },
        {
            tag: huks.HuksTag.HUKS_TAG_KEY_STORAGE_FLAG,
            value: huks.HuksKeyStorageType.HUKS_STORAGE_PERSISTENT
        },
        {
            tag: huks.HuksTag.HUKS_TAG_KEY_SIZE,
            value: huks.HuksKeySize.HUKS_RSA_KEY_SIZE_2048
        },
        {
            tag: huks.HuksTag.HUKS_TAG_PURPOSE,
            value: huks.HuksKeyPurpose.HUKS_KEY_PURPOSE_VERIFY
        },
        {
            tag: huks.HuksTag.HUKS_TAG_DIGEST,
            value: huks.HuksKeyDigest.HUKS_DIGEST_SHA256
        },
        {
            tag: huks.HuksTag.HUKS_TAG_PADDING,
            value: huks.HuksKeyPadding.HUKS_PADDING_PSS
        },
        {
            tag: huks.HuksTag.HUKS_TAG_KEY_GENERATE_TYPE,
            value: huks.HuksKeyGenerateType.HUKS_KEY_GENERATE_TYPE_DEFAULT
        },
        {
            tag: huks.HuksTag.HUKS_TAG_BLOCK_MODE,
            value: huks.HuksCipherMode.HUKS_MODE_ECB
        }
    ];
    let generateOptions: huks.HuksOptions = {
        properties: generateProperties
    };
    let attestProperties: HuksProperties[] = [
        {
            tag: huks.HuksTag.HUKS_TAG_ATTESTATION_ID_SEC_LEVEL_INFO,
            value: securityLevel
        },
        {
            tag: huks.HuksTag.HUKS_TAG_ATTESTATION_CHALLENGE,
            value: challenge
        },
        {
            tag: huks.HuksTag.HUKS_TAG_ATTESTATION_ID_VERSION_INFO,
            value: versionInfo
        },
        {
            tag: huks.HuksTag.HUKS_TAG_ATTESTATION_ID_ALIAS,
            value: aliasUint8
        }
    ];
    let attestOptions: huks.HuksOptions = {
        properties: attestProperties
    };
    try {
        huks.generateKeyItem(alias, generateOptions, (error, data) => {
            if (error) {
                console.error(`callback: generateKeyItem failed`);
            } else {
                console.info(`callback: generateKeyItem success`);
                try {
                    huks.attestKeyItem(aliasString, attestOptions, (error, data) => {
                        if (error) {
                            console.error(`callback: attestKeyItem failed`);
                        } else {
                            console.info(`callback: attestKeyItem success`);
                        }
                    });
                } catch (error) {
                    console.error(`callback: attestKeyItem input arg invalid`);
                }
            }
        });
    } catch (error) {
        console.error(`callback: generateKeyItem input arg invalid`);
    }
}

huks.attestKeyItem9+

attestKeyItem(keyAlias: string, options: HuksOptions) : Promise<HuksReturnResult>

获取密钥证书,使用Promise方式异步返回结果 。

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

参数:

参数名类型必填说明
keyAliasstring密钥别名,存放待获取证书密钥的别名。
optionsHuksOptions用于获取证书时指定所需参数与数据。

返回值:

类型说明
Promise<HuksReturnResult>Promise对象。不返回err值时表示接口使用成功,其他时为错误。

错误码:

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

错误码ID错误信息
201check permission failed.
401argument is invalid.
801api is not supported.
12000001algorithm mode is not supported.
12000002algorithm param is missing.
12000003algorithm param is invalid.
12000004operating file failed.
12000005IPC communication failed.
12000006error occured in crypto engine.
12000011queried entity does not exist.
12000012external error.
12000014memory is insufficient.

示例:

import huks from '@ohos.security.huks';
import { BusinessError } from '@ohos.base';
class HuksProperties {
    tag: huks.HuksTag = huks.HuksTag.HUKS_TAG_ALGORITHM
    value: huks.HuksKeyAlg|huks.HuksKeySize|huks.HuksKeyPurpose|huks.HuksKeyDigest|
    huks.HuksKeyStorageType|huks.HuksKeyPadding|huks.HuksKeyGenerateType|
    huks.HuksCipherMode|Uint8Array = huks.HuksKeyAlg.HUKS_ALG_ECC
}
let securityLevel = stringToUint8Array('sec_level');
let challenge = stringToUint8Array('challenge_data');
let versionInfo = stringToUint8Array('version_info');
let keyAliasString = "key attest";
function stringToUint8Array(str: string) {
    let arr: number[] = [];
    for (let i = 0, j = str.length; i < j; ++i) {
        arr.push(str.charCodeAt(i));
    }
    let tmpUint8Array = new Uint8Array(arr);
    return tmpUint8Array;
}
async function generateKey(alias: string) {
    let properties: HuksProperties[] = [
        {
            tag: huks.HuksTag.HUKS_TAG_ALGORITHM,
            value: huks.HuksKeyAlg.HUKS_ALG_RSA
        },
        {
            tag: huks.HuksTag.HUKS_TAG_KEY_STORAGE_FLAG,
            value: huks.HuksKeyStorageType.HUKS_STORAGE_PERSISTENT
        },
        {
            tag: huks.HuksTag.HUKS_TAG_KEY_SIZE,
            value: huks.HuksKeySize.HUKS_RSA_KEY_SIZE_2048
        },
        {
            tag: huks.HuksTag.HUKS_TAG_PURPOSE,
            value: huks.HuksKeyPurpose.HUKS_KEY_PURPOSE_VERIFY
        },
        {
            tag: huks.HuksTag.HUKS_TAG_DIGEST,
            value: huks.HuksKeyDigest.HUKS_DIGEST_SHA256
        },
        {
            tag: huks.HuksTag.HUKS_TAG_PADDING,
            value: huks.HuksKeyPadding.HUKS_PADDING_PSS
        },
        {
            tag: huks.HuksTag.HUKS_TAG_KEY_GENERATE_TYPE,
            value: huks.HuksKeyGenerateType.HUKS_KEY_GENERATE_TYPE_DEFAULT
        },
        {
            tag: huks.HuksTag.HUKS_TAG_BLOCK_MODE,
            value: huks.HuksCipherMode.HUKS_MODE_ECB
        }
    ];
    let options: huks.HuksOptions = {
        properties: properties
    };
    try {
        await huks.generateKeyItem(alias, options)
            .then((data) => {
                console.info(`promise: generateKeyItem success`);
            })
            .catch((error: BusinessError) => {
                console.error(`promise: generateKeyItem failed`);
            });
    } catch (error) {
        console.error(`promise: generateKeyItem input arg invalid`);
    }
}
async function attestKey() {
    let aliasString = keyAliasString;
    let aliasUint8 = stringToUint8Array(aliasString);
    let properties: HuksProperties[] = [
        {
            tag: huks.HuksTag.HUKS_TAG_ATTESTATION_ID_SEC_LEVEL_INFO,
            value: securityLevel
        },
        {
            tag: huks.HuksTag.HUKS_TAG_ATTESTATION_CHALLENGE,
            value: challenge
        },
        {
            tag: huks.HuksTag.HUKS_TAG_ATTESTATION_ID_VERSION_INFO,
            value: versionInfo
        },
        {
            tag: huks.HuksTag.HUKS_TAG_ATTESTATION_ID_ALIAS,
            value: aliasUint8
        }
    ];
    let options: huks.HuksOptions = {
        properties: properties
    };
    await generateKey(aliasString);
    try {
        await huks.attestKeyItem(aliasString, options)
            .then((data) => {
                console.info(`promise: attestKeyItem success`);
            })
            .catch((error: BusinessError) => {
                console.error(`promise: attestKeyItem failed`);
            });
    } catch (error) {
        console.error(`promise: attestKeyItem input arg invalid`);
    }
}

huks.importWrappedKeyItem9+

importWrappedKeyItem(keyAlias: string, wrappingKeyAlias: string, options: HuksOptions, callback: AsyncCallback<void>) : void

导入加密密钥,使用Callback方式回调异步返回结果 。

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

参数:

参数名类型必填说明
keyAliasstring密钥别名,存放待导入密钥的别名。
wrappingKeyAliasstring密钥别名,对应密钥用于解密加密的密钥数据。
optionsHuksOptions用于导入时所需TAG和需要导入的加密的密钥数据。其中密钥使用的算法、密钥用途、密钥长度为必选参数。
callbackAsyncCallback<void>回调函数。不返回err值时表示接口使用成功,其他时为错误。

错误码:

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

错误码ID错误信息
401argument is invalid.
801api is not supported.
12000001algorithm mode is not supported.
12000002algorithm param is missing.
12000003algorithm param is invalid.
12000004operating file failed.
12000005IPC communication failed.
12000006error occured in crypto engine.
12000011queried entity does not exist.
12000012external error.
12000013queried credential does not exist.
12000014memory is insufficient.
12000015call service failed.

示例:

import huks from '@ohos.security.huks';
import { BusinessError } from '@ohos.base';
class HuksProperties {
    tag: huks.HuksTag = huks.HuksTag.HUKS_TAG_ALGORITHM
    value: huks.HuksKeyAlg|huks.HuksKeySize|huks.HuksKeyPurpose|
    huks.HuksKeyDigest|huks.HuksKeyPadding|huks.HuksUnwrapSuite|
    huks.HuksCipherMode|huks.HuksImportKeyType = huks.HuksKeyAlg.HUKS_ALG_ECC
}
let alias1 = "importAlias";
let alias2 = "wrappingKeyAlias";
async function TestGenFunc(alias: string, options: huks.HuksOptions) {
    try {
        await genKey(alias, options)
            .then((data) => {
                console.info(`callback: generateKeyItem success`);
            })
            .catch((error: BusinessError) => {
                console.error(`callback: generateKeyItem failed`);
            });
    } catch (error) {
        console.error(`callback: generateKeyItem input arg invalid`);
    }
}
function genKey(alias: string, options: huks.HuksOptions) {
    return new Promise<void>((resolve, reject) => {
        try {
            huks.generateKeyItem(alias, options, (error, data) => {
                if (error) {
                    reject(error);
                } else {
                    resolve(data);
                }
            });
        } catch (error) {
            throw (new Error(error));
        }
    });
}
async function TestExportFunc(alias: string, options: huks.HuksOptions) {
    try {
        await exportKey(alias, options)
            .then((data) => {
                console.info(`callback: exportKeyItem success, data = ${JSON.stringify(data)}`);
            })
            .catch((error: BusinessError) => {
                console.error(`callback: exportKeyItem failed`);
            });
    } catch (error) {
        console.error(`callback: exportKeyItem input arg invalid`);
    }
}
function exportKey(alias: string, options: huks.HuksOptions) {
    return new Promise<huks.HuksReturnResult>((resolve, reject) => {
        try {
            huks.exportKeyItem(alias, options, (error, data) => {
                if (error) {
                    reject(error);
                } else {
                    resolve(data);
                }
            });
        } catch (error) {
            throw (new Error(error));
        }
    });
}
async function TestImportWrappedFunc(alias: string, wrappingAlias: string, options: huks.HuksOptions) {
    try {
        await importWrappedKey(alias, wrappingAlias, options)
            .then((data) => {
                console.info(`callback: importWrappedKeyItem success`);
            })
            .catch((error: BusinessError) => {
                console.error(`callback: importWrappedKeyItem failed`);
            });
    } catch (error) {
        console.error(`callback: importWrappedKeyItem input arg invalid`);
    }
}
function importWrappedKey(alias: string, wrappingAlias: string, options: huks.HuksOptions) {
    return new Promise<void>((resolve, reject) => {
        try {
            huks.importWrappedKeyItem(alias, wrappingAlias, options, (error, data) => {
                if (error) {
                    reject(error);
                } else {
                    resolve(data);
                }
            });
        } catch (error) {
            throw (new Error(error));
        }
    });
}
async function TestImportWrappedKeyFunc(
        alias: string,
        wrappingAlias: string,
        genOptions: huks.HuksOptions,
        importOptions: huks.HuksOptions
) {
    await TestGenFunc(wrappingAlias, genOptions);
    await TestExportFunc(wrappingAlias, genOptions);

    /* 以下操作不需要调用HUKS接口,此处不给出具体实现。
     * 假设待导入的密钥为keyA
     * 1.生成ECC公私钥keyB,公钥为keyB_pub, 私钥为keyB_pri
     * 2.使用keyB_pri和wrappingAlias密钥中获取的公钥进行密钥协商,协商出共享密钥share_key
     * 3.随机生成密钥kek,用于加密keyA,采用AES-GCM加密,加密过程中需要记录:nonce1、aad1、加密后的密文keyA_enc、加密后的tag1。
     * 4.使用share_key加密kek,采用AES-GCM加密,加密过程中需要记录:nonce2、aad2、加密后的密文kek_enc、加密后的tag2。
     * 5.拼接importOptions.inData字段,满足以下格式:
     * keyB_pub的长度(4字节) + keyB_pub的数据 + aad2的长度(4字节) + aad2的数据 +
     * nonce2的长度(4字节)   + nonce2的数据   + tag2的长度(4字节) + tag2的数据 +
     * kek_enc的长度(4字节)  + kek_enc的数据  + aad1的长度(4字节) + aad1的数据 +
     * nonce1的长度(4字节)   + nonce1的数据   + tag1的长度(4字节) + tag1的数据 +
     * keyA长度占用的内存长度(4字节)  + keyA的长度     + keyA_enc的长度(4字节) + keyA_enc的数据
     */
    /* 该处为示例代码,实际运行过程中,应使用实际导入密钥数据。数据构造方式由上注释可见说明 */
    let inputKey = new Uint8Array([0x02, 0x00, 0x00, 0x00]);
    importOptions.inData = inputKey;
    await TestImportWrappedFunc(alias, wrappingAlias, importOptions);
}
function makeGenerateOptions() {
    let properties: HuksProperties[] = [
        {
            tag: huks.HuksTag.HUKS_TAG_ALGORITHM,
            value: huks.HuksKeyAlg.HUKS_ALG_ECC
        },
        {
            tag: huks.HuksTag.HUKS_TAG_KEY_SIZE,
            value: huks.HuksKeySize.HUKS_ECC_KEY_SIZE_256
        },
        {
            tag: huks.HuksTag.HUKS_TAG_PURPOSE,
            value: huks.HuksKeyPurpose.HUKS_KEY_PURPOSE_UNWRAP
        },
        {
            tag: huks.HuksTag.HUKS_TAG_DIGEST,
            value: huks.HuksKeyDigest.HUKS_DIGEST_SHA256
        },
        {
            tag: huks.HuksTag.HUKS_TAG_IMPORT_KEY_TYPE,
            value: huks.HuksImportKeyType.HUKS_KEY_TYPE_KEY_PAIR,
        }
    ];
    let options: huks.HuksOptions = {
        properties: properties
    };
    return options;
};
function makeImportOptions() {
    let properties: HuksProperties[] = [
        {
            tag: huks.HuksTag.HUKS_TAG_ALGORITHM,
            value: huks.HuksKeyAlg.HUKS_ALG_AES
        },
        {
            tag: huks.HuksTag.HUKS_TAG_KEY_SIZE,
            value: huks.HuksKeySize.HUKS_AES_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_BLOCK_MODE,
            value: huks.HuksCipherMode.HUKS_MODE_CBC
        },
        {
            tag: huks.HuksTag.HUKS_TAG_PADDING,
            value: huks.HuksKeyPadding.HUKS_PADDING_NONE
        },
        {
            tag: huks.HuksTag.HUKS_TAG_UNWRAP_ALGORITHM_SUITE,
            value: huks.HuksUnwrapSuite.HUKS_UNWRAP_SUITE_ECDH_AES_256_GCM_NOPADDING
        }
    ];
    let options: huks.HuksOptions = {
        properties: properties
    };
    return options;
};
function huksImportWrappedKey() {
    let genOptions = makeGenerateOptions();
    let importOptions = makeImportOptions();
    TestImportWrappedKeyFunc(
        alias1,
        alias2,
        genOptions,
        importOptions
    );
}

huks.importWrappedKeyItem9+

importWrappedKeyItem(keyAlias: string, wrappingKeyAlias: string, options: HuksOptions) : Promise<void>

导入加密密钥,使用Promise方式异步返回结果。

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

参数:

参数名类型必填说明
keyAliasstring密钥别名,存放待导入密钥的别名。
wrappingKeyAliasstring密钥别名,对应密钥用于解密加密的密钥数据。
optionsHuksOptions用于导入时所需TAG和需要导入的加密的密钥数据。其中密钥使用的算法、密钥用途、密钥长度为必选参数。

错误码:

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

错误码ID错误信息
401argument is invalid.
801api is not supported.
12000001algorithm mode is not supported.
12000002algorithm param is missing.
12000003algorithm param is invalid.
12000004operating file failed.
12000005IPC communication failed.
12000006error occured in crypto engine.
12000011queried entity does not exist.
12000012external error.
12000013queried credential does not exist.
12000014memory is insufficient.
12000015call service failed.

示例:

import huks from '@ohos.security.huks';
import { BusinessError } from '@ohos.base';
/* 处理流程与callback类似,主要差异点为如下函数: */
/* 该处为示例代码,实际运行过程中,应使用实际导入密钥数据。数据构造方式由上注释可见说明 */
async function TestImportWrappedFunc(alias: string, wrappingAlias: string, options: huks.HuksOptions) {
    try {
        await huks.importWrappedKeyItem(alias, wrappingAlias, options)
            .then ((data) => {
                console.info(`promise: importWrappedKeyItem success`);
            })
            .catch((error: BusinessError) => {
                console.error(`promise: importWrappedKeyItem failed`);
            });
    } catch (error) {
        console.error(`promise: importWrappedKeyItem input arg invalid`);
    }
}

huks.exportKeyItem9+

exportKeyItem(keyAlias: string, options: HuksOptions, callback: AsyncCallback<HuksReturnResult>) : void

导出密钥,使用Callback方式回调异步返回的结果。

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

参数:

参数名类型必填说明
keyAliasstring密钥别名,应与所用密钥生成时使用的别名相同。
optionsHuksOptions空对象(此处传空即可)。
callbackAsyncCallback<HuksReturnResult>回调函数。不返回err值时表示接口使用成功,其他时为错误。outData:返回从密钥中导出的公钥。

错误码:

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

错误码ID错误信息
401argument is invalid.
801api is not supported.
12000001algorithm mode is not supported.
12000002algorithm param is missing.
12000003algorithm param is invalid.
12000004operating file failed.
12000005IPC communication failed.
12000006error occured in crypto engine.
12000011queried entity does not exist.
12000012external error.
12000014memory is insufficient.

示例:

import huks from '@ohos.security.huks';
/* 此处options选择emptyOptions来传空 */
let keyAlias = 'keyAlias';
let emptyOptions: huks.HuksOptions = {
    properties: []
};
try {
    huks.exportKeyItem(keyAlias, emptyOptions, (error, data) => {
        if (error) {
            console.error(`callback: exportKeyItem failed`);
        } else {
            console.info(`callback: exportKeyItem success, data = ${JSON.stringify(data)}`);
        }
    });
} catch (error) {
    console.error(`callback: exportKeyItem input arg invalid`);
}

huks.exportKeyItem9+

exportKeyItem(keyAlias: string, options: HuksOptions) : Promise<HuksReturnResult>

导出密钥,使用Promise方式回调异步返回的结果。

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

参数:

参数名类型必填说明
keyAliasstring密钥别名,应与所用密钥生成时使用的别名相同。
optionsHuksOptions空对象(此处传空即可)。

返回值:

类型说明
Promise<HuksReturnResult>Promise对象。不返回err值时表示接口使用成功,其他时为错误。outData:返回从密钥中导出的公钥。

错误码:

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

错误码ID错误信息
401argument is invalid.
801api is not supported.
12000001algorithm mode is not supported.
12000002algorithm param is missing.
12000003algorithm param is invalid.
12000004operating file failed.
12000005IPC communication failed.
12000006error occured in crypto engine.
12000011queried entity does not exist.
12000012external error.
12000014memory is insufficient.

示例:

import huks from '@ohos.security.huks';
import { BusinessError } from '@ohos.base';
/* 此处options选择emptyOptions来传空 */
let keyAlias = 'keyAlias';
let emptyOptions: huks.HuksOptions = {
    properties: []
};
try {
    huks.exportKeyItem(keyAlias, emptyOptions)
        .then ((data) => {
            console.info(`promise: exportKeyItem success, data = ${JSON.stringify(data)}`);
        })
        .catch((error: BusinessError) => {
            console.error(`promise: exportKeyItem failed`);
        });
} catch (error) {
    console.error(`promise: exportKeyItem input arg invalid`);
}

huks.getKeyItemProperties9+

getKeyItemProperties(keyAlias: string, options: HuksOptions, callback: AsyncCallback<HuksReturnResult>) : void

获取密钥属性,使用Callback回调异步返回结果。

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

参数:

参数名类型必填说明
keyAliasstring密钥别名,应与所用密钥生成时使用的别名相同。
optionsHuksOptions空对象(此处传空即可)。
callbackAsyncCallback<HuksReturnResult>回调函数。不返回err值时表示接口使用成功,其他时为错误。properties:返回值为生成密钥时所需参数。

错误码:

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

错误码ID错误信息
401argument is invalid.
801api is not supported.
12000001algorithm mode is not supported.
12000002algorithm param is missing.
12000003algorithm param is invalid.
12000004operating file failed.
12000005IPC communication failed.
12000006error occured in crypto engine.
12000011queried entity does not exist.
12000012external error.
12000014memory is insufficient.

示例:

import huks from '@ohos.security.huks';
/* 此处options选择emptyOptions来传空 */
let keyAlias = 'keyAlias';
let emptyOptions: huks.HuksOptions = {
    properties: []
};
try {
    huks.getKeyItemProperties(keyAlias, emptyOptions, (error, data) => {
        if (error) {
            console.error(`callback: getKeyItemProperties failed`);
        } else {
            console.info(`callback: getKeyItemProperties success, data = ${JSON.stringify(data)}`);
        }
    });
} catch (error) {
    console.error(`callback: getKeyItemProperties input arg invalid`);
}

huks.getKeyItemProperties9+

getKeyItemProperties(keyAlias: string, options: HuksOptions) : Promise<HuksReturnResult>

获取密钥属性,使用Promise回调异步返回结果。

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

参数:

参数名类型必填说明
keyAliasstring密钥别名,应与所用密钥生成时使用的别名相同。
optionsHuksOptions空对象(此处传空即可)。

返回值:

类型说明
Promise<HuksReturnResult>Promise对象。不返回err值时表示接口使用成功,其他时为错误。properties:返回值为生成密钥时所需参数。

错误码:

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

错误码ID错误信息
401argument is invalid.
801api is not supported.
12000001algorithm mode is not supported.
12000002algorithm param is missing.
12000003algorithm param is invalid.
12000004operating file failed.
12000005IPC communication failed.
12000006error occured in crypto engine.
12000011queried entity does not exist.
12000012external error.
12000014memory is insufficient.

示例:

import huks from '@ohos.security.huks';
import { BusinessError } from '@ohos.base';
/* 此处options选择emptyOptions来传空 */
let keyAlias = 'keyAlias';
let emptyOptions: huks.HuksOptions = {
    properties: []
};
try {
    huks.getKeyItemProperties(keyAlias, emptyOptions)
        .then ((data) => {
            console.info(`promise: getKeyItemProperties success, data = ${JSON.stringify(data)}`);
        })
        .catch((error: BusinessError) => {
            console.error(`promise: getKeyItemProperties failed`);
        });
} catch (error) {
    console.error(`promise: getKeyItemProperties input arg invalid`);
}

huks.isKeyItemExist9+

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

判断密钥是否存在,使用Callback回调异步返回结果 。

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

参数:

参数名类型必填说明
keyAliasstring所需查找的密钥的别名。
optionsHuksOptions空对象(此处传空即可)。
callbackAsyncCallback<boolean>回调函数。若密钥存在,data为true,若密钥不存在,则error中会输出密钥不存在的error code。

错误码:

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

错误码ID错误信息
401argument is invalid.
801api is not supported.
12000002algorithm param is missing.
12000003algorithm param is invalid.
12000004operating file failed.
12000005IPC communication failed.
12000006error occured in crypto engine.
12000011The entity does not exist.
12000012external error.
12000014memory is insufficient.

示例:

import huks from '@ohos.security.huks';
import promptAction from '@ohos.promptAction';
/* 此处options选择emptyOptions来传空 */
let keyAlias = 'keyAlias';
let emptyOptions: huks.HuksOptions = {
    properties: []
};
huks.isKeyItemExist(keyAlias, emptyOptions, (error, data) => {
    if (data) {
        promptAction.showToast({
            message: "keyAlias: " + keyAlias +"is existed!",
            duration: 2500,
        })
    } else {
        promptAction.showToast({
            message: "find key failed",
            duration: 2500,
        })
    }
});

huks.isKeyItemExist9+

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

判断密钥是否存在,使用Promise回调异步返回结果 。

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

参数:

参数名类型必填说明
keyAliasstring所需查找的密钥的别名。
optionsHuksOptions空对象(此处传空即可)。

返回值:

类型说明
Promise<boolean>Promise对象。密钥存在时,可通过then进行密钥存在后的相关处理,若不存在,可通过error处理密钥不存在后的相关业务操作。

错误码:

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

错误码ID错误信息
401argument is invalid.
801api is not supported.
12000002algorithm param is missing.
12000003algorithm param is invalid.
12000004operating file failed.
12000005IPC communication failed.
12000006error occured in crypto engine.
12000011The entity does not exist.
12000012external error.
12000014memory is insufficient.

示例:

import huks from '@ohos.security.huks';
import { BusinessError } from '@ohos.base';
import promptAction from '@ohos.promptAction';

/* 此处options选择emptyOptions来传空 */
let keyAlias = 'keyAlias';
let emptyOptions: huks.HuksOptions = {
    properties: []
};
huks.isKeyItemExist(keyAlias, emptyOptions).then((data) => {
    promptAction.showToast({
        message: "keyAlias: " + keyAlias +"is existed!",
        duration: 500,
    })
}).catch((error: BusinessError)=>{
    promptAction.showToast({
        message: "find key failed",
        duration: 6500,
    })
})

huks.initSession9+

initSession(keyAlias: string, options: HuksOptions, callback: AsyncCallback<HuksSessionHandle>) : void

initSession操作密钥接口,使用Callback回调异步返回结果。huks.initSession, huks.updateSession, huks.finishSession为三段式接口,需要一起使用。

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

参数:

参数名类型必填说明
keyAliasstringinitSession操作密钥的别名。
optionsHuksOptionsinitSession操作的参数集合。
callbackAsyncCallback<HuksSessionHandle>回调函数。将initSession操作返回的handle添加到密钥管理系统的回调。

错误码:

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

错误码ID错误信息
401argument is invalid.
801api is not supported.
12000001algorithm mode is not supported.
12000002algorithm param is missing.
12000003algorithm param is invalid.
12000004operating file failed.
12000005IPC communication failed.
12000006error occured in crypto engine.
12000010the number of sessions has reached limit.
12000011queried entity does not exist.
12000012external error.
12000014memory is insufficient.

huks.initSession9+

initSession(keyAlias: string, options: HuksOptions) : Promise<HuksSessionHandle>

initSession操作密钥接口,使用Promise方式异步返回结果。huks.initSession, huks.updateSession, huks.finishSession为三段式接口,需要一起使用。

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

参数:

参数名类型必填说明
keyAliasstringinitSession操作密钥的别名。
optionsHuksOptionsinitSession参数集合。

返回值

类型说明
Promise<HuksSessionHandle>Promise对象。将initSession操作返回的handle添加到密钥管理系统的回调。

错误码:

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

错误码ID错误信息
401argument is invalid.
801api is not supported.
12000001algorithm mode is not supported.
12000002algorithm param is missing.
12000003algorithm param is invalid.
12000004operating file failed.
12000005IPC communication failed.
12000006error occured in crypto engine.
12000010the number of sessions has reached limit.
12000011queried entity does not exist.
12000012external error.
12000014memory is insufficient.

huks.updateSession9+

updateSession(handle: number, options: HuksOptions, callback: AsyncCallback<HuksReturnResult>) : void

updateSession操作密钥接口,使用Callback回调异步返回结果。huks.initSession, huks.updateSession, huks.finishSession为三段式接口,需要一起使用。

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

参数:

参数名类型必填说明
handlenumberupdateSession操作的handle。
optionsHuksOptionsupdateSession的参数集合。
callbackAsyncCallback<HuksReturnResult>回调函数。将updateSession操作的结果添加到密钥管理系统的回调。

错误码:

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

错误码ID错误信息
401argument is invalid.
801api is not supported.
12000001algorithm mode is not supported.
12000002algorithm param is missing.
12000003algorithm param is invalid.
12000004operating file failed.
12000005IPC communication failed.
12000006error occured in crypto engine.
12000007this credential is already invalidated permanently.
12000008verify authtoken failed.
12000009authtoken is already timeout.
12000011queried entity does not exist.
12000012external error.
12000014memory is insufficient.

huks.updateSession9+

updateSession(handle: number, options: HuksOptions, token: Uint8Array, callback: AsyncCallback<HuksReturnResult>) : void

updateSession操作密钥接口,使用Callback回调异步返回结果。huks.initSession, huks.updateSession, huks.finishSession为三段式接口,需要一起使用。

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

参数:

参数名类型必填说明
handlenumberupdateSession操作的handle。
optionsHuksOptionsupdateSession操作的参数集合。
tokenUint8ArrayupdateSession操作的token。
callbackAsyncCallback<HuksReturnResult>回调函数。将updateSession操作的结果添加到密钥管理系统的回调。

错误码:

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

错误码ID错误信息
401argument is invalid.
801api is not supported.
12000001algorithm mode is not supported.
12000002algorithm param is missing.
12000003algorithm param is invalid.
12000004operating file failed.
12000005IPC communication failed.
12000006error occured in crypto engine.
12000007this credential is already invalidated permanently.
12000008verify authtoken failed.
12000009authtoken is already timeout.
12000011queried entity does not exist.
12000012external error.
12000014memory is insufficient.

huks.updateSession9+

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

updateSession操作密钥接口,使用Promise方式异步返回结果。huks.initSession, huks.updateSession, huks.finishSession为三段式接口,需要一起使用。

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

参数:

参数名类型必填说明
handlenumberupdateSession操作的handle。
optionsHuksOptionsupdateSession操作的参数集合。
tokenUint8ArrayupdateSession操作的token。

返回值

类型说明
Promise<HuksReturnResult>Promise对象。将updateSession操作的结果添加到密钥管理系统的回调。

错误码:

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

错误码ID错误信息
401argument is invalid.
801api is not supported.
12000001algorithm mode is not supported.
12000002algorithm param is missing.
12000003algorithm param is invalid.
12000004operating file failed.
12000005IPC communication failed.
12000006error occured in crypto engine.
12000007this credential is already invalidated permanently.
12000008verify authtoken failed.
12000009authtoken is already timeout.
12000011queried entity does not exist.
12000012external error.
12000014memory is insufficient.

huks.finishSession9+

finishSession(handle: number, options: HuksOptions, callback: AsyncCallback<HuksReturnResult>) : void

finishSession操作密钥接口,使用Callback回调异步返回结果。huks.initSession, huks.updateSession, huks.finishSession为三段式接口,需要一起使用。

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

参数:

参数名类型必填说明
handlenumberfinishSession操作的handle。
optionsHuksOptionsfinishSession的参数集合。
callbackAsyncCallback<HuksReturnResult>回调函数。将finishSession操作的结果添加到密钥管理系统的回调。

错误码:

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

错误码ID错误信息
401argument is invalid.
801api is not supported.
12000001algorithm mode is not supported.
12000002algorithm param is missing.
12000003algorithm param is invalid.
12000004operating file failed.
12000005IPC communication failed.
12000006error occured in crypto engine.
12000007this credential is already invalidated permanently.
12000008verify authtoken failed.
12000009authtoken is already timeout.
12000011queried entity does not exist.
12000012external error.
12000014memory is insufficient.

huks.finishSession9+

finishSession(handle: number, options: HuksOptions, token: Uint8Array, callback: AsyncCallback<HuksReturnResult>) : void

finishSession操作密钥接口,使用Callback回调异步返回结果。huks.initSession, huks.updateSession, huks.finishSession为三段式接口,需要一起使用。

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

参数:

参数名类型必填说明
handlenumberfinishSession操作的handle。
optionsHuksOptionsfinishSession的参数集合。
tokenUint8ArrayfinishSession操作的token。
callbackAsyncCallback<HuksReturnResult>回调函数。将finishSession操作的结果添加到密钥管理系统的回调。

错误码:

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

错误码ID错误信息
401argument is invalid.
801api is not supported.
12000001algorithm mode is not supported.
12000002algorithm param is missing.
12000003algorithm param is invalid.
12000004operating file failed.
12000005IPC communication failed.
12000006error occured in crypto engine.
12000007this credential is already invalidated permanently.
12000008verify authtoken failed.
12000009authtoken is already timeout.
12000011queried entity does not exist.
12000012external error.
12000014memory is insufficient.

huks.finishSession9+

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

finishSession操作密钥接口,使用Promise方式异步返回结果。huks.initSession, huks.updateSession, huks.finishSession为三段式接口,需要一起使用。

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

参数:

参数名类型必填说明
handlenumberfinishSession操作的handle。
optionsHuksOptionsfinishSession操作的参数集合。
tokenUint8ArrayfinishSession操作的token。

返回值

类型说明
Promise<HuksReturnResult>Promise对象,用于获取异步返回结果。

错误码:

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

错误码ID错误信息
401argument is invalid.
801api is not supported.
12000001algorithm mode is not supported.
12000002algorithm param is missing.
12000003algorithm param is invalid.
12000004operating file failed.
12000005IPC communication failed.
12000006error occured in crypto engine.
12000007this credential is already invalidated permanently.
12000008verify authtoken failed.
12000009authtoken is already timeout.
12000011queried entity does not exist.
12000012external error.
12000014memory is insufficient.

huks.abortSession9+

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

abortSession操作密钥接口,使用Callback回调异步返回结果 。

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

参数:

参数名类型必填说明
handlenumberabortSession操作的handle。
optionsHuksOptionsabortSession操作的参数集合。
callbackAsyncCallback<void>回调函数。将abortSession操作的结果添加到密钥管理系统的回调。

错误码:

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

错误码ID错误信息
401argument is invalid.
801api is not supported.
12000004operating file failed.
12000005IPC communication failed.
12000006error occured in crypto engine.
12000012external error.
12000014memory is insufficient.

示例:

import huks from '@ohos.security.huks';
/* huks.initSession, huks.updateSession, huks.finishSession为三段式接口,需要一起使用,当
 * huks.initSession和huks.updateSession
 * 以及huks.finishSession操作中的任一阶段发生错误时,
 * 都需要调用huks.abortSession来终止密钥的使用。
 *
 * 以下以RSA1024密钥的callback功能使用为例
 */
class HuksProperties {
    tag: huks.HuksTag = huks.HuksTag.HUKS_TAG_ALGORITHM
    value: huks.HuksKeyAlg|huks.HuksKeySize|huks.HuksKeyPurpose|huks.HuksKeyDigest|
    huks.HuksKeyPadding|huks.HuksCipherMode = huks.HuksKeyAlg.HUKS_ALG_ECC
}
function stringToUint8Array(str: string) {
    let arr: number[] = [];
    for (let i = 0, j = str.length; i < j; ++i) {
        arr.push(str.charCodeAt(i));
    }
    let tmpUint8Array = new Uint8Array(arr);
    return tmpUint8Array;
}
let keyAlias = "HuksDemoRSA";
let properties: HuksProperties[] = []
let options: huks.HuksOptions = {
    properties: properties,
    inData: new Uint8Array(0)
};
let handle: number = 0;
async function generateKey() {
    properties[0] = {
        tag: huks.HuksTag.HUKS_TAG_ALGORITHM,
        value: huks.HuksKeyAlg.HUKS_ALG_RSA
    };
    properties[1] = {
        tag: huks.HuksTag.HUKS_TAG_KEY_SIZE,
        value: huks.HuksKeySize.HUKS_RSA_KEY_SIZE_1024
    };
    properties[2] = {
        tag: huks.HuksTag.HUKS_TAG_PURPOSE,
        value: huks.HuksKeyPurpose.HUKS_KEY_PURPOSE_ENCRYPT
    };
    properties[3] = {
        tag: huks.HuksTag.HUKS_TAG_PADDING,
        value: huks.HuksKeyPadding.HUKS_PADDING_PKCS1_V1_5
    };
    properties[4] = {
        tag: huks.HuksTag.HUKS_TAG_DIGEST,
        value: huks.HuksKeyDigest.HUKS_DIGEST_SHA256
    };
    properties[5] = {
        tag: huks.HuksTag.HUKS_TAG_BLOCK_MODE,
        value: huks.HuksCipherMode.HUKS_MODE_ECB,
    }
    try {
        await huks.generateKeyItem(keyAlias, options, (error, data) => {
            if (error) {
                console.error(`callback: generateKeyItem failed`);
            } else {
                console.info(`callback: generateKeyItem success`);
            }
        });
    } catch (error) {
        console.error(`callback: generateKeyItem input arg invalid`);
    }
}
async function huksInit() {
    console.log('enter huksInit');
    try {
        huks.initSession(keyAlias, options, (error, data) => {
            if (error) {
                console.error(`callback: initSession failed`);
            } else {
                console.info(`callback: initSession success, data = ${JSON.stringify(data)}`);
                handle = data.handle;
            }
        });
    } catch (error) {
        console.error(`callback: initSession input arg invalid`);
    }
}
async function huksUpdate() {
    console.log('enter huksUpdate');
    options.inData = stringToUint8Array("huksHmacTest");
    try {
        huks.updateSession(handle, options, (error, data) => {
            if (error) {
                console.error(`callback: updateSession failed`);
            } else {
                console.info(`callback: updateSession success, data = ${JSON.stringify(data)}`);
            }
        });
    } catch (error) {
        console.error(`callback: updateSession input arg invalid`);
    }
}
async function huksFinish() {
    console.log('enter huksFinish');
    options.inData = new Uint8Array(0);
    try {
        huks.finishSession(handle, options, (error, data) => {
            if (error) {
                console.error(`callback: finishSession failed`);
            } else {
                console.info(`callback: finishSession success, data = ${JSON.stringify(data)}`);
            }
        });
    } catch (error) {
        console.error(`callback: finishSession input arg invalid`);
    }
}
async function huksAbort() {
    console.log('enter huksAbort');
    try {
        huks.abortSession(handle, options, (error, data) => {
            if (error) {
                console.error(`callback: abortSession failed`);
            } else {
                console.info(`callback: abortSession success`);
            }
        });
    } catch (error) {
        console.error(`callback: abortSession input arg invalid`);
    }
}

huks.abortSession9+

abortSession(handle: number, options: HuksOptions) : Promise<void>;

abortSession操作密钥接口,使用Promise方式异步返回结果。

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

参数:

参数名类型必填说明
handlenumberabortSession操作的handle。
optionsHuksOptionsabortSession操作的参数集合。

返回值

类型说明
Promise<void>Promise对象。将abortSession操作的结果添加到密钥管理系统的回调。

错误码:

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

错误码ID错误信息
401argument is invalid.
801api is not supported.
12000004operating file failed.
12000005IPC communication failed.
12000006error occured in crypto engine.
12000012external error.
12000014memory is insufficient.

示例:

import huks from '@ohos.security.huks';
import { BusinessError } from '@ohos.base';
/* huks.initSession, huks.updateSession, huks.finishSession为三段式接口,需要一起使用,当
 * huks.initSession和huks.updateSession
 * 以及huks.finishSession操作中的任一阶段发生错误时,
 * 都需要调用huks.abortSession来终止密钥的使用。
 *
 * 以下以RSA1024密钥的callback功能使用为例
 */
class HuksProperties {
    tag: huks.HuksTag = huks.HuksTag.HUKS_TAG_ALGORITHM
    value: huks.HuksKeyAlg|huks.HuksKeySize|huks.HuksKeyPurpose|
    huks.HuksKeyDigest|huks.HuksKeyPadding|huks.HuksKeyGenerateType|
    huks.HuksCipherMode = huks.HuksKeyAlg.HUKS_ALG_ECC
}

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

let keyAlias = "HuksDemoRSA";
let properties: HuksProperties[] = []
let options: huks.HuksOptions = {
    properties: properties,
    inData: new Uint8Array(0)
};
let handle: number = 0;

async function generateKey() {
    properties[0] = {
        tag: huks.HuksTag.HUKS_TAG_ALGORITHM,
        value: huks.HuksKeyAlg.HUKS_ALG_RSA
    };
    properties[1] = {
        tag: huks.HuksTag.HUKS_TAG_KEY_SIZE,
        value: huks.HuksKeySize.HUKS_RSA_KEY_SIZE_1024
    };
    properties[2] = {
        tag: huks.HuksTag.HUKS_TAG_PURPOSE,
        value: huks.HuksKeyPurpose.HUKS_KEY_PURPOSE_ENCRYPT
    };
    properties[3] = {
        tag: huks.HuksTag.HUKS_TAG_PADDING,
        value: huks.HuksKeyPadding.HUKS_PADDING_PKCS1_V1_5
    };
    properties[4] = {
        tag: huks.HuksTag.HUKS_TAG_DIGEST,
        value: huks.HuksKeyDigest.HUKS_DIGEST_SHA256
    };
    properties[5] = {
        tag: huks.HuksTag.HUKS_TAG_BLOCK_MODE,
        value: huks.HuksCipherMode.HUKS_MODE_ECB,
    }

    try {
        await huks.generateKeyItem(keyAlias, options)
            .then((data) => {
                console.info(`promise: generateKeyItem success`);
            })
            .catch((error: BusinessError) => {
                console.error(`promise: generateKeyItem failed`);
            });
    } catch (error) {
        console.error(`promise: generateKeyItem input arg invalid`);
    }
}

async function huksInit() {
    console.log('enter huksInit');
    try {
        await huks.initSession(keyAlias, options)
            .then((data) => {
                console.info(`promise: initSession success, data = ${JSON.stringify(data)}`);
                handle = data.handle;
            })
            .catch((error: BusinessError) => {
                console.error(`promise: initSession key failed`);
            });
    } catch (error) {
        console.error(`promise: initSession input arg invalid`);
    }
}

async function huksUpdate() {
    console.log('enter huksUpdate');
    options.inData = stringToUint8Array("huksHmacTest");
    try {
        await huks.updateSession(handle, options)
            .then((data) => {
                console.info(`promise: updateSession success, data = ${JSON.stringify(data)}`);
            })
            .catch((error: BusinessError) => {
                console.error(`promise: updateSession failed`);
            });
    } catch (error) {
        console.error(`promise: updateSession input arg invalid`);
    }
}

async function huksFinish() {
    console.log('enter huksFinish');
    options.inData = new Uint8Array(0);
    try {
        await huks.finishSession(handle, options)
            .then((data) => {
                console.info(`promise: finishSession success, data = ${JSON.stringify(data)}`);
            })
            .catch((error: BusinessError) => {
                console.error(`promise: finishSession failed`);
            });
    } catch (error) {
        console.error(`promise: finishSession input arg invalid`);
    }
}

async function huksAbort() {
    console.log('enter huksAbort');
    try {
        await huks.abortSession(handle, options)
            .then((data) => {
                console.info(`promise: abortSession success`);
            })
            .catch((error: BusinessError) => {
                console.error(`promise: abortSession failed`);
            });
    } catch (error) {
        console.error(`promise: abortSession input arg invalid`);
    }
}

HuksExceptionErrCode9+

表示错误码的枚举以及对应的错误信息, 错误码表示错误类型,错误信息展示错误详情。

关于错误码的具体信息,可在错误码参考文档中查看。

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

名称说明
HUKS_ERR_CODE_PERMISSION_FAIL201权限错误导致失败。
HUKS_ERR_CODE_ILLEGAL_ARGUMENT401参数错误导致失败。
HUKS_ERR_CODE_NOT_SUPPORTED_API801不支持的API。
HUKS_ERR_CODE_FEATURE_NOT_SUPPORTED12000001不支持的功能/特性。
HUKS_ERR_CODE_MISSING_CRYPTO_ALG_ARGUMENT12000002缺少密钥算法参数。
HUKS_ERR_CODE_INVALID_CRYPTO_ALG_ARGUMENT12000003无效密钥算法参数。
HUKS_ERR_CODE_FILE_OPERATION_FAIL12000004文件操作失败。
HUKS_ERR_CODE_COMMUNICATION_FAIL12000005通信失败。
HUKS_ERR_CODE_CRYPTO_FAIL12000006算法库操作失败。
HUKS_ERR_CODE_KEY_AUTH_PERMANENTLY_INVALIDATED12000007密钥访问失败-密钥访问失效。
HUKS_ERR_CODE_KEY_AUTH_VERIFY_FAILED12000008密钥访问失败-密钥认证失败。
HUKS_ERR_CODE_KEY_AUTH_TIME_OUT12000009密钥访问失败-密钥访问超时。
HUKS_ERR_CODE_SESSION_LIMIT12000010密钥操作会话数已达上限。
HUKS_ERR_CODE_ITEM_NOT_EXIST12000011目标对象不存在。
HUKS_ERR_CODE_EXTERNAL_ERROR12000012外部错误。
HUKS_ERR_CODE_CREDENTIAL_NOT_EXIST12000013缺失所需凭据。
HUKS_ERR_CODE_INSUFFICIENT_MEMORY12000014内存不足。
HUKS_ERR_CODE_CALL_SERVICE_FAILED12000015调用其他系统服务失败。

HuksKeyPurpose

表示密钥用途。

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

名称说明
HUKS_KEY_PURPOSE_ENCRYPT1表示密钥用于对明文进行加密操作。
系统能力: SystemCapability.Security.Huks.Core
HUKS_KEY_PURPOSE_DECRYPT2表示密钥用于对密文进行解密操作。
系统能力: SystemCapability.Security.Huks.Core
HUKS_KEY_PURPOSE_SIGN4表示密钥用于对数据进行签名。
系统能力: SystemCapability.Security.Huks.Extension
HUKS_KEY_PURPOSE_VERIFY8表示密钥用于验证签名后的数据。
系统能力: SystemCapability.Security.Huks.Extension
HUKS_KEY_PURPOSE_DERIVE16表示密钥用于派生密钥。
系统能力: SystemCapability.Security.Huks.Extension
HUKS_KEY_PURPOSE_WRAP32表示密钥用于加密导出。
系统能力: SystemCapability.Security.Huks.Extension
HUKS_KEY_PURPOSE_UNWRAP64表示密钥加密导入。
系统能力: SystemCapability.Security.Huks.Extension
HUKS_KEY_PURPOSE_MAC128表示密钥用于生成mac消息验证码。
系统能力: SystemCapability.Security.Huks.Extension
HUKS_KEY_PURPOSE_AGREE256表示密钥用于进行密钥协商。
系统能力: SystemCapability.Security.Huks.Extension

HuksKeyDigest

表示摘要算法。

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

名称说明
HUKS_DIGEST_NONE0表示无摘要算法。
HUKS_DIGEST_MD51表示MD5摘要算法。
HUKS_DIGEST_SM39+2表示SM3摘要算法。
HUKS_DIGEST_SHA110表示SHA1摘要算法。
HUKS_DIGEST_SHA22411表示SHA224摘要算法。
HUKS_DIGEST_SHA25612表示SHA256摘要算法。
HUKS_DIGEST_SHA38413表示SHA384摘要算法。
HUKS_DIGEST_SHA51214表示SHA512摘要算法。

HuksKeyPadding

表示补齐算法。

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

名称说明
HUKS_PADDING_NONE0表示不使用补齐算法。
系统能力: SystemCapability.Security.Huks.Core
HUKS_PADDING_OAEP1表示使用OAEP补齐算法。
系统能力: SystemCapability.Security.Huks.Extension
HUKS_PADDING_PSS2表示使用PSS补齐算法。
系统能力: SystemCapability.Security.Huks.Extension
HUKS_PADDING_PKCS1_V1_53表示使用PKCS1_V1_5补齐算法。
系统能力: SystemCapability.Security.Huks.Extension
HUKS_PADDING_PKCS54表示使用PKCS5补齐算法。
系统能力: SystemCapability.Security.Huks.Extension
HUKS_PADDING_PKCS75表示使用PKCS7补齐算法。
系统能力: SystemCapability.Security.Huks.Core

HuksCipherMode

表示加密模式。

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

名称说明
HUKS_MODE_ECB1表示使用ECB加密模式。
系统能力: SystemCapability.Security.Huks.Core
HUKS_MODE_CBC2表示使用CBC加密模式。
系统能力: SystemCapability.Security.Huks.Core
HUKS_MODE_CTR3表示使用CTR加密模式。
系统能力: SystemCapability.Security.Huks.Core
HUKS_MODE_OFB4表示使用OFB加密模式。
系统能力: SystemCapability.Security.Huks.Extension
HUKS_MODE_CCM31表示使用CCM加密模式。
系统能力: SystemCapability.Security.Huks.Extension
HUKS_MODE_GCM32表示使用GCM加密模式。
系统能力: SystemCapability.Security.Huks.Core

HuksKeySize

表示密钥长度。

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

名称说明
HUKS_RSA_KEY_SIZE_512512表示使用RSA算法的密钥长度为512bit。
系统能力: SystemCapability.Security.Huks.Extension
HUKS_RSA_KEY_SIZE_768768表示使用RSA算法的密钥长度为768bit。
系统能力: SystemCapability.Security.Huks.Extension
HUKS_RSA_KEY_SIZE_10241024表示使用RSA算法的密钥长度为1024bit。
系统能力: SystemCapability.Security.Huks.Extension
HUKS_RSA_KEY_SIZE_20482048表示使用RSA算法的密钥长度为2048bit。
系统能力: SystemCapability.Security.Huks.Extension
HUKS_RSA_KEY_SIZE_30723072表示使用RSA算法的密钥长度为3072bit。
系统能力: SystemCapability.Security.Huks.Extension
HUKS_RSA_KEY_SIZE_40964096表示使用RSA算法的密钥长度为4096bit。
系统能力: SystemCapability.Security.Huks.Extension
HUKS_ECC_KEY_SIZE_224224表示使用ECC算法的密钥长度为224bit。
系统能力: SystemCapability.Security.Huks.Extension
HUKS_ECC_KEY_SIZE_256256表示使用ECC算法的密钥长度为256bit。
系统能力: SystemCapability.Security.Huks.Extension
HUKS_ECC_KEY_SIZE_384384表示使用ECC算法的密钥长度为384bit。
系统能力: SystemCapability.Security.Huks.Extension
HUKS_ECC_KEY_SIZE_521521表示使用ECC算法的密钥长度为521bit。
系统能力: SystemCapability.Security.Huks.Extension
HUKS_AES_KEY_SIZE_128128表示使用AES算法的密钥长度为128bit。
系统能力: SystemCapability.Security.Huks.Core
HUKS_AES_KEY_SIZE_192192表示使用AES算法的密钥长度为192bit。
系统能力: SystemCapability.Security.Huks.Core
HUKS_AES_KEY_SIZE_256256表示使用AES算法的密钥长度为256bit。
系统能力: SystemCapability.Security.Huks.Core
HUKS_AES_KEY_SIZE_512512表示使用AES算法的密钥长度为512bit。
系统能力: SystemCapability.Security.Huks.Core
HUKS_CURVE25519_KEY_SIZE_256256表示使用CURVE25519算法的密钥长度为256bit。
系统能力: SystemCapability.Security.Huks.Extension
HUKS_DH_KEY_SIZE_20482048表示使用DH算法的密钥长度为2048bit。
系统能力: SystemCapability.Security.Huks.Extension
HUKS_DH_KEY_SIZE_30723072表示使用DH算法的密钥长度为3072bit。
系统能力: SystemCapability.Security.Huks.Extension
HUKS_DH_KEY_SIZE_40964096表示使用DH算法的密钥长度为4096bit。
系统能力: SystemCapability.Security.Huks.Extension
HUKS_SM2_KEY_SIZE_2569+256表示SM2算法的密钥长度为256bit。
系统能力: SystemCapability.Security.Huks.Extension
HUKS_SM4_KEY_SIZE_1289+128表示SM4算法的密钥长度为128bit。
系统能力: SystemCapability.Security.Huks.Extension

HuksKeyAlg

表示密钥使用的算法。

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

名称说明
HUKS_ALG_RSA1表示使用RSA算法。
系统能力: SystemCapability.Security.Huks.Extension
HUKS_ALG_ECC2表示使用ECC算法。
系统能力: SystemCapability.Security.Huks.Extension
HUKS_ALG_DSA3表示使用DSA算法。
系统能力: SystemCapability.Security.Huks.Extension
HUKS_ALG_AES20表示使用AES算法。
系统能力: SystemCapability.Security.Huks.Core
HUKS_ALG_HMAC50表示使用HMAC算法。
系统能力: SystemCapability.Security.Huks.Extension
HUKS_ALG_HKDF51表示使用HKDF算法。
系统能力: SystemCapability.Security.Huks.Extension
HUKS_ALG_PBKDF252表示使用PBKDF2算法。
系统能力: SystemCapability.Security.Huks.Extension
HUKS_ALG_ECDH100表示使用ECDH算法。
系统能力: SystemCapability.Security.Huks.Extension
HUKS_ALG_X25519101表示使用X25519算法。
系统能力: SystemCapability.Security.Huks.Extension
HUKS_ALG_ED25519102表示使用ED25519算法。
系统能力: SystemCapability.Security.Huks.Extension
HUKS_ALG_DH103表示使用DH算法。
系统能力: SystemCapability.Security.Huks.Extension
HUKS_ALG_SM29+150表示使用SM2算法。
系统能力: SystemCapability.Security.Huks.Extension
HUKS_ALG_SM39+151表示使用SM3算法。
系统能力: SystemCapability.Security.Huks.Extension
HUKS_ALG_SM49+152表示使用SM4算法。
系统能力: SystemCapability.Security.Huks.Extension

HuksKeyGenerateType

表示生成密钥的类型。

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

名称说明
HUKS_KEY_GENERATE_TYPE_DEFAULT0默认生成的密钥。
HUKS_KEY_GENERATE_TYPE_DERIVE1派生生成的密钥。
HUKS_KEY_GENERATE_TYPE_AGREE2协商生成的密钥。

HuksKeyFlag

表示密钥的产生方式。

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

名称说明
HUKS_KEY_FLAG_IMPORT_KEY1表示通过导入公钥接口导入的密钥。
HUKS_KEY_FLAG_GENERATE_KEY2表示通过生成密钥接口生成的密钥。
HUKS_KEY_FLAG_AGREE_KEY3表示通过生成密钥协商接口生成的密钥。
HUKS_KEY_FLAG_DERIVE_KEY4表示通过生成密钥派生接口生成的密钥。

HuksKeyStorageType

表示密钥存储方式。

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

名称说明
HUKS_STORAGE_TEMP(deprecated)0表示通过本地直接管理密钥。
> 说明: 从API version 10开始废弃,由于开发者正常使用密钥管理过程中并不需要使用此TAG,故无替代接口。针对针对密钥派生场景,可使用HUKS_STORAGE_ONLY_USED_IN_HUKS 与 HUKS_STORAGE_KEY_EXPORT_ALLOWED。
系统能力: SystemCapability.Security.Huks.Core
HUKS_STORAGE_PERSISTENT(deprecated)1表示通过HUKS service管理密钥。
> 说明: 从API version 10开始废弃,由于开发者正常使用密钥管理过程中并不需要使用此TAG,故无替代接口。针对密钥派生场景,可使用HUKS_STORAGE_ONLY_USED_IN_HUKS 与 HUKS_STORAGE_KEY_EXPORT_ALLOWED。
系统能力: SystemCapability.Security.Huks.Core
HUKS_STORAGE_ONLY_USED_IN_HUKS10+2表示主密钥派生的密钥存储于huks中,由HUKS进行托管。
系统能力: SystemCapability.Security.Huks.Extension
HUKS_STORAGE_KEY_EXPORT_ALLOWED10+3表示主密钥派生的密钥直接导出给业务方,HUKS不对其进行托管服务。
系统能力: SystemCapability.Security.Huks.Extension

HuksSendType

表示发送Tag的方式。

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

名称说明
HUKS_SEND_TYPE_ASYNC0表示异步发送TAG。
HUKS_SEND_TYPE_SYNC1表示同步发送TAG。

HuksUnwrapSuite9+

表示导入加密密钥的算法套件。

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

名称说明
HUKS_UNWRAP_SUITE_X25519_AES_256_GCM_NOPADDING1导入加密密钥时,X25519密钥协商后使用AES-256 GCM加密。
HUKS_UNWRAP_SUITE_ECDH_AES_256_GCM_NOPADDING2导入加密密钥时,ECDH密钥协商后使用AES-256 GCM加密。

HuksImportKeyType9+

表示导入密钥的密钥类型,默认为导入公钥,导入对称密钥时不需要该字段。

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

名称说明
HUKS_KEY_TYPE_PUBLIC_KEY0表示导入的密钥类型为公钥。
HUKS_KEY_TYPE_PRIVATE_KEY1表示导入的密钥类型为私钥。
HUKS_KEY_TYPE_KEY_PAIR2表示导入的密钥类型为公私钥对。

HuksRsaPssSaltLenType10+

表示Rsa在签名验签、padding为pss时需指定的salt_len类型。

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

名称说明
HUKS_RSA_PSS_SALT_LEN_DIGEST10+0表示以摘要长度设置salt_len。
HUKS_RSA_PSS_SALT_LEN_MAX10+1表示以最大长度设置salt_len。

HuksUserAuthType9+

表示用户认证类型。

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

名称说明
HUKS_USER_AUTH_TYPE_FINGERPRINT1 << 0表示用户认证类型为指纹。
HUKS_USER_AUTH_TYPE_FACE1 << 1表示用户认证类型为人脸 。
HUKS_USER_AUTH_TYPE_PIN1 << 2表示用户认证类型为PIN码。

HuksAuthAccessType9+

表示安全访问控制类型。

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

名称说明
HUKS_AUTH_ACCESS_INVALID_CLEAR_PASSWORD1 << 0表示安全访问控制类型为清除密码后密钥无效。
HUKS_AUTH_ACCESS_INVALID_NEW_BIO_ENROLL1 << 1表示安全访问控制类型为新录入生物特征后密钥无效。
HUKS_AUTH_ACCESS_ALWAYS_VALID11+1 << 2表示安全访问控制类型为该密钥总是有效。

HuksChallengeType9+

表示密钥使用时生成challenge的类型。

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

名称说明
HUKS_CHALLENGE_TYPE_NORMAL0表示challenge为普通类型,默认32字节。
HUKS_CHALLENGE_TYPE_CUSTOM1表示challenge为用户自定义类型。支持使用多个密钥仅一次认证。
HUKS_CHALLENGE_TYPE_NONE2表示免challenge类型。

HuksChallengePosition9+

表示challenge类型为用户自定义类型时,生成的challenge有效长度仅为8字节连续的数据,且仅支持4种位置 。

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

名称说明
HUKS_CHALLENGE_POS_00表示0~7字节为当前密钥的有效challenge。
HUKS_CHALLENGE_POS_11表示8~15字节为当前密钥的有效challenge。
HUKS_CHALLENGE_POS_22表示16~23字节为当前密钥的有效challenge。
HUKS_CHALLENGE_POS_33表示24~31字节为当前密钥的有效challenge。

HuksSecureSignType9+

表示生成或导入密钥时,指定该密钥的签名类型。

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

名称说明
HUKS_SECURE_SIGN_WITH_AUTHINFO1表示签名类型为携带认证信息。生成或导入密钥时指定该字段,则在使用密钥进行签名时,对待签名的数据添加认证信息后进行签名。

HuksTagType

表示Tag的数据类型。

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

名称说明
HUKS_TAG_TYPE_INVALID0 << 28表示非法的Tag类型。
HUKS_TAG_TYPE_INT1 << 28表示该Tag的数据类型为int类型的number。
HUKS_TAG_TYPE_UINT2 << 28表示该Tag的数据类型为uint类型的number。
HUKS_TAG_TYPE_ULONG3 << 28表示该Tag的数据类型为bigint。
HUKS_TAG_TYPE_BOOL4 << 28表示该Tag的数据类型为boolean。
HUKS_TAG_TYPE_BYTES5 << 28表示该Tag的数据类型为Uint8Array。

HuksTag

表示调用参数的Tag。

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

名称说明
HUKS_TAG_INVALID(deprecated)HuksTagType.HUKS_TAG_TYPE_INVALID |0表示非法的Tag。从API version 9开始废弃。
系统能力: SystemCapability.Security.Huks.Core
HUKS_TAG_ALGORITHMHuksTagType.HUKS_TAG_TYPE_UINT |1表示算法的Tag。
系统能力: SystemCapability.Security.Huks.Core
HUKS_TAG_PURPOSEHuksTagType.HUKS_TAG_TYPE_UINT |2表示密钥用途的Tag。
系统能力: SystemCapability.Security.Huks.Core
HUKS_TAG_KEY_SIZEHuksTagType.HUKS_TAG_TYPE_UINT |3表示密钥长度的Tag。
系统能力: SystemCapability.Security.Huks.Core
HUKS_TAG_DIGESTHuksTagType.HUKS_TAG_TYPE_UINT |4表示摘要算法的Tag。
系统能力: SystemCapability.Security.Huks.Extension
HUKS_TAG_PADDINGHuksTagType.HUKS_TAG_TYPE_UINT |5表示补齐算法的Tag。
系统能力: SystemCapability.Security.Huks.Core
HUKS_TAG_BLOCK_MODEHuksTagType.HUKS_TAG_TYPE_UINT |6表示加密模式的Tag。
系统能力: SystemCapability.Security.Huks.Core
HUKS_TAG_KEY_TYPEHuksTagType.HUKS_TAG_TYPE_UINT |7表示密钥类型的Tag。
系统能力: SystemCapability.Security.Huks.Core
HUKS_TAG_ASSOCIATED_DATAHuksTagType.HUKS_TAG_TYPE_BYTES |8表示附加身份验证数据的Tag。
系统能力: SystemCapability.Security.Huks.Core
HUKS_TAG_NONCEHuksTagType.HUKS_TAG_TYPE_BYTES |9表示密钥加解密的字段。
系统能力: SystemCapability.Security.Huks.Core
HUKS_TAG_IVHuksTagType.HUKS_TAG_TYPE_BYTES |10表示密钥初始化的向量。
系统能力: SystemCapability.Security.Huks.Core
HUKS_TAG_INFOHuksTagType.HUKS_TAG_TYPE_BYTES |11表示密钥派生时的info。
系统能力: SystemCapability.Security.Huks.Core
HUKS_TAG_SALTHuksTagType.HUKS_TAG_TYPE_BYTES |12表示密钥派生时的盐值。
系统能力: SystemCapability.Security.Huks.Extension
HUKS_TAG_PWD(deprecated)HuksTagType.HUKS_TAG_TYPE_BYTES |13表示密钥派生时的password。从API version 9开始废弃。
系统能力: SystemCapability.Security.Huks.Core
HUKS_TAG_ITERATIONHuksTagType.HUKS_TAG_TYPE_UINT |14表示密钥派生时的迭代次数。
系统能力: SystemCapability.Security.Huks.Extension
HUKS_TAG_KEY_GENERATE_TYPEHuksTagType.HUKS_TAG_TYPE_UINT |15表示生成密钥类型的Tag。
系统能力: SystemCapability.Security.Huks.Core
HUKS_TAG_DERIVE_MAIN_KEY(deprecated)HuksTagType.HUKS_TAG_TYPE_BYTES |16表示密钥派生时的主密钥。从API version 9开始废弃。
系统能力: SystemCapability.Security.Huks.Extension
HUKS_TAG_DERIVE_FACTOR(deprecated)HuksTagType.HUKS_TAG_TYPE_BYTES |17表示密钥派生时的派生因子。从API version 9开始废弃。
系统能力: SystemCapability.Security.Huks.Extension
HUKS_TAG_DERIVE_ALG(deprecated)HuksTagType.HUKS_TAG_TYPE_UINT |18表示密钥派生时的算法类型。从API version 9开始废弃。
系统能力: SystemCapability.Security.Huks.Extension
HUKS_TAG_AGREE_ALGHuksTagType.HUKS_TAG_TYPE_UINT |19表示密钥协商时的算法类型。
系统能力: SystemCapability.Security.Huks.Extension
HUKS_TAG_AGREE_PUBLIC_KEY_IS_KEY_ALIASHuksTagType.HUKS_TAG_TYPE_BOOL |20表示密钥协商时的公钥别名。
系统能力: SystemCapability.Security.Huks.Extension
HUKS_TAG_AGREE_PRIVATE_KEY_ALIASHuksTagType.HUKS_TAG_TYPE_BYTES |21表示密钥协商时的私钥别名。
系统能力: SystemCapability.Security.Huks.Extension
HUKS_TAG_AGREE_PUBLIC_KEYHuksTagType.HUKS_TAG_TYPE_BYTES |22表示密钥协商时的公钥。
系统能力: SystemCapability.Security.Huks.Extension
HUKS_TAG_KEY_ALIASHuksTagType.HUKS_TAG_TYPE_BYTES |23表示密钥别名。
系统能力: SystemCapability.Security.Huks.Core
HUKS_TAG_DERIVE_KEY_SIZEHuksTagType.HUKS_TAG_TYPE_UINT |24表示派生密钥的大小。
系统能力: SystemCapability.Security.Huks.Extension
HUKS_TAG_IMPORT_KEY_TYPE9+HuksTagType.HUKS_TAG_TYPE_UINT |25表示导入的密钥类型。
系统能力: SystemCapability.Security.Huks.Extension
HUKS_TAG_UNWRAP_ALGORITHM_SUITE9+HuksTagType.HUKS_TAG_TYPE_UINT |26表示导入加密密钥的套件。
系统能力: SystemCapability.Security.Huks.Extension
HUKS_TAG_DERIVED_AGREED_KEY_STORAGE_FLAG10+HuksTagType.HUKS_TAG_TYPE_UINT |29表示派生密钥/协商密钥的存储类型。
系统能力: SystemCapability.Security.Huks.Extension
HUKS_TAG_RSA_PSS_SALT_LEN_TYPE10+HuksTagType.HUKS_TAG_TYPE_UINT |30表示rsa_pss_salt_length的类型。
系统能力: SystemCapability.Security.Huks.Extension
HUKS_TAG_ACTIVE_DATETIME(deprecated)HuksTagType.HUKS_TAG_TYPE_ULONG |201原为证书业务预留字段,当前证书管理已独立,此字段废弃,不再预留。
系统能力: SystemCapability.Security.Huks.Extension
HUKS_TAG_ORIGINATION_EXPIRE_DATETIME(deprecated)HuksTagType.HUKS_TAG_TYPE_ULONG |202原为证书业务预留字段,当前证书管理已独立,此字段废弃,不再预留。
系统能力: SystemCapability.Security.Huks.Core
HUKS_TAG_USAGE_EXPIRE_DATETIME(deprecated)HuksTagType.HUKS_TAG_TYPE_ULONG |203原为证书业务预留字段,当前证书管理已独立,此字段废弃,不再预留。
系统能力: SystemCapability.Security.Huks.Core
HUKS_TAG_CREATION_DATETIME(deprecated)HuksTagType.HUKS_TAG_TYPE_ULONG |204原为证书业务预留字段,当前证书管理已独立,此字段废弃,不再预留。
系统能力: SystemCapability.Security.Huks.Core
HUKS_TAG_ALL_USERSHuksTagType.HUKS_TAG_TYPE_BOOL |301预留
系统能力: SystemCapability.Security.Huks.Extension
HUKS_TAG_USER_IDHuksTagType.HUKS_TAG_TYPE_UINT |302表示当前密钥属于哪个userID
系统能力: SystemCapability.Security.Huks.Extension
HUKS_TAG_NO_AUTH_REQUIREDHuksTagType.HUKS_TAG_TYPE_BOOL |303预留。
系统能力: SystemCapability.Security.Huks.Extension
HUKS_TAG_USER_AUTH_TYPEHuksTagType.HUKS_TAG_TYPE_UINT |304表示用户认证类型。从HuksUserAuthType中选择,需要与安全访问控制类型同时设置。支持同时指定两种用户认证类型,如:安全访问控制类型指定为HKS_SECURE_ACCESS_INVALID_NEW_BIO_ENROLL时,密钥访问认证类型可以指定以下三种: HKS_USER_AUTH_TYPE_FACE 、HKS_USER_AUTH_TYPE_FINGERPRINT、HKS_USER_AUTH_TYPE_FACE |HKS_USER_AUTH_TYPE_FINGERPRINT
系统能力: SystemCapability.Security.Huks.Extension
HUKS_TAG_AUTH_TIMEOUTHuksTagType.HUKS_TAG_TYPE_UINT |305表示authtoken单次有效期。
系统能力: SystemCapability.Security.Huks.Extension
HUKS_TAG_AUTH_TOKENHuksTagType.HUKS_TAG_TYPE_BYTES |306用于传入authToken的字段
系统能力: SystemCapability.Security.Huks.Extension
HUKS_TAG_KEY_AUTH_ACCESS_TYPE9+HuksTagType.HUKS_TAG_TYPE_UINT |307表示安全访问控制类型。从HuksAuthAccessType中选择,需要和用户认证类型同时设置。
系统能力: SystemCapability.Security.Huks.Extension
HUKS_TAG_KEY_SECURE_SIGN_TYPE9+HuksTagType.HUKS_TAG_TYPE_UINT |308表示生成或导入密钥时,指定该密钥的签名类型。
系统能力: SystemCapability.Security.Huks.Extension
HUKS_TAG_CHALLENGE_TYPE9+HuksTagType.HUKS_TAG_TYPE_UINT |309表示密钥使用时生成的challenge类型。从HuksChallengeType中选择
系统能力: SystemCapability.Security.Huks.Extension
HUKS_TAG_CHALLENGE_POS9+HuksTagType.HUKS_TAG_TYPE_UINT |310表示challenge类型为用户自定义类型时,huks产生的challenge有效长度仅为8字节连续的数据。从HuksChallengePosition中选择。
系统能力: SystemCapability.Security.Huks.Extension
HUKS_TAG_KEY_AUTH_PURPOSE10+HuksTagType.HUKS_TAG_TYPE_UINT |311表示密钥认证用途的tag
系统能力: SystemCapability.Security.Huks.Extension
HUKS_TAG_ATTESTATION_CHALLENGEHuksTagType.HUKS_TAG_TYPE_BYTES |501表示attestation时的挑战值。
系统能力: SystemCapability.Security.Huks.Extension
HUKS_TAG_ATTESTATION_APPLICATION_IDHuksTagType.HUKS_TAG_TYPE_BYTES |502表示attestation时拥有该密钥的application的Id。
系统能力: SystemCapability.Security.Huks.Extension
HUKS_TAG_ATTESTATION_ID_BRAND(deprecated)HuksTagType.HUKS_TAG_TYPE_BYTES |503表示设备的品牌。从API version 9开始废弃。
系统能力: SystemCapability.Security.Huks.Extension
HUKS_TAG_ATTESTATION_ID_DEVICE(deprecated)HuksTagType.HUKS_TAG_TYPE_BYTES |504表示设备的设备ID。从API version 9开始废弃。
系统能力: SystemCapability.Security.Huks.Extension
HUKS_TAG_ATTESTATION_ID_PRODUCT(deprecated)HuksTagType.HUKS_TAG_TYPE_BYTES |505表示设备的产品名。从API version 9开始废弃。
系统能力: SystemCapability.Security.Huks.Extension
HUKS_TAG_ATTESTATION_ID_SERIAL(deprecated)HuksTagType.HUKS_TAG_TYPE_BYTES |506表示设备的SN号。从API version 9开始废弃。
系统能力: SystemCapability.Security.Huks.Extension
HUKS_TAG_ATTESTATION_ID_IMEI(deprecated)HuksTagType.HUKS_TAG_TYPE_BYTES |507表示设备的IMEI号。从API version 9开始废弃。
系统能力: SystemCapability.Security.Huks.Extension
HUKS_TAG_ATTESTATION_ID_MEID(deprecated)HuksTagType.HUKS_TAG_TYPE_BYTES |508表示设备的MEID号。从API version 9开始废弃。
系统能力: SystemCapability.Security.Huks.Extension
HUKS_TAG_ATTESTATION_ID_MANUFACTURER(deprecated)HuksTagType.HUKS_TAG_TYPE_BYTES |509表示设备的制造商。从API version 9开始废弃。
系统能力: SystemCapability.Security.Huks.Extension
HUKS_TAG_ATTESTATION_ID_MODEL(deprecated)HuksTagType.HUKS_TAG_TYPE_BYTES |510表示设备的型号。从API version 9开始废弃。
系统能力: SystemCapability.Security.Huks.Extension
HUKS_TAG_ATTESTATION_ID_ALIASHuksTagType.HUKS_TAG_TYPE_BYTES |511表示attestation时的密钥别名。
系统能力: SystemCapability.Security.Huks.Extension
HUKS_TAG_ATTESTATION_ID_SOCID(deprecated)HuksTagType.HUKS_TAG_TYPE_BYTES |512表示设备的SOCID。从API version 9开始废弃。
系统能力: SystemCapability.Security.Huks.Extension
HUKS_TAG_ATTESTATION_ID_UDID(deprecated)HuksTagType.HUKS_TAG_TYPE_BYTES |513表示设备的UDID。从API version 9开始废弃。
系统能力: SystemCapability.Security.Huks.Extension
HUKS_TAG_ATTESTATION_ID_SEC_LEVEL_INFOHuksTagType.HUKS_TAG_TYPE_BYTES |514表示attestation时的安全凭据。
系统能力: SystemCapability.Security.Huks.Extension
HUKS_TAG_ATTESTATION_ID_VERSION_INFOHuksTagType.HUKS_TAG_TYPE_BYTES |515表示attestation时的版本号。
系统能力: SystemCapability.Security.Huks.Extension
HUKS_TAG_IS_KEY_ALIASHuksTagType.HUKS_TAG_TYPE_BOOL |1001表示是否使用生成key时传入的别名的Tag。
系统能力: SystemCapability.Security.Huks.Core
HUKS_TAG_KEY_STORAGE_FLAGHuksTagType.HUKS_TAG_TYPE_UINT |1002表示密钥存储方式的Tag。
系统能力: SystemCapability.Security.Huks.Core
HUKS_TAG_IS_ALLOWED_WRAPHuksTagType.HUKS_TAG_TYPE_BOOL |1003预留。
系统能力: SystemCapability.Security.Huks.Extension
HUKS_TAG_KEY_WRAP_TYPEHuksTagType.HUKS_TAG_TYPE_UINT |1004预留。
系统能力: SystemCapability.Security.Huks.Extension
HUKS_TAG_KEY_AUTH_IDHuksTagType.HUKS_TAG_TYPE_BYTES |1005预留。
系统能力: SystemCapability.Security.Huks.Extension
HUKS_TAG_KEY_ROLEHuksTagType.HUKS_TAG_TYPE_UINT |1006预留。
系统能力: SystemCapability.Security.Huks.Extension
HUKS_TAG_KEY_FLAGHuksTagType.HUKS_TAG_TYPE_UINT |1007表示密钥标志的Tag。
系统能力: SystemCapability.Security.Huks.Core
HUKS_TAG_IS_ASYNCHRONIZEDHuksTagType.HUKS_TAG_TYPE_UINT |1008预留。
系统能力: SystemCapability.Security.Huks.Extension
HUKS_TAG_SECURE_KEY_ALIAS(deprecated)HuksTagType.HUKS_TAG_TYPE_BOOL |1009原为预留字段,从API version 9开始废弃。
系统能力: SystemCapability.Security.Huks.Core
HUKS_TAG_SECURE_KEY_UUID(deprecated)HuksTagType.HUKS_TAG_TYPE_BYTES |1010原为预留字段,从API version 9开始废弃。
系统能力: SystemCapability.Security.Huks.Extension
HUKS_TAG_KEY_DOMAINHuksTagType.HUKS_TAG_TYPE_UINT |1011预留。
系统能力: SystemCapability.Security.Huks.Core
HUKS_TAG_PROCESS_NAME(deprecated)HuksTagType.HUKS_TAG_TYPE_BYTES |10001表示进程名称的Tag。从API version 9开始废弃。
系统能力: SystemCapability.Security.Huks.Core
HUKS_TAG_PACKAGE_NAME(deprecated)HuksTagType.HUKS_TAG_TYPE_BYTES |10002原为预留字段,从API version 9开始废弃。
系统能力: SystemCapability.Security.Huks.Extension
HUKS_TAG_ACCESS_TIME(deprecated)HuksTagType.HUKS_TAG_TYPE_UINT |10003原为预留字段,从API version 9开始废弃。
系统能力: SystemCapability.Security.Huks.Extension
HUKS_TAG_USES_TIME(deprecated)HuksTagType.HUKS_TAG_TYPE_UINT |10004原为预留字段,从API version 9开始废弃。
系统能力: SystemCapability.Security.Huks.Extension
HUKS_TAG_CRYPTO_CTX(deprecated)HuksTagType.HUKS_TAG_TYPE_ULONG |10005原为预留字段,从API version 9开始废弃。
系统能力: SystemCapability.Security.Huks.Extension
HUKS_TAG_KEYHuksTagType.HUKS_TAG_TYPE_BYTES |10006预留。
系统能力: SystemCapability.Security.Huks.Core
HUKS_TAG_KEY_VERSION(deprecated)HuksTagType.HUKS_TAG_TYPE_UINT |10007表示密钥版本的Tag。从API version 9开始废弃。
系统能力: SystemCapability.Security.Huks.Extension
HUKS_TAG_PAYLOAD_LEN(deprecated)HuksTagType.HUKS_TAG_TYPE_UINT |10008原为预留字段,从API version 9开始废弃。
系统能力: SystemCapability.Security.Huks.Extension
HUKS_TAG_AE_TAGHuksTagType.HUKS_TAG_TYPE_BYTES |10009用于传入GCM模式中的AEAD数据的字段。
系统能力: SystemCapability.Security.Huks.Core
HUKS_TAG_IS_KEY_HANDLE(deprecated)HuksTagType.HUKS_TAG_TYPE_ULONG |10010原为预留字段,从API version 9开始废弃。
系统能力: SystemCapability.Security.Huks.Core
HUKS_TAG_OS_VERSION(deprecated)HuksTagType.HUKS_TAG_TYPE_UINT |10101表示操作系统版本的Tag。从API version 9开始废弃。
系统能力: SystemCapability.Security.Huks.Core
HUKS_TAG_OS_PATCHLEVEL(deprecated)HuksTagType.HUKS_TAG_TYPE_UINT |10102表示操作系统补丁级别的Tag。从API version 9开始废弃。
系统能力: SystemCapability.Security.Huks.Core
HUKS_TAG_SYMMETRIC_KEY_DATAHuksTagType.HUKS_TAG_TYPE_BYTES |20001预留。
系统能力: SystemCapability.Security.Huks.Core
HUKS_TAG_ASYMMETRIC_PUBLIC_KEY_DATAHuksTagType.HUKS_TAG_TYPE_BYTES |20002预留。
系统能力: SystemCapability.Security.Huks.Extension
HUKS_TAG_ASYMMETRIC_PRIVATE_KEY_DATAHuksTagType.HUKS_TAG_TYPE_BYTES |20003预留。
系统能力: SystemCapability.Security.Huks.Extension

huks.generateKey(deprecated)

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

生成密钥,使用Callback回调异步返回结果。

说明:

从API version 9开始废弃,建议使用huks.generateKeyItem9+替代。

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

参数:

参数名类型必填说明
keyAliasstring别名。
optionsHuksOptions用于存放生成key所需TAG。
callbackAsyncCallback<HuksResult>回调函数。返回HUKS_SUCCESS时表示接口使用成功,其余结果请参考HuksResult进行错误码查询。

示例:

import huks from '@ohos.security.huks';
/* 以生成RSA512密钥为例 */
class HuksProperties {
    tag: huks.HuksTag = huks.HuksTag.HUKS_TAG_ALGORITHM
    value: huks.HuksKeyAlg|huks.HuksKeySize|huks.HuksKeyPurpose|
    huks.HuksKeyDigest|huks.HuksKeyPadding = huks.HuksKeyAlg.HUKS_ALG_ECC
}
let keyAlias = 'keyAlias';
let properties: HuksProperties[] = [
    {
        tag: huks.HuksTag.HUKS_TAG_ALGORITHM,
        value: huks.HuksKeyAlg.HUKS_ALG_RSA
    },
    {
        tag: huks.HuksTag.HUKS_TAG_KEY_SIZE,
        value: huks.HuksKeySize.HUKS_RSA_KEY_SIZE_512
    },
    {
        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_OAEP
    },
    {
        tag: huks.HuksTag.HUKS_TAG_DIGEST,
        value: huks.HuksKeyDigest.HUKS_DIGEST_SHA256
    }
];
let options: huks.HuksOptions = {
    properties: properties
};
huks.generateKey(keyAlias, options, (err, data) => {
});

huks.generateKey(deprecated)

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

生成密钥,使用Promise方式异步返回结果。

说明:

从API version 9开始废弃,建议使用huks.generateKeyItem9+替代。

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

参数:

参数名类型必填说明
keyAliasstring密钥别名。
optionsHuksOptions用于存放生成key所需TAG。

返回值

类型说明
Promise<HuksResult>Promise对象。返回HUKS_SUCCESS时表示接口使用成功,其他时为错误。

示例:

import huks from '@ohos.security.huks';
/* 以生成ECC256密钥为例 */
class HuksProperties {
    tag: huks.HuksTag = huks.HuksTag.HUKS_TAG_ALGORITHM
    value: huks.HuksKeyAlg|huks.HuksKeySize|huks.HuksKeyPurpose|
    huks.HuksKeyDigest = huks.HuksKeyAlg.HUKS_ALG_ECC
}

let keyAlias = 'keyAlias';
let properties: HuksProperties[] = [
    {
        tag: huks.HuksTag.HUKS_TAG_ALGORITHM,
        value: huks.HuksKeyAlg.HUKS_ALG_ECC
    },
    {
        tag: huks.HuksTag.HUKS_TAG_KEY_SIZE,
        value: huks.HuksKeySize.HUKS_ECC_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_SHA256
    }
];
let options: huks.HuksOptions = {
    properties: properties
};
let result = huks.generateKey(keyAlias, options);

huks.deleteKey(deprecated)

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

删除密钥,使用Callback回调异步返回结果。

说明:

从API version 9开始废弃,建议使用huks.deleteKeyItem9+替代。

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

参数:

参数名类型必填说明
keyAliasstring密钥别名,应为生成key时传入的别名。
optionsHuksOptions空对象(此处传空即可)。
callbackAsyncCallback<HuksResult>回调函数。返回HUKS_SUCCESS时表示接口使用成功,其他时为错误。

示例:

import huks from '@ohos.security.huks';
/* 此处options选择emptyOptions传空 */
let keyAlias = 'keyAlias';
let emptyOptions: huks.HuksOptions = {
    properties: []
};
huks.deleteKey(keyAlias, emptyOptions, (err, data) => {
});

huks.deleteKey(deprecated)

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

删除密钥,使用Promise方式异步返回结果。

说明:

从API version 9开始废弃,建议使用huks.deleteKeyItem9+替代。

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

参数:

参数名类型必填说明
keyAliasstring密钥别名,应为生成key时传入的别名。
optionsHuksOptions空对象(此处传空即可)。

返回值:

类型说明
Promise<HuksResult>Promise对象。返回HUKS_SUCCESS时表示接口使用成功,其他时为错误。

示例:

import huks from '@ohos.security.huks';
/* 此处options选择emptyOptions传空 */
let keyAlias = 'keyAlias';
let emptyOptions: huks.HuksOptions = {
    properties: []
};
let result = huks.deleteKey(keyAlias, emptyOptions);

huks.importKey(deprecated)

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

导入明文密钥,使用Callback方式回调异步返回结果 。

说明:

从API version 9开始废弃,建议使用huks.importKeyItem9+替代。

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

参数:

参数名类型必填说明
keyAliasstring密钥别名。
optionsHuksOptions用于导入时所需TAG和需要导入的密钥。
callbackAsyncCallback<HuksResult>回调函数。返回HUKS_SUCCESS时表示接口使用成功,其他时为错误。

示例:

import huks from '@ohos.security.huks';
/* 以导入AES256密钥为例 */
class HuksProperties {
    tag: huks.HuksTag = huks.HuksTag.HUKS_TAG_ALGORITHM
    value: huks.HuksKeyAlg|huks.HuksKeySize|huks.HuksKeyPurpose|
    huks.HuksKeyPadding|huks.HuksCipherMode = huks.HuksKeyAlg.HUKS_ALG_ECC
}
let plainTextSize32 = makeRandomArr(32);
function makeRandomArr(size: number) {
    let arr = new Uint8Array(size);
    for (let i = 0; i < size; i++) {
        arr[i] = Math.floor(Math.random() * 10);
    }
    return arr;
};
let keyAlias = 'keyAlias';
let properties: HuksProperties[] = [
    {
        tag: huks.HuksTag.HUKS_TAG_ALGORITHM,
        value: huks.HuksKeyAlg.HUKS_ALG_AES
    },
    {
        tag: huks.HuksTag.HUKS_TAG_KEY_SIZE,
        value: huks.HuksKeySize.HUKS_AES_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_PADDING,
        value: huks.HuksKeyPadding.HUKS_PADDING_PKCS7
    },
    {
        tag: huks.HuksTag.HUKS_TAG_BLOCK_MODE,
        value: huks.HuksCipherMode.HUKS_MODE_ECB
    }
];
let options: huks.HuksOptions = {
    properties: properties,
    inData: plainTextSize32
};
huks.importKey(keyAlias, options, (err, data) => {
});

huks.importKey(deprecated)

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

导入明文密钥,使用Promise方式异步返回结果。

说明:

从API version 9开始废弃,建议使用huks.importKeyItem9+替代。

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

参数:

参数名类型必填说明
keyAliasstring密钥别名。
optionsHuksOptions用于导入时所需TAG和需要导入的密钥。

返回值:

类型说明
Promise<HuksResult>Promise对象。返回HUKS_SUCCESS时表示接口使用成功,其他时为错误。

示例:

import huks from '@ohos.security.huks';
/* 以导入AES128为例 */
class HuksProperties {
    tag: huks.HuksTag = huks.HuksTag.HUKS_TAG_ALGORITHM
    value: huks.HuksKeyAlg|huks.HuksKeySize|huks.HuksKeyPurpose|
    huks.HuksKeyPadding|huks.HuksCipherMode = huks.HuksKeyAlg.HUKS_ALG_ECC
}
let plainTextSize32 = makeRandomArr(32);
function makeRandomArr(size: number) {
    let arr = new Uint8Array(size);
    for (let i = 0; i < size; i++) {
        arr[i] = Math.floor(Math.random() * 10);
    }
    return arr;
};
/*第一步:生成密钥*/
let keyAlias = 'keyAlias';
let properties: HuksProperties[] = [
    {
        tag: huks.HuksTag.HUKS_TAG_ALGORITHM,
        value: huks.HuksKeyAlg.HUKS_ALG_AES
    },
    {
        tag: huks.HuksTag.HUKS_TAG_KEY_SIZE,
        value: huks.HuksKeySize.HUKS_AES_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_ECB
    }
];
let huksoptions: huks.HuksOptions = {
    properties: properties,
    inData: plainTextSize32
};
let result = huks.importKey(keyAlias, huksoptions);

huks.exportKey(deprecated)

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

导出密钥,使用Callback方式回调异步返回的结果。

说明:

从API version 9开始废弃,建议使用huks.exportKeyItem9+替代。

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

参数:

参数名类型必填说明
keyAliasstring密钥别名,应与所用密钥生成时使用的别名相同。
optionsHuksOptions空对象(此处传空即可)。
callbackAsyncCallback<HuksResult>回调函数。返回HUKS_SUCCESS时表示接口使用成功,其他时为错误。outData:返回从密钥中导出的公钥。

示例:

import huks from '@ohos.security.huks';
/* 此处options选择emptyOptions来传空 */
let keyAlias = 'keyAlias';
let emptyOptions: huks.HuksOptions = {
    properties: []
};
huks.exportKey(keyAlias, emptyOptions, (err, data) => {
});

huks.exportKey(deprecated)

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

导出密钥,使用Promise方式回调异步返回的结果。

说明:

从API version 9开始废弃,建议使用huks.exportKeyItem9+替代。

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

参数:

参数名类型必填说明
keyAliasstring密钥别名,应与所用密钥生成时使用的别名相同。
optionsHuksOptions空对象(此处传空即可)。

返回值:

类型说明
Promise<HuksResult>Promise对象。返回HUKS_SUCCESS时表示接口使用成功,其他时为错误。outData:返回从密钥中导出的公钥。

示例:

import huks from '@ohos.security.huks';
/* 此处options选择emptyOptions来传空 */
let keyAlias = 'keyAlias';
let emptyOptions: huks.HuksOptions = {
    properties: []
};
let result = huks.exportKey(keyAlias, emptyOptions);

huks.getKeyProperties(deprecated)

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

获取密钥属性,使用Callback回调异步返回结果。

说明:

从API version 9开始废弃,建议使用huks.getKeyItemProperties9+替代。

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

参数:

参数名类型必填说明
keyAliasstring密钥别名,应与所用密钥生成时使用的别名相同。
optionsHuksOptions空对象(此处传空即可)。
callbackAsyncCallback<HuksResult>回调函数。errorCode:返回HUKS_SUCCESS时表示接口使用成功,其他时为错误。

示例:

import huks from '@ohos.security.huks';
/* 此处options选择emptyOptions来传空 */
let keyAlias = 'keyAlias';
let emptyOptions: huks.HuksOptions = {
    properties: []
};
huks.getKeyProperties(keyAlias, emptyOptions, (err, data) => {
});

huks.getKeyProperties(deprecated)

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

获取密钥属性,使用Promise回调异步返回结果。

说明:

从API version 9开始废弃,建议使用huks.getKeyItemProperties9+替代。

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

参数:

参数名类型必填说明
keyAliasstring密钥别名,应与所用密钥生成时使用的别名相同。
optionsHuksOptions空对象(此处传空即可)。

返回值:

类型说明
Promise<HuksResult>Promise对象。errorCode:返回HUKS_SUCCESS时表示接口使用成功,其他时为错误。properties:返回值为生成密钥时所需参数。

示例:

import huks from '@ohos.security.huks';
/* 此处options选择emptyOptions来传空 */
let keyAlias = 'keyAlias';
let emptyOptions: huks.HuksOptions = {
    properties: []
};
let result = huks.getKeyProperties(keyAlias, emptyOptions);

huks.isKeyExist(deprecated)

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

判断密钥是否存在,使用Callback回调异步返回结果 。

说明:

从API version 9开始废弃,建议使用huks.isKeyItemExist9+替代。

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

参数:

参数名类型必填说明
keyAliasstring所需查找的密钥的别名。
optionsHuksOptions空对象(此处传空即可)。
callbackAsyncCallback<boolean>回调函数。false代表密钥不存在,true代表密钥存在。

示例:

import huks from '@ohos.security.huks';
/* 此处options选择emptyOptions来传空 */
let keyAlias = 'keyAlias';
let emptyOptions: huks.HuksOptions = {
    properties: []
};
huks.isKeyExist(keyAlias, emptyOptions, (err, data) => {
});

huks.isKeyExist(deprecated)

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

判断密钥是否存在,使用Promise回调异步返回结果 。

说明:

从API version 9开始废弃,建议使用huks.isKeyItemExist9+替代。

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

参数:

参数名类型必填说明
keyAliasstring所需查找的密钥的别名。
optionsHuksOptions空对象(此处传空即可)。

返回值:

类型说明
Promise<boolean>Promise对象。false代表密钥不存在,true代表密钥存在。

示例:

import huks from '@ohos.security.huks';
/* 此处options选择emptyOptions来传空 */
let keyAlias = 'keyAlias';
let emptyOptions: huks.HuksOptions = {
    properties: []
};
let result = huks.isKeyExist(keyAlias, emptyOptions);

huks.init(deprecated)

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

init操作密钥接口,使用Callback回调异步返回结果。huks.init, huks.update, huks.finish为三段式接口,需要一起使用。

说明:

从API version 9开始废弃,建议使用huks.initSession9+替代。

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

参数:

参数名类型必填说明
keyAliasstringInit操作密钥的别名。
optionsHuksOptionsInit操作的参数集合。
callbackAsyncCallback<HuksHandle>回调函数。将Init操作操作返回的handle添加到密钥管理系统的回调。

huks.init(deprecated)

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

init操作密钥接口,使用Promise方式异步返回结果。huks.init, huks.update, huks.finish为三段式接口,需要一起使用。

说明:

从API version 9开始废弃,建议使用huks.initSession9+替代。

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

参数:

参数名类型必填说明
keyAliasstringInit操作密钥的别名。
optionsHuksOptionsInit参数集合。

返回值

类型说明
Promise<HuksHandle>Promise对象。将Init操作返回的handle添加到密钥管理系统的回调。

huks.update(deprecated)

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

update操作密钥接口,使用Callback回调异步返回结果。huks.init, huks.update, huks.finish为三段式接口,需要一起使用。

说明:

从API version 9开始废弃,建议使用huks.updateSession9+替代。

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

参数:

参数名类型必填说明
handlenumberUpdate操作的handle。
tokenUint8ArrayUpdate操作的token。
optionsHuksOptionsUpdate操作的参数集合。
callbackAsyncCallback<HuksResult>回调函数。将Update操作的结果添加到密钥管理系统的回调。

huks.update(deprecated)

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

update操作密钥接口,使用Promise方式异步返回结果。huks.init, huks.update, huks.finish为三段式接口,需要一起使用。

说明:

从API version 9开始废弃,建议使用huks.updateSession9+替代。

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

参数:

参数名类型必填说明
handlenumberUpdate操作的handle。
tokenUint8ArrayUpdate操作的token。
optionsHuksOptionsUpdate操作的参数集合。

返回值

类型说明
Promise<HuksResult>Promise对象。将Update操作的结果添加到密钥管理系统的回调。

huks.finish(deprecated)

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

finish操作密钥接口,使用Callback回调异步返回结果。huks.init, huks.update, huks.finish为三段式接口,需要一起使用。

说明:

从API version 9开始废弃,建议使用huks.finishSession9+替代。

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

参数:

参数名类型必填说明
handlenumberFinish操作的handle。
optionsHuksOptionsFinish的参数集合。
callbackAsyncCallback<HuksResult>回调函数。将Finish操作的结果添加到密钥管理系统的回调。

huks.finish(deprecated)

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

finish操作密钥接口,使用Promise方式异步返回结果。huks.init, huks.update, huks.finish为三段式接口,需要一起使用。

说明:

从API version 9开始废弃,建议使用huks.finishSession9+替代。

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

参数:

参数名类型必填说明
handlenumberFinish操作的handle。
optionsHuksOptionsFinish操作的参数集合。

返回值

类型说明
Promise<HuksResult>Promise对象,用于获取异步返回结果。

huks.abort(deprecated)

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

abort操作密钥接口,使用Callback回调异步返回结果。

说明:

从API version 9开始废弃,建议使用huks.abortSession9+替代。

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

参数:

参数名类型必填说明
handlenumberAbort操作的handle。
optionsHuksOptionsAbort操作的参数集合。
callbackAsyncCallback<HuksResult>回调函数。将Abort操作的结果添加到密钥管理系统的回调。

示例:

import huks from '@ohos.security.huks';
import { BusinessError } from '@ohos.base';
/* huks.init, huks.update, huks.finish为三段式接口,需要一起使用,当huks.init和huks.update
 * 以及huks.finish操作中的任一阶段发生错误时,都需要调用huks.abort来终止密钥的使用。
 *
 * 以下以RSA1024密钥的callback操作使用为例
 */
class HuksProperties {
    tag: huks.HuksTag = huks.HuksTag.HUKS_TAG_ALGORITHM
    value: huks.HuksKeyAlg|huks.HuksKeySize|huks.HuksKeyPurpose|
    huks.HuksKeyDigest|huks.HuksKeyPadding = huks.HuksKeyAlg.HUKS_ALG_ECC
}
let keyalias = "HuksDemoRSA";
let properties: HuksProperties[] = [];
let options: huks.HuksOptions = {
    properties: properties,
    inData: new Uint8Array(0)
};
let handle: number = 0;
let resultMessage = "";
async function generateKey() {
    properties[0] = {
        tag: huks.HuksTag.HUKS_TAG_ALGORITHM,
        value: huks.HuksKeyAlg.HUKS_ALG_RSA
    };
    properties[1] = {
        tag: huks.HuksTag.HUKS_TAG_KEY_SIZE,
        value: huks.HuksKeySize.HUKS_RSA_KEY_SIZE_1024
    };
    properties[2] = {
        tag: huks.HuksTag.HUKS_TAG_PURPOSE,
        value: huks.HuksKeyPurpose.HUKS_KEY_PURPOSE_ENCRYPT
    };
    properties[3] = {
        tag: huks.HuksTag.HUKS_TAG_PADDING,
        value: huks.HuksKeyPadding.HUKS_PADDING_OAEP
    };
    properties[4] = {
        tag: huks.HuksTag.HUKS_TAG_DIGEST,
        value: huks.HuksKeyDigest.HUKS_DIGEST_SHA256
    };
    huks.generateKey(keyalias, options);
}
function stringToUint8Array(str: string) {
    let arr: number[] = [];
    for (let i = 0, j = str.length; i < j; ++i) {
        arr.push(str.charCodeAt(i));
    }
    let tmpUint8Array = new Uint8Array(arr);
    return tmpUint8Array;
}
async function huksInit() {
    await huks.init(keyalias, options).then((data) => {
        console.log(`test init data: ${JSON.stringify(data)}`);
        handle = data.handle;
    }).catch((err: BusinessError) => {
        console.log("test init err information: " + JSON.stringify(err))
    })
}
async function huksUpdate() {
    options.inData = stringToUint8Array("huksHmacTest");
    await huks.update(handle, options.inData, options).then((data) => {
        if (data.errorCode === 0) {
            resultMessage += "update success!";
        } else {
            resultMessage += "update fail!";
        }
    });
    console.log(resultMessage);
}
function huksFinish() {
    options.inData = stringToUint8Array("HuksDemoHMAC");
    huks.finish(handle, options).then((data) => {
        if (data.errorCode === 0) {
            resultMessage = "finish success!";
        } else {
            resultMessage = "finish fail errorCode: " + data.errorCode;
        }
    }).catch((err: BusinessError) => {
        resultMessage = "finish fail, catch errorMessage:" + JSON.stringify(err)
    });
    console.log(resultMessage);
}
async function huksAbort() {
    new Promise<huks.HuksResult>((resolve, reject) => {
        huks.abort(handle, options, (err, data) => {
            console.log(`Huks_Demo hmac huksAbort1 data ${JSON.stringify(data)}`);
            console.log(`Huks_Demo hmac huksAbort1 err ${JSON.stringify(err)}`);
        });
    });
}

huks.abort(deprecated)

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

abort操作密钥接口,使用Promise方式异步返回结果。

说明:

从API version 9开始废弃,建议使用huks.abortSession9+替代。

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

参数:

参数名类型必填说明
handlenumberAbort操作的handle。
optionsHuksOptionsAbort操作的参数集合。

返回值

类型说明
Promise<HuksResult>Promise对象。将Abort操作的结果添加到密钥管理系统的回调。

示例:

import huks from '@ohos.security.huks';
import { BusinessError } from '@ohos.base';
/* huks.init, huks.update, huks.finish为三段式接口,需要一起使用,当huks.init和huks.update
 * 以及huks.finish操作中的任一阶段发生错误时,都需要调用huks.abort来终止密钥的使用。
 *
 * 以下以RSA1024密钥的promise操作使用为例
 */
class HuksProperties {
    tag: huks.HuksTag = huks.HuksTag.HUKS_TAG_ALGORITHM
    value: huks.HuksKeyAlg|huks.HuksKeySize|huks.HuksKeyPurpose|
    huks.HuksKeyPadding|huks.HuksKeyDigest = huks.HuksKeyAlg.HUKS_ALG_ECC
}
let keyalias = "HuksDemoRSA";
let properties: HuksProperties[] = [];
let options: huks.HuksOptions = {
    properties: properties,
    inData: new Uint8Array(0)
};
let handle: number = 0;
let resultMessage = "";

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

async function generateKey() {
    properties[0] = {
        tag: huks.HuksTag.HUKS_TAG_ALGORITHM,
        value: huks.HuksKeyAlg.HUKS_ALG_RSA
    };
    properties[1] = {
        tag: huks.HuksTag.HUKS_TAG_KEY_SIZE,
        value: huks.HuksKeySize.HUKS_RSA_KEY_SIZE_1024
    };
    properties[2] = {
        tag: huks.HuksTag.HUKS_TAG_PURPOSE,
        value: huks.HuksKeyPurpose.HUKS_KEY_PURPOSE_ENCRYPT
    };
    properties[3] = {
        tag: huks.HuksTag.HUKS_TAG_PADDING,
        value: huks.HuksKeyPadding.HUKS_PADDING_OAEP
    };
    properties[4] = {
        tag: huks.HuksTag.HUKS_TAG_DIGEST,
        value: huks.HuksKeyDigest.HUKS_DIGEST_SHA256
    };
    huks.generateKey(keyalias, options, (err, data) => {
    });
}

async function huksInit() {
    return new Promise<huks.HuksHandle>((resolve, reject) => {
        huks.init(keyalias, options, async (err, data) => {
            if (data.errorCode === 0) {
                resultMessage = "init success!"
                handle = data.handle;
            } else {
                resultMessage = "init fail errorCode: " + data.errorCode
            }
        });
    });
}

async function huksUpdate() {
    options.inData = stringToUint8Array("huksHmacTest");
    new Promise<huks.HuksResult>((resolve, reject) => {
        huks.update(handle, options.inData, options, (err, data) => {
            if (data.errorCode === 0) {
                resultMessage += "update success!";
            } else {
                resultMessage += "update fail!";
            }
        });
    });
    console.log(resultMessage);

}

async function huksFinish() {
    options.inData = stringToUint8Array("0");
    new Promise<huks.HuksResult>((resolve, reject) => {
        huks.finish(handle, options, (err, data) => {
            if (data.errorCode === 0) {
                resultMessage = "finish success!";
            } else {
                resultMessage = "finish fail errorCode: " + data.errorCode;
            }
        });
    });
}

function huksAbort() {
    huks.abort(handle, options).then((data) => {
        if (data.errorCode === 0) {
            resultMessage = "abort success!";
        } else {
            resultMessage = "abort fail errorCode: " + data.errorCode;
        }
    }).catch((err: BusinessError) => {
        resultMessage = "abort fail, catch errorMessage:" + JSON.stringify(err)
    });
    console.log(resultMessage);
}

HuksHandle(deprecated)

huks Handle结构体。

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

说明:

从API version 9开始废弃,建议使用HuksSessionHandle9+替代。

名称类型必填说明
errorCodenumber表示错误码。
handlenumber表示handle值。
tokenUint8Array表示init操作之后获取到的challenge信息。

HuksResult(deprecated)

调用接口返回的result。

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

说明:

名称类型必填说明
errorCodenumber表示错误码。
outDataUint8Array表示输出数据。
propertiesArray<HuksParam>表示属性信息。
certChainsArray<string>表示证书链数据。

HuksErrorCode(deprecated)

表示错误码的枚举。

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

说明:

从API version 9开始废弃,建议使用HuksExceptionErrCode9+替代。

名称说明
HUKS_SUCCESS0表示成功。
HUKS_FAILURE-1表示失败。
HUKS_ERROR_BAD_STATE-2表示错误的状态。
HUKS_ERROR_INVALID_ARGUMENT-3表示无效的数据。
HUKS_ERROR_NOT_SUPPORTED-4表示不支持。
HUKS_ERROR_NO_PERMISSION-5表示没有许可。
HUKS_ERROR_INSUFFICIENT_DATA-6表示数据不足。
HUKS_ERROR_BUFFER_TOO_SMALL-7表示缓冲区太小。
HUKS_ERROR_INSUFFICIENT_MEMORY-8表示内存不足。
HUKS_ERROR_COMMUNICATION_FAILURE-9表示通讯失败。
HUKS_ERROR_STORAGE_FAILURE-10表示存储故障。
HUKS_ERROR_HARDWARE_FAILURE-11表示硬件故障。
HUKS_ERROR_ALREADY_EXISTS-12表示已经存在。
HUKS_ERROR_NOT_EXIST-13表示不存在。
HUKS_ERROR_NULL_POINTER-14表示空指针。
HUKS_ERROR_FILE_SIZE_FAIL-15表示文件大小失败。
HUKS_ERROR_READ_FILE_FAIL-16表示读取文件失败。
HUKS_ERROR_INVALID_PUBLIC_KEY-17表示无效的公钥。
HUKS_ERROR_INVALID_PRIVATE_KEY-18表示无效的私钥。
HUKS_ERROR_INVALID_KEY_INFO-19表示无效的密钥信息。
HUKS_ERROR_HASH_NOT_EQUAL-20表示哈希不相等。
HUKS_ERROR_MALLOC_FAIL-21表示MALLOC 失败。
HUKS_ERROR_WRITE_FILE_FAIL-22表示写文件失败。
HUKS_ERROR_REMOVE_FILE_FAIL-23表示删除文件失败。
HUKS_ERROR_OPEN_FILE_FAIL-24表示打开文件失败。
HUKS_ERROR_CLOSE_FILE_FAIL-25表示关闭文件失败。
HUKS_ERROR_MAKE_DIR_FAIL-26表示创建目录失败。
HUKS_ERROR_INVALID_KEY_FILE-27表示无效的密钥文件。
HUKS_ERROR_IPC_MSG_FAIL-28表示IPC 信息失败。
HUKS_ERROR_REQUEST_OVERFLOWS-29表示请求溢出。
HUKS_ERROR_PARAM_NOT_EXIST-30表示参数不存在。
HUKS_ERROR_CRYPTO_ENGINE_ERROR-31表示CRYPTO ENGINE错误。
HUKS_ERROR_COMMUNICATION_TIMEOUT-32表示通讯超时。
HUKS_ERROR_IPC_INIT_FAIL-33表示IPC 初始化失败。
HUKS_ERROR_IPC_DLOPEN_FAIL-34表示IPC DLOPEN 失败。
HUKS_ERROR_EFUSE_READ_FAIL-35表示EFUSE 读取失败。
HUKS_ERROR_NEW_ROOT_KEY_MATERIAL_EXIST-36表示存在新的根密钥材料。
HUKS_ERROR_UPDATE_ROOT_KEY_MATERIAL_FAIL-37表示更新根密钥材料失败。
HUKS_ERROR_VERIFICATION_FAILED-38表示验证证书链失败。
HUKS_ERROR_CHECK_GET_ALG_FAIL-100表示检查获取 ALG 失败。
HUKS_ERROR_CHECK_GET_KEY_SIZE_FAIL-101表示检查获取密钥大小失败。
HUKS_ERROR_CHECK_GET_PADDING_FAIL-102表示检查获取填充失败。
HUKS_ERROR_CHECK_GET_PURPOSE_FAIL-103表示检查获取目的失败。
HUKS_ERROR_CHECK_GET_DIGEST_FAIL-104表示检查获取摘要失败。
HUKS_ERROR_CHECK_GET_MODE_FAIL-105表示检查获取模式失败。
HUKS_ERROR_CHECK_GET_NONCE_FAIL-106表示检查获取随机数失败。
HUKS_ERROR_CHECK_GET_AAD_FAIL-107表示检查获取 AAD 失败。
HUKS_ERROR_CHECK_GET_IV_FAIL-108表示检查 GET IV 失败。
HUKS_ERROR_CHECK_GET_AE_TAG_FAIL-109表示检查获取 AE 标记失败。
HUKS_ERROR_CHECK_GET_SALT_FAIL-110表示检查获取SALT失败。
HUKS_ERROR_CHECK_GET_ITERATION_FAIL-111表示检查获取迭代失败。
HUKS_ERROR_INVALID_ALGORITHM-112表示无效的算法。
HUKS_ERROR_INVALID_KEY_SIZE-113表示无效的密钥大小。
HUKS_ERROR_INVALID_PADDING-114表示无效的填充。
HUKS_ERROR_INVALID_PURPOSE-115表示无效的目的。
HUKS_ERROR_INVALID_MODE-116表示无效模式。
HUKS_ERROR_INVALID_DIGEST-117表示无效的摘要。
HUKS_ERROR_INVALID_SIGNATURE_SIZE-118表示签名大小无效。
HUKS_ERROR_INVALID_IV-119表示无效的 IV。
HUKS_ERROR_INVALID_AAD-120表示无效的 AAD。
HUKS_ERROR_INVALID_NONCE-121表示无效的随机数。
HUKS_ERROR_INVALID_AE_TAG-122表示无效的 AE 标签。
HUKS_ERROR_INVALID_SALT-123表示无效SALT。
HUKS_ERROR_INVALID_ITERATION-124表示无效的迭代。
HUKS_ERROR_INVALID_OPERATION-125表示无效操作。
HUKS_ERROR_INTERNAL_ERROR-999表示内部错误。
HUKS_ERROR_UNKNOWN_ERROR-1000表示未知错误。

你可能感兴趣的鸿蒙文章

harmony 鸿蒙接口

harmony 鸿蒙系统公共事件定义(待停用)

harmony 鸿蒙系统公共事件定义

harmony 鸿蒙开发说明

harmony 鸿蒙企业设备管理概述(仅对系统应用开放)

harmony 鸿蒙BundleStatusCallback

harmony 鸿蒙@ohos.bundle.innerBundleManager (innerBundleManager模块)

harmony 鸿蒙@ohos.distributedBundle (分布式包管理)

harmony 鸿蒙@ohos.bundle (Bundle模块)

harmony 鸿蒙@ohos.enterprise.EnterpriseAdminExtensionAbility (企业设备管理扩展能力)

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