harmony 鸿蒙@ohos.security.huks (HUKS)

2022-08-09 浏览 (1285)

@ohos.security.huks (HUKS)

The HUKS module provides KeyStore (KS) capabilities for applications, including key management and key cryptography operations. The keys managed by OpenHarmony Universal KeyStore (HUKS) can be imported by applications or generated by calling the HUKS APIs.

NOTE

The initial APIs of this module are supported since API version 8. Newly added APIs will be marked with a superscript to indicate their earliest API version.

Modules to Import

import huks from '@ohos.security.huks'

HuksParam

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

System capability: SystemCapability.Security.Huks.Core

NameTypeMandatoryDescription
tagHuksTagYesTag.
valueboolean|number|bigint|Uint8ArrayYesValue of the tag.

HuksOptions

Defines the options used in the APIs.

System capability: SystemCapability.Security.Huks.Core

NameTypeMandatoryDescription
propertiesArray<HuksParam>NoProperties used to hold the HuksParam array.
inDataUint8ArrayNoInput data.

HuksSessionHandle9+

Defines the HUKS handle structure.

System capability: SystemCapability.Security.Huks.Core

NameTypeMandatoryDescription
handlenumberYesValue of the handle.
challengeUint8ArrayNoChallenge obtained after the initSession operation.

HuksReturnResult9+

Defines the HuksResult struct.

System capability: SystemCapability.Security.Huks.Core

NameTypeMandatoryDescription
outDataUint8ArrayNoOutput data.
propertiesArray<HuksParam>NoProperty information.
certChainsArray<string>NoCertificate chain information.

huks.generateKeyItem9+

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

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

System capability: SystemCapability.Security.Huks.Core

Parameters

NameTypeMandatoryDescription
keyAliasstringYesAlias of the key.
optionsHuksOptionsYesTags required for generating the key. The algorithm, key purpose, and key length are mandatory.
callbackAsyncCallback<void>YesCallback invoked to return the result. If no error is captured, the key is successfully generated. In this case, the API does not return the key content because the key is always protected in a TEE. If an error is captured, an exception occurs in the generation process.

Error codes

For details about the error codes, see HUKS Error Codes.

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

Example

import huks from '@ohos.security.huks';
/* Generate an ECC key of 256 bits. */
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>

Generates a key. This API uses a promise to return the result. Because the key is always protected in a trusted environment (such as a TEE), the promise does not return the key content. It returns only the information indicating whether the API is successfully called.

System capability: SystemCapability.Security.Huks.Extension

Parameters

NameTypeMandatoryDescription
keyAliasstringYesAlias of the key.
optionsHuksOptionsYesTags required for generating the key. The algorithm, key purpose, and key length are mandatory.

Error codes

For details about the error codes, see HUKS Error Codes.

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

Example

/* Generate an ECC key of 256 bits. */
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

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

System capability: SystemCapability.Security.Huks.Core

Parameters

NameTypeMandatoryDescription
keyAliasstringYesKey alias passed in when the key was generated.
optionsHuksOptionsYesEmpty object (leave this parameter empty).
callbackAsyncCallback<void>YesCallback invoked to return the result. If the operation is successful, no err value is returned; otherwise, an error code is returned.

Error codes

For details about the error codes, see HUKS Error Codes.

IDError Message
401argument is invalid.
801api is not supported.
12000004operating file failed.
12000005IPC communication failed.
12000011queried entity does not exist.
12000012external error.
12000014memory is insufficient.

Example

import huks from '@ohos.security.huks';
/* Set options to 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>

Deletes a key. This API uses a promise to return the result.

System capability: SystemCapability.Security.Huks.Extension

Parameters

NameTypeMandatoryDescription
keyAliasstringYesKey alias passed in when the key was generated.
optionsHuksOptionsYesEmpty object (leave this parameter empty).

Error codes

For details about the error codes, see HUKS Error Codes.

IDError Message
401argument is invalid.
801api is not supported.
12000004operating file failed.
12000005IPC communication failed.
12000011queried entity does not exist.
12000012external error.
12000014memory is insufficient.

Example

import huks from '@ohos.security.huks';
import { BusinessError } from '@ohos.base';
/* Set options to 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

Obtains the SDK version of the current system.

System capability: SystemCapability.Security.Huks.Extension

Parameters

NameTypeMandatoryDescription
optionsHuksOptionsYesEmpty object, which is used to hold the SDK version.

Return value

TypeDescription
stringSDK version obtained.

Example

import huks from '@ohos.security.huks';
/* Set options to emptyOptions. */
let emptyOptions: huks.HuksOptions = {
    properties: []
};
let result = huks.getSdkVersion(emptyOptions);

huks.importKeyItem9+

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

Imports a key in plaintext. This API uses an asynchronous callback to return the result.

System capability: SystemCapability.Security.Huks.Extension

Parameters

NameTypeMandatoryDescription
keyAliasstringYesAlias of the key.
optionsHuksOptionsYesTags required for the import and key to import. The algorithm, key purpose, and key length are mandatory.
callbackAsyncCallback<void>YesCallback invoked to return the result. If the operation is successful, no err value is returned; otherwise, an error code is returned.

Error codes

For details about the error codes, see HUKS Error Codes.

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

Example

import huks from '@ohos.security.huks';
/* Import an AES key of 256 bits. */
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>

Imports a key in plaintext. This API uses a promise to return the result.

System capability: SystemCapability.Security.Huks.Extension

Parameters

NameTypeMandatoryDescription
keyAliasstringYesAlias of the key.
optionsHuksOptionsYesTags required for the import and key to import. The algorithm, key purpose, and key length are mandatory.

Error codes

For details about the error codes, see HUKS Error Codes.

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

Example

import huks from '@ohos.security.huks';
import { BusinessError } from '@ohos.base';
/* Import an AES key of 128 bits. */
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;
};
/* Step 1 Generate a key. */
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

Obtains the certificate used to verify a key. This API uses an asynchronous callback to return the result.

System capability: SystemCapability.Security.Huks.Extension

Parameters

NameTypeMandatoryDescription
keyAliasstringYesAlias of the key. The certificate to be obtained stores the key.
optionsHuksOptionsYesParameters and data required for obtaining the certificate.
callbackAsyncCallback<HuksReturnResult>YesCallback invoked to return the result. If the operation is successful, no err value is returned; otherwise, an error code is returned.

Error codes

For details about the error codes, see HUKS Error Codes.

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

Example

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>

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

System capability: SystemCapability.Security.Huks.Extension

Parameters

NameTypeMandatoryDescription
keyAliasstringYesAlias of the key. The certificate to be obtained stores the key.
optionsHuksOptionsYesParameters and data required for obtaining the certificate.

Return value

TypeDescription
Promise<HuksReturnResult>Promise used to return the result. If the operation is successful, no err value is returned; otherwise, an error code is returned.

Error codes

For details about the error codes, see HUKS Error Codes.

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

Example

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

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

System capability: SystemCapability.Security.Huks.Extension

Parameters

NameTypeMandatoryDescription
keyAliasstringYesAlias of the wrapped key to import.
wrappingKeyAliasstringYesAlias of the data used to unwrap the key imported.
optionsHuksOptionsYesTags required for the import and the wrapped key to import. The algorithm, key purpose, and key length are mandatory.
callbackAsyncCallback<void>YesCallback invoked to return the result. If the operation is successful, no err value is returned; otherwise, an error code is returned.

Error codes

For details about the error codes, see HUKS Error Codes.

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

Example

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);

    /*The following operations do not invoke the HUKS APIs, and the specific implementation is not provided here.
     * For example, import **keyA**.
     * 1. Use ECC to generate a public and private key pair **keyB**. The public key is **keyB_pub**, and the private key is **keyB_pri**.
     * 2. Use **keyB_pri** and the public key obtained from **wrappingAlias** to negotiate the shared key **share_key**.
     * 3. Randomly generate a key **kek** and use it to encrypt **keyA** with AES-GCM. During the encryption, record **nonce1**, **aad1**, ciphertext **keyA_enc**, and encrypted **tag1**.
     * 4. Use **share_key** to encrypt **kek** with AES-GCM. During the encryption, record **nonce2**, **aad2**, ciphertext **kek_enc**, and encrypted **tag2**.
     * 5. Generate the **importOptions.inData** field in the following format:
     * keyB_pub length (4 bytes) + keyB_pub + aad2 length (4 bytes) + aad2 +
     * nonce2 length (4 bytes) + nonce2 + tag2 length (4 bytes) + tag2 +
     * kek_enc length (4 bytes) + kek_enc + aad1 length (4 bytes) + aad1 +
     * nonce1 length (4 bytes) + nonce1 + tag1 length (4 bytes) + tag1 +
     * Memory occupied by the keyA length (4 bytes) + keyA length + keyA_enc length (4 bytes) + keyA_enc
     */
    /* The key data imported vary with the sample code given below. The data structure is described in the preceding comments. */
    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>

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

System capability: SystemCapability.Security.Huks.Extension

Parameters

NameTypeMandatoryDescription
keyAliasstringYesAlias of the wrapped key to import.
wrappingKeyAliasstringYesAlias of the data used to unwrap the key imported.
optionsHuksOptionsYesTags required for the import and the wrapped key to import. The algorithm, key purpose, and key length are mandatory.

Error codes

For details about the error codes, see HUKS Error Codes.

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

Example

import huks from '@ohos.security.huks';
import { BusinessError } from '@ohos.base';
/* The process is similar as if a callback is used, except the following:*/
/* The key data imported vary with the sample code given below. The data structure is described in the preceding comments. */
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

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

System capability: SystemCapability.Security.Huks.Extension

Parameters

NameTypeMandatoryDescription
keyAliasstringYesKey alias, which must be the same as the alias used when the key was generated.
optionsHuksOptionsYesEmpty object (leave this parameter empty).
callbackAsyncCallback<HuksReturnResult>YesCallback invoked to return the result. If the operation is successful, no err value is returned and outData contains the public key exported. If the operation fails, an error code is returned.

Error codes

For details about the error codes, see HUKS Error Codes.

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

Example

import huks from '@ohos.security.huks';
/* Set options to 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>

Exports a key. This API uses a promise to return the result.

System capability: SystemCapability.Security.Huks.Extension

Parameters

NameTypeMandatoryDescription
keyAliasstringYesKey alias, which must be the same as the alias used when the key was generated.
optionsHuksOptionsYesEmpty object (leave this parameter empty).

Return value

TypeDescription
Promise<HuksReturnResult>Promise used to return the result. If the operation is successful, no err value is returned and outData contains the public key exported. If the operation fails, an error code is returned.

Error codes

For details about the error codes, see HUKS Error Codes.

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

Example

import huks from '@ohos.security.huks';
import { BusinessError } from '@ohos.base';
/* Set options to 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

Obtains key properties. This API uses an asynchronous callback to return the result.

System capability: SystemCapability.Security.Huks.Extension

Parameters

NameTypeMandatoryDescription
keyAliasstringYesKey alias, which must be the same as the alias used when the key was generated.
optionsHuksOptionsYesEmpty object (leave this parameter empty).
callbackAsyncCallback<HuksReturnResult>YesCallback invoked to return the result. If the operation is successful, no err value is returned and properties contains the parameters required for generating the key. If the operation fails, an error code is returned.

Error codes

For details about the error codes, see HUKS Error Codes.

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

Example

import huks from '@ohos.security.huks';
/* Set options to 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>

Obtains key properties. This API uses a promise to return the result.

System capability: SystemCapability.Security.Huks.Extension

Parameters

NameTypeMandatoryDescription
keyAliasstringYesKey alias, which must be the same as the alias used when the key was generated.
optionsHuksOptionsYesEmpty object (leave this parameter empty).

Return value

TypeDescription
Promise<HuksReturnResult>Promise used to return the result. If the operation is successful, no err value is returned and properties contains the parameters required for generating the key. If the operation fails, an error code is returned.

Error codes

For details about the error codes, see HUKS Error Codes.

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

Example

import huks from '@ohos.security.huks';
import { BusinessError } from '@ohos.base';
/* Set options to 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

Checks whether a key exists. This API uses an asynchronous callback to return the result.

System capability: SystemCapability.Security.Huks.Core

Parameters

NameTypeMandatoryDescription
keyAliasstringYesAlias of the key to check.
optionsHuksOptionsYesEmpty object (leave this parameter empty).
callbackAsyncCallback<boolean>YesCallback invoked to return the result. If the key exists, data is true. If the key does not exist, error is the error code.

Error codes

For details about the error codes, see HUKS Error Codes.

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

Example

import huks from '@ohos.security.huks';
import promptAction from '@ohos.promptAction';
/* Set options to 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>

Checks whether a key exists. This API uses a promise to return the result.

System capability: SystemCapability.Security.Huks.Extension

Parameters

NameTypeMandatoryDescription
keyAliasstringYesAlias of the key to check.
optionsHuksOptionsYesEmpty object (leave this parameter empty).

Return value

TypeDescription
Promise<boolean>Promise used to return the result. If the key exists, then() performs subsequent operations. If the key does not exist, error() performs the related service operations.

Error codes

For details about the error codes, see HUKS Error Codes.

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

Example

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

/* Set options to 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

Initializes the data for a key operation. This API uses an asynchronous callback to return the result. huks.initSession, huks.updateSession, and huks.finishSession must be used together.

System capability: SystemCapability.Security.Huks.Core

Parameters

NameTypeMandatoryDescription
keyAliasstringYesAlias of the key involved in the initSession operation.
optionsHuksOptionsYesParameter set used for the initSession operation.
callbackAsyncCallback<HuksSessionHandle>YesCallback invoked to return a session handle for subsequent operations.

Error codes

For details about the error codes, see HUKS Error Codes.

IDError Message
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>

Initializes the data for a key operation. This API uses a promise to return the result. huks.initSession, huks.updateSession, and huks.finishSession must be used together.

System capability: SystemCapability.Security.Huks.Extension

Parameters

NameTypeMandatoryDescription
keyAliasstringYesAlias of the key involved in the initSession operation.
optionsHuksOptionsYesParameter set used for the initSession operation.

Return value

TypeDescription
Promise<HuksSessionHandle>Promise used to return a session handle for subsequent operations.

Error codes

For details about the error codes, see HUKS Error Codes.

IDError Message
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

Updates the key operation by segment. This API uses an asynchronous callback to return the result. huks.initSession, huks.updateSession, and huks.finishSession must be used together.

System capability: SystemCapability.Security.Huks.Core

Parameters

NameTypeMandatoryDescription
handlenumberYesHandle for the updateSession operation.
optionsHuksOptionsYesParameter set used for the updateSession operation.
callbackAsyncCallback<HuksReturnResult>YesCallback invoked to return the updateSession operation result.

Error codes

For details about the error codes, see HUKS Error Codes.

IDError Message
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

Updates the key operation by segment. This API uses an asynchronous callback to return the result. huks.initSession, huks.updateSession, and huks.finishSession must be used together.

System capability: SystemCapability.Security.Huks.Extension

Parameters

NameTypeMandatoryDescription
handlenumberYesHandle for the updateSession operation.
optionsHuksOptionsYesParameter set used for the updateSession operation.
tokenUint8ArrayYesToken of the updateSession operation.
callbackAsyncCallback<HuksReturnResult>YesCallback invoked to return the updateSession operation result.

Error codes

For details about the error codes, see HUKS Error Codes.

IDError Message
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>

Updates the key operation by segment. This API uses a promise to return the result. huks.initSession, huks.updateSession, and huks.finishSession must be used together.

System capability: SystemCapability.Security.Huks.Extension

Parameters

NameTypeMandatoryDescription
handlenumberYesHandle for the updateSession operation.
optionsHuksOptionsYesParameter set used for the updateSession operation.
tokenUint8ArrayNoToken of the updateSession operation.

Return value

TypeDescription
Promise<HuksReturnResult>Promise used to return the updateSession operation result.

Error codes

For details about the error codes, see HUKS Error Codes.

IDError Message
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

Finishes the key operation to release resources. This API uses an asynchronous callback to return the result. huks.initSession, huks.updateSession, and huks.finishSession must be used together.

System capability: SystemCapability.Security.Huks.Core

Parameters

NameTypeMandatoryDescription
handlenumberYesHandle for the finishSession operation.
optionsHuksOptionsYesParameter set used for the finishSession operation.
callbackAsyncCallback<HuksReturnResult>YesCallback invoked to return the finishSession operation result.

Error codes

For details about the error codes, see HUKS Error Codes.

IDError Message
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

Finishes the key operation to release resources. This API uses an asynchronous callback to return the result. huks.initSession, huks.updateSession, and huks.finishSession must be used together.

System capability: SystemCapability.Security.Huks.Extension

Parameters

NameTypeMandatoryDescription
handlenumberYesHandle for the finishSession operation.
optionsHuksOptionsYesParameter set used for the finishSession operation.
tokenUint8ArrayYesToken of the finishSession operation.
callbackAsyncCallback<HuksReturnResult>YesCallback invoked to return the finishSession operation result.

Error codes

For details about the error codes, see HUKS Error Codes.

IDError Message
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>

Finishes the key operation to release resources. This API uses a promise to return the result. huks.initSession, huks.updateSession, and huks.finishSession must be used together.

System capability: SystemCapability.Security.Huks.Extension

Parameters

NameTypeMandatoryDescription
handlenumberYesHandle for the finishSession operation.
optionsHuksOptionsYesParameter set used for the finishSession operation.
tokenUint8ArrayNoToken of the finishSession operation.

Return value

TypeDescription
Promise<HuksReturnResult>Promise used to return the result.

Error codes

For details about the error codes, see HUKS Error Codes.

IDError Message
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

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

System capability: SystemCapability.Security.Huks.Core

Parameters

NameTypeMandatoryDescription
handlenumberYesHandle for the abortSession operation.
optionsHuksOptionsYesParameter set used for the abortSession operation.
callbackAsyncCallback<void>YesCallback invoked to return the abortSession operation result.

Error codes

For details about the error codes, see HUKS Error Codes.

IDError Message
401argument is invalid.
801api is not supported.
12000004operating file failed.
12000005IPC communication failed.
12000006error occured in crypto engine.
12000012external error.
12000014memory is insufficient.

Example

import huks from '@ohos.security.huks';
/* huks.initSession, huks.updateSession, and huks.finishSession must be used together.
 * If an error occurs in any of huks.initSession, huks.updateSession,
 * and huks.finishSession operations,
 * huks.abortSession must be called to terminate the use of the key.
 *
 * The following uses the callback of an RSA1024 key as an example.
 */
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>;

Aborts a key operation. This API uses a promise to return the result.

System capability: SystemCapability.Security.Huks.Extension

Parameters

NameTypeMandatoryDescription
handlenumberYesHandle for the abortSession operation.
optionsHuksOptionsYesParameter set used for the abortSession operation.

Return value

TypeDescription
Promise<void>Promise used to return the abortSession operation result.

Error codes

For details about the error codes, see HUKS Error Codes.

IDError Message
401argument is invalid.
801api is not supported.
12000004operating file failed.
12000005IPC communication failed.
12000006error occured in crypto engine.
12000012external error.
12000014memory is insufficient.

Example

import huks from '@ohos.security.huks';
import { BusinessError } from '@ohos.base';
/* huks.initSession, huks.updateSession, and huks.finishSession must be used together.
 * If an error occurs in any of huks.initSession, huks.updateSession,
 * and huks.finishSession operations,
 * huks.abortSession must be called to terminate the use of the key.
 *
 * The following uses the callback of an RSA1024 key as an example.
 */
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+

Enumerates the error codes.

For details about the error codes, see KUKS Error Codes.

System capability: SystemCapability.Security.Huks.Core

NameValueDescription
HUKS_ERR_CODE_PERMISSION_FAIL201Permission verification failed.
HUKS_ERR_CODE_ILLEGAL_ARGUMENT401Invalid parameters are detected.
HUKS_ERR_CODE_NOT_SUPPORTED_API801The API is not supported.
HUKS_ERR_CODE_FEATURE_NOT_SUPPORTED12000001The feature is not supported.
HUKS_ERR_CODE_MISSING_CRYPTO_ALG_ARGUMENT12000002Key algorithm parameters are missing.
HUKS_ERR_CODE_INVALID_CRYPTO_ALG_ARGUMENT12000003Invalid key algorithm parameters are detected.
HUKS_ERR_CODE_FILE_OPERATION_FAIL12000004The file operation failed.
HUKS_ERR_CODE_COMMUNICATION_FAIL12000005The communication failed.
HUKS_ERR_CODE_CRYPTO_FAIL12000006Failed to operate the algorithm library.
HUKS_ERR_CODE_KEY_AUTH_PERMANENTLY_INVALIDATED12000007Failed to access the key because the key has expired.
HUKS_ERR_CODE_KEY_AUTH_VERIFY_FAILED12000008Failed to access the key because the authentication has failed.
HUKS_ERR_CODE_KEY_AUTH_TIME_OUT12000009Key access timed out.
HUKS_ERR_CODE_SESSION_LIMIT12000010The number of key operation sessions has reached the limit.
HUKS_ERR_CODE_ITEM_NOT_EXIST12000011The target object does not exist.
HUKS_ERR_CODE_EXTERNAL_ERROR12000012An external error occurs.
HUKS_ERR_CODE_CREDENTIAL_NOT_EXIST12000013The credential does not exist.
HUKS_ERR_CODE_INSUFFICIENT_MEMORY12000014The memory is insufficient.
HUKS_ERR_CODE_CALL_SERVICE_FAILED12000015Failed to call other system services.

HuksKeyPurpose

Enumerates the key purposes.

System capability: SystemCapability.Security.Huks.Core

NameValueDescription
HUKS_KEY_PURPOSE_ENCRYPT1Used to encrypt the plaintext.
System capability: SystemCapability.Security.Huks.Core
HUKS_KEY_PURPOSE_DECRYPT2Used to decrypt the cipher text.
System capability: SystemCapability.Security.Huks.Core
HUKS_KEY_PURPOSE_SIGN4Used for signing.
System capability: SystemCapability.Security.Huks.Extension
HUKS_KEY_PURPOSE_VERIFY8Used to verify the signature.
System capability: SystemCapability.Security.Huks.Extension
HUKS_KEY_PURPOSE_DERIVE16Used to derive a key.
System capability: SystemCapability.Security.Huks.Extension
HUKS_KEY_PURPOSE_WRAP32Used for an encrypted export.
System capability: SystemCapability.Security.Huks.Extension
HUKS_KEY_PURPOSE_UNWRAP64Used for an encrypted import.
System capability: SystemCapability.Security.Huks.Extension
HUKS_KEY_PURPOSE_MAC128Used to generate a message authentication code (MAC).
System capability: SystemCapability.Security.Huks.Extension
HUKS_KEY_PURPOSE_AGREE256Used for key agreement.
System capability: SystemCapability.Security.Huks.Extension

HuksKeyDigest

Enumerates the digest algorithms.

System capability: SystemCapability.Security.Huks.Extension

NameValueDescription
HUKS_DIGEST_NONE0No digest algorithm
HUKS_DIGEST_MD51MD5
HUKS_DIGEST_SM39+2SM3
HUKS_DIGEST_SHA110SHA-1
HUKS_DIGEST_SHA22411SHA-224
HUKS_DIGEST_SHA25612SHA-256
HUKS_DIGEST_SHA38413SHA-384
HUKS_DIGEST_SHA51214SHA-512

HuksKeyPadding

Enumerates the padding algorithms.

System capability: SystemCapability.Security.Huks.Core

NameValueDescription
HUKS_PADDING_NONE0No padding algorithm
System capability: SystemCapability.Security.Huks.Core
HUKS_PADDING_OAEP1Optimal Asymmetric Encryption Padding (OAEP)
System capability: SystemCapability.Security.Huks.Extension
HUKS_PADDING_PSS2Probabilistic Signature Scheme (PSS)
System capability: SystemCapability.Security.Huks.Extension
HUKS_PADDING_PKCS1_V1_53Public Key Cryptography Standards (PKCS) #1 v1.5
System capability: SystemCapability.Security.Huks.Extension
HUKS_PADDING_PKCS54PKCS #5
System capability: SystemCapability.Security.Huks.Extension
HUKS_PADDING_PKCS75PKCS #7
System capability: SystemCapability.Security.Huks.Core

HuksCipherMode

Enumerates the cipher modes.

System capability: SystemCapability.Security.Huks.Core

NameValueDescription
HUKS_MODE_ECB1Electronic Code Block (ECB) mode
System capability: SystemCapability.Security.Huks.Core
HUKS_MODE_CBC2Cipher Block Chaining (CBC) mode
System capability: SystemCapability.Security.Huks.Core
HUKS_MODE_CTR3Counter (CTR) mode
System capability: SystemCapability.Security.Huks.Core
HUKS_MODE_OFB4Output Feedback (OFB) mode
System capability: SystemCapability.Security.Huks.Extension
HUKS_MODE_CCM31Counter with CBC-MAC (CCM) mode
System capability: SystemCapability.Security.Huks.Extension
HUKS_MODE_GCM32Galois/Counter (GCM) mode
System capability: SystemCapability.Security.Huks.Core

HuksKeySize

Enumerates the key sizes.

System capability: SystemCapability.Security.Huks.Core

NameValueDescription
HUKS_RSA_KEY_SIZE_512512Rivest-Shamir-Adleman (RSA) key of 512 bits
System capability: SystemCapability.Security.Huks.Extension
HUKS_RSA_KEY_SIZE_768768RSA key of 768 bits
System capability: SystemCapability.Security.Huks.Extension
HUKS_RSA_KEY_SIZE_10241024RSA key of 1024 bits
System capability: SystemCapability.Security.Huks.Extension
HUKS_RSA_KEY_SIZE_20482048RSA key of 2048 bits
System capability: SystemCapability.Security.Huks.Extension
HUKS_RSA_KEY_SIZE_30723072RSA key of 3072 bits
System capability: SystemCapability.Security.Huks.Extension
HUKS_RSA_KEY_SIZE_40964096RSA key of 4096 bits
System capability: SystemCapability.Security.Huks.Extension
HUKS_ECC_KEY_SIZE_224224Elliptic Curve Cryptography (ECC) key of 224 bits
System capability: SystemCapability.Security.Huks.Extension
HUKS_ECC_KEY_SIZE_256256ECC key of 256 bits
System capability: SystemCapability.Security.Huks.Extension
HUKS_ECC_KEY_SIZE_384384ECC key of 384 bits
System capability: SystemCapability.Security.Huks.Extension
HUKS_ECC_KEY_SIZE_521521ECC key of 521 bits
System capability: SystemCapability.Security.Huks.Extension
HUKS_AES_KEY_SIZE_128128Advanced Encryption Standard (AES) key of 128 bits
System capability: SystemCapability.Security.Huks.Core
HUKS_AES_KEY_SIZE_192192AES key of 192 bits
System capability: SystemCapability.Security.Huks.Core
HUKS_AES_KEY_SIZE_256256AES key of 256 bits
System capability: SystemCapability.Security.Huks.Core
HUKS_AES_KEY_SIZE_512512AES key of 512 bits
System capability: SystemCapability.Security.Huks.Core
HUKS_CURVE25519_KEY_SIZE_256256Curve25519 key of 256 bits
System capability: SystemCapability.Security.Huks.Extension
HUKS_DH_KEY_SIZE_20482048Diffie-Hellman (DH) key of 2048 bits
System capability: SystemCapability.Security.Huks.Extension
HUKS_DH_KEY_SIZE_30723072DH key of 3072 bits
System capability: SystemCapability.Security.Huks.Extension
HUKS_DH_KEY_SIZE_40964096DH key of 4096 bits
System capability: SystemCapability.Security.Huks.Extension
HUKS_SM2_KEY_SIZE_2569+256ShangMi2 (SM2) key of 256 bits
System capability: SystemCapability.Security.Huks.Extension
HUKS_SM4_KEY_SIZE_1289+128ShangMi4 (SM4) key of 128 bits
System capability: SystemCapability.Security.Huks.Extension

HuksKeyAlg

Enumerates the key algorithms.

System capability: SystemCapability.Security.Huks.Core

NameValueDescription
HUKS_ALG_RSA1RSA
System capability: SystemCapability.Security.Huks.Extension
HUKS_ALG_ECC2ECC
System capability: SystemCapability.Security.Huks.Extension
HUKS_ALG_DSA3DSA
System capability: SystemCapability.Security.Huks.Extension
HUKS_ALG_AES20AES
System capability: SystemCapability.Security.Huks.Core
HUKS_ALG_HMAC50HMAC
System capability: SystemCapability.Security.Huks.Extension
HUKS_ALG_HKDF51HKDF
System capability: SystemCapability.Security.Huks.Extension
HUKS_ALG_PBKDF252PBKDF2
System capability: SystemCapability.Security.Huks.Extension
HUKS_ALG_ECDH100ECDH
System capability: SystemCapability.Security.Huks.Extension
HUKS_ALG_X25519101X25519
System capability: SystemCapability.Security.Huks.Extension
HUKS_ALG_ED25519102ED25519
System capability: SystemCapability.Security.Huks.Extension
HUKS_ALG_DH103DH
System capability: SystemCapability.Security.Huks.Extension
HUKS_ALG_SM29+150SM2
System capability: SystemCapability.Security.Huks.Extension
HUKS_ALG_SM39+151SM3
System capability: SystemCapability.Security.Huks.Extension
HUKS_ALG_SM49+152SM4
System capability: SystemCapability.Security.Huks.Extension

HuksKeyGenerateType

Enumerates the key generation types.

System capability: SystemCapability.Security.Huks.Extension

NameValueDescription
HUKS_KEY_GENERATE_TYPE_DEFAULT0Key generated by default.
HUKS_KEY_GENERATE_TYPE_DERIVE1Derived key.
HUKS_KEY_GENERATE_TYPE_AGREE2Key generated by agreement.

HuksKeyFlag

Enumerates the key generation modes.

System capability: SystemCapability.Security.Huks.Core

NameValueDescription
HUKS_KEY_FLAG_IMPORT_KEY1Import a key using an API.
HUKS_KEY_FLAG_GENERATE_KEY2Generate a key by using an API.
HUKS_KEY_FLAG_AGREE_KEY3Generate a key by using a key agreement API.
HUKS_KEY_FLAG_DERIVE_KEY4Derive a key by using an API.

HuksKeyStorageType

Enumerates the key storage modes.

System capability: SystemCapability.Security.Huks.Core

NameValueDescription
HUKS_STORAGE_TEMP(deprecated)0The key is managed locally.
NOTE: This tag is deprecated since API version 10. No substitute is provided because this tag is not used in key management. In key derivation scenarios, use HUKS_STORAGE_ONLY_USED_IN_HUKS or HUKS_STORAGE_KEY_EXPORT_ALLOWED.
System capability: SystemCapability.Security.Huks.Core
HUKS_STORAGE_PERSISTENT(deprecated)1The key is managed by the HUKS service.
NOTE: This tag is deprecated since API version 10. No substitute is provided because this tag is not used in key management. In key derivation scenarios, use HUKS_STORAGE_ONLY_USED_IN_HUKS or HUKS_STORAGE_KEY_EXPORT_ALLOWED.
System capability: SystemCapability.Security.Huks.Core
HUKS_STORAGE_ONLY_USED_IN_HUKS10+2The key derived from the master key is stored in the HUKS and managed by the HUKS.
System capability: SystemCapability.Security.Huks.Extension
HUKS_STORAGE_KEY_EXPORT_ALLOWED10+3The key derived from the master key is exported to the service, and not managed by the HUKS.
System capability: SystemCapability.Security.Huks.Extension

HuksSendType

Enumerates the tag transfer modes.

System capability: SystemCapability.Security.Huks.Extension

NameValueDescription
HUKS_SEND_TYPE_ASYNC0The tag is sent asynchronously.
HUKS_SEND_TYPE_SYNC1The tag is sent synchronously.

HuksUnwrapSuite9+

Enumerates the algorithm suites used for importing a wrapped key.

System capability: SystemCapability.Security.Huks.Extension

NameValueDescription
HUKS_UNWRAP_SUITE_X25519_AES_256_GCM_NOPADDING1Use X25519 for key agreement and then use AES-256 GCM to encrypt the key.
HUKS_UNWRAP_SUITE_ECDH_AES_256_GCM_NOPADDING2Use ECDH for key agreement and then use AES-256 GCM to encrypt the key.

HuksImportKeyType9+

Enumerates the types of keys to import. By default, a public key is imported. This field is not required when a symmetric key is imported.

System capability: SystemCapability.Security.Huks.Extension

NameValueDescription
HUKS_KEY_TYPE_PUBLIC_KEY0Public key
HUKS_KEY_TYPE_PRIVATE_KEY1Private key
HUKS_KEY_TYPE_KEY_PAIR2Public and private key pair

HuksRsaPssSaltLenType10+

Enumerates the salt_len types to set when PSS padding is used in RSA signing or signature verification.

System capability: SystemCapability.Security.Huks.Extension

NameValueDescription
HUKS_RSA_PSS_SALT_LEN_DIGEST10+0salt_len is set to the digest length.
HUKS_RSA_PSS_SALT_LEN_MAX10+1salt_len is set to the maximum length.

HuksUserAuthType9+

Enumerates the user authentication types.

System capability: SystemCapability.Security.Huks.Extension

NameValueDescription
HUKS_USER_AUTH_TYPE_FINGERPRINT1 << 0Fingerprint authentication.
HUKS_USER_AUTH_TYPE_FACE1 << 1Facial authentication.
HUKS_USER_AUTH_TYPE_PIN1 << 2PIN authentication.

HuksAuthAccessType9+

Enumerates the access control types.

System capability: SystemCapability.Security.Huks.Extension

NameValueDescription
HUKS_AUTH_ACCESS_INVALID_CLEAR_PASSWORD1 << 0The key becomes invalid after the password is cleared.
HUKS_AUTH_ACCESS_INVALID_NEW_BIO_ENROLL1 << 1The key becomes invalid after a new biometric feature is added.
HUKS_AUTH_ACCESS_ALWAYS_VALID11+1 << 2The key is always valid.

HuksChallengeType9+

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

System capability: SystemCapability.Security.Huks.Extension

NameValueDescription
HUKS_CHALLENGE_TYPE_NORMAL0Normal challenge, which is of 32 bytes by default.
HUKS_CHALLENGE_TYPE_CUSTOM1Custom challenge, which supports only one authentication for multiple keys.
HUKS_CHALLENGE_TYPE_NONE2Challenge is not required.

HuksChallengePosition9+

Enumerates the positions of the 8-byte valid value in a custom challenge generated.

System capability: SystemCapability.Security.Huks.Extension

NameValueDescription
HUKS_CHALLENGE_POS_00Bytes 0 to 7.
HUKS_CHALLENGE_POS_11Bytes 8 to 15.
HUKS_CHALLENGE_POS_22Bytes 16 to 23.
HUKS_CHALLENGE_POS_33Bytes 24 to 31.

HuksSecureSignType9+

Defines the signature type of the key generated or imported.

System capability: SystemCapability.Security.Huks.Extension

NameValueDescription
HUKS_SECURE_SIGN_WITH_AUTHINFO1The signature carries authentication information. This field is specified when a key is generated or imported. When the key is used for signing, the data will be added with the authentication information and then be signed.

HuksTagType

Enumerates the tag data types.

System capability: SystemCapability.Security.Huks.Core

NameValueDescription
HUKS_TAG_TYPE_INVALID0 << 28Invalid tag type.
HUKS_TAG_TYPE_INT1 << 28Number of the int type.
HUKS_TAG_TYPE_UINT2 << 28Number of the uint type.
HUKS_TAG_TYPE_ULONG3 << 28BigInt.
HUKS_TAG_TYPE_BOOL4 << 28Boolean.
HUKS_TAG_TYPE_BYTES5 << 28Uint8Array.

HuksTag

Enumerates the tags used to invoke parameters.

System capability: SystemCapability.Security.Huks.Core

NameValueDescription
HUKS_TAG_INVALID(deprecated)HuksTagType.HUKS_TAG_TYPE_INVALID |0Invalid tag. It is deprecated since API version 9.
System capability: SystemCapability.Security.Huks.Core
HUKS_TAG_ALGORITHMHuksTagType.HUKS_TAG_TYPE_UINT |1Algorithm.
System capability: SystemCapability.Security.Huks.Core
HUKS_TAG_PURPOSEHuksTagType.HUKS_TAG_TYPE_UINT |2Purpose of the key.
System capability: SystemCapability.Security.Huks.Core
HUKS_TAG_KEY_SIZEHuksTagType.HUKS_TAG_TYPE_UINT |3Key size.
System capability: SystemCapability.Security.Huks.Core
HUKS_TAG_DIGESTHuksTagType.HUKS_TAG_TYPE_UINT |4Digest algorithm.
System capability: SystemCapability.Security.Huks.Extension
HUKS_TAG_PADDINGHuksTagType.HUKS_TAG_TYPE_UINT |5Padding algorithm.
System capability: SystemCapability.Security.Huks.Core
HUKS_TAG_BLOCK_MODEHuksTagType.HUKS_TAG_TYPE_UINT |6Cipher mode.
System capability: SystemCapability.Security.Huks.Core
HUKS_TAG_KEY_TYPEHuksTagType.HUKS_TAG_TYPE_UINT |7Key type.
System capability: SystemCapability.Security.Huks.Core
HUKS_TAG_ASSOCIATED_DATAHuksTagType.HUKS_TAG_TYPE_BYTES |8Associated authentication data.
System capability: SystemCapability.Security.Huks.Core
HUKS_TAG_NONCEHuksTagType.HUKS_TAG_TYPE_BYTES |9Field for key encryption and decryption.
System capability: SystemCapability.Security.Huks.Core
HUKS_TAG_IVHuksTagType.HUKS_TAG_TYPE_BYTES |10IV.
System capability: SystemCapability.Security.Huks.Core
HUKS_TAG_INFOHuksTagType.HUKS_TAG_TYPE_BYTES |11Information generated during key derivation.
System capability: SystemCapability.Security.Huks.Core
HUKS_TAG_SALTHuksTagType.HUKS_TAG_TYPE_BYTES |12Salt value used for key derivation.
System capability: SystemCapability.Security.Huks.Extension
HUKS_TAG_PWD(deprecated)HuksTagType.HUKS_TAG_TYPE_BYTES |13Password used for key derivation. It is deprecated since API version 9.
System capability: SystemCapability.Security.Huks.Core
HUKS_TAG_ITERATIONHuksTagType.HUKS_TAG_TYPE_UINT |14Number of iterations for key derivation.
System capability: SystemCapability.Security.Huks.Extension
HUKS_TAG_KEY_GENERATE_TYPEHuksTagType.HUKS_TAG_TYPE_UINT |15Key generation type.
System capability: SystemCapability.Security.Huks.Core
HUKS_TAG_DERIVE_MAIN_KEY(deprecated)HuksTagType.HUKS_TAG_TYPE_BYTES |16Main key for key derivation. It is deprecated since API version 9.
System capability: SystemCapability.Security.Huks.Extension
HUKS_TAG_DERIVE_FACTOR(deprecated)HuksTagType.HUKS_TAG_TYPE_BYTES |17Factor for key derivation. It is deprecated since API version 9.
System capability: SystemCapability.Security.Huks.Extension
HUKS_TAG_DERIVE_ALG(deprecated)HuksTagType.HUKS_TAG_TYPE_UINT |18Type of the algorithm used for key derivation. It is deprecated since API version 9.
System capability: SystemCapability.Security.Huks.Extension
HUKS_TAG_AGREE_ALGHuksTagType.HUKS_TAG_TYPE_UINT |19Type of the algorithm used for key agreement.
System capability: SystemCapability.Security.Huks.Extension
HUKS_TAG_AGREE_PUBLIC_KEY_IS_KEY_ALIASHuksTagType.HUKS_TAG_TYPE_BOOL |20Public key alias used in key agreement.
System capability: SystemCapability.Security.Huks.Extension
HUKS_TAG_AGREE_PRIVATE_KEY_ALIASHuksTagType.HUKS_TAG_TYPE_BYTES |21Private key alias used in key agreement.
System capability: SystemCapability.Security.Huks.Extension
HUKS_TAG_AGREE_PUBLIC_KEYHuksTagType.HUKS_TAG_TYPE_BYTES |22Public key used in key agreement.
System capability: SystemCapability.Security.Huks.Extension
HUKS_TAG_KEY_ALIASHuksTagType.HUKS_TAG_TYPE_BYTES |23Key alias.
System capability: SystemCapability.Security.Huks.Core
HUKS_TAG_DERIVE_KEY_SIZEHuksTagType.HUKS_TAG_TYPE_UINT |24Size of the derived key.
System capability: SystemCapability.Security.Huks.Extension
HUKS_TAG_IMPORT_KEY_TYPE9+HuksTagType.HUKS_TAG_TYPE_UINT |25Type of the imported key.
System capability: SystemCapability.Security.Huks.Extension
HUKS_TAG_UNWRAP_ALGORITHM_SUITE9+HuksTagType.HUKS_TAG_TYPE_UINT |26Algorithm suite required for encrypted imports.
System capability: SystemCapability.Security.Huks.Extension
HUKS_TAG_DERIVED_AGREED_KEY_STORAGE_FLAG10+HuksTagType.HUKS_TAG_TYPE_UINT |29Storage type of the derived key or agreed key.
System capability: SystemCapability.Security.Huks.Extension
HUKS_TAG_RSA_PSS_SALT_LEN_TYPE10+HuksTagType.HUKS_TAG_TYPE_UINT |30Type of the rsa_pss_salt_length.
System capability: SystemCapability.Security.Huks.Extension
HUKS_TAG_ACTIVE_DATETIME(deprecated)HuksTagType.HUKS_TAG_TYPE_ULONG |201Parameter originally reserved for certificate management. It is deprecated because certificate management is no longer implemented in this module.
System capability: SystemCapability.Security.Huks.Extension
HUKS_TAG_ORIGINATION_EXPIRE_DATETIME(deprecated)HuksTagType.HUKS_TAG_TYPE_ULONG |202Parameter originally reserved for certificate management. It is deprecated because certificate management is no longer implemented in this module.
System capability: SystemCapability.Security.Huks.Core
HUKS_TAG_USAGE_EXPIRE_DATETIME(deprecated)HuksTagType.HUKS_TAG_TYPE_ULONG |203Parameter originally reserved for certificate management. It is deprecated because certificate management is no longer implemented in this module.
System capability: SystemCapability.Security.Huks.Core
HUKS_TAG_CREATION_DATETIME(deprecated)HuksTagType.HUKS_TAG_TYPE_ULONG |204Parameter originally reserved for certificate management. It is deprecated because certificate management is no longer implemented in this module.
System capability: SystemCapability.Security.Huks.Core
HUKS_TAG_ALL_USERSHuksTagType.HUKS_TAG_TYPE_BOOL |301Reserved.
System capability: SystemCapability.Security.Huks.Extension
HUKS_TAG_USER_IDHuksTagType.HUKS_TAG_TYPE_UINT |302ID of the user to which the key belongs.
System capability: SystemCapability.Security.Huks.Extension
HUKS_TAG_NO_AUTH_REQUIREDHuksTagType.HUKS_TAG_TYPE_BOOL |303Reserved.
System capability: SystemCapability.Security.Huks.Extension
HUKS_TAG_USER_AUTH_TYPEHuksTagType.HUKS_TAG_TYPE_UINT |304User authentication type. For details, see HuksUserAuthType. This parameter must be set together with HuksAuthAccessType. You can set a maximum of two user authentication types at a time. For example, if HuksAuthAccessType is HKS_SECURE_ACCESS_INVALID_NEW_BIO_ENROLL, you can set two of HKS_USER_AUTH_TYPE_FACE, HKS_USER_AUTH_TYPE_FINGERPRINT, and **HKS_USER_AUTH_TYPE_FACE**.
HUKS_TAG_AUTH_TIMEOUTHuksTagType.HUKS_TAG_TYPE_UINT |305Timeout period of an authentication token.
System capability: SystemCapability.Security.Huks.Extension
HUKS_TAG_AUTH_TOKENHuksTagType.HUKS_TAG_TYPE_BYTES |306Used to pass in the authentication token.
System capability: SystemCapability.Security.Huks.Extension
HUKS_TAG_KEY_AUTH_ACCESS_TYPE9+HuksTagType.HUKS_TAG_TYPE_UINT |307Access control type. For details, see HuksAuthAccessType. This parameter must be set together with HuksUserAuthType.
System capability: SystemCapability.Security.Huks.Extension
HUKS_TAG_KEY_SECURE_SIGN_TYPE9+HuksTagType.HUKS_TAG_TYPE_UINT |308Signature type of the key generated or imported.
System capability: SystemCapability.Security.Huks.Extension
HUKS_TAG_CHALLENGE_TYPE9+HuksTagType.HUKS_TAG_TYPE_UINT |309Type of the challenge generated for a key. For details, see HuksChallengeType.
System capability: SystemCapability.Security.Huks.Extension
HUKS_TAG_CHALLENGE_POS9+HuksTagType.HUKS_TAG_TYPE_UINT |310Position of the 8-byte valid value in a custom challenge. For details, see HuksChallengePosition.
System capability: SystemCapability.Security.Huks.Extension
HUKS_TAG_KEY_AUTH_PURPOSE10+HuksTagType.HUKS_TAG_TYPE_UINT |311Key authentication purpose.
System capability: SystemCapability.Security.Huks.Extension
HUKS_TAG_ATTESTATION_CHALLENGEHuksTagType.HUKS_TAG_TYPE_BYTES |501Challenge value used in the attestation.
System capability: SystemCapability.Security.Huks.Extension
HUKS_TAG_ATTESTATION_APPLICATION_IDHuksTagType.HUKS_TAG_TYPE_BYTES |502Application ID used in the attestation.
System capability: SystemCapability.Security.Huks.Extension
HUKS_TAG_ATTESTATION_ID_BRAND(deprecated)HuksTagType.HUKS_TAG_TYPE_BYTES |503Brand of the device. It is deprecated since API version 9.
System capability: SystemCapability.Security.Huks.Extension
HUKS_TAG_ATTESTATION_ID_DEVICE(deprecated)HuksTagType.HUKS_TAG_TYPE_BYTES |504ID of the device. It is deprecated since API version 9.
System capability: SystemCapability.Security.Huks.Extension
HUKS_TAG_ATTESTATION_ID_PRODUCT(deprecated)HuksTagType.HUKS_TAG_TYPE_BYTES |505Product name of the device. It is deprecated since API version 9.
System capability: SystemCapability.Security.Huks.Extension
HUKS_TAG_ATTESTATION_ID_SERIAL(deprecated)HuksTagType.HUKS_TAG_TYPE_BYTES |506SN of the device. It is deprecated since API version 9.
System capability: SystemCapability.Security.Huks.Extension
HUKS_TAG_ATTESTATION_ID_IMEI(deprecated)HuksTagType.HUKS_TAG_TYPE_BYTES |507International mobile equipment identity (IMEI) of the device. It is deprecated since API version 9.
System capability: SystemCapability.Security.Huks.Extension
HUKS_TAG_ATTESTATION_ID_MEID(deprecated)HuksTagType.HUKS_TAG_TYPE_BYTES |508Mobile equipment identity (MEID) of the device. It is deprecated since API version 9.
System capability: SystemCapability.Security.Huks.Extension
HUKS_TAG_ATTESTATION_ID_MANUFACTURER(deprecated)HuksTagType.HUKS_TAG_TYPE_BYTES |509Manufacturer of the device. It is deprecated since API version 9.
System capability: SystemCapability.Security.Huks.Extension
HUKS_TAG_ATTESTATION_ID_MODEL(deprecated)HuksTagType.HUKS_TAG_TYPE_BYTES |510Device model. It is deprecated since API version 9.
System capability: SystemCapability.Security.Huks.Extension
HUKS_TAG_ATTESTATION_ID_ALIASHuksTagType.HUKS_TAG_TYPE_BYTES |511Key alias used in the attestation.
System capability: SystemCapability.Security.Huks.Extension
HUKS_TAG_ATTESTATION_ID_SOCID(deprecated)HuksTagType.HUKS_TAG_TYPE_BYTES |512System-on-a-chip (SoCID) of the device. It is deprecated since API version 9.
System capability: SystemCapability.Security.Huks.Extension
HUKS_TAG_ATTESTATION_ID_UDID(deprecated)HuksTagType.HUKS_TAG_TYPE_BYTES |513Unique device identifier (UDID) of the device. It is deprecated since API version 9.
System capability: SystemCapability.Security.Huks.Extension
HUKS_TAG_ATTESTATION_ID_SEC_LEVEL_INFOHuksTagType.HUKS_TAG_TYPE_BYTES |514Security level used in the attestation.
System capability: SystemCapability.Security.Huks.Extension
HUKS_TAG_ATTESTATION_ID_VERSION_INFOHuksTagType.HUKS_TAG_TYPE_BYTES |515Version information used in the attestation.
System capability: SystemCapability.Security.Huks.Extension
HUKS_TAG_IS_KEY_ALIASHuksTagType.HUKS_TAG_TYPE_BOOL |1001Whether to use the alias passed in during key generation.
System capability: SystemCapability.Security.Huks.Core
HUKS_TAG_KEY_STORAGE_FLAGHuksTagType.HUKS_TAG_TYPE_UINT |1002Key storage mode.
System capability: SystemCapability.Security.Huks.Core
HUKS_TAG_IS_ALLOWED_WRAPHuksTagType.HUKS_TAG_TYPE_BOOL |1003Reserved.
System capability: SystemCapability.Security.Huks.Extension
HUKS_TAG_KEY_WRAP_TYPEHuksTagType.HUKS_TAG_TYPE_UINT |1004Reserved.
System capability: SystemCapability.Security.Huks.Extension
HUKS_TAG_KEY_AUTH_IDHuksTagType.HUKS_TAG_TYPE_BYTES |1005Reserved.
System capability: SystemCapability.Security.Huks.Extension
HUKS_TAG_KEY_ROLEHuksTagType.HUKS_TAG_TYPE_UINT |1006Reserved.
System capability: SystemCapability.Security.Huks.Extension
HUKS_TAG_KEY_FLAGHuksTagType.HUKS_TAG_TYPE_UINT |1007Flag of the key.
System capability: SystemCapability.Security.Huks.Core
HUKS_TAG_IS_ASYNCHRONIZEDHuksTagType.HUKS_TAG_TYPE_UINT |1008Reserved.
System capability: SystemCapability.Security.Huks.Extension
HUKS_TAG_SECURE_KEY_ALIAS(deprecated)HuksTagType.HUKS_TAG_TYPE_BOOL |1009Reserved filed, which is deprecated since API version 9.
System capability: SystemCapability.Security.Huks.Core
HUKS_TAG_SECURE_KEY_UUID(deprecated)HuksTagType.HUKS_TAG_TYPE_BYTES |1010Reserved filed, which is deprecated since API version 9.
System capability: SystemCapability.Security.Huks.Extension
HUKS_TAG_KEY_DOMAINHuksTagType.HUKS_TAG_TYPE_UINT |1011Reserved.
System capability: SystemCapability.Security.Huks.Core
HUKS_TAG_PROCESS_NAME(deprecated)HuksTagType.HUKS_TAG_TYPE_BYTES |10001Process name. It is deprecated since API version 9.
System capability: SystemCapability.Security.Huks.Core
HUKS_TAG_PACKAGE_NAME(deprecated)HuksTagType.HUKS_TAG_TYPE_BYTES |10002Reserved filed, which is deprecated since API version 9.
System capability: SystemCapability.Security.Huks.Extension
HUKS_TAG_ACCESS_TIME(deprecated)HuksTagType.HUKS_TAG_TYPE_UINT |10003Reserved filed, which is deprecated since API version 9.
System capability: SystemCapability.Security.Huks.Extension
HUKS_TAG_USES_TIME(deprecated)HuksTagType.HUKS_TAG_TYPE_UINT |10004Reserved filed, which is deprecated since API version 9.
System capability: SystemCapability.Security.Huks.Extension
HUKS_TAG_CRYPTO_CTX(deprecated)HuksTagType.HUKS_TAG_TYPE_ULONG |10005Reserved filed, which is deprecated since API version 9.
System capability: SystemCapability.Security.Huks.Extension
HUKS_TAG_KEYHuksTagType.HUKS_TAG_TYPE_BYTES |10006Reserved.
System capability: SystemCapability.Security.Huks.Core
HUKS_TAG_KEY_VERSION(deprecated)HuksTagType.HUKS_TAG_TYPE_UINT |10007Key version. It is deprecated since API version 9.
System capability: SystemCapability.Security.Huks.Extension
HUKS_TAG_PAYLOAD_LEN(deprecated)HuksTagType.HUKS_TAG_TYPE_UINT |10008Reserved filed, which is deprecated since API version 9.
System capability: SystemCapability.Security.Huks.Extension
HUKS_TAG_AE_TAGHuksTagType.HUKS_TAG_TYPE_BYTES |10009Used to pass in the AEAD in GCM mode.
System capability: SystemCapability.Security.Huks.Core
HUKS_TAG_IS_KEY_HANDLE(deprecated)HuksTagType.HUKS_TAG_TYPE_ULONG |10010Reserved filed, which is deprecated since API version 9.
System capability: SystemCapability.Security.Huks.Core
HUKS_TAG_OS_VERSION(deprecated)HuksTagType.HUKS_TAG_TYPE_UINT |10101OS version. It is deprecated since API version 9.
System capability: SystemCapability.Security.Huks.Core
HUKS_TAG_OS_PATCHLEVEL(deprecated)HuksTagType.HUKS_TAG_TYPE_UINT |10102OS patch level. It is deprecated since API version 9.
System capability: SystemCapability.Security.Huks.Core
HUKS_TAG_SYMMETRIC_KEY_DATAHuksTagType.HUKS_TAG_TYPE_BYTES |20001Reserved.
System capability: SystemCapability.Security.Huks.Core
HUKS_TAG_ASYMMETRIC_PUBLIC_KEY_DATAHuksTagType.HUKS_TAG_TYPE_BYTES |20002Reserved.
System capability: SystemCapability.Security.Huks.Extension
HUKS_TAG_ASYMMETRIC_PRIVATE_KEY_DATAHuksTagType.HUKS_TAG_TYPE_BYTES |20003Reserved.
System capability: SystemCapability.Security.Huks.Extension

huks.generateKey(deprecated)

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

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

NOTE

This API is deprecated since API version 9. You are advised to use huks.generateKeyItem9+.

System capability: SystemCapability.Security.Huks.Extension

Parameters

NameTypeMandatoryDescription
keyAliasstringYesAlias of the key.
optionsHuksOptionsYesTags required for generating the key.
callbackAsyncCallback<HuksResult>YesCallback invoked to return the result. If the operation is successful, HUKS_SUCCESS is returned. If the operation fails, an error code defined in HuksResult is returned.

Example

import huks from '@ohos.security.huks';
/* Generate an RSA key of 512 bits. */
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>

Generates a key. This API uses a promise to return the result.

NOTE

This API is deprecated since API version 9. You are advised to use huks.generateKeyItem9+.

System capability: SystemCapability.Security.Huks.Extension

Parameters

NameTypeMandatoryDescription
keyAliasstringYesAlias of the key.
optionsHuksOptionsYesTags required for generating the key.

Return value

TypeDescription
Promise<HuksResult>Promise used to return the result. If the operation is successful, HUKS_SUCCESS is returned. If the operation fails, an error code is returned.

Example

import huks from '@ohos.security.huks';
/* Generate an ECC key of 256 bits. */
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

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

NOTE

This API is deprecated since API version 9. You are advised to use huks.deleteKeyItem9+.

System capability: SystemCapability.Security.Huks.Extension

Parameters

NameTypeMandatoryDescription
keyAliasstringYesKey alias passed in when the key was generated.
optionsHuksOptionsYesEmpty object (leave this parameter empty).
callbackAsyncCallback<HuksResult>YesCallback invoked to return the result. If the operation is successful, HUKS_SUCCESS is returned. If the operation fails, an error code is returned.

Example

import huks from '@ohos.security.huks';
/* Set options to 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>

Deletes a key. This API uses a promise to return the result.

NOTE

This API is deprecated since API version 9. You are advised to use huks.deleteKeyItem9+.

System capability: SystemCapability.Security.Huks.Extension

Parameters

NameTypeMandatoryDescription
keyAliasstringYesKey alias passed in when the key was generated.
optionsHuksOptionsYesEmpty object (leave this parameter empty).

Return value

TypeDescription
Promise<HuksResult>Promise used to return the result. If the operation is successful, HUKS_SUCCESS is returned. If the operation fails, an error code is returned.

Example

import huks from '@ohos.security.huks';
/* Set options to 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

Imports a key in plaintext. This API uses an asynchronous callback to return the result.

NOTE

This API is deprecated since API version 9. You are advised to use huks.importKeyItem9+.

System capability: SystemCapability.Security.Huks.Extension

Parameters

NameTypeMandatoryDescription
keyAliasstringYesAlias of the key.
optionsHuksOptionsYesTags required for the import and key to import.
callbackAsyncCallback<HuksResult>YesCallback invoked to return the result. If the operation is successful, HUKS_SUCCESS is returned. If the operation fails, an error code is returned.

Example

import huks from '@ohos.security.huks';
/* Import an AES key of 256 bits. */
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>

Imports a key in plaintext. This API uses a promise to return the result.

NOTE

This API is deprecated since API version 9. You are advised to use huks.importKeyItem9+.

System capability: SystemCapability.Security.Huks.Extension

Parameters

NameTypeMandatoryDescription
keyAliasstringYesAlias of the key.
optionsHuksOptionsYesTags required for the import and key to import.

Return value

TypeDescription
Promise<HuksResult>Promise used to return the result. If the operation is successful, HUKS_SUCCESS is returned. If the operation fails, an error code is returned.

Example

import huks from '@ohos.security.huks';
/* Import an AES key of 128 bits. */
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;
};
/* Step 1 Generate a key. */
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

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

NOTE

This API is deprecated since API version 9. You are advised to use huks.exportKeyItem9+.

System capability: SystemCapability.Security.Huks.Extension

Parameters

NameTypeMandatoryDescription
keyAliasstringYesKey alias, which must be the same as the alias used when the key was generated.
optionsHuksOptionsYesEmpty object (leave this parameter empty).
callbackAsyncCallback<HuksResult>YesCallback invoked to return the result. If the operation is successful, HUKS_SUCCESS is returned and outData contains the public key exported. If the operation fails, an error code is returned.

Example

import huks from '@ohos.security.huks';
/* Set options to 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>

Exports a key. This API uses a promise to return the result.

NOTE

This API is deprecated since API version 9. You are advised to use huks.exportKeyItem9+.

System capability: SystemCapability.Security.Huks.Extension

Parameters

NameTypeMandatoryDescription
keyAliasstringYesKey alias, which must be the same as the alias used when the key was generated.
optionsHuksOptionsYesEmpty object (leave this parameter empty).

Return value

TypeDescription
Promise<HuksResult>Promise used to return the result. If the operation is successful, HUKS_SUCCESS is returned and outData contains the public key exported. If the operation fails, an error code is returned.

Example

import huks from '@ohos.security.huks';
/* Set options to 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

Obtains key properties. This API uses an asynchronous callback to return the result.

NOTE

This API is deprecated since API version 9. You are advised to use huks.getKeyItemProperties9+.

System capability: SystemCapability.Security.Huks.Extension

Parameters

NameTypeMandatoryDescription
keyAliasstringYesKey alias, which must be the same as the alias used when the key was generated.
optionsHuksOptionsYesEmpty object (leave this parameter empty).
callbackAsyncCallback<HuksResult>YesCallback invoked to return the result. If the operation is successful, errorCode is HUKS_SUCCESS; otherwise, an error code is returned.

Example

import huks from '@ohos.security.huks';
/* Set options to 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>

Obtains key properties. This API uses a promise to return the result.

NOTE

This API is deprecated since API version 9. You are advised to use huks.getKeyItemProperties9+.

System capability: SystemCapability.Security.Huks.Extension

Parameters

NameTypeMandatoryDescription
keyAliasstringYesKey alias, which must be the same as the alias used when the key was generated.
optionsHuksOptionsYesEmpty object (leave this parameter empty).

Return value

TypeDescription
Promise<HuksResult>Promise used to return the result. If the operation is successful, errorCode is HUKS_SUCCESS and properties contains the parameters required for generating the key. If the operation fails, an error code is returned.

Example

import huks from '@ohos.security.huks';
/* Set options to 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

Checks whether a key exists. This API uses an asynchronous callback to return the result.

NOTE

This API is deprecated since API version 9. You are advised to use huks.isKeyItemExist9+.

System capability: SystemCapability.Security.Huks.Extension

Parameters

NameTypeMandatoryDescription
keyAliasstringYesAlias of the key to check.
optionsHuksOptionsYesEmpty object (leave this parameter empty).
callbackAsyncCallback<boolean>YesCallback invoked to return the result. The value true means the key exists; the value false means the opposite.

Example

import huks from '@ohos.security.huks';
/* Set options to 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>

Checks whether a key exists. This API uses a promise to return the result.

NOTE

This API is deprecated since API version 9. You are advised to use huks.isKeyItemExist9+.

System capability: SystemCapability.Security.Huks.Extension

Parameters

NameTypeMandatoryDescription
keyAliasstringYesAlias of the key to check.
optionsHuksOptionsYesEmpty object (leave this parameter empty).

Return value

TypeDescription
Promise<boolean>Promise used to return the result. The value true means the key exists; the value false means the opposite.

Example

import huks from '@ohos.security.huks';
/* Set options to 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

Initializes the data for a key operation. This API uses an asynchronous callback to return the result. huks.init, huks.update, and huks.finish must be used together.

NOTE

This API is deprecated since API version 9. You are advised to use huks.initSession9+.

System capability: SystemCapability.Security.Huks.Extension

Parameters

NameTypeMandatoryDescription
keyAliasstringYesAlias of the target key.
optionsHuksOptionsYesParameter set used for the init operation.
callbackAsyncCallback<HuksHandle>YesCallback invoked to return a session handle for subsequent operations.

huks.init(deprecated)

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

Initializes the data for a key operation. This API uses a promise to return the result. huks.init, huks.update, and huks.finish must be used together.

NOTE

This API is deprecated since API version 9. You are advised to use huks.initSession9+.

System capability: SystemCapability.Security.Huks.Extension

Parameters

NameTypeMandatoryDescription
keyAliasstringYesAlias of the target key.
optionsHuksOptionsYesParameter set used for the init operation.

Return value

TypeDescription
Promise<HuksHandle>Promise used to return a session handle for subsequent operations.

huks.update(deprecated)

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

Updates the key operation by segment. This API uses an asynchronous callback to return the result. huks.init, huks.update, and huks.finish must be used together.

NOTE

This API is deprecated since API version 9. You are advised to use huks.updateSession9+.

System capability: SystemCapability.Security.Huks.Extension

Parameters

NameTypeMandatoryDescription
handlenumberYesHandle for the update operation.
tokenUint8ArrayNoToken of the update operation.
optionsHuksOptionsYesParameter set used for the update operation.
callbackAsyncCallback<HuksResult>YesCallback invoked to return the update operation result.

huks.update(deprecated)

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

Updates the key operation by segment. This API uses a promise to return the result. huks.init, huks.update, and huks.finish must be used together.

NOTE

This API is deprecated since API version 9. You are advised to use huks.updateSession9+.

System capability: SystemCapability.Security.Huks.Extension

Parameters

NameTypeMandatoryDescription
handlenumberYesHandle for the update operation.
tokenUint8ArrayNoToken of the update operation.
optionsHuksOptionsYesParameter set used for the update operation.

Return value

TypeDescription
Promise<HuksResult>Promise used to return the update operation result.

huks.finish(deprecated)

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

Finishes the key operation to release resources. This API uses an asynchronous callback to return the result. huks.init, huks.update, and huks.finish must be used together.

NOTE

This API is deprecated since API version 9. You are advised to use huks.finishSession9+.

System capability: SystemCapability.Security.Huks.Extension

Parameters

NameTypeMandatoryDescription
handlenumberYesHandle for the finish operation.
optionsHuksOptionsYesParameter set used for the finish operation.
callbackAsyncCallback<HuksResult>YesCallback invoked to return the finish operation result.

huks.finish(deprecated)

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

Finishes the key operation to release resources. This API uses a promise to return the result. huks.init, huks.update, and huks.finish must be used together.

NOTE

This API is deprecated since API version 9. You are advised to use huks.finishSession9+.

System capability: SystemCapability.Security.Huks.Extension

Parameters

NameTypeMandatoryDescription
handlenumberYesHandle for the finish operation.
optionsHuksOptionsYesParameter set used for the finish operation.

Return value

TypeDescription
Promise<HuksResult>Promise used to return the result.

huks.abort(deprecated)

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

Aborts the use of the key. This API uses an asynchronous callback to return the result.

NOTE

This API is deprecated since API version 9. You are advised to use huks.abortSession9+.

System capability: SystemCapability.Security.Huks.Extension

Parameters

NameTypeMandatoryDescription
handlenumberYesHandle for the abort operation.
optionsHuksOptionsYesParameter set used for the abort operation.
callbackAsyncCallback<HuksResult>YesCallback invoked to return the abort operation result.

Example

import huks from '@ohos.security.huks';
import { BusinessError } from '@ohos.base';
/* huks.init, huks.update, and huks.finish must be used together.
 * If an error occurs in any of them, huks.abort must be called to terminate the use of the key.
 *
 * The following uses the callback of an RSA 1024 key as an example.
 */
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 = "Failed to complete the key operation. 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>;

Aborts the use of the key. This API uses a promise to return the result.

NOTE

This API is deprecated since API version 9. You are advised to use huks.abortSession9+.

System capability: SystemCapability.Security.Huks.Extension

Parameters

NameTypeMandatoryDescription
handlenumberYesHandle for the abort operation.
optionsHuksOptionsYesParameter set used for the abort operation.

Return value

TypeDescription
Promise<HuksResult>Promise used to return the abort operation result.

Example

import huks from '@ohos.security.huks';
import { BusinessError } from '@ohos.base';
/* huks.init, huks.update, and huks.finish must be used together.
 * If an error occurs in any of them, huks.abort must be called to terminate the use of the key.
 *
 * The following uses the promise of an RSA 1024-bit key as an example.
 */
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 = "Failed to abort the use of the key. catch errorMessage:" + JSON.stringify(err)
    });
    console.log(resultMessage);
}

HuksHandle(deprecated)

Defines the HUKS handle structure.

System capability: SystemCapability.Security.Huks.Extension

NOTE

This API is deprecated since API version 9. You are advised to use HuksSessionHandle9+.

NameTypeMandatoryDescription
errorCodenumberYesError code.
handlenumberYesValue of the handle.
tokenUint8ArrayNoChallenge obtained after the init operation.

HuksResult(deprecated)

Defines the HuksResult struct.

System capability: SystemCapability.Security.Huks.Extension

NOTE

NameTypeMandatoryDescription
errorCodenumberYesError code.
outDataUint8ArrayNoOutput data.
propertiesArray<HuksParam>NoProperty information.
certChainsArray<string>NoCertificate chain information.

HuksErrorCode(deprecated)

Enumerates the error codes.

System capability: SystemCapability.Security.Huks.Extension

NOTE

This API is deprecated since API version 9. You are advised to use HuksExceptionErrCode9+.

NameValueDescription
HUKS_SUCCESS0Success.
HUKS_FAILURE-1Failure.
HUKS_ERROR_BAD_STATE-2Incorrect state.
HUKS_ERROR_INVALID_ARGUMENT-3Invalid argument.
HUKS_ERROR_NOT_SUPPORTED-4Not supported.
HUKS_ERROR_NO_PERMISSION-5No permission.
HUKS_ERROR_INSUFFICIENT_DATA-6Insufficient data.
HUKS_ERROR_BUFFER_TOO_SMALL-7Insufficient buffer.
HUKS_ERROR_INSUFFICIENT_MEMORY-8Insufficient memory.
HUKS_ERROR_COMMUNICATION_FAILURE-9Communication failure.
HUKS_ERROR_STORAGE_FAILURE-10Insufficient storage space.
HUKS_ERROR_HARDWARE_FAILURE-11Hardware fault.
HUKS_ERROR_ALREADY_EXISTS-12The object already exists.
HUKS_ERROR_NOT_EXIST-13The object does not exist.
HUKS_ERROR_NULL_POINTER-14Null pointer.
HUKS_ERROR_FILE_SIZE_FAIL-15Incorrect file size.
HUKS_ERROR_READ_FILE_FAIL-16Failed to read the file.
HUKS_ERROR_INVALID_PUBLIC_KEY-17Invalid public key.
HUKS_ERROR_INVALID_PRIVATE_KEY-18Invalid private key.
HUKS_ERROR_INVALID_KEY_INFO-19Invalid key information.
HUKS_ERROR_HASH_NOT_EQUAL-20The hash values are not equal.
HUKS_ERROR_MALLOC_FAIL-21MALLOC failed.
HUKS_ERROR_WRITE_FILE_FAIL-22Failed to write the file.
HUKS_ERROR_REMOVE_FILE_FAIL-23Failed to delete the file.
HUKS_ERROR_OPEN_FILE_FAIL-24Failed to open the file.
HUKS_ERROR_CLOSE_FILE_FAIL-25Failed to close the file.
HUKS_ERROR_MAKE_DIR_FAIL-26Failed to create the directory.
HUKS_ERROR_INVALID_KEY_FILE-27Invalid key file.
HUKS_ERROR_IPC_MSG_FAIL-28Incorrect IPC information.
HUKS_ERROR_REQUEST_OVERFLOWS-29Request overflows.
HUKS_ERROR_PARAM_NOT_EXIST-30The parameter does not exist.
HUKS_ERROR_CRYPTO_ENGINE_ERROR-31CRYPTO ENGINE error.
HUKS_ERROR_COMMUNICATION_TIMEOUT-32Communication timed out.
HUKS_ERROR_IPC_INIT_FAIL-33IPC initialization failed.
HUKS_ERROR_IPC_DLOPEN_FAIL-34IPC DLOPEN failed.
HUKS_ERROR_EFUSE_READ_FAIL-35Failed to read eFUSE.
HUKS_ERROR_NEW_ROOT_KEY_MATERIAL_EXIST-36New root key material exists.
HUKS_ERROR_UPDATE_ROOT_KEY_MATERIAL_FAIL-37Failed to update the root key material.
HUKS_ERROR_VERIFICATION_FAILED-38Failed to verify the certificate chain.
HUKS_ERROR_CHECK_GET_ALG_FAIL-100Failed to obtain the ALG.
HUKS_ERROR_CHECK_GET_KEY_SIZE_FAIL-101Failed to obtain the key size.
HUKS_ERROR_CHECK_GET_PADDING_FAIL-102Failed to obtain the padding algorithm.
HUKS_ERROR_CHECK_GET_PURPOSE_FAIL-103Failed to obtain the key purpose.
HUKS_ERROR_CHECK_GET_DIGEST_FAIL-104Failed to obtain the digest algorithm.
HUKS_ERROR_CHECK_GET_MODE_FAIL-105Failed to obtain the cipher mode.
HUKS_ERROR_CHECK_GET_NONCE_FAIL-106Failed to obtain the nonce.
HUKS_ERROR_CHECK_GET_AAD_FAIL-107Failed to obtain the AAD.
HUKS_ERROR_CHECK_GET_IV_FAIL-108Failed to obtain the initialization vector (IV).
HUKS_ERROR_CHECK_GET_AE_TAG_FAIL-109Failed to obtain the AE flag.
HUKS_ERROR_CHECK_GET_SALT_FAIL-110Failed to obtain the salt value.
HUKS_ERROR_CHECK_GET_ITERATION_FAIL-111Failed to obtain the number of iterations.
HUKS_ERROR_INVALID_ALGORITHM-112Invalid algorithm.
HUKS_ERROR_INVALID_KEY_SIZE-113Invalid key size.
HUKS_ERROR_INVALID_PADDING-114Invalid padding algorithm.
HUKS_ERROR_INVALID_PURPOSE-115Invalid key purpose.
HUKS_ERROR_INVALID_MODE-116Invalid cipher mode.
HUKS_ERROR_INVALID_DIGEST-117Invalid digest algorithm.
HUKS_ERROR_INVALID_SIGNATURE_SIZE-118Invalid signature size.
HUKS_ERROR_INVALID_IV-119Invalid IV.
HUKS_ERROR_INVALID_AAD-120Invalid AAD.
HUKS_ERROR_INVALID_NONCE-121Invalid nonce.
HUKS_ERROR_INVALID_AE_TAG-122Invalid AE tag.
HUKS_ERROR_INVALID_SALT-123Invalid salt value.
HUKS_ERROR_INVALID_ITERATION-124Invalid iteration count.
HUKS_ERROR_INVALID_OPERATION-125Invalid operation.
HUKS_ERROR_INTERNAL_ERROR-999Internal error.
HUKS_ERROR_UNKNOWN_ERROR-1000Unknown error.

你可能感兴趣的鸿蒙文章

harmony 鸿蒙APIs

harmony 鸿蒙System Common Events (To Be Deprecated Soon)

harmony 鸿蒙System Common Events

harmony 鸿蒙API Reference Document Description

harmony 鸿蒙Enterprise Device Management Overview (for System Applications Only)

harmony 鸿蒙BundleStatusCallback

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

harmony 鸿蒙@ohos.distributedBundle (Distributed Bundle Management)

harmony 鸿蒙@ohos.bundle (Bundle)

harmony 鸿蒙@ohos.enterprise.EnterpriseAdminExtensionAbility (EnterpriseAdminExtensionAbility)

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