未验证 提交 f0c60f05 编写于 作者: O openharmony_ci 提交者: Gitee

!12354 [翻译完成】#I617VY

Merge pull request !12354 from Annie_wang/PR11444
# HUKS Development # HUKS Development
## When to Use OpenHarmony Universal KeyStore (HUKS) provides KeyStore (KS) capabilities for applications, including key management and key cryptography operations. HUKS also provides APIs for applications to import or generate keys.
OpenHarmony Universal KeyStore (HUKS) provides KeyStore (KS) capabilities for applications, including key management and key cryptography operations. HUKS also provides APIs for applications to import or generate keys. > **NOTE**<br>
>
## JS-based Development > This document is based on API version 9 and applies only to ArkTS development.
1. Import the HUKS module. ### **Prerequisites**
```js The HUKS module must have been imported.
import huks from '@ohos.security.huks'
``` ```ts
import huks from '@ohos.security.huks'
2. Call **generateKey()** to generate a key. ```
**keyAlias** indicates the alias of the key generated. **options** indicates the parameters used for generating the key. Set **options** based on the algorithms to be used. ### Generating a Key
The return value indicates whether the key is successfully generated. Generate a key for an application by specifying the alias and key parameters.
```js > **NOTE**
var alias = 'testAlias'; >
var properties = new Array(); > 1. When a key is used if the parameters passed in does not comply with the parameters passed in during the key generation, the parameter verification will fail.
properties[0] = { >
tag: huks.HuksTag.HUKS_TAG_ALGORITHM, > 2. If an optional parameter required by the algorithm is not passed in during the key generation process, it must be passed in when the key is used.
value: huks.HuksKeyAlg.HUKS_ALG_ECC
}; **Supported Key Types**
properties[1] = {
tag: huks.HuksTag.HUKS_TAG_KEY_SIZE, The following lists the mandatory parameters for key generation, including the key algorithm, key length, and key usage.
value: huks.HuksKeySize.HUKS_ECC_KEY_SIZE_224
}; | HUKS_ALG_ALGORITHM | HUKS_ALG_KEY_SIZE | HUKS_ALG_PURPOSE |
properties[2] = { | ------------------ | :----------------------------------------------------------- | ------------------------------------------------------------ |
tag: huks.HuksTag.HUKS_TAG_PURPOSE, | HUKS_ALG_RSA | HUKS_RSA_KEY_SIZE_512 HUKS_RSA_KEY_SIZE_768 HUKS_RSA_KEY_SIZE_1024 HUKS_RSA_KEY_SIZE_2048 HUKS_RSA_KEY_SIZE_3072 HUKS_RSA_KEY_SIZE_4096 | HUKS_KEY_PURPOSE_ENCRYPT HUKS_KEY_PURPOSE_DECRYPT HUKS_KEY_PURPOSE_SIGN HUKS_KEY_PURPOSE_VERIFY |
value: huks.HuksKeyPurpose.HUKS_KEY_PURPOSE_AGREE | HUKS_ALG_AES | HUKS_AES_KEY_SIZE_128 HUKS_AES_KEY_SIZE_192 HUKS_AES_KEY_SIZE_256 | HUKS_KEY_PURPOSE_ENCRYPT HUKS_KEY_PURPOSE_DECRYPT HUKS_KEY_PURPOSE_DERIVE |
}; | HUKS_ALG_ECC | HUKS_ECC_KEY_SIZE_224, HUKS_ECC_KEY_SIZE_256, HUKS_ECC_KEY_SIZE_384, HUKS_ECC_KEY_SIZE_521| HUKS_KEY_PURPOSE_SIGN HUKS_KEY_PURPOSE_VERIFY |
properties[3] = { | HUKS_ALG_X25519 | HUKS_CURVE25519_KEY_SIZE_256 | HUKS_KEY_PURPOSE_AGREE |
tag: huks.HuksTag.HUKS_TAG_DIGEST, | HUKS_ALG_ED25519 | HUKS_CURVE25519_KEY_SIZE_256 | HUKS_KEY_PURPOSE_SIGN HUKS_KEY_PURPOSE_VERIFY |
value: huks.HuksKeyDigest.HUKS_DIGEST_NONE | HUKS_ALG_DSA | HUKS_RSA_KEY_SIZE_1024 | HUKS_KEY_PURPOSE_SIGN HUKS_KEY_PURPOSE_VERIFY |
}; | HUKS_ALG_DH | HUKS_DH_KEY_SIZE_2048, HUKS_DH_KEY_SIZE_3072, HUKS_DH_KEY_SIZE_4096| HUKS_KEY_PURPOSE_AGREE |
var options = { | HUKS_ALG_ECDH | HUKS_ECC_KEY_SIZE_224, HUKS_ECC_KEY_SIZE_256, HUKS_ECC_KEY_SIZE_384, HUKS_ECC_KEY_SIZE_521| HUKS_KEY_PURPOSE_AGREE |
properties: properties | HUKS_ALG_SM2 | HUKS_SM2_KEY_SIZE_256 | HUKS_KEY_PURPOSE_SIGN HUKS_KEY_PURPOSE_VERIFY |
} | HUKS_ALG_SM4 | HUKS_SM4_KEY_SIZE_128 | HUKS_KEY_PURPOSE_ENCRYPT or HUKS_KEY_PURPOSE_DECRYPT |
var resultA = huks.generateKey(alias, options);
``` Before you get started, understand the following variables:
3. Call **Init()** to initialize data for a key operation. | Parameter | Type | Mandatory| Description |
| ---------------- | ----------- | ---- | ------------------------------------------------------------ |
**Alias** indicates the alias of the key, and **options** indicates the parameters used for initialization. Set **options** based on the algorithms to be used. | genKeyAlias | string | Yes | Alias of the key generated. |
| genKeyProperties | HuksOptions | Yes | Tags required for generating the key. The key algorithm, key usage, and key length are mandatory.|
The return value indicates whether the **Init** operation is successful.
For details about the APIs, see [HUKS](../reference/apis/js-apis-huks.md).
```js
var alias = 'test001' ```ts
var properties = new Array(); /* Generate an ECC key of 256 bits. */
properties[0] = { let keyAlias = 'keyAlias';
tag: huks.HuksTag.HUKS_TAG_ALGORITHM, let properties = new Array();
value: huks.HuksKeyAlg.HUKS_ALG_DH // Mandatory parameter.
}; properties[0] = {
properties[1] = { tag: huks.HuksTag.HUKS_TAG_ALGORITHM,
tag: huks.HuksTag.HUKS_TAG_PURPOSE, value: huks.HuksKeyAlg.HUKS_ALG_ECC
value: huks.HuksKeyPurpose.HUKS_KEY_PURPOSE_AGREE };
}; // Mandatory parameter.
properties[2] = { properties[1] = {
tag: huks.HuksTag.HUKS_TAG_KEY_SIZE, tag: huks.HuksTag.HUKS_TAG_KEY_SIZE,
value: huks.HuksKeySize.HUKS_DH_KEY_SIZE_4096 value: huks.HuksKeySize.HUKS_ECC_KEY_SIZE_256
}; };
var options = { // Mandatory parameter.
properties: properties properties[2] = {
}; tag: huks.HuksTag.HUKS_TAG_PURPOSE,
huks.init(alias, options, function(err, data) { value:
if (err.code !== 0) { huks.HuksKeyPurpose.HUKS_KEY_PURPOSE_SIGN |
console.log("test init err information: " + JSON.stringify(err)); huks.HuksKeyPurpose.HUKS_KEY_PURPOSE_VERIFY
} else { };
console.log(`test init data: ${JSON.stringify(data)}`); // Optional parameter.
} properties[3] = {
}) tag: huks.HuksTag.HUKS_TAG_DIGEST,
``` value: huks.HuksKeyDigest.HUKS_DIGEST_SHA256
};
4. Call **update()** to add data for the key operation by segment. let options = {
properties: properties
**handle** indicates the session ID for the **update** operation. **options** indicates the parameters used for the **update** operation. Set **options** based on the algorithms to be used. };
try {
The return value indicates whether the **update** operation is successful. huks.generateKeyItem(keyAlias, options, function (error, data) {
if (error) {
```js console.error(`callback: generateKeyItem failed, code: ${error.code}, msg: ${error.message}`);
var properties = new Array(); } else {
properties[0] = { console.info(`callback: generateKeyItem key success`);
tag: huks.HuksTag.HUKS_TAG_ALGORITHM, }
value: huks.HuksKeyAlg.HUKS_ALG_DH });
}; } catch (error) {
properties[1] = { console.error(`callback: generateKeyItem input arg invalid, code: ${error.code}, msg: ${error.message}`);
tag: huks.HuksTag.HUKS_TAG_PURPOSE, }
value: huks.HuksKeyPurpose.HUKS_KEY_PURPOSE_AGREE ```
};
properties[2] = {
tag: huks.HuksTag.HUKS_TAG_KEY_SIZE,
value: huks.HuksKeySize.HUKS_DH_KEY_SIZE_4096
};
var options = {
properties: properties
};
var result = huks.update(handle, options)
```
5. Call **finish()** to complete the operation.
**handle** indicates the session ID of the **finish** operation. **options** indicates the parameters used for this operation. Set **options** based on the algorithms to be used.
The return value indicates whether the **finish** operation is successful.
```js
var properties = new Array();
properties[0] = {
tag: huks.HuksTag.HUKS_TAG_ALGORITHM,
value: huks.HuksKeyAlg.HUKS_ALG_DH
};
properties[1] = {
tag: huks.HuksTag.HUKS_TAG_PURPOSE,
value: huks.HuksKeyPurpose.HUKS_KEY_PURPOSE_AGREE
};
properties[2] = {
tag: huks.HuksTag.HUKS_TAG_KEY_SIZE,
value: huks.HuksKeySize.HUKS_DH_KEY_SIZE_4096
};
var options = {
properties: properties
};
var result = huks.finish(handle, options)
```
## TS-based Development
### Key Import and Export ### Key Import and Export
The **HUKS** module allows an application to export the public key of its own asymmetric keys (public/private key pairs) based on the key alias. The **HUKS** module allows the public key of its own asymmetric key (public and private key pair) to be exported based on the key alias.
The **HUKS** module also supports import of external keys. Except the public keys of asymmetric keys, the keys imported into the HUKS cannot be exported in their lifecycle. If the alias of the key to be imported already exists in HUKS, the newly imported key will overwrite the existing one. The **HUKS** module also supports import of external keys. Except the public keys of asymmetric keys, the keys imported into the HUKS cannot be exported in their lifecycle. If the alias of the key to be imported already exists in HUKS, the newly imported key will overwrite the existing one.
...@@ -142,11 +106,11 @@ The development procedure is as follows: ...@@ -142,11 +106,11 @@ The development procedure is as follows:
2. Export the key. 2. Export the key.
3. Import the key. 3. Import the key.
**Supported types of keys to import** **Supported Types of Keys to Import**
AES128, AES192, AES256, RSA512, RSA768, RSA1024, RSA2048, RSA3072, RSA4096, HmacSHA1, HmacSHA224, HmacSHA256, HmacSHA384, HmacSHA512, ECC224, ECC256, ECC384, ECC521, Curve25519, DSA, SM2, SM3, SM4 AES128, AES192, AES256, RSA512, RSA768, RSA1024, RSA2048, RSA3072, RSA4096, HmacSHA1, HmacSHA224, HmacSHA256, HmacSHA384, HmacSHA512, ECC224, ECC256, ECC384, ECC521, Curve25519, DSA, SM2, SM3, SM4
**Supported types of keys to export** **Supported Types of Keys to Export**
RSA512, RSA768, RSA1024, RSA2048, RSA3072, RSA4096, ECC224, ECC256, ECC384, ECC521, Curve25519, DSA, SM2 RSA512, RSA768, RSA1024, RSA2048, RSA3072, RSA4096, ECC224, ECC256, ECC384, ECC521, Curve25519, DSA, SM2
...@@ -156,125 +120,662 @@ RSA512, RSA768, RSA1024, RSA2048, RSA3072, RSA4096, ECC224, ECC256, ECC384, ECC5 ...@@ -156,125 +120,662 @@ RSA512, RSA768, RSA1024, RSA2048, RSA3072, RSA4096, ECC224, ECC256, ECC384, ECC5
Before you get started, understand the following variables: Before you get started, understand the following variables:
| Parameter | Type | Mandatory| Description | | Parameter | Type | Mandatory| Description |
| ----------------- | ----------- | ---- | ------------------------ | | -------------- | ----------- | ---- | ------------------------ |
| srcKeyAlias | string | Yes | Alias of the key generated. | | exportKeyAlias | string | Yes | Alias of the key to generate. |
| srcKeyAliasSecond | string | Yes | Alias of the key imported. | | importKeyAlias | string | Yes | Alias of the key to import. |
| huksOptions | HuksOptions | Yes | Tags required for generating the key.| | huksOptions | HuksOptions | Yes | Tags required for generating the key.|
| encryptOptions | HuksOptions | Yes | Tags required for importing the key.| | encryptOptions | HuksOptions | Yes | Tags required for importing the key.|
For details about the APIs, see [HUKS](../reference/apis/js-apis-huks.md). For details about the APIs, see [HUKS](../reference/apis/js-apis-huks.md).
**Example** **Example**
```ts ```ts
/* Generate an RSA512 key. */ /* Export an RSA512 key and import DH2048, RSA512, x25519, and ECC256 keys.*/
var srcKeyAlias = 'hukRsaKeyAlias'; import huks from '@ohos.security.huks';
var srcKeyAliasSecond = 'huksRsaKeyAliasSecond';
var exportKey; function StringToUint8Array(str) {
let arr = [];
for (let i = 0, j = str.length; i < j; ++i) {
arr.push(str.charCodeAt(i));
}
return new Uint8Array(arr);
}
function Uint8ArrayToString(fileData) {
let dataString = '';
for (let i = 0; i < fileData.length; i++) {
dataString += String.fromCharCode(fileData[i]);
}
return dataString;
}
function Uint32ToUint8(value) {
let arr = new Uint8Array(4 * value.length);
for (let i = 0, j = value.length; i < j; i++) {
arr[i * 4+3] = (value[i] >> 24) & 0xFF;
arr[i * 4+2] = (value[i] >> 16) & 0xFF;
arr[i * 4+1] = (value[i] >> 8) & 0xFF;
arr[i*4] = (value[i]) & 0xFF;
}
return arr;
}
async function publicGenKeyFunc(keyAlias: string, huksOptions: huks.HuksOptions) {
console.info(`enter callback generateKeyItem`);
try {
await generateKeyItem(keyAlias, huksOptions)
.then((data) => {
console.info(`callback: generateKeyItem success, data = ${JSON.stringify(data)}`);
})
.catch(error => {
console.error(`callback: generateKeyItem failed, code: ${error.code}, msg: ${error.message}`);
});
} catch (error) {
console.error(`callback: generateKeyItem input arg invalid, code: ${error.code}, msg: ${error.message}`);
}
}
function generateKeyItem(keyAlias: string, huksOptions: huks.HuksOptions) {
return new Promise((resolve, reject) => {
try {
huks.generateKeyItem(keyAlias, huksOptions, function (error, data) {
if (error) {
reject(error);
} else {
resolve(data);
}
});
} catch (error) {
throw (error);
}
});
}
async function publicExportKeyFunc(keyAlias: string, huksOptions: huks.HuksOptions) {
console.info(`enter callback export`);
try {
await exportKeyItem(keyAlias, huksOptions)
.then((data) => {
console.info(`callback: exportKeyItem success, data = ${JSON.stringify(data)}`);
})
.catch(error => {
console.error(`callback: exportKeyItem failed, code: ${error.code}, msg: ${error.message}`);
});
} catch (error) {
console.error(`callback: exportKeyItem input arg invalid, code: ${error.code}, msg: ${error.message}`);
}
}
function exportKeyItem(keyAlias: string, huksOptions: huks.HuksOptions): Promise<huks.HuksReturnResult> {
return new Promise((resolve, reject) => {
try {
huks.exportKeyItem(keyAlias, huksOptions, function (error, data) {
if (error) {
reject(error);
} else {
resolve(data);
}
});
} catch (error) {
throw (error);
}
});
}
async function publicImportKeyFunc(keyAlias: string, huksOptions: huks.HuksOptions) {
console.info(`enter promise importKeyItem`);
try {
await importKeyItem(keyAlias, huksOptions)
.then((data) => {
console.info(`callback: importKeyItem success, data = ${JSON.stringify(data)}`);
})
.catch(error => {
console.error(`callback: importKeyItem failed, code: ${error.code}, msg: ${error.message}`);
});
} catch (error) {
console.error(`callback: importKeyItem input arg invalid, code: ${error.code}, msg: ${error.message}`);
}
}
function importKeyItem(keyAlias: string, huksOptions: huks.HuksOptions) {
return new Promise((resolve, reject) => {
try {
huks.importKeyItem(keyAlias, huksOptions, function (error, data) {
if (error) {
reject(error);
} else {
resolve(data);
}
});
} catch (error) {
throw (error);
}
});
}
async function publicDeleteKeyFunc(keyAlias: string, huksOptions: huks.HuksOptions) {
console.info(`enter callback deleteKeyItem`);
try {
await deleteKeyItem(keyAlias, huksOptions)
.then((data) => {
console.info(`callback: deleteKeyItem key success, data = ${JSON.stringify(data)}`);
})
.catch(error => {
console.error(`callback: deleteKeyItem failed, code: ${error.code}, msg: ${error.message}`);
});
} catch (error) {
console.error(`callback: deleteKeyItem input arg invalid, code: ${error.code}, msg: ${error.message}`);
}
}
function deleteKeyItem(keyAlias: string, huksOptions: huks.HuksOptions) {
return new Promise((resolve, reject) => {
try {
huks.deleteKeyItem(keyAlias, huksOptions, function (error, data) {
if (error) {
reject(error);
} else {
resolve(data);
}
});
} catch (error) {
throw (error);
}
});
}
async function testImportExport() { // Export the RSA key.
async function testExportRsa() {
let exportKeyAlias = 'export_rsa_key';
/* Configure the parameters for generating the key. */ /* Configure the parameters for generating the key. */
var properties = new Array(); let exportProperties = new Array();
properties[0] = { exportProperties[0] = {
tag: huks.HuksTag.HUKS_TAG_ALGORITHM, tag: huks.HuksTag.HUKS_TAG_ALGORITHM,
value: huks.HuksKeyAlg.HUKS_ALG_RSA, value: huks.HuksKeyAlg.HUKS_ALG_RSA
} }
properties[1] = { exportProperties[1] = {
tag: huks.HuksTag.HUKS_TAG_PURPOSE, tag: huks.HuksTag.HUKS_TAG_PURPOSE,
value: value:
huks.HuksKeyPurpose.HUKS_KEY_PURPOSE_ENCRYPT | huks.HuksKeyPurpose.HUKS_KEY_PURPOSE_ENCRYPT |
huks.HuksKeyPurpose.HUKS_KEY_PURPOSE_DECRYPT, huks.HuksKeyPurpose.HUKS_KEY_PURPOSE_DECRYPT
} }
properties[2] = { exportProperties[2] = {
tag: huks.HuksTag.HUKS_TAG_KEY_SIZE, tag: huks.HuksTag.HUKS_TAG_KEY_SIZE,
value: huks.HuksKeySize.HUKS_RSA_KEY_SIZE_512, value: huks.HuksKeySize.HUKS_RSA_KEY_SIZE_512
} }
properties[3] = { exportProperties[3] = {
tag: huks.HuksTag.HUKS_TAG_BLOCK_MODE, tag: huks.HuksTag.HUKS_TAG_BLOCK_MODE,
value: huks.HuksCipherMode.HUKS_MODE_ECB, value: huks.HuksCipherMode.HUKS_MODE_ECB
} }
properties[4] = { exportProperties[4] = {
tag: huks.HuksTag.HUKS_TAG_PADDING, tag: huks.HuksTag.HUKS_TAG_PADDING,
value: huks.HuksKeyPadding.HUKS_PADDING_PKCS1_V1_5, value: huks.HuksKeyPadding.HUKS_PADDING_PKCS1_V1_5
} }
properties[5] = { exportProperties[5] = {
tag: huks.HuksTag.HUKS_TAG_DIGEST, tag: huks.HuksTag.HUKS_TAG_DIGEST,
value: huks.HuksKeyDigest.HUKS_DIGEST_SHA256, value: huks.HuksKeyDigest.HUKS_DIGEST_SHA256
} }
var huksOptions = { let huksOptions = {
properties: properties, properties: exportProperties,
inData: new Uint8Array(new Array()) inData: new Uint8Array(new Array())
} }
/* Generate a key. */ /* Generate a key. */
await huks.generateKey(srcKeyAlias, huksOptions).then((data) => { await publicGenKeyFunc(exportKeyAlias, huksOptions);
console.info(`test generateKey data: ${JSON.stringify(data)}`);
}).catch((err) => {
console.info('test generateKey err information: ' + JSON.stringify(err));
});
/* Export the key. */ /* Export the key. */
await huks.exportKey(srcKeyAlias, huksOptions).then((data) => { await publicExportKeyFunc(exportKeyAlias, huksOptions);
console.info(`test ExportKey data: ${JSON.stringify(data)}`); await publicDeleteKeyFunc(exportKeyAlias, huksOptions);
exportKey = data.outData; }
}).catch((err) => {
console.info('test ImportKey err information: ' + JSON.stringify(err));
});
/* Configure parameters for importing the key. */ // DH key
var propertiesEncrypt = new Array(); let g_dhPubData = new Uint8Array([
propertiesEncrypt[0] = { 0x8a, 0xbf, 0x16, 0x67, 0x1b, 0x92, 0x4b, 0xf2, 0xe0, 0x02, 0xc5, 0x1f, 0x84, 0x00, 0xf8, 0x93,
0x0f, 0x74, 0xe7, 0x0f, 0xba, 0x78, 0x30, 0xa8, 0x2d, 0x92, 0xef, 0x9b, 0x80, 0xeb, 0x76, 0xea,
0x26, 0x74, 0x72, 0x63, 0x6a, 0x27, 0xc3, 0x8f, 0xcf, 0xbe, 0x82, 0xa2, 0x8b, 0xdc, 0x65, 0x58,
0xe3, 0xff, 0x29, 0x97, 0xad, 0xb3, 0x4a, 0x2c, 0x50, 0x08, 0xb5, 0x68, 0xe1, 0x90, 0x5a, 0xdc,
0x48, 0xb3, 0x6b, 0x7a, 0xce, 0x2e, 0x81, 0x3d, 0x38, 0x35, 0x59, 0xdc, 0x39, 0x8a, 0x97, 0xfe,
0x20, 0x86, 0x20, 0xdb, 0x55, 0x38, 0x23, 0xca, 0xb5, 0x5b, 0x61, 0x00, 0xdc, 0x45, 0xe2, 0xa1,
0xf4, 0x1e, 0x7b, 0x01, 0x7a, 0x84, 0x36, 0xa4, 0xa8, 0x1c, 0x0d, 0x3d, 0xde, 0x57, 0x66, 0x73,
0x4e, 0xaf, 0xee, 0xb0, 0xb0, 0x69, 0x0c, 0x13, 0xba, 0x76, 0xff, 0x2e, 0xb6, 0x16, 0xf9, 0xfc,
0xd6, 0x09, 0x5b, 0xc7, 0x37, 0x65, 0x84, 0xd5, 0x82, 0x8a, 0xd7, 0x5b, 0x57, 0xe3, 0x0e, 0x89,
0xbe, 0x05, 0x05, 0x55, 0x2e, 0x9f, 0x94, 0x8a, 0x53, 0xdc, 0xb7, 0x00, 0xb2, 0x6a, 0x7b, 0x8e,
0xdf, 0x6e, 0xa4, 0x6d, 0x13, 0xb6, 0xbc, 0xaa, 0x8e, 0x44, 0x11, 0x50, 0x32, 0x91, 0x56, 0xa2,
0x22, 0x3f, 0x2f, 0x08, 0xbb, 0x4d, 0xbb, 0x69, 0xe6, 0xb1, 0xc2, 0x70, 0x79, 0x15, 0x54, 0xad,
0x4a, 0x29, 0xef, 0xa9, 0x3e, 0x64, 0x8d, 0xf1, 0x90, 0xf4, 0xa7, 0x93, 0x8c, 0x7a, 0x02, 0x4d,
0x38, 0x1f, 0x58, 0xb8, 0xe4, 0x7c, 0xe1, 0x66, 0x1c, 0x72, 0x30, 0xf3, 0x4c, 0xf4, 0x24, 0xd1,
0x2d, 0xb7, 0xf1, 0x5a, 0x0f, 0xb8, 0x20, 0xc5, 0x90, 0xe5, 0xca, 0x45, 0x84, 0x5c, 0x08, 0x08,
0xbf, 0xf9, 0x69, 0x41, 0xf5, 0x49, 0x85, 0x31, 0x35, 0x14, 0x69, 0x12, 0x57, 0x9c, 0xc8, 0xb7]);
let g_dhPriData = new Uint8Array([
0x01, 0xbc, 0xa7, 0x42, 0x25, 0x79, 0xc5, 0xaf, 0x0f, 0x9c, 0xde, 0x00, 0x3b, 0x58, 0x5c, 0xd1,
0x1d, 0x7b, 0xcf, 0x66, 0xcd, 0xa9, 0x10, 0xae, 0x92, 0x2d, 0x3c, 0xb7, 0xf3]);
let g_dhX509PubData = new Uint8Array([
0x30, 0x82, 0x02, 0x29, 0x30, 0x82, 0x01, 0x1b, 0x06, 0x09, 0x2a, 0x86, 0x48, 0x86, 0xf7, 0x0d,
0x01, 0x03, 0x01, 0x30, 0x82, 0x01, 0x0c, 0x02, 0x82, 0x01, 0x01, 0x00, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xad, 0xf8, 0x54, 0x58, 0xa2, 0xbb, 0x4a, 0x9a, 0xaf, 0xdc, 0x56, 0x20,
0x27, 0x3d, 0x3c, 0xf1, 0xd8, 0xb9, 0xc5, 0x83, 0xce, 0x2d, 0x36, 0x95, 0xa9, 0xe1, 0x36, 0x41,
0x14, 0x64, 0x33, 0xfb, 0xcc, 0x93, 0x9d, 0xce, 0x24, 0x9b, 0x3e, 0xf9, 0x7d, 0x2f, 0xe3, 0x63,
0x63, 0x0c, 0x75, 0xd8, 0xf6, 0x81, 0xb2, 0x02, 0xae, 0xc4, 0x61, 0x7a, 0xd3, 0xdf, 0x1e, 0xd5,
0xd5, 0xfd, 0x65, 0x61, 0x24, 0x33, 0xf5, 0x1f, 0x5f, 0x06, 0x6e, 0xd0, 0x85, 0x63, 0x65, 0x55,
0x3d, 0xed, 0x1a, 0xf3, 0xb5, 0x57, 0x13, 0x5e, 0x7f, 0x57, 0xc9, 0x35, 0x98, 0x4f, 0x0c, 0x70,
0xe0, 0xe6, 0x8b, 0x77, 0xe2, 0xa6, 0x89, 0xda, 0xf3, 0xef, 0xe8, 0x72, 0x1d, 0xf1, 0x58, 0xa1,
0x36, 0xad, 0xe7, 0x35, 0x30, 0xac, 0xca, 0x4f, 0x48, 0x3a, 0x79, 0x7a, 0xbc, 0x0a, 0xb1, 0x82,
0xb3, 0x24, 0xfb, 0x61, 0xd1, 0x08, 0xa9, 0x4b, 0xb2, 0xc8, 0xe3, 0xfb, 0xb9, 0x6a, 0xda, 0xb7,
0x60, 0xd7, 0xf4, 0x68, 0x1d, 0x4f, 0x42, 0xa3, 0xde, 0x39, 0x4d, 0xf4, 0xae, 0x56, 0xed, 0xe7,
0x63, 0x72, 0xbb, 0x19, 0x0b, 0x07, 0xa7, 0xc8, 0xee, 0x0a, 0x6d, 0x70, 0x9e, 0x02, 0xfc, 0xe1,
0xcd, 0xf7, 0xe2, 0xec, 0xc0, 0x34, 0x04, 0xcd, 0x28, 0x34, 0x2f, 0x61, 0x91, 0x72, 0xfe, 0x9c,
0xe9, 0x85, 0x83, 0xff, 0x8e, 0x4f, 0x12, 0x32, 0xee, 0xf2, 0x81, 0x83, 0xc3, 0xfe, 0x3b, 0x1b,
0x4c, 0x6f, 0xad, 0x73, 0x3b, 0xb5, 0xfc, 0xbc, 0x2e, 0xc2, 0x20, 0x05, 0xc5, 0x8e, 0xf1, 0x83,
0x7d, 0x16, 0x83, 0xb2, 0xc6, 0xf3, 0x4a, 0x26, 0xc1, 0xb2, 0xef, 0xfa, 0x88, 0x6b, 0x42, 0x38,
0x61, 0x28, 0x5c, 0x97, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0x02, 0x01, 0x02, 0x02,
0x02, 0x00, 0xe1, 0x03, 0x82, 0x01, 0x06, 0x00, 0x02, 0x82, 0x01, 0x01, 0x00, 0x8a, 0xbf, 0x16,
0x67, 0x1b, 0x92, 0x4b, 0xf2, 0xe0, 0x02, 0xc5, 0x1f, 0x84, 0x00, 0xf8, 0x93, 0x0f, 0x74, 0xe7,
0x0f, 0xba, 0x78, 0x30, 0xa8, 0x2d, 0x92, 0xef, 0x9b, 0x80, 0xeb, 0x76, 0xea, 0x26, 0x74, 0x72,
0x63, 0x6a, 0x27, 0xc3, 0x8f, 0xcf, 0xbe, 0x82, 0xa2, 0x8b, 0xdc, 0x65, 0x58, 0xe3, 0xff, 0x29,
0x97, 0xad, 0xb3, 0x4a, 0x2c, 0x50, 0x08, 0xb5, 0x68, 0xe1, 0x90, 0x5a, 0xdc, 0x48, 0xb3, 0x6b,
0x7a, 0xce, 0x2e, 0x81, 0x3d, 0x38, 0x35, 0x59, 0xdc, 0x39, 0x8a, 0x97, 0xfe, 0x20, 0x86, 0x20,
0xdb, 0x55, 0x38, 0x23, 0xca, 0xb5, 0x5b, 0x61, 0x00, 0xdc, 0x45, 0xe2, 0xa1, 0xf4, 0x1e, 0x7b,
0x01, 0x7a, 0x84, 0x36, 0xa4, 0xa8, 0x1c, 0x0d, 0x3d, 0xde, 0x57, 0x66, 0x73, 0x4e, 0xaf, 0xee,
0xb0, 0xb0, 0x69, 0x0c, 0x13, 0xba, 0x76, 0xff, 0x2e, 0xb6, 0x16, 0xf9, 0xfc, 0xd6, 0x09, 0x5b,
0xc7, 0x37, 0x65, 0x84, 0xd5, 0x82, 0x8a, 0xd7, 0x5b, 0x57, 0xe3, 0x0e, 0x89, 0xbe, 0x05, 0x05,
0x55, 0x2e, 0x9f, 0x94, 0x8a, 0x53, 0xdc, 0xb7, 0x00, 0xb2, 0x6a, 0x7b, 0x8e, 0xdf, 0x6e, 0xa4,
0x6d, 0x13, 0xb6, 0xbc, 0xaa, 0x8e, 0x44, 0x11, 0x50, 0x32, 0x91, 0x56, 0xa2, 0x22, 0x3f, 0x2f,
0x08, 0xbb, 0x4d, 0xbb, 0x69, 0xe6, 0xb1, 0xc2, 0x70, 0x79, 0x15, 0x54, 0xad, 0x4a, 0x29, 0xef,
0xa9, 0x3e, 0x64, 0x8d, 0xf1, 0x90, 0xf4, 0xa7, 0x93, 0x8c, 0x7a, 0x02, 0x4d, 0x38, 0x1f, 0x58,
0xb8, 0xe4, 0x7c, 0xe1, 0x66, 0x1c, 0x72, 0x30, 0xf3, 0x4c, 0xf4, 0x24, 0xd1, 0x2d, 0xb7, 0xf1,
0x5a, 0x0f, 0xb8, 0x20, 0xc5, 0x90, 0xe5, 0xca, 0x45, 0x84, 0x5c, 0x08, 0x08, 0xbf, 0xf9, 0x69,
0x41, 0xf5, 0x49, 0x85, 0x31, 0x35, 0x14, 0x69, 0x12, 0x57, 0x9c, 0xc8, 0xb7]);
// X25519 key
let g_x25519PubData = new Uint8Array([
0x9c, 0xf6, 0x7a, 0x8d, 0xce, 0xc2, 0x7f, 0xa7, 0xd9, 0xfd, 0xf1, 0xad, 0xac, 0xf0, 0xb3, 0x8c,
0xe8, 0x16, 0xa2, 0x65, 0xcc, 0x18, 0x55, 0x60, 0xcd, 0x2f, 0xf5, 0xe5, 0x72, 0xc9, 0x3c, 0x54]);
// X25519 public key
let g_x25519PriData = new Uint8Array([
0x20, 0xd5, 0xbb, 0x54, 0x6f, 0x1f, 0x00, 0x30, 0x4e, 0x33, 0x38, 0xb9, 0x8e, 0x6a, 0xdf, 0xad,
0x33, 0x6f, 0x51, 0x23, 0xff, 0x4d, 0x95, 0x26, 0xdc, 0xb0, 0x74, 0xb2, 0x5c, 0x7e, 0x85, 0x6c]);
// RSA key
let g_nData = new Uint8Array([
0xb6, 0xd8, 0x9b, 0x33, 0x78, 0xa2, 0x63, 0x21, 0x84, 0x47, 0xa1, 0x72, 0 x3d, 0x73, 0x10, 0xbd,
0xe9, 0x5d, 0x78, 0x44, 0x3d, 0x80, 0x18, 0x12, 0x60, 0xed, 0x29, 0x3e, 0xc7, 0x23, 0x0d, 0x3f,
0x02, 0x59, 0x28, 0xe2, 0x8f, 0x83, 0xdf, 0x37, 0x4b, 0x77, 0xce, 0x5f, 0xb6, 0xcd, 0x61, 0x72,
0xee, 0x01, 0xe2, 0x37, 0x4d, 0xfd, 0x4f, 0x39, 0xcf, 0xbd, 0xff, 0x84, 0x57, 0x44, 0xa5, 0x03]);
let g_eData = new Uint8Array([0x01, 0x00, 0x01]);
let g_dData = new Uint8Array([
0x35, 0x63, 0x89, 0xed, 0xbd, 0x8b, 0xac, 0xe6, 0x5c, 0x79, 0x8d, 0xea, 0x8d, 0x86, 0xcb, 0x9c,
0xa8, 0x47, 0x62, 0x96, 0x8a, 0x5e, 0x9c, 0xa8, 0xc1, 0x24, 0x7e, 0xa6, 0x95, 0xfe, 0xe6, 0x1e,
0xc0, 0xf3, 0x29, 0x76, 0xbb, 0x4d, 0xe4, 0xbc, 0x78, 0x64, 0xe1, 0x79, 0xcd, 0x8a, 0x45, 0xac,
0x5c, 0x88, 0xea, 0xb4, 0x10, 0xd8, 0x90, 0x65, 0x7b, 0x94, 0xe8, 0x87, 0x30, 0x2a, 0x04, 0x01]);
let g_pubData = new Uint8Array([
0x30, 0x5c, 0x30, 0x0d, 0x06, 0x09, 0x2a, 0x86, 0x48, 0x86, 0xf7, 0x0d, 0x01, 0x01, 0x01, 0x05,
0x00, 0x03, 0x4b, 0x00, 0x30, 0x48, 0x02, 0x41, 0x00, 0x9e, 0x93, 0x57, 0xc4, 0xab, 0xde, 0x30,
0xc5, 0x3f, 0x3b, 0x33, 0xa6, 0xdc, 0x4a, 0xdb, 0xbf, 0x12, 0x9e, 0x5d, 0xc4, 0xba, 0x0e, 0x15,
0x06, 0x41, 0xd8, 0x96, 0x43, 0xca, 0xc5, 0xea, 0x9f, 0xdd, 0xa0, 0x2a, 0xf1, 0x53, 0x46, 0x14,
0x36, 0x7a, 0xab, 0xbc, 0x92, 0x1b, 0x07, 0xc6, 0x9a, 0x7d, 0x0c, 0xd0, 0xa0, 0x0f, 0x31, 0xd5,
0x38, 0x84, 0x6c, 0x08, 0xcb, 0x9b, 0x10, 0xa6, 0x4d, 0x02, 0x03, 0x01, 0x00, 0x01]);
// ECC key
let g_eccXData = new Uint8Array([
0xa5, 0xb8, 0xa3, 0x78, 0x1d, 0x6d, 0x76, 0xe0, 0xb3, 0xf5, 0x6f, 0x43, 0x9d, 0xcf, 0x60, 0xf6,
0x0b, 0x3f, 0x64, 0x45, 0xa8, 0x3f, 0x1a, 0x96, 0xf1, 0xa1, 0xa4, 0x5d, 0x3e, 0x2c, 0x3f, 0x13]);
let g_eccYData = new Uint8Array([
0xd7, 0x81, 0xf7, 0x2a, 0xb5, 0x8d, 0x19, 0x3d, 0x9b, 0x96, 0xc7, 0x6a, 0x10, 0xf0, 0xaa, 0xbc,
0x91, 0x6f, 0x4d, 0xa7, 0x09, 0xb3, 0x57, 0x88, 0x19, 0x6f, 0x00, 0x4b, 0xad, 0xee, 0x34, 0x35]);
let g_eccZData = new Uint8Array([
0xfb, 0x8b, 0x9f, 0x12, 0xa0, 0x83, 0x19, 0xbe, 0x6a, 0x6f, 0x63, 0x2a, 0x7c, 0x86, 0xba, 0xca,
0x64, 0x0b, 0x88, 0x96, 0xe2, 0xfa, 0x77, 0xbc, 0x71, 0xe3, 0x0f, 0x0f, 0x9e, 0x3c, 0xe5, 0xf9]);
let g_eccPubData = new Uint8Array([
0x30, 0x59, 0x30, 0x13, 0x06, 0x07, 0x2a, 0x86, 0x48, 0xce, 0x3d, 0x02, 0x01, 0x06, 0x08, 0x2a,
0x86, 0x48, 0xce, 0x3d, 0x03, 0x01, 0x07, 0x03, 0x42, 0x00, 0x04, 0xa5, 0xb8, 0xa3, 0x78, 0x1d,
0x6d, 0x76, 0xe0, 0xb3, 0xf5, 0x6f, 0x43, 0x9d, 0xcf, 0x60, 0xf6, 0x0b, 0x3f, 0x64, 0x45, 0xa8,
0x3f, 0x1a, 0x96, 0xf1, 0xa1, 0xa4, 0x5d, 0x3e, 0x2c, 0x3f, 0x13, 0xd7, 0x81, 0xf7, 0x2a, 0xb5,
0x8d, 0x19, 0x3d, 0x9b, 0x96, 0xc7, 0x6a, 0x10, 0xf0, 0xaa, 0xbc, 0x91, 0x6f, 0x4d, 0xa7, 0x09,
0xb3, 0x57, 0x88, 0x19, 0x6f, 0x00, 0x4b, 0xad, 0xee, 0x34, 0x35]);
// Import the DH2048 key.
async function ImportDhTest(alg, keyType) {
let importKeyAlias = 'import_dh_key';
let properties = new Array();
properties[0] = {
tag: huks.HuksTag.HUKS_TAG_ALGORITHM, tag: huks.HuksTag.HUKS_TAG_ALGORITHM,
value: huks.HuksKeyAlg.HUKS_ALG_RSA, value: huks.HuksKeyAlg.HUKS_ALG_DH
} }
propertiesEncrypt[1] = { properties[1] = {
tag: huks.HuksTag.HUKS_TAG_PURPOSE,
value: huks.HuksKeyPurpose.HUKS_KEY_PURPOSE_AGREE
}
properties[2] = {
tag: huks.HuksTag.HUKS_TAG_KEY_SIZE, tag: huks.HuksTag.HUKS_TAG_KEY_SIZE,
value: huks.HuksKeySize.HUKS_RSA_KEY_SIZE_512, value: huks.HuksKeySize.HUKS_DH_KEY_SIZE_2048
} }
propertiesEncrypt[2] = { properties[3] = {
tag: huks.HuksTag.HUKS_TAG_PADDING, tag: huks.HuksTag.HUKS_TAG_IMPORT_KEY_TYPE,
value: huks.HuksKeyPadding.HUKS_PADDING_PKCS1_V1_5, value: huks.HuksImportKeyType.HUKS_KEY_TYPE_PUBLIC_KEY
} }
propertiesEncrypt[3] = { properties[4] = {
tag: huks.HuksTag.HUKS_TAG_BLOCK_MODE, tag: huks.HuksTag.HUKS_TAG_DIGEST,
value: huks.HuksCipherMode.HUKS_MODE_ECB, value: huks.HuksKeyDigest.HUKS_DIGEST_SHA256
} }
propertiesEncrypt[4] = { let huksOptions = {
properties: properties,
inData: new Uint8Array(new Array())
}
huksOptions.properties[0].value = alg;
huksOptions.properties[3].value = keyType;
// Compare the key types.
if (huksOptions.properties[3].value === huks.HuksImportKeyType.HUKS_KEY_TYPE_KEY_PAIR) {
/* Concatenate the huksOptions.inData field with a non-public key in the following format:
* keyAlg type (4 bytes) + key_dh length (4 bytes) +
* g_dhPubData length (4 bytes) + g_dhPriData length (4 bytes) +
* Reserved size (4 bytes) + g_dhPubData + g_dhPriData
*/
// Key pair
let Material = new Uint32Array([huks.HuksKeyAlg.HUKS_ALG_DH, huks.HuksKeySize.HUKS_DH_KEY_SIZE_2048, g_dhPubData.length, g_dhPriData.length, 0]);
let u8Material = Uint32ToUint8(Material);
let strMaterial = Uint8ArrayToString(u8Material);
let strXData = strMaterial.concat(Uint8ArrayToString(g_dhPubData));
let strData = strXData.concat(Uint8ArrayToString(g_dhPriData));
huksOptions.inData = StringToUint8Array(strData);
} else if (huksOptions.properties[3].value === huks.HuksImportKeyType.HUKS_KEY_TYPE_PRIVATE_KEY) {
// Private key
let Material = new Uint32Array([huks.HuksKeyAlg.HUKS_ALG_DH, huks.HuksKeySize.HUKS_DH_KEY_SIZE_2048, 0, g_dhPriData.length, 0]);
let u8Material = Uint32ToUint8(Material);
let strMaterial = Uint8ArrayToString(u8Material);
let strData = strMaterial.concat(Uint8ArrayToString(g_dhPriData));
huksOptions.inData = StringToUint8Array(strData);
} else if (huksOptions.properties[3].value === huks.HuksImportKeyType.HUKS_KEY_TYPE_PUBLIC_KEY) {
// Public key
huksOptions.inData = g_dhX509PubData;
}
await publicImportKeyFunc(importKeyAlias, huksOptions);
await publicDeleteKeyFunc(importKeyAlias, huksOptions);
}
// Import the ECC256 key.
async function ImportEccTest(alg, keyType) {
let importKeyAlias = 'import_ecc_key';
let properties = new Array();
properties[0] = {
tag: huks.HuksTag.HUKS_TAG_ALGORITHM,
value: huks.HuksKeyAlg.HUKS_ALG_ECC
}
properties[1] = {
tag: huks.HuksTag.HUKS_TAG_PURPOSE,
value: huks.HuksKeyPurpose.HUKS_KEY_PURPOSE_AGREE
}
properties[2] = {
tag: huks.HuksTag.HUKS_TAG_KEY_SIZE,
value: huks.HuksKeySize.HUKS_ECC_KEY_SIZE_256
}
properties[3] = {
tag: huks.HuksTag.HUKS_TAG_IMPORT_KEY_TYPE,
value: huks.HuksImportKeyType.HUKS_KEY_TYPE_KEY_PAIR
}
properties[4] = {
tag: huks.HuksTag.HUKS_TAG_DIGEST, tag: huks.HuksTag.HUKS_TAG_DIGEST,
value: huks.HuksKeyDigest.HUKS_DIGEST_SHA256, value: huks.HuksKeyDigest.HUKS_DIGEST_SHA256
} }
propertiesEncrypt[5] = { let huksOptions = {
properties: properties,
inData: new Uint8Array(new Array())
}
huksOptions.properties[0].value = alg;
huksOptions.properties[3].value = keyType;
// Compare the key types.
if (huksOptions.properties[3].value === huks.HuksImportKeyType.HUKS_KEY_TYPE_KEY_PAIR) {
/* Concatenate the huksOptions.inData field with a non-public key in the following format:
* keyAlg type (4 bytes) + key_ecc length (4 bytes) +
* g_eccXData length (4 bytes) + g_eccYData length (4 bytes) +
* g_eccZData length (4 bytes) + g_eccXData +
* g_eccYData + g_eccZData
*/
// Key pair
let Material = new Uint32Array([huks.HuksKeyAlg.HUKS_ALG_ECC, huks.HuksKeySize.HUKS_ECC_KEY_SIZE_256, g_eccXData.length, g_eccYData.length, g_eccZData.length]);
let u8Material = Uint32ToUint8(Material);
let strMaterial = Uint8ArrayToString(u8Material);
let strXData = strMaterial.concat(Uint8ArrayToString(g_eccXData));
let strYData = strXData.concat(Uint8ArrayToString(g_eccYData));
let strData = strYData.concat(Uint8ArrayToString(g_eccZData));
huksOptions.inData = StringToUint8Array(strData);
} else if (huksOptions.properties[3].value === huks.HuksImportKeyType.HUKS_KEY_TYPE_PRIVATE_KEY) {
// Private key
huksOptions.properties[3].value == huks.HuksImportKeyType.HUKS_KEY_TYPE_PRIVATE_KEY
let Material = new Uint32Array([huks.HuksKeyAlg.HUKS_ALG_ECC, huks.HuksKeySize.HUKS_ECC_KEY_SIZE_256, 0, 0, g_eccZData.length]);
let u8Material = Uint32ToUint8(Material);
let strMaterial = Uint8ArrayToString(u8Material);
let strData = strMaterial.concat(Uint8ArrayToString(g_eccZData));
huksOptions.inData = StringToUint8Array(strData);
} else if (huksOptions.properties[3].value === huks.HuksImportKeyType.HUKS_KEY_TYPE_PUBLIC_KEY) {
// Public key
huksOptions.inData = g_eccPubData;
}
await publicImportKeyFunc(importKeyAlias, huksOptions);
await publicDeleteKeyFunc(importKeyAlias, huksOptions);
}
// Import the RSA512 key.
async function ImportRsaTest(alg, keyType) {
let importKeyAlias = 'import_rsa_key';
let properties = new Array();
properties[0] = {
tag: huks.HuksTag.HUKS_TAG_ALGORITHM,
value: huks.HuksKeyAlg.HUKS_ALG_RSA
}
properties[1] = {
tag: huks.HuksTag.HUKS_TAG_PURPOSE, tag: huks.HuksTag.HUKS_TAG_PURPOSE,
value: huks.HuksKeyPurpose.HUKS_KEY_PURPOSE_ENCRYPT, value: huks.HuksKeyPurpose.HUKS_KEY_PURPOSE_SIGN
} }
var encryptOptions = { properties[2] = {
properties: propertiesEncrypt, tag: huks.HuksTag.HUKS_TAG_DIGEST,
value: huks.HuksKeyDigest.HUKS_DIGEST_SHA256
}
properties[3] = {
tag: huks.HuksTag.HUKS_TAG_PADDING,
value: huks.HuksKeyPadding.HUKS_PADDING_PSS
}
properties[4] = {
tag: huks.HuksTag.HUKS_TAG_KEY_SIZE,
value: huks.HuksKeySize.HUKS_RSA_KEY_SIZE_512
}
properties[5] = {
tag: huks.HuksTag.HUKS_TAG_IMPORT_KEY_TYPE,
value: huks.HuksImportKeyType.HUKS_KEY_TYPE_KEY_PAIR
}
let huksOptions = {
properties: properties,
inData: new Uint8Array(new Array()) inData: new Uint8Array(new Array())
} }
huksOptions.properties[0].value = alg;
huksOptions.properties[3].value = keyType;
// Compare the key types.
if (huksOptions.properties[5].value === huks.HuksImportKeyType.HUKS_KEY_TYPE_KEY_PAIR) {
/* Concatenate the huksOptions.inData field with a non-public key in the following format:
* keyAlg type (4 bytes) + key_rsa length (4 bytes) +
* g_nData length (4 bytes) + g_eData length (4 bytes) +
* g_dData length (4 bytes) + g_nData +
* g_eData + g_dData
*/
// Key pair
let Material = new Uint32Array([huks.HuksKeyAlg.HUKS_ALG_RSA, huks.HuksKeySize.HUKS_RSA_KEY_SIZE_512, g_nData.length, g_eData.length, g_dData.length]);
let u8Material = Uint32ToUint8(Material);
let strMaterial = Uint8ArrayToString(u8Material);
let strNData = strMaterial.concat(Uint8ArrayToString(g_nData));
let strEData = strNData.concat(Uint8ArrayToString(g_eData));
let strData = strEData.concat(Uint8ArrayToString(g_dData));
huksOptions.inData = StringToUint8Array(strData);
} else if (huksOptions.properties[5].value === huks.HuksImportKeyType.HUKS_KEY_TYPE_PRIVATE_KEY) {
// Private key
let Material = new Uint32Array([huks.HuksKeyAlg.HUKS_ALG_RSA, huks.HuksKeySize.HUKS_RSA_KEY_SIZE_512, g_nData.length, 0, g_dData.length]);
let u8Material = Uint32ToUint8(Material);
let strMaterial = Uint8ArrayToString(u8Material);
let strNData = strMaterial.concat(Uint8ArrayToString(g_nData));
let strData = strNData.concat(Uint8ArrayToString(g_dData));
huksOptions.inData = StringToUint8Array(strData);
} else if (huksOptions.properties[5].value === huks.HuksImportKeyType.HUKS_KEY_TYPE_PUBLIC_KEY) {
// Public key
huksOptions.inData = g_pubData;
}
await publicImportKeyFunc(importKeyAlias, huksOptions);
await publicDeleteKeyFunc(importKeyAlias, huksOptions);
}
/* Import the key. */ // Import the X25519 key.
encryptOptions.inData = exportKey; async function ImportX25519Test(alg, keyType) {
await huks.importKey(srcKeyAliasSecond, encryptOptions).then((data) => { let importKeyAlias = 'import_x25519_key';
console.info(`test ImportKey data: ${JSON.stringify(data)}`); let properties = new Array();
}).catch((err) => { properties[0] = {
console.info('test ImportKey err information: ' + JSON.stringify(err)); tag: huks.HuksTag.HUKS_TAG_ALGORITHM,
}); value: huks.HuksKeyAlg.HUKS_ALG_X25519
}
properties[1] = {
tag: huks.HuksTag.HUKS_TAG_PURPOSE,
value: huks.HuksKeyPurpose.HUKS_KEY_PURPOSE_AGREE
}
properties[2] = {
tag: huks.HuksTag.HUKS_TAG_KEY_SIZE,
value: huks.HuksKeySize.HUKS_CURVE25519_KEY_SIZE_256
}
properties[3] = {
tag: huks.HuksTag.HUKS_TAG_IMPORT_KEY_TYPE,
value: huks.HuksImportKeyType.HUKS_KEY_TYPE_KEY_PAIR
}
properties[4] = {
tag: huks.HuksTag.HUKS_TAG_DIGEST,
value: huks.HuksKeyDigest.HUKS_DIGEST_SHA256
}
let huksOptions = {
properties: properties,
inData: new Uint8Array(new Array())
}
huksOptions.properties[0].value = alg;
huksOptions.properties[3].value = keyType;
// Compare the key types.
if (huksOptions.properties[3].value === huks.HuksImportKeyType.HUKS_KEY_TYPE_KEY_PAIR) {
/* Concatenate the huksOptions.inData field with a non-public key in the following format:
* keyAlg type (4 bytes) + key_x25519 length (4 bytes) +
* g_x25519PubData length (4) + g_x25519PriData length (4) +
* Reserved size (4 bytes) + g_x25519PubData +
* g_x25519PriData
*/
// Key pair
let Material = new Uint32Array([huks.HuksKeyAlg.HUKS_ALG_X25519, huks.HuksKeySize.HUKS_CURVE25519_KEY_SIZE_256, g_x25519PriData.length, g_x25519PubData.length, 0]);
let u8Material = Uint32ToUint8(Material);
let strMaterial = Uint8ArrayToString(u8Material);
let strXData = strMaterial.concat(Uint8ArrayToString(g_x25519PubData));
let strData = strXData.concat(Uint8ArrayToString(g_x25519PriData));
huksOptions.inData = StringToUint8Array(strData);
} else if (huksOptions.properties[3].value === huks.HuksImportKeyType.HUKS_KEY_TYPE_PRIVATE_KEY) {
// Private key
huksOptions.inData = g_x25519PriData;
} else if (huksOptions.properties[3].value === huks.HuksImportKeyType.HUKS_KEY_TYPE_PUBLIC_KEY) {
// Public key
huksOptions.inData = g_x25519PubData;
}
await publicImportKeyFunc(importKeyAlias, huksOptions);
await publicDeleteKeyFunc(importKeyAlias, huksOptions);
}
@Entry
@Component
struct Index {
build() {
Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) {
Button() {
Text('testExportRsa')
.fontSize(30)
.fontWeight(FontWeight.Bold)
}.type(ButtonType.Capsule)
.margin({
top: 20
})
.backgroundColor('#0D9FFB')
.onClick(() => {
testExportRsa();
})
Button() {
Text('testImportDh')
.fontSize(30)
.fontWeight(FontWeight.Bold)
}.type(ButtonType.Capsule)
.margin({
top: 20
})
.backgroundColor('#0D9FFB')
.onClick(() => {
ImportDhTest(huks.HuksKeyAlg.HUKS_ALG_DH, huks.HuksImportKeyType.HUKS_KEY_TYPE_PRIVATE_KEY);
})
Button() {
Text('testImportRsa')
.fontSize(30)
.fontWeight(FontWeight.Bold)
}.type(ButtonType.Capsule)
.margin({
top: 20
})
.backgroundColor('#0D9FFB')
.onClick(() => {
ImportRsaTest(huks.HuksKeyAlg.HUKS_ALG_RSA, huks.HuksImportKeyType.HUKS_KEY_TYPE_KEY_PAIR);
})
Button() {
Text('testImportX25519')
.fontSize(30)
.fontWeight(FontWeight.Bold)
}.type(ButtonType.Capsule)
.margin({
top: 20
})
.backgroundColor('#0D9FFB')
.onClick(() => {
ImportX25519Test(huks.HuksKeyAlg.HUKS_ALG_X25519, huks.HuksImportKeyType.HUKS_KEY_TYPE_PRIVATE_KEY);
})
Button() {
Text('testImportEcc')
.fontSize(30)
.fontWeight(FontWeight.Bold)
}.type(ButtonType.Capsule)
.margin({
top: 20
})
.backgroundColor('#0D9FFB')
.onClick(() => {
ImportEccTest(huks.HuksKeyAlg.HUKS_ALG_ECC, huks.HuksImportKeyType.HUKS_KEY_TYPE_PUBLIC_KEY);
})
}
.width('100%')
.height('100%')
}
} }
``` ```
### Secure key Import ### Secure Key Import
The service invoker and HUKS negotiate a shared symmetric key to encrypt and decrypt the intermediate key and the key to be imported. After the encrypted key is imported, it is decrypted and saved in HUKS. The keys in plaintext can be processed in HUKS only. The service invoker and HUKS negotiate a shared symmetric key to encrypt and decrypt the intermediate key and the key to be imported. After the encrypted key is imported, it is decrypted and saved in HUKS. The keys in plaintext can be processed in HUKS only.
The development procedure is as follows: The development procedure is as follows:
1. Generate a key pair in HUKS. The key pair is used to encrypt the key to import. 1. Generate a key pair in HUKS. The key pair is used to encrypt the key to import.
2. Export the public key of the key pair and obtain a shared key through key agreement. 2. Export the public key of the key pair and obtain a shared secret through key agreement.
3. Generate intermediate key materials and encrypt the key. 3. Generate intermediate key materials to encrypt the key.
4. Import the key. 4. Import the key.
**Supported key types**: **Supported Key Types**
AES128, AES192, AES256, RSA512, RSA768, RSA1024, RSA2048, RSA3072, RSA4096, HmacSHA1, HmacSHA224, HmacSHA256, HmacSHA384, HmacSHA512, ECC224, ECC256, ECC384, ECC521, Curve25519, DSA, SM2, SM3, SM4 AES128, AES192, AES256, RSA512, RSA768, RSA1024, RSA2048, RSA3072, RSA4096, HmacSHA1, HmacSHA224, HmacSHA256, HmacSHA384, HmacSHA512, ECC224, ECC256, ECC384, ECC521, Curve25519, DSA, SM2, SM3, SM4
...@@ -291,7 +792,7 @@ Before you get started, understand the following variables: ...@@ -291,7 +792,7 @@ Before you get started, understand the following variables:
| -------------- | ----------- | ---- | -------------------------------- | | -------------- | ----------- | ---- | -------------------------------- |
| importAlias | string | Yes | Alias of the key to import. | | importAlias | string | Yes | Alias of the key to import. |
| wrapAlias | string | Yes | Alias of the key. | | wrapAlias | string | Yes | Alias of the key. |
| genWrapOptions | HuksOptions | Yes | Tags required for generating the wrapping the key.| | genWrapOptions | HuksOptions | Yes | Tags required for generating the key.|
| importOptions | HuksOptions | Yes | Tags required for importing the encrypted key. | | importOptions | HuksOptions | Yes | Tags required for importing the encrypted key. |
For details about the APIs, see [HUKS](../reference/apis/js-apis-huks.md). For details about the APIs, see [HUKS](../reference/apis/js-apis-huks.md).
...@@ -299,87 +800,211 @@ For details about the APIs, see [HUKS](../reference/apis/js-apis-huks.md). ...@@ -299,87 +800,211 @@ For details about the APIs, see [HUKS](../reference/apis/js-apis-huks.md).
**Example** **Example**
```ts ```ts
var inputEccPair = new Uint8Array([ import huks from '@ohos.security.huks';
0x02, 0x00, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x20, 0x00, 0x00,
0x00, 0x20, 0x00, 0x00, 0x00, 0x20, 0x00, 0x00, 0x00, 0xa5, 0xb8, async function publicExportKeyFunc(keyAlias:string, huksOptions:huks.HuksOptions) {
0xa3, 0x78, 0x1d, 0x6d, 0x76, 0xe0, 0xb3, 0xf5, 0x6f, 0x43, 0x9d, console.info(`enter callback export`);
0xcf, 0x60, 0xf6, 0x0b, 0x3f, 0x64, 0x45, 0xa8, 0x3f, 0x1a, 0x96, try {
0xf1, 0xa1, 0xa4, 0x5d, 0x3e, 0x2c, 0x3f, 0x13, 0xd7, 0x81, 0xf7, await exportKeyItem(keyAlias, huksOptions)
0x2a, 0xb5, 0x8d, 0x19, 0x3d, 0x9b, 0x96, 0xc7, 0x6a, 0x10, 0xf0, .then ((data) => {
0xaa, 0xbc, 0x91, 0x6f, 0x4d, 0xa7, 0x09, 0xb3, 0x57, 0x88, 0x19, console.info(`callback: exportKeyItem success, data = ${JSON.stringify(data)}`);
0x6f, 0x00, 0x4b, 0xad, 0xee, 0x34, 0x35, 0xfb, 0x8b, 0x9f, 0x12, if (data.outData !== null) {
0xa0, 0x83, 0x19, 0xbe, 0x6a, 0x6f, 0x63, 0x2a, 0x7c, 0x86, 0xba, exportKey = data.outData;
0xca, 0x64, 0x0b, 0x88, 0x96, 0xe2, 0xfa, 0x77, 0xbc, 0x71, 0xe3, }
0x0f, 0x0f, 0x9e, 0x3c, 0xe5, 0xf9]); })
.catch(error => {
var exportWrappingKey; console.error(`callback: exportKeyItem failed, code: ${error.code}, msg: ${error.message}`);
var importAlias = "importAlias"; });
var wrapAlias = "wrappingKeyAlias"; } catch (error) {
console.error(`callback: exportKeyItem input arg invalid, code: ${error.code}, msg: ${error.message}`);
async function TestGenFunc(alias, options) { }
await genKey(alias, options).then((data) => {
console.log(`test genKey data: ${JSON.stringify(data)}`);
})
.catch((err) => {
console.log('test genKey err information: ' + JSON.stringify(err));
});
} }
function genKey(alias, options) { function exportKeyItem(keyAlias:string, huksOptions:huks.HuksOptions) : Promise<huks.HuksReturnResult> {
return new Promise((resolve, reject) => { return new Promise((resolve, reject) => {
huks.importKey(alias, options, function (err, data) { try {
console.log(`test genKey data: ${JSON.stringify(data)}`); huks.exportKeyItem(keyAlias, huksOptions, function (error, data) {
if (err.code !== 0) { if (error) {
console.log('test genKey err information: ' + JSON.stringify(err)); reject(error);
reject(err); } else {
} else { resolve(data);
resolve(data); }
} });
}); } catch (error) {
throw(error);
}
}); });
} }
async function TestExportFunc(alias, options) { async function publicImportKeyFunc(keyAlias:string, huksOptions:huks.HuksOptions) {
await exportKey(alias, options).then((data) => { console.info(`enter promise importKeyItem`);
console.log(`test exportKey data: ${JSON.stringify(data)}`); try {
}) await importKeyItem(keyAlias, huksOptions)
.catch((err) => { .then ((data) => {
console.log('test exportKey err information: ' + JSON.stringify(err)); console.info(`callback: importKeyItem success, data = ${JSON.stringify(data)}`);
})
.catch(error => {
console.error(`callback: importKeyItem failed, code: ${error.code}, msg: ${error.message}`);
});
} catch (error) {
console.error(`callback: importKeyItem input arg invalid, code: ${error.code}, msg: ${error.message}`);
}
}
function importKeyItem(keyAlias:string, huksOptions:huks.HuksOptions) {
return new Promise((resolve, reject) => {
try {
huks.importKeyItem(keyAlias, huksOptions, function (error, data) {
if (error) {
reject(error);
} else {
resolve(data);
}
});
} catch (error) {
throw(error);
}
}); });
} }
function exportKey(alias, options) { async function publicImportWrappedKey(keyAlias:string, wrappingKeyAlias:string, huksOptions:huks.HuksOptions) {
console.info(`enter callback importWrappedKeyItem`);
try {
await importWrappedKeyItem(keyAlias, wrappingKeyAlias, huksOptions)
.then ((data) => {
console.info(`callback: importWrappedKeyItem success, data = ${JSON.stringify(data)}`);
})
.catch(error => {
console.error(`callback: importWrappedKeyItem failed, code: ${error.code}, msg: ${error.message}`);
});
} catch (error) {
console.error(`callback: importWrappedKeyItem input arg invalid, code: ${error.code}, msg: ${error.message}`);
}
}
function importWrappedKeyItem(keyAlias:string, wrappingKeyAlias:string, huksOptions:huks.HuksOptions) {
return new Promise((resolve, reject) => { return new Promise((resolve, reject) => {
huks.exportKey(alias, options, function (err, data) { try {
console.log(`test exportKey data: ${JSON.stringify(data)}`); huks.importWrappedKeyItem(keyAlias, wrappingKeyAlias, huksOptions, function (error, data) {
if (err.code !== 0) { if (error) {
console.log('test exportKey err information: ' + JSON.stringify(err)); reject(error);
reject(err); } else {
} else { resolve(data);
exportWrappingKey = data.outData; }
resolve(data); });
} } catch (error) {
}); throw(error);
}
}); });
} }
async function TestImportWrappedFunc(alias, wrappingAlias, options) { async function publicDeleteKeyFunc(keyAlias:string, huksOptions:huks.HuksOptions) {
var result = await huks.importWrappedKey(alias, wrappingAlias, options); console.info(`enter callback deleteKeyItem`);
if (result.errorCode === 0) { try {
console.error('test importWrappedKey success'); await deleteKeyItem(keyAlias, huksOptions)
} else { .then ((data) => {
console.error('test importWrappedKey fail'); console.info(`callback: deleteKeyItem key success, data = ${JSON.stringify(data)}`);
})
.catch(error => {
console.error(`callback: deleteKeyItem failed, code: ${error.code}, msg: ${error.message}`);
});
} catch (error) {
console.error(`callback: deleteKeyItem input arg invalid, code: ${error.code}, msg: ${error.message}`);
} }
} }
async function TestImportWrappedKeyFunc( function deleteKeyItem(keyAlias:string, huksOptions:huks.HuksOptions) {
importAlias, return new Promise((resolve, reject) => {
wrappingAlias, try {
genOptions, huks.deleteKeyItem(keyAlias, huksOptions, function (error, data) {
importOptions if (error) {
) { reject(error);
await TestGenFunc(wrappingAlias, genOptions); } else {
await TestExportFunc(wrappingAlias, genOptions); resolve(data);
}
});
} catch (error) {
throw(error);
}
});
}
let importAlias = "importAlias";
let wrapAlias = "wrappingKeyAlias";
let exportKey;
let inputEccPair = new Uint8Array([
0x02, 0x00, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x20, 0x00, 0x00, 0x00, 0x20, 0x00, 0x00, 0x00,
0x20, 0x00, 0x00, 0x00, 0xa5, 0xb8, 0xa3, 0x78, 0x1d, 0x6d, 0x76, 0xe0, 0xb3, 0xf5, 0x6f, 0x43,
0x9d, 0xcf, 0x60, 0xf6, 0x0b, 0x3f, 0x64, 0x45, 0xa8, 0x3f, 0x1a, 0x96, 0xf1, 0xa1, 0xa4, 0x5d,
0x3e, 0x2c, 0x3f, 0x13, 0xd7, 0x81, 0xf7, 0x2a, 0xb5, 0x8d, 0x19, 0x3d, 0x9b, 0x96, 0xc7, 0x6a,
0x10, 0xf0, 0xaa, 0xbc, 0x91, 0x6f, 0x4d, 0xa7, 0x09, 0xb3, 0x57, 0x88, 0x19, 0x6f, 0x00, 0x4b,
0xad, 0xee, 0x34, 0x35, 0xfb, 0x8b, 0x9f, 0x12, 0xa0, 0x83, 0x19, 0xbe, 0x6a, 0x6f, 0x63, 0x2a,
0x7c, 0x86, 0xba, 0xca, 0x64, 0x0b, 0x88, 0x96, 0xe2, 0xfa, 0x77, 0xbc, 0x71, 0xe3, 0x0f, 0x0f,
0x9e, 0x3c, 0xe5, 0xf9]);
let properties = new Array();
properties[0] = {
tag: huks.HuksTag.HUKS_TAG_ALGORITHM,
value: huks.HuksKeyAlg.HUKS_ALG_ECC
};
properties[1] = {
tag: huks.HuksTag.HUKS_TAG_KEY_SIZE,
value: huks.HuksKeySize.HUKS_ECC_KEY_SIZE_256
};
properties[2] = {
tag: huks.HuksTag.HUKS_TAG_PURPOSE,
value: huks.HuksKeyPurpose.HUKS_KEY_PURPOSE_UNWRAP
};
properties[3] = {
tag: huks.HuksTag.HUKS_TAG_DIGEST,
value: huks.HuksKeyDigest.HUKS_DIGEST_SHA256
};
properties[4] = {
tag: huks.HuksTag.HUKS_TAG_IMPORT_KEY_TYPE,
value: huks.HuksImportKeyType.HUKS_KEY_TYPE_KEY_PAIR,
};
let huksOptions = {
properties: properties,
inData: inputEccPair
};
let importProperties = new Array();
importProperties[0] = {
tag: huks.HuksTag.HUKS_TAG_ALGORITHM,
value: huks.HuksKeyAlg.HUKS_ALG_AES
};
importProperties[1] = {
tag: huks.HuksTag.HUKS_TAG_KEY_SIZE,
value: huks.HuksKeySize.HUKS_AES_KEY_SIZE_256
};
importProperties[2] = {
tag: huks.HuksTag.HUKS_TAG_PURPOSE,
value: huks.HuksKeyPurpose.HUKS_KEY_PURPOSE_ENCRYPT | huks.HuksKeyPurpose.HUKS_KEY_PURPOSE_DECRYPT
};
importProperties[3] = {
tag: huks.HuksTag.HUKS_TAG_BLOCK_MODE,
value: huks.HuksCipherMode.HUKS_MODE_CBC
};
importProperties[4] = {
tag: huks.HuksTag.HUKS_TAG_PADDING,
value: huks.HuksKeyPadding.HUKS_PADDING_NONE
};
importProperties[5] = {
tag: huks.HuksTag.HUKS_TAG_UNWRAP_ALGORITHM_SUITE,
value: huks.HuksUnwrapSuite.HUKS_UNWRAP_SUITE_ECDH_AES_256_GCM_NOPADDING
};
let importOptions = {
properties: importProperties,
inData: new Uint8Array(new Array())
};
async function importWrappedKeyItemTest() {
console.info(`enter ImportWrapKey test`);
await publicImportKeyFunc(wrapAlias, huksOptions);
await publicExportKeyFunc(wrapAlias, huksOptions);
/* The following operation does not involve calling of HUKS APIs, and the specific implementation is not provided here. /* The following operation does not involve calling of HUKS APIs, and the specific implementation is not provided here.
* For example, import keyA. * For example, import keyA.
...@@ -394,111 +1019,56 @@ async function TestImportWrappedKeyFunc( ...@@ -394,111 +1019,56 @@ async function TestImportWrappedKeyFunc(
* nonce1 length (4 bytes) + nonce1 + tag1 length (4 bytes) + tag1 + * 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 * Memory occupied by the keyA length (4 bytes) + keyA length + keyA_enc length (4 bytes) + keyA_enc
*/ */
var inputKey = new Uint8Array([ let inputKey = new Uint8Array([
0x5b, 0x00, 0x00, 0x00, 0x30, 0x59, 0x30, 0x13, 0x06, 0x07, 0x2a, 0x5b, 0x00, 0x00, 0x00, 0x30, 0x59, 0x30, 0x13, 0x06, 0x07, 0x2a, 0x86, 0x48, 0xce, 0x3d, 0x02,
0x86, 0x48, 0xce, 0x3d, 0x02, 0x01, 0x06, 0x08, 0x2a, 0x86, 0x48, 0x01, 0x06, 0x08, 0x2a, 0x86, 0x48, 0xce, 0x3d, 0x03, 0x01, 0x07, 0x03, 0x42, 0x00, 0x04, 0xc0,
0xce, 0x3d, 0x03, 0x01, 0x07, 0x03, 0x42, 0x00, 0x04, 0xc0, 0xfe, 0xfe, 0x1c, 0x67, 0xde, 0x86, 0x0e, 0xfb, 0xaf, 0xb5, 0x85, 0x52, 0xb4, 0x0e, 0x1f, 0x6c, 0x6c,
0x1c, 0x67, 0xde, 0x86, 0x0e, 0xfb, 0xaf, 0xb5, 0x85, 0x52, 0xb4, 0xaa, 0xc5, 0xd9, 0xd2, 0x4d, 0xb0, 0x8a, 0x72, 0x24, 0xa1, 0x99, 0xaf, 0xfc, 0x3e, 0x55, 0x5a,
0x0e, 0x1f, 0x6c, 0x6c, 0xaa, 0xc5, 0xd9, 0xd2, 0x4d, 0xb0, 0x8a, 0xac, 0x99, 0x3d, 0xe8, 0x34, 0x72, 0xb9, 0x47, 0x9c, 0xa6, 0xd8, 0xfb, 0x00, 0xa0, 0x1f, 0x9f,
0x72, 0x24, 0xa1, 0x99, 0xaf, 0xfc, 0x3e, 0x55, 0x5a, 0xac, 0x99, 0x7a, 0x41, 0xe5, 0x44, 0x3e, 0xb2, 0x76, 0x08, 0xa2, 0xbd, 0xe9, 0x41, 0xd5, 0x2b, 0x9e, 0x10,
0x3d, 0xe8, 0x34, 0x72, 0xb9, 0x47, 0x9c, 0xa6, 0xd8, 0xfb, 0x00, 0x00, 0x00, 0x00, 0xbf, 0xf9, 0x69, 0x41, 0xf5, 0x49, 0x85, 0x31, 0x35, 0x14, 0x69, 0x12, 0x57,
0xa0, 0x1f, 0x9f, 0x7a, 0x41, 0xe5, 0x44, 0x3e, 0xb2, 0x76, 0x08, 0x9c, 0xc8, 0xb7, 0x10, 0x00, 0x00, 0x00, 0x2d, 0xb7, 0xf1, 0x5a, 0x0f, 0xb8, 0x20, 0xc5, 0x90,
0xa2, 0xbd, 0xe9, 0x41, 0xd5, 0x2b, 0x9e, 0x10, 0x00, 0x00, 0x00, 0xe5, 0xca, 0x45, 0x84, 0x5c, 0x08, 0x08, 0x10, 0x00, 0x00, 0x00, 0x43, 0x25, 0x1b, 0x2f, 0x5b,
0xbf, 0xf9, 0x69, 0x41, 0xf5, 0x49, 0x85, 0x31, 0x35, 0x14, 0x69, 0x86, 0xd8, 0x87, 0x04, 0x4d, 0x38, 0xc2, 0x65, 0xcc, 0x9e, 0xb7, 0x20, 0x00, 0x00, 0x00, 0xf4,
0x12, 0x57, 0x9c, 0xc8, 0xb7, 0x10, 0x00, 0x00, 0x00, 0x2d, 0xb7, 0xe8, 0x93, 0x28, 0x0c, 0xfa, 0x4e, 0x11, 0x6b, 0xe8, 0xbd, 0xa8, 0xe9, 0x3f, 0xa7, 0x8f, 0x2f,
0xf1, 0x5a, 0x0f, 0xb8, 0x20, 0xc5, 0x90, 0xe5, 0xca, 0x45, 0x84, 0xe3, 0xb3, 0xbf, 0xaf, 0xce, 0xe5, 0x06, 0x2d, 0xe6, 0x45, 0x5d, 0x19, 0x26, 0x09, 0xe7, 0x10,
0x5c, 0x08, 0x08, 0x10, 0x00, 0x00, 0x00, 0x43, 0x25, 0x1b, 0x2f, 0x00, 0x00, 0x00, 0xf4, 0x1e, 0x7b, 0x01, 0x7a, 0x84, 0x36, 0xa4, 0xa8, 0x1c, 0x0d, 0x3d, 0xde,
0x5b, 0x86, 0xd8, 0x87, 0x04, 0x4d, 0x38, 0xc2, 0x65, 0xcc, 0x9e, 0x57, 0x66, 0x73, 0x10, 0x00, 0x00, 0x00, 0xe3, 0xff, 0x29, 0x97, 0xad, 0xb3, 0x4a, 0x2c, 0x50,
0xb7, 0x20, 0x00, 0x00, 0x00, 0xf4, 0xe8, 0x93, 0x28, 0x0c, 0xfa, 0x08, 0xb5, 0x68, 0xe1, 0x90, 0x5a, 0xdc, 0x10, 0x00, 0x00, 0x00, 0x26, 0xae, 0xdc, 0x4e, 0xa5,
0x4e, 0x11, 0x6b, 0xe8, 0xbd, 0xa8, 0xe9, 0x3f, 0xa7, 0x8f, 0x2f, 0x6e, 0xb1, 0x38, 0x14, 0x24, 0x47, 0x1c, 0x41, 0x89, 0x63, 0x11, 0x04, 0x00, 0x00, 0x00, 0x20,
0xe3, 0xb3, 0xbf, 0xaf, 0xce, 0xe5, 0x06, 0x2d, 0xe6, 0x45, 0x5d, 0x00, 0x00, 0x00, 0x20, 0x00, 0x00, 0x00, 0x0b, 0xcb, 0xa9, 0xa8, 0x5f, 0x5a, 0x9d, 0xbf, 0xa1,
0x19, 0x26, 0x09, 0xe7, 0x10, 0x00, 0x00, 0x00, 0xf4, 0x1e, 0x7b, 0xfc, 0x72, 0x74, 0x87, 0x79, 0xf2, 0xf4, 0x22, 0x0c, 0x8a, 0x4d, 0xd8, 0x7e, 0x10, 0xc8, 0x44,
0x01, 0x7a, 0x84, 0x36, 0xa4, 0xa8, 0x1c, 0x0d, 0x3d, 0xde, 0x57, 0x17, 0x95, 0xab, 0x3b, 0xd2, 0x8f, 0x0a
0x66, 0x73, 0x10, 0x00, 0x00, 0x00, 0xe3, 0xff, 0x29, 0x97, 0xad, ]);
0xb3, 0x4a, 0x2c, 0x50, 0x08, 0xb5, 0x68, 0xe1, 0x90, 0x5a, 0xdc,
0x10, 0x00, 0x00, 0x00, 0x26, 0xae, 0xdc, 0x4e, 0xa5, 0x6e, 0xb1,
0x38, 0x14, 0x24, 0x47, 0x1c, 0x41, 0x89, 0x63, 0x11, 0x04, 0x00,
0x00, 0x00, 0x20, 0x00, 0x00, 0x00, 0x20, 0x00, 0x00, 0x00, 0x0b,
0xcb, 0xa9, 0xa8, 0x5f, 0x5a, 0x9d, 0xbf, 0xa1, 0xfc, 0x72, 0x74,
0x87, 0x79, 0xf2, 0xf4, 0x22, 0x0c, 0x8a, 0x4d, 0xd8, 0x7e, 0x10,
0xc8, 0x44, 0x17, 0x95, 0xab, 0x3b, 0xd2, 0x8f, 0x0a]);
importOptions.inData = inputKey; importOptions.inData = inputKey;
await TestImportWrappedFunc(importAlias, wrappingAlias, importOptions); await publicImportWrappedKey(importAlias, wrapAlias, importOptions);
}
function makePubKeyOptions() {
var properties = new Array();
properties[0] = {
tag: huks.HuksTag.HUKS_TAG_ALGORITHM,
value: huks.HuksKeyAlg.HUKS_ALG_ECC
};
properties[1] = {
tag: huks.HuksTag.HUKS_TAG_KEY_SIZE,
value: huks.HuksKeySize.HUKS_ECC_KEY_SIZE_256
};
properties[2] = {
tag: huks.HuksTag.HUKS_TAG_PURPOSE,
value: huks.HuksKeyPurpose.HUKS_KEY_PURPOSE_UNWRAP
};
properties[3] = {
tag: huks.HuksTag.HUKS_TAG_DIGEST,
value: huks.HuksKeyDigest.HUKS_DIGEST_SHA256
};
properties[4] = {
tag: huks.HuksTag.HUKS_TAG_IMPORT_KEY_TYPE,
value: huks.HuksImportKeyType.HUKS_KEY_TYPE_KEY_PAIR,
};
var options = {
properties: properties,
inData: inputEccPair
};
return options;
}
function makeImportOptions() { await publicDeleteKeyFunc(wrapAlias, huksOptions);
var properties = new Array(); await publicDeleteKeyFunc(importAlias, importOptions);
properties[0] = {
tag: huks.HuksTag.HUKS_TAG_ALGORITHM,
value: huks.HuksKeyAlg.HUKS_ALG_AES
};
properties[1] = {
tag: huks.HuksTag.HUKS_TAG_KEY_SIZE,
value: huks.HuksKeySize.HUKS_AES_KEY_SIZE_256
};
properties[2] = {
tag: huks.HuksTag.HUKS_TAG_PURPOSE,
value:
huks.HuksKeyPurpose.HUKS_KEY_PURPOSE_ENCRYPT |
huks.HuksKeyPurpose.HUKS_KEY_PURPOSE_DECRYPT
};
properties[3] = {
tag: huks.HuksTag.HUKS_TAG_BLOCK_MODE,
value: huks.HuksCipherMode.HUKS_MODE_CBC
};
properties[4] = {
tag: huks.HuksTag.HUKS_TAG_PADDING,
value: huks.HuksKeyPadding.HUKS_PADDING_NONE
};
properties[5] = {
tag: huks.HuksTag.HUKS_TAG_UNWRAP_ALGORITHM_SUITE,
value: huks.HuksUnwrapSuite.HUKS_UNWRAP_SUITE_ECDH_AES_256_GCM_NOPADDING
};
var options = {
properties: properties
};
return options;
} }
function huksImportWrappedKey() { @Entry
var genOptions = makePubKeyOptions(); @Component
var importOptions = makeImportOptions(); struct Index {
TestImportWrappedKeyFunc( build() {
importAlias, Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) {
wrapAlias, Button() {
genOptions, Text('importWrappedKeyItemTest')
importOptions .fontSize(30)
); .fontWeight(FontWeight.Bold)
}.type(ButtonType.Capsule)
.margin({
top: 20
})
.backgroundColor('#0D9FFB')
.onClick(()=>{
importWrappedKeyItemTest();
})
}
.width('100%')
.height('100%')
}
} }
``` ```
...@@ -516,20 +1086,20 @@ The development procedure is as follows: ...@@ -516,20 +1086,20 @@ The development procedure is as follows:
| HUKS_ALG_ALGORITHM | HUKS_TAG_PURPOSE | HUKS_TAG_DIGEST | HUKS_TAG_PADDING | HUKS_TAG_BLOCK_MODE | HUKS_TAG_IV | | HUKS_ALG_ALGORITHM | HUKS_TAG_PURPOSE | HUKS_TAG_DIGEST | HUKS_TAG_PADDING | HUKS_TAG_BLOCK_MODE | HUKS_TAG_IV |
| ------------------------------------------------------------ | -------------------------------------------------- | ------------------------------------------------------------ | ------------------------------------------------------------ | ------------------------------------------- | ----------- | | ------------------------------------------------------------ | -------------------------------------------------- | ------------------------------------------------------------ | ------------------------------------------------------------ | ------------------------------------------- | ----------- |
| HUKS_ALG_SM4 (supported key length: HUKS_SM4_KEY_SIZE_128)| HUKS_KEY_PURPOSE_ENCRYPT HUKS_KEY_PURPOSE_DECRYPT | Optional | HUKS_PADDING_NONE | HUKS_MODE_CTR HUKS_MODE_ECB HUKS_MODE_CBC | Mandatory | | HUKS_ALG_SM4 (supported key length: HUKS_SM4_KEY_SIZE_128)| HUKS_KEY_PURPOSE_ENCRYPT or HUKS_KEY_PURPOSE_DECRYPT| Optional | HUKS_PADDING_NONE | HUKS_MODE_CTR HUKS_MODE_ECB HUKS_MODE_CBC | Mandatory |
| HUKS_ALG_SM4 (supported key length: HUKS_SM4_KEY_SIZE_128)| HUKS_KEY_PURPOSE_ENCRYPT HUKS_KEY_PURPOSE_DECRYPT | Optional | HUKS_PADDING_PKCS7 | HUKS_MODE_ECB HUKS_MODE_CBC | Mandatory | | HUKS_ALG_SM4 (supported key length: HUKS_SM4_KEY_SIZE_128)| HUKS_KEY_PURPOSE_ENCRYPT or HUKS_KEY_PURPOSE_DECRYPT| Optional | HUKS_PADDING_PKCS7 | HUKS_MODE_ECB HUKS_MODE_CBC | Mandatory |
| HUKS_ALG_RSA (supported key lengths: HUKS_SM4_KEY_SIZE_512, HUKS_SM4_KEY_SIZE_768, HUKS_SM4_KEY_SIZE_1024, HUKS_SM4_KEY_SIZE_2048, HUKS_SM4_KEY_SIZE_3072, HUKS_SM4_KEY_SIZE_4096)| HUKS_KEY_PURPOSE_ENCRYPT HUKS_KEY_PURPOSE_DECRYPT | HUKS_DIGEST_SHA1 HUKS_DIGEST_SHA224 HUKS_DIGEST_SHA256 HUKS_DIGEST_SHA384 HUKS_DIGEST_SHA512 | HUKS_PADDING_NONE HUKS_PADDING_PKCS1_V1_5 HUKS_PADDING_OAEP | HUKS_MODE_ECB | Optional | | HUKS_ALG_RSA (supported lengths: HUKS_RSA_KEY_SIZE_512, HUKS_RSA_KEY_SIZE_768, HUKS_RSA_KEY_SIZE_1024, HUKS_RSA_KEY_SIZE_2048, HUKS_RSA_KEY_SIZE_3072, HUKS_RSA_KEY_SIZE_4096)| HUKS_KEY_PURPOSE_ENCRYPT or HUKS_KEY_PURPOSE_DECRYPT| HUKS_DIGEST_SHA1 HUKS_DIGEST_SHA224 HUKS_DIGEST_SHA256 HUKS_DIGEST_SHA384 HUKS_DIGEST_SHA512 | HUKS_PADDING_NONE HUKS_PADDING_PKCS1_V1_5 HUKS_PADDING_OAEP | HUKS_MODE_ECB | Optional |
| HUKS_ALG_ALGORITHM | HUKS_TAG_PURPOSE | HUKS_TAG_PADDING | HUKS_TAG_BLOCK_MODE | HUKS_TAG_IV | HUKS_TAG_NONCE | HUKS_TAG_ASSOCIATED_DATA | HUKS_TAG_AE_TAG | | HUKS_ALG_ALGORITHM | HUKS_TAG_PURPOSE | HUKS_TAG_PADDING | HUKS_TAG_BLOCK_MODE | HUKS_TAG_IV | HUKS_TAG_NONCE | HUKS_TAG_ASSOCIATED_DATA | HUKS_TAG_AE_TAG |
| ------------------------------------------------------------ | ------------------------ | ------------------------------------- | ---------------------------- | ----------- | -------------- | ------------------------ | --------------- | | ------------------------------------------------------------ | ------------------------ | ------------------------------------- | ---------------------------- | ----------- | -------------- | ------------------------ | --------------- |
| HUKS_ALG_AES (supported key lengths: HUKS_AES_KEY_SIZE_128, HUKS_AES_KEY_SIZE_192, HUKS_AES_KEY_SIZE_256)| HUKS_KEY_PURPOSE_ENCRYPT | HUKS_PADDING_NONE HUKS_PADDING_PKCS7 | HUKS_MODE_CBC | Mandatory | Optional | Optional | Optional | | HUKS_ALG_AES (supported key lengths: HUKS_AES_KEY_SIZE_128, HUKS_AES_KEY_SIZE_192, HUKS_AES_KEY_SIZE_256)| HUKS_KEY_PURPOSE_ENCRYPT | HUKS_PADDING_NONE, HUKS_PADDING_PKCS7| HUKS_MODE_CBC | Mandatory | Optional | Optional | Optional |
| HUKS_ALG_AES | HUKS_KEY_PURPOSE_ENCRYPT | HUKS_PADDING_NONE | HUKS_MODE_CCM HUKS_MODE_GCM | Optional | Mandatory | Mandatory | Optional | | HUKS_ALG_AES | HUKS_KEY_PURPOSE_ENCRYPT | HUKS_PADDING_NONE | HUKS_MODE_CCM HUKS_MODE_GCM | Optional | Mandatory | Mandatory | Optional |
| HUKS_ALG_AES | HUKS_KEY_PURPOSE_ENCRYPT | HUKS_PADDING_NONE | HUKS_MODE_CTR | Mandatory | Optional | Optional | Optional | | HUKS_ALG_AES | HUKS_KEY_PURPOSE_ENCRYPT | HUKS_PADDING_NONE | HUKS_MODE_CTR | Mandatory | Optional | Optional | Optional |
| HUKS_ALG_AES | HUKS_KEY_PURPOSE_ENCRYPT | HUKS_PADDING_PKCS7 HUKS_PADDING_NONE | HUKS_MODE_ECB | Mandatory | Optional | Optional | Optional | | HUKS_ALG_AES | HUKS_KEY_PURPOSE_ENCRYPT | HUKS_PADDING_PKCS7 HUKS_PADDING_NONE | HUKS_MODE_ECB | Mandatory | Optional | Optional | Optional |
| HUKS_ALG_AES | HUKS_KEY_PURPOSE_DECRYPT | HUKS_PADDING_NONE HUKS_PADDING_PKCS7 | HUKS_MODE_CBC | Mandatory | Optional | Optional | Mandatory | | HUKS_ALG_AES | HUKS_KEY_PURPOSE_DECRYPT | HUKS_PADDING_NONE, HUKS_PADDING_PKCS7| HUKS_MODE_CBC | Mandatory | Optional | Optional | Mandatory |
| HUKS_ALG_AES | HUKS_KEY_PURPOSE_DECRYPT | HUKS_PADDING_NONE | HUKS_MODE_CCM HUKS_MODE_GCM | Optional | Mandatory | Mandatory | Optional | | HUKS_ALG_AES | HUKS_KEY_PURPOSE_DECRYPT | HUKS_PADDING_NONE | HUKS_MODE_CCM HUKS_MODE_GCM | Optional | Mandatory | Mandatory | Optional |
| HUKS_ALG_AES | HUKS_KEY_PURPOSE_DECRYPT | HUKS_PADDING_NONE | HUKS_MODE_CTR | Mandatory | Optional | Optional | Optional | | HUKS_ALG_AES | HUKS_KEY_PURPOSE_DECRYPT | HUKS_PADDING_NONE | HUKS_MODE_CTR | Mandatory | Optional | Optional | Optional |
| HUKS_ALG_AES | HUKS_KEY_PURPOSE_DECRYPT | HUKS_PADDING_NONE HUKS_PADDING_PKCS7 | HUKS_MODE_ECB | Mandatory | Optional | Optional | Optional | | HUKS_ALG_AES | HUKS_KEY_PURPOSE_DECRYPT | HUKS_PADDING_NONE, HUKS_PADDING_PKCS7| HUKS_MODE_ECB | Mandatory | Optional | Optional | Optional |
> **NOTE**<br> > **NOTE**<br>
> >
...@@ -553,31 +1123,177 @@ For details about the APIs, see [HUKS](../reference/apis/js-apis-huks.md). ...@@ -553,31 +1123,177 @@ For details about the APIs, see [HUKS](../reference/apis/js-apis-huks.md).
* *
* The following uses the Promise() operation of an SM4 128-bit key as an example. * The following uses the Promise() operation of an SM4 128-bit key as an example.
*/ */
function sm4CipherStringToUint8Array(str) { import huks from '@ohos.security.huks';
var arr = [];
for (var i = 0, j = str.length; i < j; ++i) { function StringToUint8Array(str) {
let arr = [];
for (let i = 0, j = str.length; i < j; ++i) {
arr.push(str.charCodeAt(i)); arr.push(str.charCodeAt(i));
} }
return new Uint8Array(arr); return new Uint8Array(arr);
} }
function sm4CipherUint8ArrayToString(fileData) {
var dataString = ''; function Uint8ArrayToString(fileData) {
for (var i = 0; i < fileData.length; i++) { let dataString = '';
for (let i = 0; i < fileData.length; i++) {
dataString += String.fromCharCode(fileData[i]); dataString += String.fromCharCode(fileData[i]);
} }
return dataString; return dataString;
} }
var handle; async function publicGenKeyFunc(keyAlias:string, huksOptions:huks.HuksOptions) {
var IV = '0000000000000000'; console.info(`enter callback generateKeyItem`);
var cipherInData = 'Hks_SM4_Cipher_Test_101010101010101010110_string'; try {
var srcKeyAlias = 'huksCipherSm4SrcKeyAlias'; await generateKeyItem(keyAlias, huksOptions)
var encryptUpdateResult = new Array(); .then((data) => {
var decryptUpdateResult = new Array(); console.info(`callback: generateKeyItem success, data = ${JSON.stringify(data)}`);
})
.catch(error => {
console.error(`callback: generateKeyItem failed, code: ${error.code}, msg: ${error.message}`);
});
} catch (error) {
console.error(`callback: generateKeyItem input arg invalid, code: ${error.code}, msg: ${error.message}`);
}
}
function generateKeyItem(keyAlias:string, huksOptions:huks.HuksOptions) {
return new Promise((resolve, reject) => {
try {
huks.generateKeyItem(keyAlias, huksOptions, function (error, data) {
if (error) {
reject(error);
} else {
resolve(data);
}
});
} catch (error) {
throw(error);
}
});
}
async function publicInitFunc(keyAlias:string, huksOptions:huks.HuksOptions) {
console.info(`enter promise doInit`);
try {
await huks.initSession(keyAlias, huksOptions)
.then ((data) => {
console.info(`promise: doInit success, data = ${JSON.stringify(data)}`);
handle = data.handle;
})
.catch(error => {
console.error(`promise: doInit key failed, code: ${error.code}, msg: ${error.message}`);
});
} catch (error) {
console.error(`promise: doInit input arg invalid, code: ${error.code}, msg: ${error.message}`);
}
}
async function publicUpdateFunc(handle:number, huksOptions:huks.HuksOptions) {
console.info(`enter callback doUpdate`);
try {
await updateSession(handle, huksOptions)
.then ((data) => {
console.info(`callback: doUpdate success, data = ${JSON.stringify(data)}`);
updateResult = Array.from(data.outData);
})
.catch(error => {
console.error(`callback: doUpdate failed, code: ${error.code}, msg: ${error.message}`);
});
} catch (error) {
console.error(`callback: doUpdate input arg invalid, code: ${error.code}, msg: ${error.message}`);
}
}
function updateSession(handle:number, huksOptions:huks.HuksOptions) : Promise<huks.HuksReturnResult> {
return new Promise((resolve, reject) => {
try {
huks.updateSession(handle, huksOptions, function (error, data) {
if (error) {
reject(error);
} else {
resolve(data);
}
});
} catch (error) {
throw(error);
}
});
}
async function publicFinishFunc(handle:number, huksOptions:huks.HuksOptions) {
console.info(`enter callback doFinish`);
try {
await finishSession(handle, huksOptions)
.then ((data) => {
finishOutData = Uint8ArrayToString(new Uint8Array(updateResult));
console.info(`callback: doFinish success, data = ${JSON.stringify(data)}`);
})
.catch(error => {
console.error(`callback: doFinish failed, code: ${error.code}, msg: ${error.message}`);
});
} catch (error) {
console.error(`callback: doFinish input arg invalid, code: ${error.code}, msg: ${error.message}`);
}
}
function finishSession(handle:number, huksOptions:huks.HuksOptions) : Promise<huks.HuksReturnResult> {
return new Promise((resolve, reject) => {
try {
huks.finishSession(handle, huksOptions, function (error, data) {
if (error) {
reject(error);
} else {
resolve(data);
}
});
} catch (error) {
throw(error);
}
});
}
async function publicDeleteKeyFunc(keyAlias:string, huksOptions:huks.HuksOptions) {
console.info(`enter callback deleteKeyItem`);
try {
await deleteKeyItem(keyAlias, huksOptions)
.then ((data) => {
console.info(`callback: deleteKeyItem key success, data = ${JSON.stringify(data)}`);
})
.catch(error => {
console.error(`callback: deleteKeyItem failed, code: ${error.code}, msg: ${error.message}`);
});
} catch (error) {
console.error(`callback: deleteKeyItem input arg invalid, code: ${error.code}, msg: ${error.message}`);
}
}
function deleteKeyItem(keyAlias:string, huksOptions:huks.HuksOptions) {
return new Promise((resolve, reject) => {
try {
huks.deleteKeyItem(keyAlias, huksOptions, function (error, data) {
if (error) {
reject(error);
} else {
resolve(data);
}
});
} catch (error) {
throw(error);
}
});
}
async function testCipher() { let IV = '0000000000000000';
let cipherInData = 'Hks_SM4_Cipher_Test_101010101010101010110_string';
let srcKeyAlias = 'huksCipherSm4SrcKeyAlias';
let encryptUpdateResult = new Array();
let handle;
let updateResult = new Array();
let finishOutData;
async function testSm4Cipher() {
/* Integrate the key generation parameter set and key encryption parameter set. */ /* Integrate the key generation parameter set and key encryption parameter set. */
var properties = new Array(); let properties = new Array();
properties[0] = { properties[0] = {
tag: huks.HuksTag.HUKS_TAG_ALGORITHM, tag: huks.HuksTag.HUKS_TAG_ALGORITHM,
value: huks.HuksKeyAlg.HUKS_ALG_SM4, value: huks.HuksKeyAlg.HUKS_ALG_SM4,
...@@ -600,12 +1316,12 @@ async function testCipher() { ...@@ -600,12 +1316,12 @@ async function testCipher() {
tag: huks.HuksTag.HUKS_TAG_PADDING, tag: huks.HuksTag.HUKS_TAG_PADDING,
value: huks.HuksKeyPadding.HUKS_PADDING_NONE, value: huks.HuksKeyPadding.HUKS_PADDING_NONE,
} }
var huksOptions = { let huksOptions = {
properties: properties, properties: properties,
inData: new Uint8Array(new Array()) inData: new Uint8Array(new Array())
} }
var propertiesEncrypt = new Array(); let propertiesEncrypt = new Array();
propertiesEncrypt[0] = { propertiesEncrypt[0] = {
tag: huks.HuksTag.HUKS_TAG_ALGORITHM, tag: huks.HuksTag.HUKS_TAG_ALGORITHM,
value: huks.HuksKeyAlg.HUKS_ALG_SM4, value: huks.HuksKeyAlg.HUKS_ALG_SM4,
...@@ -628,89 +1344,79 @@ async function testCipher() { ...@@ -628,89 +1344,79 @@ async function testCipher() {
} }
propertiesEncrypt[5] = { propertiesEncrypt[5] = {
tag: huks.HuksTag.HUKS_TAG_IV, tag: huks.HuksTag.HUKS_TAG_IV,
value: sm4CipherStringToUint8Array(IV), value: StringToUint8Array(IV),
} }
var encryptOptions = { let encryptOptions = {
properties: propertiesEncrypt, properties: propertiesEncrypt,
inData: new Uint8Array(new Array()) inData: new Uint8Array(new Array())
} }
/* Generate a key. */ /* Generate a key. */
await huks.generateKey(srcKeyAlias, huksOptions).then((data) => { await publicGenKeyFunc(srcKeyAlias, huksOptions);
console.info(`test generateKey data: ${JSON.stringify(data)}`);
}).catch((err) => {
console.info('test generateKey err information: ' + JSON.stringify(err));
});
/* Encrypt the key. */ /* Encrypt the key. */
await huks.init(srcKeyAlias, encryptOptions).then((data) => { await publicInitFunc(srcKeyAlias, encryptOptions);
console.info(`test init data: ${JSON.stringify(data)}`);
handle = data.handle; encryptOptions.inData = StringToUint8Array(cipherInData);
}).catch((err) => { await publicUpdateFunc(handle, encryptOptions);
console.info('test init err information: ' + JSON.stringify(err)); encryptUpdateResult = updateResult;
});
encryptOptions.inData = sm4CipherStringToUint8Array(cipherInData);
await huks.update(handle, encryptOptions).then(async (data) => {
console.info(`test update data ${JSON.stringify(data)}`);
encryptUpdateResult = Array.from(data.outData);
}).catch((err) => {
console.info('test update err information: ' + err);
});
encryptOptions.inData = new Uint8Array(new Array()); encryptOptions.inData = new Uint8Array(new Array());
await huks.finish(handle, encryptOptions).then((data) => { await publicFinishFunc(handle, encryptOptions);
console.info(`test finish data: ${JSON.stringify(data)}`); if (finishOutData === cipherInData) {
var finishData = sm4CipherUint8ArrayToString(new Uint8Array(encryptUpdateResult)); console.info('test finish encrypt err ');
if (finishData === cipherInData) { } else {
console.info('test finish encrypt err '); console.info('test finish encrypt success');
} else { }
console.info('test finish encrypt success');
}
}).catch((err) => {
console.info('test finish err information: ' + JSON.stringify(err));
});
/* Modify the key encryption parameter set to the decryption parameter set. */ /* Modify the key encryption parameter set to the decryption parameter set. */
propertiesEncrypt.splice(1, 1, { propertiesEncrypt.splice(1, 1, {
tag: huks.HuksTag.HUKS_TAG_PURPOSE, tag: huks.HuksTag.HUKS_TAG_PURPOSE,
value: huks.HuksKeyPurpose.HUKS_KEY_PURPOSE_DECRYPT, value: huks.HuksKeyPurpose.HUKS_KEY_PURPOSE_DECRYPT,
}); });
var decryptOptions = { let decryptOptions = {
properties: propertiesEncrypt, properties: propertiesEncrypt,
inData: new Uint8Array(new Array()) inData: new Uint8Array(new Array())
} }
/* Decrypt the key. */ /* Decrypt the key. */
await huks.init(srcKeyAlias, decryptOptions).then((data) => { await publicInitFunc(srcKeyAlias, decryptOptions);
console.info(`test init data: ${JSON.stringify(data)}`);
handle = data.handle;
}).catch((err) => {
console.info('test init err information: ' + JSON.stringify(err));
});
decryptOptions.inData = new Uint8Array(encryptUpdateResult); decryptOptions.inData = new Uint8Array(encryptUpdateResult);
await huks.update(handle, decryptOptions).then(async (data) => { await publicUpdateFunc(handle, decryptOptions);
console.info(`test update data ${JSON.stringify(data)}`);
decryptUpdateResult = Array.from(data.outData);
}).catch((err) => {
console.info('test update err information: ' + err);
});
decryptOptions.inData = new Uint8Array(new Array()); decryptOptions.inData = new Uint8Array(new Array());
await huks.finish(handle, decryptOptions).then((data) => { await publicFinishFunc(handle, decryptOptions);
console.info(`test finish data: ${JSON.stringify(data)}`); if (finishOutData === cipherInData) {
var finishData = sm4CipherUint8ArrayToString(new Uint8Array(decryptUpdateResult)); console.info('test finish decrypt success ');
if (finishData === cipherInData) { } else {
console.info('test finish decrypt success '); console.info('test finish decrypt err');
} else { }
console.info('test finish decrypt err');
}
}).catch((err) => {
console.info('test finish err information: ' + JSON.stringify(err));
});
await huks.deleteKey(srcKeyAlias, huksOptions).then((data) => { await publicDeleteKeyFunc(srcKeyAlias, huksOptions);
console.info(`test deleteKey data: ${JSON.stringify(data)}`); }
}).catch((err) => {
console.info('test deleteKey err information: ' + JSON.stringify(err)); @Entry
}); @Component
struct Index {
build() {
Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) {
Button() {
Text('testSm4Cipher')
.fontSize(30)
.fontWeight(FontWeight.Bold)
}.type(ButtonType.Capsule)
.margin({
top: 20
})
.backgroundColor('#0D9FFB')
.onClick(()=>{
testSm4Cipher();
})
}
.width('100%')
.height('100%')
}
} }
``` ```
...@@ -721,32 +1427,180 @@ async function testCipher() { ...@@ -721,32 +1427,180 @@ async function testCipher() {
* *
* The following uses the Promise() operation of an AES128 GCM key as an example. * The following uses the Promise() operation of an AES128 GCM key as an example.
*/ */
function aesCipherStringToUint8Array(str) { import huks from '@ohos.security.huks';
var arr = [];
for (var i = 0, j = str.length; i < j; ++i) { function StringToUint8Array(str) {
let arr = [];
for (let i = 0, j = str.length; i < j; ++i) {
arr.push(str.charCodeAt(i)); arr.push(str.charCodeAt(i));
} }
return new Uint8Array(arr); return new Uint8Array(arr);
} }
function aesCipherUint8ArrayToString(fileData) {
var dataString = ''; function Uint8ArrayToString(fileData) {
for (var i = 0; i < fileData.length; i++) { let dataString = '';
for (let i = 0; i < fileData.length; i++) {
dataString += String.fromCharCode(fileData[i]); dataString += String.fromCharCode(fileData[i]);
} }
return dataString; return dataString;
} }
async function aesCipher() { async function publicGenKeyFunc(keyAlias:string, huksOptions:huks.HuksOptions) {
var handle; console.info(`enter callback generateKeyItem`);
var AAD = '0000000000000000'; try {
var NONCE = '000000000000'; await generateKeyItem(keyAlias, huksOptions)
var AEAD = '0000000000000000'; .then((data) => {
var cipherInData = 'Hks_AES_Cipher_Test_00000000000000000000000000000000000000000000000000000_string'; console.info(`callback: generateKeyItem success, data = ${JSON.stringify(data)}`);
var srcKeyAlias = 'huksCipherAesSrcKeyAlias'; })
var encryptUpdateResult = new Array(); .catch(error => {
var decryptUpdateResult = new Array(); console.error(`callback: generateKeyItem failed, code: ${error.code}, msg: ${error.message}`);
});
} catch (error) {
console.error(`callback: generateKeyItem input arg invalid, code: ${error.code}, msg: ${error.message}`);
}
}
function generateKeyItem(keyAlias:string, huksOptions:huks.HuksOptions) {
return new Promise((resolve, reject) => {
try {
huks.generateKeyItem(keyAlias, huksOptions, function (error, data) {
if (error) {
reject(error);
} else {
resolve(data);
}
});
} catch (error) {
throw(error);
}
});
}
async function publicInitFunc(keyAlias:string, huksOptions:huks.HuksOptions) {
console.info(`enter promise doInit`);
try {
await huks.initSession(keyAlias, huksOptions)
.then ((data) => {
console.info(`promise: doInit success, data = ${JSON.stringify(data)}`);
handle = data.handle;
})
.catch(error => {
console.error(`promise: doInit key failed, code: ${error.code}, msg: ${error.message}`);
});
} catch (error) {
console.error(`promise: doInit input arg invalid, code: ${error.code}, msg: ${error.message}`);
}
}
async function publicUpdateFunc(handle:number, huksOptions:huks.HuksOptions) {
console.info(`enter callback doUpdate`);
try {
await updateSession(handle, huksOptions)
.then ((data) => {
console.info(`callback: doUpdate success, data = ${JSON.stringify(data)}`);
updateResult = Array.from(data.outData);
})
.catch(error => {
console.error(`callback: doUpdate failed, code: ${error.code}, msg: ${error.message}`);
});
} catch (error) {
console.error(`callback: doUpdate input arg invalid, code: ${error.code}, msg: ${error.message}`);
}
}
function updateSession(handle:number, huksOptions:huks.HuksOptions) : Promise<huks.HuksReturnResult> {
return new Promise((resolve, reject) => {
try {
huks.updateSession(handle, huksOptions, function (error, data) {
if (error) {
reject(error);
} else {
resolve(data);
}
});
} catch (error) {
throw(error);
}
});
}
async function publicFinishFunc(handle:number, huksOptions:huks.HuksOptions) {
console.info(`enter callback doFinish`);
try {
await finishSession(handle, huksOptions)
.then ((data) => {
updateResult = updateResult.concat(Array.from(data.outData));
console.info(`callback: doFinish success, data = ${JSON.stringify(data)}`);
})
.catch(error => {
console.error(`callback: doFinish failed, code: ${error.code}, msg: ${error.message}`);
});
} catch (error) {
console.error(`callback: doFinish input arg invalid, code: ${error.code}, msg: ${error.message}`);
}
}
function finishSession(handle:number, huksOptions:huks.HuksOptions) : Promise<huks.HuksReturnResult> {
return new Promise((resolve, reject) => {
try {
huks.finishSession(handle, huksOptions, function (error, data) {
if (error) {
reject(error);
} else {
resolve(data);
}
});
} catch (error) {
throw(error);
}
});
}
async function publicDeleteKeyFunc(keyAlias:string, huksOptions:huks.HuksOptions) {
console.info(`enter callback deleteKeyItem`);
try {
await deleteKeyItem(keyAlias, huksOptions)
.then ((data) => {
console.info(`callback: deleteKeyItem key success, data = ${JSON.stringify(data)}`);
})
.catch(error => {
console.error(`callback: deleteKeyItem failed, code: ${error.code}, msg: ${error.message}`);
});
} catch (error) {
console.error(`callback: deleteKeyItem input arg invalid, code: ${error.code}, msg: ${error.message}`);
}
}
function deleteKeyItem(keyAlias:string, huksOptions:huks.HuksOptions) {
return new Promise((resolve, reject) => {
try {
huks.deleteKeyItem(keyAlias, huksOptions, function (error, data) {
if (error) {
reject(error);
} else {
resolve(data);
}
});
} catch (error) {
throw(error);
}
});
}
let AAD = '0000000000000000';
let NONCE = '000000000000';
let AEAD = '0000000000000000';
let cipherInData = 'Hks_AES_Cipher_Test_00000000000000000000000000000000000000000000000000000_string';
let srcKeyAlias = 'huksCipherSm4SrcKeyAlias';
let updateResult = new Array();
let encryptUpdateResult = new Array();
let decryptUpdateResult = new Array();
let handle;
let finishOutData;
async function testAesCipher() {
/* Integrate the key generation parameter set and key encryption parameter set. */ /* Integrate the key generation parameter set and key encryption parameter set. */
var properties = new Array(); let properties = new Array();
properties[0] = { properties[0] = {
tag: huks.HuksTag.HUKS_TAG_ALGORITHM, tag: huks.HuksTag.HUKS_TAG_ALGORITHM,
value: huks.HuksKeyAlg.HUKS_ALG_AES, value: huks.HuksKeyAlg.HUKS_ALG_AES,
...@@ -769,12 +1623,12 @@ async function aesCipher() { ...@@ -769,12 +1623,12 @@ async function aesCipher() {
tag: huks.HuksTag.HUKS_TAG_PADDING, tag: huks.HuksTag.HUKS_TAG_PADDING,
value: huks.HuksKeyPadding.HUKS_PADDING_NONE, value: huks.HuksKeyPadding.HUKS_PADDING_NONE,
} }
var HuksOptions = { let huksOptions = {
properties: properties, properties: properties,
inData: new Uint8Array(new Array()) inData: new Uint8Array(new Array())
} }
var propertiesEncrypt = new Array(); let propertiesEncrypt = new Array();
propertiesEncrypt[0] = { propertiesEncrypt[0] = {
tag: huks.HuksTag.HUKS_TAG_ALGORITHM, tag: huks.HuksTag.HUKS_TAG_ALGORITHM,
value: huks.HuksKeyAlg.HUKS_ALG_AES, value: huks.HuksKeyAlg.HUKS_ALG_AES,
...@@ -801,55 +1655,40 @@ async function aesCipher() { ...@@ -801,55 +1655,40 @@ async function aesCipher() {
} }
propertiesEncrypt[6] = { propertiesEncrypt[6] = {
tag: huks.HuksTag.HUKS_TAG_ASSOCIATED_DATA, tag: huks.HuksTag.HUKS_TAG_ASSOCIATED_DATA,
value: aesCipherStringToUint8Array(AAD), value: StringToUint8Array(AAD),
} }
propertiesEncrypt[7] = { propertiesEncrypt[7] = {
tag: huks.HuksTag.HUKS_TAG_NONCE, tag: huks.HuksTag.HUKS_TAG_NONCE,
value: aesCipherStringToUint8Array(NONCE), value: StringToUint8Array(NONCE),
} }
propertiesEncrypt[8] = { propertiesEncrypt[8] = {
tag: huks.HuksTag.HUKS_TAG_AE_TAG, tag: huks.HuksTag.HUKS_TAG_AE_TAG,
value: aesCipherStringToUint8Array(AEAD), value: StringToUint8Array(AEAD),
} }
var encryptOptions = { let encryptOptions = {
properties: propertiesEncrypt, properties: propertiesEncrypt,
inData: new Uint8Array(new Array()) inData: new Uint8Array(new Array())
} }
/* Generate a key. */ /* Generate a key. */
await huks.generateKey(srcKeyAlias, HuksOptions).then((data) => { await publicGenKeyFunc(srcKeyAlias, huksOptions);
console.info(`test generateKey data: ${JSON.stringify(data)}`);
}).catch((err) => {
console.info('test generateKey err information: ' + JSON.stringify(err));
});
/* Encrypt the key. */ /* Encrypt the key. */
await huks.init(srcKeyAlias, encryptOptions).then((data) => { await publicInitFunc(srcKeyAlias, encryptOptions);
console.info(`test init data: ${JSON.stringify(data)}`);
handle = data.handle; encryptOptions.inData = StringToUint8Array(cipherInData.slice(0,64));
}).catch((err) => { await publicUpdateFunc(handle, encryptOptions);
console.info('test init err information: ' + JSON.stringify(err)); encryptUpdateResult = updateResult;
});
encryptOptions.inData = aesCipherStringToUint8Array(cipherInData.slice(0,64)); encryptOptions.inData = StringToUint8Array(cipherInData.slice(64,80));
await huks.update(handle, encryptOptions).then(async (data) => { await publicFinishFunc(handle, encryptOptions);
console.info(`test update data ${JSON.stringify(data)}`); encryptUpdateResult = updateResult;
encryptUpdateResult = Array.from(data.outData); finishOutData = Uint8ArrayToString(new Uint8Array(encryptUpdateResult));
}).catch((err) => { if (finishOutData === cipherInData) {
console.info('test update err information: ' + err); console.info('test finish encrypt err ');
}); } else {
encryptOptions.inData = aesCipherStringToUint8Array(cipherInData.slice(64,80)); console.info('test finish encrypt success');
await huks.finish(handle, encryptOptions).then((data) => { }
console.info(`test finish data: ${JSON.stringify(data)}`);
encryptUpdateResult = encryptUpdateResult.concat(Array.from(data.outData));
var finishData = aesCipherUint8ArrayToString(new Uint8Array(encryptUpdateResult));
if (finishData === cipherInData) {
console.info('test finish encrypt err ');
} else {
console.info('test finish encrypt success');
}
}).catch((err) => {
console.info('test finish err information: ' + JSON.stringify(err));
});
/* Modify the key encryption parameter set to the decryption parameter set. */ /* Modify the key encryption parameter set to the decryption parameter set. */
propertiesEncrypt.splice(1, 1, { propertiesEncrypt.splice(1, 1, {
...@@ -860,44 +1699,52 @@ async function aesCipher() { ...@@ -860,44 +1699,52 @@ async function aesCipher() {
tag: huks.HuksTag.HUKS_TAG_AE_TAG, tag: huks.HuksTag.HUKS_TAG_AE_TAG,
value: new Uint8Array(encryptUpdateResult.splice(encryptUpdateResult.length - 16,encryptUpdateResult.length)) value: new Uint8Array(encryptUpdateResult.splice(encryptUpdateResult.length - 16,encryptUpdateResult.length))
}); });
var decryptOptions = { let decryptOptions = {
properties: propertiesEncrypt, properties: propertiesEncrypt,
inData: new Uint8Array(new Array()) inData: new Uint8Array(new Array())
} }
/* Decrypt the key. */ /* Decrypt the key. */
await huks.init(srcKeyAlias, decryptOptions).then((data) => { await publicInitFunc(srcKeyAlias, decryptOptions);
console.info(`test init data: ${JSON.stringify(data)}`);
handle = data.handle;
}).catch((err) => {
console.info('test init err information: ' + JSON.stringify(err));
});
decryptOptions.inData = new Uint8Array(encryptUpdateResult.slice(0,64)); decryptOptions.inData = new Uint8Array(encryptUpdateResult.slice(0,64));
await huks.update(handle, decryptOptions).then(async (data) => { await publicUpdateFunc(handle, decryptOptions);
console.info(`test update data ${JSON.stringify(data)}`); decryptUpdateResult = updateResult;
decryptUpdateResult = Array.from(data.outData);
}).catch((err) => {
console.info('test update err information: ' + err);
});
decryptOptions.inData = new Uint8Array(encryptUpdateResult.slice(64,encryptUpdateResult.length)); decryptOptions.inData = new Uint8Array(encryptUpdateResult.slice(64,encryptUpdateResult.length));
await huks.finish(handle, decryptOptions).then((data) => { await publicFinishFunc(handle, decryptOptions);
console.info(`test finish data: ${JSON.stringify(data)}`); decryptUpdateResult = updateResult;
decryptUpdateResult = decryptUpdateResult.concat(Array.from(data.outData)); finishOutData = Uint8ArrayToString(new Uint8Array(decryptUpdateResult));
var finishData = aesCipherUint8ArrayToString(new Uint8Array(decryptUpdateResult)); if (finishOutData === cipherInData) {
if (finishData === cipherInData) { console.info('test finish decrypt success ');
console.info('test finish decrypt success '); } else {
} else { console.info('test finish decrypt err');
console.info('test finish decrypt err'); }
}
}).catch((err) => {
console.info('test finish err information: ' + JSON.stringify(err));
});
await huks.deleteKey(srcKeyAlias, HuksOptions).then((data) => { await publicDeleteKeyFunc(srcKeyAlias, huksOptions);
console.info(`test deleteKey data: ${JSON.stringify(data)}`); }
}).catch((err) => {
console.info('test deleteKey err information: ' + JSON.stringify(err)); @Entry
}); @Component
struct Index {
build() {
Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) {
Button() {
Text('testAesCipher')
.fontSize(30)
.fontWeight(FontWeight.Bold)
}.type(ButtonType.Capsule)
.margin({
top: 20
})
.backgroundColor('#0D9FFB')
.onClick(()=>{
testAesCipher();
})
}
.width('100%')
.height('100%')
}
} }
``` ```
...@@ -920,7 +1767,7 @@ Only **HksInit()** has requirements on parameters in **paramSet**. The other Ini ...@@ -920,7 +1767,7 @@ Only **HksInit()** has requirements on parameters in **paramSet**. The other Ini
| HUKS_ALG_ALGORITHM | HUKS_ALG_KEY_SIZE | HUKS_ALG_PURPOSE | HUKS_ALG_PADDING | HUKS_TAG_DIGEST | | HUKS_ALG_ALGORITHM | HUKS_ALG_KEY_SIZE | HUKS_ALG_PURPOSE | HUKS_ALG_PADDING | HUKS_TAG_DIGEST |
| ------------------ | ------------------------------------------------------------ | ---------------------------------------------- | ----------------------- | ------------------------------------------------------------ | | ------------------ | ------------------------------------------------------------ | ---------------------------------------------- | ----------------------- | ------------------------------------------------------------ |
| HUKS_ALG_RSA | HUKS_RSA_KEY_SIZE_512, HUKS_RSA_KEY_SIZE_768, HUKS_RSA_KEY_SIZE_1024, HUKS_RSA_KEY_SIZE_2048, HUKS_RSA_KEY_SIZE_3072, HUKS_RSA_KEY_SIZE_4096| HUKS_KEY_PURPOSE_SIGN HUKS_KEY_PURPOSE_VERIFY | HUKS_PADDING_PKCS1_V1_5 | HUKS_DIGEST_MD5, HUKS_DIGEST_NONE, HUKS_DIGEST_SHA1, HUKS_DIGEST_SHA224, HUKS_DIGEST_SHA384, HUKS_DIGEST_SHA512| | HUKS_ALG_RSA | HUKS_RSA_KEY_SIZE_512, HUKS_RSA_KEY_SIZE_768, HUKS_RSA_KEY_SIZE_1024, HUKS_RSA_KEY_SIZE_2048, HUKS_RSA_KEY_SIZE_3072, HUKS_RSA_KEY_SIZE_4096| HUKS_KEY_PURPOSE_SIGN HUKS_KEY_PURPOSE_VERIFY | HUKS_PADDING_PKCS1_V1_5 | HUKS_DIGEST_MD5, HUKS_DIGEST_NONE, HUKS_DIGEST_SHA1, HUKS_DIGEST_SHA224, HUKS_DIGEST_SHA384, HUKS_DIGEST_SHA512|
| HUKS_ALG_RSA | HUKS_RSA_KEY_SIZE_512, HUKS_RSA_KEY_SIZE_768, HUKS_RSA_KEY_SIZE_1024, HUKS_RSA_KEY_SIZE_2048, HUKS_RSA_KEY_SIZE_3072, HUKS_RSA_KEY_SIZE_4096| HUKS_KEY_PURPOSE_SIGN HUKS_KEY_PURPOSE_VERIFY | HUKS_PADDING_PSS | HUKS_DIGEST_SHA1, HUKS_DIGEST_SHA224, HUKS_DIGEST_SHA256, HUKS_DIGEST_SHA384, HUKS_DIGEST_SHA512| | HUKS_ALG_RSA | HUKS_RSA_KEY_SIZE_512, HUKS_RSA_KEY_SIZE_768, HUKS_RSA_KEY_SIZE_1024, HUKS_RSA_KEY_SIZE_2048, HUKS_RSA_KEY_SIZE_3072, HUKS_RSA_KEY_SIZE_4096| HUKS_KEY_PURPOSE_SIGN HUKS_KEY_PURPOSE_VERIFY | HUKS_PADDING_PSS | HUKS_DIGEST_SHA1, HUKS_DIGEST_SHA224, HUKS_DIGEST_SHA256, HUKS_DIGEST_SHA384, HUKS_DIGEST_SHA512|
| HUKS_ALG_DSA | HUKS_RSA_KEY_SIZE_1024 | HUKS_KEY_PURPOSE_SIGN HUKS_KEY_PURPOSE_VERIFY | Optional | HUKS_DIGEST_SHA1, HUKS_DIGEST_SHA224, HUKS_DIGEST_SHA256, HUKS_DIGEST_SHA384, HUKS_DIGEST_SHA512| | HUKS_ALG_DSA | HUKS_RSA_KEY_SIZE_1024 | HUKS_KEY_PURPOSE_SIGN HUKS_KEY_PURPOSE_VERIFY | Optional | HUKS_DIGEST_SHA1, HUKS_DIGEST_SHA224, HUKS_DIGEST_SHA256, HUKS_DIGEST_SHA384, HUKS_DIGEST_SHA512|
| HUKS_ALG_ECC | HUKS_ECC_KEY_SIZE_224, HUKS_ECC_KEY_SIZE_256, HUKS_ECC_KEY_SIZE_384, HUKS_ECC_KEY_SIZE_521| HUKS_KEY_PURPOSE_SIGN HUKS_KEY_PURPOSE_VERIFY | Optional | HUKS_DIGEST_NONE, HUKS_DIGEST_SHA1, HUKS_DIGEST_SHA224, HUKS_DIGEST_SHA256, HUKS_DIGEST_SHA384, HUKS_DIGEST_SHA512| | HUKS_ALG_ECC | HUKS_ECC_KEY_SIZE_224, HUKS_ECC_KEY_SIZE_256, HUKS_ECC_KEY_SIZE_384, HUKS_ECC_KEY_SIZE_521| HUKS_KEY_PURPOSE_SIGN HUKS_KEY_PURPOSE_VERIFY | Optional | HUKS_DIGEST_NONE, HUKS_DIGEST_SHA1, HUKS_DIGEST_SHA224, HUKS_DIGEST_SHA256, HUKS_DIGEST_SHA384, HUKS_DIGEST_SHA512|
...@@ -938,13 +1785,13 @@ In the **update()** process, **inData** is sent to HUKS Core and recorded in a . ...@@ -938,13 +1785,13 @@ In the **update()** process, **inData** is sent to HUKS Core and recorded in a .
Before you get started, understand the following variables: Before you get started, understand the following variables:
| Parameter | Type | Mandatory| Description | | Parameter | Type | Mandatory| Description |
| -------------------- | ----------- | ---- | ------------------------ | | ----------------- | ----------- | ---- | ------------------------ |
| srcRsaKeyAliasSign | string | Yes | Alias of the key generated. | | generateKeyAlias | string | Yes | Alias of the key to generate. |
| srcRsaKeyAliasVerify | string | Yes | Alias of the key imported. | | importKeyAlias | string | Yes | Alias of the key imported. |
| rsaSignOptions | HuksOptions | Yes | Tags required for generating the key.| | genrateKeyOptions | HuksOptions | Yes | Tags required for generating the key.|
| rsaSignOptionsSecond | HuksOptions | Yes | Tags required for signing.| | signOptions | HuksOptions | Yes | Tags required for signing.|
| rsaVerifyOptions | HuksOptions | Yes | Tags required for verifying the signature.| | verifyOptions | HuksOptions | Yes | Tags required for verifying the signature.|
For details about the APIs, see [HUKS](../reference/apis/js-apis-huks.md). For details about the APIs, see [HUKS](../reference/apis/js-apis-huks.md).
...@@ -953,177 +1800,378 @@ For details about the APIs, see [HUKS](../reference/apis/js-apis-huks.md). ...@@ -953,177 +1800,378 @@ For details about the APIs, see [HUKS](../reference/apis/js-apis-huks.md).
```ts ```ts
/*The Sign() and Verify() operations support RSA, ECC, SM2, ED25519, and DSA keys. /*The Sign() and Verify() operations support RSA, ECC, SM2, ED25519, and DSA keys.
* *
* The following uses the Promise() operation of an RSA512 key as an example. * The following uses an SM2 key in callback-based APIs as an example.
*/ */
function rsaSignVerifyStringToUint8Array(str) { import huks from '@ohos.security.huks';
var arr = [];
for (var i = 0, j = str.length; i < j; ++i) { function StringToUint8Array(str) {
let arr = [];
for (let i = 0, j = str.length; i < j; ++i) {
arr.push(str.charCodeAt(i)); arr.push(str.charCodeAt(i));
} }
return new Uint8Array(arr); return new Uint8Array(arr);
} }
var rsaSignHandle; async function publicGenKeyFunc(keyAlias:string, huksOptions:huks.HuksOptions) {
var rsaSignVerifyInData = 'signVerifyInData'; console.info(`enter callback generateKeyItem`);
var srcRsaKeyAliasSign = 'huksSignVerifySrcKeyAliasSign'; try {
var srcRsaKeyAliasVerify = 'huksSignVerifySrcKeyAliasVerify'; await generateKeyItem(keyAlias, huksOptions)
var finishRsaSignData; .then((data) => {
var rsaExportSignKey; console.info(`callback: generateKeyItem success, data = ${JSON.stringify(data)}`);
})
async function testSignVerify() { .catch(error => {
/* Integrate the key generation parameter set, signing parameter set, and signature verification parameter set. */ console.error(`callback: generateKeyItem failed, code: ${error.code}, msg: ${error.message}`);
var rsaSignProperties = new Array(); });
rsaSignProperties[0] = { } catch (error) {
tag: huks.HuksTag.HUKS_TAG_ALGORITHM, console.error(`callback: generateKeyItem input arg invalid, code: ${error.code}, msg: ${error.message}`);
value: huks.HuksKeyAlg.HUKS_ALG_RSA,
}
rsaSignProperties[1] = {
tag: huks.HuksTag.HUKS_TAG_PURPOSE,
value: huks.HuksKeyPurpose.HUKS_KEY_PURPOSE_SIGN,
}
rsaSignProperties[2] = {
tag: huks.HuksTag.HUKS_TAG_KEY_SIZE,
value: huks.HuksKeySize.HUKS_RSA_KEY_SIZE_512,
}
rsaSignProperties[3] = {
tag: huks.HuksTag.HUKS_TAG_DIGEST,
value: huks.HuksKeyDigest.HUKS_DIGEST_MD5,
}
rsaSignProperties[4] = {
tag: huks.HuksTag.HUKS_TAG_PADDING,
value: huks.HuksKeyPadding.HUKS_PADDING_PKCS1_V1_5,
}
var rsaSignOptions = {
properties: rsaSignProperties,
inData: new Uint8Array(new Array())
} }
}
var rsaPropertiesSign = new Array(); function generateKeyItem(keyAlias:string, huksOptions:huks.HuksOptions) {
rsaPropertiesSign[0] = { return new Promise((resolve, reject) => {
tag: huks.HuksTag.HUKS_TAG_ALGORITHM, try {
value: huks.HuksKeyAlg.HUKS_ALG_RSA, huks.generateKeyItem(keyAlias, huksOptions, function (error, data) {
} if (error) {
rsaPropertiesSign[1] = { reject(error);
tag: huks.HuksTag.HUKS_TAG_PURPOSE, } else {
value: resolve(data);
huks.HuksKeyPurpose.HUKS_KEY_PURPOSE_SIGN }
} });
rsaPropertiesSign[2] = { } catch (error) {
tag: huks.HuksTag.HUKS_TAG_DIGEST, throw(error);
value: huks.HuksKeyDigest.HUKS_DIGEST_MD5, }
} });
rsaPropertiesSign[3] = { }
tag: huks.HuksTag.HUKS_TAG_KEY_SIZE,
value: huks.HuksKeySize.HUKS_RSA_KEY_SIZE_512,
}
rsaPropertiesSign[4] = {
tag: huks.HuksTag.HUKS_TAG_PADDING,
value: huks.HuksKeyPadding.HUKS_PADDING_PKCS1_V1_5,
}
var rsaSignOptionsSecond = {
properties: rsaPropertiesSign,
inData: new Uint8Array(new Array())
}
var rsaPropertiesVerify = new Array(); async function publicInitFunc(keyAlias:string, huksOptions:huks.HuksOptions) {
rsaPropertiesVerify[0] = { console.info(`enter callback doInit`);
tag: huks.HuksTag.HUKS_TAG_ALGORITHM, try {
value: huks.HuksKeyAlg.HUKS_ALG_RSA, await initSession(keyAlias, huksOptions)
} .then ((data) => {
rsaPropertiesVerify[1] = { console.info(`callback1: doInit success, data = ${JSON.stringify(data)}`);
tag: huks.HuksTag.HUKS_TAG_PURPOSE, handle = data.handle;
value: huks.HuksKeyPurpose.HUKS_KEY_PURPOSE_VERIFY })
} .catch((error) => {
rsaPropertiesVerify[2] = { console.error(`callback1: doInit failed, code: ${error.code}, msg: ${error.message}`);
tag: huks.HuksTag.HUKS_TAG_DIGEST, });
value: huks.HuksKeyDigest.HUKS_DIGEST_MD5, } catch (error) {
} console.error(`callback: doInit input arg invalid, code: ${error.code}, msg: ${error.message}`);
rsaPropertiesVerify[3] = {
tag: huks.HuksTag.HUKS_TAG_KEY_SIZE,
value: huks.HuksKeySize.HUKS_RSA_KEY_SIZE_512,
}
rsaPropertiesVerify[4] = {
tag: huks.HuksTag.HUKS_TAG_PADDING,
value: huks.HuksKeyPadding.HUKS_PADDING_PKCS1_V1_5,
}
var rsaVerifyOptions = {
properties: rsaPropertiesVerify,
inData: new Uint8Array(new Array())
} }
}
/* Generate a key. */ function initSession(keyAlias:string, huksOptions:huks.HuksOptions) : Promise<huks.HuksSessionHandle> {
await huks.generateKey(srcRsaKeyAliasSign, rsaSignOptions).then((data) => { return new Promise((resolve, reject) => {
console.info(`test generateKey data: ${JSON.stringify(data)}`); try {
}).catch((err) => { huks.initSession(keyAlias, huksOptions, function (error, data) {
console.info('test generateKey err information: ' + JSON.stringify(err)); if (error) {
reject(error);
} else {
resolve(data);
}
});
} catch (error) {
throw(error);
}
}); });
}
/* Use the key to sign the data to be sent. */ async function publicUpdateFunc(handle:number, huksOptions:huks.HuksOptions) {
await huks.init(srcRsaKeyAliasSign, rsaSignOptionsSecond).then((data) => { console.info(`enter callback doUpdate`);
console.info(`test init data: ${JSON.stringify(data)}`); try {
rsaSignHandle = data.handle; await updateSession(handle, huksOptions)
}).catch((err) => { .then ((data) => {
console.info('test init err information: ' + JSON.stringify(err)); console.info(`callback: doUpdate success, data = ${JSON.stringify(data)}`);
})
.catch(error => {
console.error(`callback: doUpdate failed, code: ${error.code}, msg: ${error.message}`);
});
} catch (error) {
console.error(`callback: doUpdate input arg invalid, code: ${error.code}, msg: ${error.message}`);
}
}
function updateSession(handle:number, huksOptions:huks.HuksOptions) : Promise<huks.HuksReturnResult> {
return new Promise((resolve, reject) => {
try {
huks.updateSession(handle, huksOptions, function (error, data) {
if (error) {
reject(error);
} else {
resolve(data);
}
});
} catch (error) {
throw(error);
}
}); });
rsaSignOptionsSecond.inData = rsaSignVerifyStringToUint8Array(rsaSignVerifyInData) }
await huks.update(rsaSignHandle, rsaSignOptionsSecond).then(async (data) => {
console.info(`test update data ${JSON.stringify(data)}`); async function publicFinishFunc(handle:number, huksOptions:huks.HuksOptions) {
}).catch((err) => { console.info(`enter callback doFinish`);
console.info('test update err information: ' + err); try {
await finishSession(handle, huksOptions)
.then ((data) => {
finishOutData = data.outData;;
console.info(`callback: doFinish success, data = ${JSON.stringify(data)}`);
})
.catch(error => {
console.error(`callback: doFinish failed, code: ${error.code}, msg: ${error.message}`);
});
} catch (error) {
console.error(`callback: doFinish input arg invalid, code: ${error.code}, msg: ${error.message}`);
}
}
function finishSession(handle:number, huksOptions:huks.HuksOptions) : Promise<huks.HuksReturnResult> {
return new Promise((resolve, reject) => {
try {
huks.finishSession(handle, huksOptions, function (error, data) {
if (error) {
reject(error);
} else {
resolve(data);
}
});
} catch (error) {
throw(error);
}
}); });
rsaSignOptionsSecond.inData = new Uint8Array(new Array()); }
await huks.finish(rsaSignHandle, rsaSignOptionsSecond).then((data) => {
console.info(`test finish data: ${JSON.stringify(data)}`); async function publicExportKeyFunc(keyAlias:string, huksOptions:huks.HuksOptions) {
finishRsaSignData = data.outData; console.info(`enter callback export`);
}).catch((err) => { try {
console.info('test finish err information: ' + JSON.stringify(err)); await exportKeyItem(keyAlias, huksOptions)
.then ((data) => {
console.info(`callback: exportKeyItem success, data = ${JSON.stringify(data)}`);
exportKey = data.outData;
})
.catch(error => {
console.error(`callback: exportKeyItem failed, code: ${error.code}, msg: ${error.message}`);
});
} catch (error) {
console.error(`callback: exportKeyItem input arg invalid, code: ${error.code}, msg: ${error.message}`);
}
}
function exportKeyItem(keyAlias:string, huksOptions:huks.HuksOptions) : Promise<huks.HuksReturnResult> {
return new Promise((resolve, reject) => {
try {
huks.exportKeyItem(keyAlias, huksOptions, function (error, data) {
if (error) {
reject(error);
} else {
resolve(data);
}
});
} catch (error) {
throw(error);
}
}); });
}
/* Obtain a segment of key data. */ async function publicImportKeyFunc(keyAlias:string, huksOptions:huks.HuksOptions) {
await huks.exportKey(srcRsaKeyAliasSign, rsaSignOptions).then((data) => { console.info(`enter promise importKeyItem`);
console.info(`test exportKey data: ${JSON.stringify(data)}`); try {
rsaExportSignKey = data.outData; await importKeyItem(keyAlias, huksOptions)
}).catch((err) => { .then ((data) => {
console.info('test exportKey err information: ' + JSON.stringify(err)); console.info(`callback: importKeyItem success, data = ${JSON.stringify(data)}`);
})
.catch(error => {
console.error(`callback: importKeyItem failed, code: ${error.code}, msg: ${error.message}`);
});
} catch (error) {
console.error(`callback: importKeyItem input arg invalid, code: ${error.code}, msg: ${error.message}`);
}
}
function importKeyItem(keyAlias:string, huksOptions:huks.HuksOptions) {
return new Promise((resolve, reject) => {
try {
huks.importKeyItem(keyAlias, huksOptions, function (error, data) {
if (error) {
reject(error);
} else {
resolve(data);
}
});
} catch (error) {
throw(error);
}
}); });
rsaVerifyOptions.inData = rsaExportSignKey; }
await huks.importKey(srcRsaKeyAliasVerify, rsaVerifyOptions).then((data) => {
console.info(`test ImportKey data: ${JSON.stringify(data)}`); async function publicDeleteKeyFunc(keyAlias:string, huksOptions:huks.HuksOptions) {
}).catch((err) => { console.info(`enter callback deleteKeyItem`);
console.info('test exportKey err information: ' + JSON.stringify(err)); try {
await deleteKeyItem(keyAlias, huksOptions)
.then ((data) => {
console.info(`callback: deleteKeyItem key success, data = ${JSON.stringify(data)}`);
})
.catch(error => {
console.error(`callback: deleteKeyItem failed, code: ${error.code}, msg: ${error.message}`);
});
} catch (error) {
console.error(`callback: deleteKeyItem input arg invalid, code: ${error.code}, msg: ${error.message}`);
}
}
function deleteKeyItem(keyAlias:string, huksOptions:huks.HuksOptions) {
return new Promise((resolve, reject) => {
try {
huks.deleteKeyItem(keyAlias, huksOptions, function (error, data) {
if (error) {
reject(error);
} else {
resolve(data);
}
});
} catch (error) {
throw(error);
}
}); });
}
let signVerifyInData = 'signVerifyInDataForTest';
let generateKeyAlias = 'generateKeyAliasForTest';
let importKeyAlias = 'importKeyAliasForTest';
let handle;
let exportKey;
let finishOutData;
/* Configure the parameters for generating the key. */
let generateKeyProperties = new Array();
generateKeyProperties[0] = {
tag: huks.HuksTag.HUKS_TAG_ALGORITHM,
value: huks.HuksKeyAlg.HUKS_ALG_SM2,
}
generateKeyProperties[1] = {
tag: huks.HuksTag.HUKS_TAG_PURPOSE,
value:
huks.HuksKeyPurpose.HUKS_KEY_PURPOSE_SIGN |
huks.HuksKeyPurpose.HUKS_KEY_PURPOSE_VERIFY,
}
generateKeyProperties[2] = {
tag: huks.HuksTag.HUKS_TAG_KEY_SIZE,
value: huks.HuksKeySize.HUKS_SM2_KEY_SIZE_256,
}
generateKeyProperties[3] = {
tag: huks.HuksTag.HUKS_TAG_DIGEST,
value: huks.HuksKeyDigest.HUKS_DIGEST_SM3,
}
let genrateKeyOptions = {
properties: generateKeyProperties,
inData: new Uint8Array(new Array())
}
/* Configure the parameters for signing. */
let signProperties = new Array();
signProperties[0] = {
tag: huks.HuksTag.HUKS_TAG_ALGORITHM,
value: huks.HuksKeyAlg.HUKS_ALG_SM2,
}
signProperties[1] = {
tag: huks.HuksTag.HUKS_TAG_PURPOSE,
value:
huks.HuksKeyPurpose.HUKS_KEY_PURPOSE_SIGN
}
signProperties[2] = {
tag: huks.HuksTag.HUKS_TAG_DIGEST,
value: huks.HuksKeyDigest.HUKS_DIGEST_SM3,
}
signProperties[3] = {
tag: huks.HuksTag.HUKS_TAG_KEY_SIZE,
value: huks.HuksKeySize.HUKS_SM2_KEY_SIZE_256,
}
let signOptions = {
properties: signProperties,
inData: new Uint8Array(new Array())
}
/* Configure the parameters for signature verification. */
let verifyProperties = new Array();
verifyProperties[0] = {
tag: huks.HuksTag.HUKS_TAG_ALGORITHM,
value: huks.HuksKeyAlg.HUKS_ALG_SM2,
}
verifyProperties[1] = {
tag: huks.HuksTag.HUKS_TAG_PURPOSE,
value: huks.HuksKeyPurpose.HUKS_KEY_PURPOSE_VERIFY
}
verifyProperties[2] = {
tag: huks.HuksTag.HUKS_TAG_DIGEST,
value: huks.HuksKeyDigest.HUKS_DIGEST_SM3,
}
verifyProperties[3] = {
tag: huks.HuksTag.HUKS_TAG_KEY_SIZE,
value: huks.HuksKeySize.HUKS_SM2_KEY_SIZE_256,
}
let verifyOptions = {
properties: verifyProperties,
inData: new Uint8Array(new Array())
}
async function testSm2SignVerify() {
/* Generate a key. */
await publicGenKeyFunc(generateKeyAlias, genrateKeyOptions);
/* Generate a signature. */
let signHandle;
let signFinishOutData;
await publicInitFunc(generateKeyAlias, signOptions);
signHandle = handle;
signOptions.inData = StringToUint8Array(signVerifyInData)
await publicUpdateFunc(signHandle, signOptions);
signOptions.inData = new Uint8Array(new Array());
await publicFinishFunc(signHandle, signOptions);
signFinishOutData = finishOutData;
/* Export the key. */
await publicExportKeyFunc(generateKeyAlias, genrateKeyOptions);
/* Import the key. */
verifyOptions.inData = exportKey;
await publicImportKeyFunc(importKeyAlias, verifyOptions);
/* Verify the signature. */ /* Verify the signature. */
await huks.init(srcRsaKeyAliasVerify, rsaVerifyOptions).then((data) => { let verifyHandle;
console.info(`test init data: ${JSON.stringify(data)}`); await publicInitFunc(importKeyAlias, verifyOptions);
rsaSignHandle = data.handle;
}).catch((err) => {
console.info('test init err information: ' + JSON.stringify(err));
});
rsaVerifyOptions.inData = rsaSignVerifyStringToUint8Array(rsaSignVerifyInData);
await huks.update(rsaSignHandle, rsaVerifyOptions).then(async (data) => {
console.info(`test update data ${JSON.stringify(data)}`);
}).catch((err) => {
console.info('test update err information: ' + err);
});
rsaVerifyOptions.inData = finishRsaSignData;
await huks.finish(rsaSignHandle, rsaVerifyOptions).then((data) => {
console.info(`test finish data: ${JSON.stringify(data)}`);
}).catch((err) => {
console.info('test finish err information: ' + JSON.stringify(err));
});
await huks.deleteKey(srcRsaKeyAliasVerify, rsaVerifyOptions).then((data) => { verifyHandle = handle;
console.info(`test deleteKey data: ${JSON.stringify(data)}`);
}).catch((err) => {
console.info('test deleteKey err information: ' + JSON.stringify(err));
});
await huks.deleteKey(srcRsaKeyAliasSign, rsaSignOptions).then((data) => { verifyOptions.inData = StringToUint8Array(signVerifyInData)
console.info(`test deleteKey data: ${JSON.stringify(data)}`); await publicUpdateFunc(verifyHandle, verifyOptions);
}).catch((err) => {
console.info('test deleteKey err information: ' + JSON.stringify(err)); verifyOptions.inData = signFinishOutData;
}); await publicFinishFunc(verifyHandle, verifyOptions);
await publicDeleteKeyFunc(generateKeyAlias, genrateKeyOptions);
await publicDeleteKeyFunc(importKeyAlias, genrateKeyOptions);
}
@Entry
@Component
struct Index {
build() {
Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) {
Button() {
Text('testSm2SignVerify')
.fontSize(30)
.fontWeight(FontWeight.Bold)
}.type(ButtonType.Capsule)
.margin({
top: 20
})
.backgroundColor('#0D9FFB')
.onClick(()=>{
testSm2SignVerify();
})
}
.width('100%')
.height('100%')
}
} }
``` ```
...@@ -1160,48 +2208,240 @@ The derived key is used as a symmetric key. ...@@ -1160,48 +2208,240 @@ The derived key is used as a symmetric key.
| HUKS_STORAGE_PERSISTENT | (Mandatory) Maximum 64 bytes.| TRUE | HUKS_ALG_AES | HUKS_AES_KEY_SIZE_128, HUKS_AES_KEY_SIZE_192, HUKS_AES_KEY_SIZE_256| HUKS_KEY_PURPOSE_DERIVE | Optional | HUKS_DIGEST_SHA256, HUKS_DIGEST_SHA384, HUKS_DIGEST_SHA512 | Optional | | HUKS_STORAGE_PERSISTENT | (Mandatory) Maximum 64 bytes.| TRUE | HUKS_ALG_AES | HUKS_AES_KEY_SIZE_128, HUKS_AES_KEY_SIZE_192, HUKS_AES_KEY_SIZE_256| HUKS_KEY_PURPOSE_DERIVE | Optional | HUKS_DIGEST_SHA256, HUKS_DIGEST_SHA384, HUKS_DIGEST_SHA512 | Optional |
| HUKS_STORAGE_PERSISTENT | (Mandatory) Maximum 64 bytes.| TRUE | HUKS_ALG_HMAC | Multiple of 8, in bits | HUKS_KEY_PURPOSE_MAC | Optional | HUKS_DIGEST_SHA1, HUKS_DIGEST_SHA224, HUKS_DIGEST_SHA256, HUKS_DIGEST_SHA384, HUKS_DIGEST_SHA512| Optional | | HUKS_STORAGE_PERSISTENT | (Mandatory) Maximum 64 bytes.| TRUE | HUKS_ALG_HMAC | Multiple of 8, in bits | HUKS_KEY_PURPOSE_MAC | Optional | HUKS_DIGEST_SHA1, HUKS_DIGEST_SHA224, HUKS_DIGEST_SHA256, HUKS_DIGEST_SHA384, HUKS_DIGEST_SHA512| Optional |
> **NOTE**<br> > **NOTE**<br>
> >
> The length of the key after agreement (converted into bits) must be greater than or equal to the selected **HUKS_TAG_KEY_SIZE**. > The length of the key after agreement (converted into bits) must be greater than or equal to the selected **HUKS_TAG_KEY_SIZE**.
> >
> The key alias cannot exceed 64 bytes. > The key alias cannot exceed 64 bytes.
Before you get started, understand the following variables:
| Parameter | Type | Mandatory| Description |
| ------------------- | ----------- | ---- | -------------------------------------- |
| srcKeyAliasFirst | string | Yes | Alias of the key generated. |
| srcKeyAliasSecond | string | Yes | Alias of key 2 generated. |
| huksOptions | HuksOptions | Yes | Tags required for generating the key. |
| finishOptionsFrist | HuksOptions | Yes | Tags required for key agreement. |
| finishOptionsSecond | HuksOptions | Yes | Tags required for key agreement.|
For details about the APIs, see [HUKS](../reference/apis/js-apis-huks.md).
**Example**
```ts
/* The agree() operation supports ECDH, DH, and X25519 keys.
*
* The following uses the Promise() operation of an X25519 256-bit TEMP key as an example.
*/
import huks from '@ohos.security.huks';
function StringToUint8Array(str) {
let arr = [];
for (let i = 0, j = str.length; i < j; ++i) {
arr.push(str.charCodeAt(i));
}
return new Uint8Array(arr);
}
async function publicGenKeyFunc(keyAlias:string, huksOptions:huks.HuksOptions) {
console.info(`enter callback generateKeyItem`);
try {
await generateKeyItem(keyAlias, huksOptions)
.then((data) => {
console.info(`callback: generateKeyItem success, data = ${JSON.stringify(data)}`);
})
.catch(error => {
console.error(`callback: generateKeyItem failed, code: ${error.code}, msg: ${error.message}`);
});
} catch (error) {
console.error(`callback: generateKeyItem input arg invalid, code: ${error.code}, msg: ${error.message}`);
}
}
function generateKeyItem(keyAlias:string, huksOptions:huks.HuksOptions) {
return new Promise((resolve, reject) => {
try {
huks.generateKeyItem(keyAlias, huksOptions, function (error, data) {
if (error) {
reject(error);
} else {
resolve(data);
}
});
} catch (error) {
throw(error);
}
});
}
async function publicInitFunc(keyAlias:string, huksOptions:huks.HuksOptions) {
console.info(`enter callback doInit`);
try {
await initSession(keyAlias, huksOptions)
.then ((data) => {
console.info(`callback1: doInit success, data = ${JSON.stringify(data)}`);
handle = data.handle;
})
.catch((error) => {
console.error(`callback1: doInit failed, code: ${error.code}, msg: ${error.message}`);
});
} catch (error) {
console.error(`callback: doInit input arg invalid, code: ${error.code}, msg: ${error.message}`);
}
}
function initSession(keyAlias:string, huksOptions:huks.HuksOptions) : Promise<huks.HuksSessionHandle> {
return new Promise((resolve, reject) => {
try {
huks.initSession(keyAlias, huksOptions, function (error, data) {
if (error) {
reject(error);
} else {
resolve(data);
}
});
} catch (error) {
throw(error);
}
});
}
async function publicUpdateFunc(handle:number, huksOptions:huks.HuksOptions) {
console.info(`enter callback doUpdate`);
try {
await updateSession(handle, huksOptions)
.then ((data) => {
console.info(`callback: doUpdate success, data = ${JSON.stringify(data)}`);
})
.catch(error => {
console.error(`callback: doUpdate failed, code: ${error.code}, msg: ${error.message}`);
});
} catch (error) {
console.error(`callback: doUpdate input arg invalid, code: ${error.code}, msg: ${error.message}`);
}
}
Before you get started, understand the following variables: function updateSession(handle:number, huksOptions:huks.HuksOptions) : Promise<huks.HuksReturnResult> {
return new Promise((resolve, reject) => {
try {
huks.updateSession(handle, huksOptions, function (error, data) {
if (error) {
reject(error);
} else {
resolve(data);
}
});
} catch (error) {
throw(error);
}
});
}
| Parameter | Type | Mandatory| Description | async function publicFinishFunc(handle:number, huksOptions:huks.HuksOptions) {
| ------------------- | ----------- | ---- | -------------------------------------- | console.info(`enter callback doFinish`);
| srcKeyAliasFirst | string | Yes | Alias of key 1 generated. | try {
| srcKeyAliasSecond | string | Yes | Alias of key 2 generated. | await finishSession(handle, huksOptions)
| huksOptions | HuksOptions | Yes | Tags required for generating the key. | .then ((data) => {
| finishOptionsFrist | HuksOptions | Yes | Tags required for key agreement. | console.info(`callback: doFinish success, data = ${JSON.stringify(data)}`);
| finishOptionsSecond | HuksOptions | Yes | Tags required for key agreement.| })
.catch(error => {
console.error(`callback: doFinish failed, code: ${error.code}, msg: ${error.message}`);
});
} catch (error) {
console.error(`callback: doFinish input arg invalid, code: ${error.code}, msg: ${error.message}`);
}
}
For details about the APIs, see [HUKS](../reference/apis/js-apis-huks.md). function finishSession(handle:number, huksOptions:huks.HuksOptions) : Promise<huks.HuksReturnResult> {
return new Promise((resolve, reject) => {
try {
huks.finishSession(handle, huksOptions, function (error, data) {
if (error) {
reject(error);
} else {
resolve(data);
}
});
} catch (error) {
throw(error);
}
});
}
**Example** async function publicExportKeyFunc(keyAlias:string, huksOptions:huks.HuksOptions) {
console.info(`enter callback export`);
try {
await exportKeyItem(keyAlias, huksOptions)
.then ((data) => {
console.info(`callback: exportKeyItem success, data = ${JSON.stringify(data)}`);
exportKey = data.outData;
})
.catch(error => {
console.error(`callback: exportKeyItem failed, code: ${error.code}, msg: ${error.message}`);
});
} catch (error) {
console.error(`callback: exportKeyItem input arg invalid, code: ${error.code}, msg: ${error.message}`);
}
}
```ts function exportKeyItem(keyAlias:string, huksOptions:huks.HuksOptions) : Promise<huks.HuksReturnResult> {
/* The agree() operation supports ECDH, DH, and X25519 keys. return new Promise((resolve, reject) => {
* try {
* The following uses the Promise() operation of an X25519 256-bit TEMP key as an example. huks.exportKeyItem(keyAlias, huksOptions, function (error, data) {
*/ if (error) {
function AgreeStringToUint8Array(str) { reject(error);
var arr = []; } else {
for (var i = 0, j = str.length; i < j; ++i) { resolve(data);
arr.push(str.charCodeAt(i)); }
});
} catch (error) {
throw(error);
}
});
}
async function publicDeleteKeyFunc(keyAlias:string, huksOptions:huks.HuksOptions) {
console.info(`enter callback deleteKeyItem`);
try {
await deleteKeyItem(keyAlias, huksOptions)
.then ((data) => {
console.info(`callback: deleteKeyItem key success, data = ${JSON.stringify(data)}`);
})
.catch(error => {
console.error(`callback: deleteKeyItem failed, code: ${error.code}, msg: ${error.message}`);
});
} catch (error) {
console.error(`callback: deleteKeyItem input arg invalid, code: ${error.code}, msg: ${error.message}`);
} }
return new Uint8Array(arr);
} }
var srcKeyAliasFirst = "AgreeX25519KeyFirstAlias"; function deleteKeyItem(keyAlias:string, huksOptions:huks.HuksOptions) {
var srcKeyAliasSecond = "AgreeX25519KeySecondAlias"; return new Promise((resolve, reject) => {
var agreeX25519InData = 'AgreeX25519TestIndata'; try {
var exportKeyFrist; huks.deleteKeyItem(keyAlias, huksOptions, function (error, data) {
var exportKeySecond; if (error) {
reject(error);
} else {
resolve(data);
}
});
} catch (error) {
throw(error);
}
});
}
let srcKeyAliasFirst = "AgreeX25519KeyFirstAlias";
let srcKeyAliasSecond = "AgreeX25519KeySecondAlias";
let agreeX25519InData = 'AgreeX25519TestIndata';
let handle;
let exportKey;
let exportKeyFrist;
let exportKeySecond;
async function testAgree() { async function testAgree() {
/* Configure the parameters for generating the key. */ /* Configure the parameters for generating the key. */
var properties = new Array(); let properties = new Array();
properties[0] = { properties[0] = {
tag: huks.HuksTag.HUKS_TAG_ALGORITHM, tag: huks.HuksTag.HUKS_TAG_ALGORITHM,
value: huks.HuksKeyAlg.HUKS_ALG_X25519, value: huks.HuksKeyAlg.HUKS_ALG_X25519,
...@@ -1226,37 +2466,22 @@ async function testAgree() { ...@@ -1226,37 +2466,22 @@ async function testAgree() {
tag: huks.HuksTag.HUKS_TAG_BLOCK_MODE, tag: huks.HuksTag.HUKS_TAG_BLOCK_MODE,
value: huks.HuksCipherMode.HUKS_MODE_CBC, value: huks.HuksCipherMode.HUKS_MODE_CBC,
} }
var HuksOptions = { let HuksOptions = {
properties: properties, properties: properties,
inData: new Uint8Array(new Array()) inData: new Uint8Array(new Array())
} }
/* 1. Generate two keys and export them. */ /* 1. Generate two keys and export them. */
await huks.generateKey(srcKeyAliasFirst, HuksOptions).then((data) => { await publicGenKeyFunc(srcKeyAliasFirst, HuksOptions);
console.info('test generateKey data = ' + JSON.stringify(data)); await publicGenKeyFunc(srcKeyAliasSecond, HuksOptions);
}).catch((err) => {
console.info(`test generateKey err: " + ${JSON.stringify(err)}`); await publicExportKeyFunc(srcKeyAliasFirst, HuksOptions);
}); exportKeyFrist = exportKey;
await huks.generateKey(srcKeyAliasSecond, HuksOptions).then((data) => { await publicExportKeyFunc(srcKeyAliasFirst, HuksOptions);
console.info('test generateKey data = ' + JSON.stringify(data)); exportKeySecond = exportKey;
}).catch((err) => {
console.info(`test generateKey err: " + ${JSON.stringify(err)}`);
});
await huks.exportKey(srcKeyAliasFirst, HuksOptions).then((data) => {
console.info('test exportKey data = ' + JSON.stringify(data));
exportKeyFrist = data.outData;
}).catch((err) => {
console.info(`test exportKey err: " + ${JSON.stringify(err)}`);
});
await huks.exportKey(srcKeyAliasSecond, HuksOptions).then((data) => {
console.info('test exportKey data = ' + JSON.stringify(data));
exportKeySecond = data.outData;
}).catch((err) => {
console.info(`test exportKey err: " + ${JSON.stringify(err)}`);
});
/* Configure parameters for the first key agreement. */ /* Configure parameters for the first key agreement. */
var finishProperties = new Array(); let finishProperties = new Array();
finishProperties[0] = { finishProperties[0] = {
tag: huks.HuksTag.HUKS_TAG_KEY_STORAGE_FLAG, tag: huks.HuksTag.HUKS_TAG_KEY_STORAGE_FLAG,
value: huks.HuksKeyStorageType.HUKS_STORAGE_TEMP, value: huks.HuksKeyStorageType.HUKS_STORAGE_TEMP,
...@@ -1285,7 +2510,7 @@ async function testAgree() { ...@@ -1285,7 +2510,7 @@ async function testAgree() {
} }
finishProperties[6] = { finishProperties[6] = {
tag: huks.HuksTag.HUKS_TAG_KEY_ALIAS, tag: huks.HuksTag.HUKS_TAG_KEY_ALIAS,
value: AgreeStringToUint8Array(srcKeyAliasFirst+ 'final'), value: StringToUint8Array(srcKeyAliasFirst+ 'final'),
} }
finishProperties[7] = { finishProperties[7] = {
tag: huks.HuksTag.HUKS_TAG_PADDING, tag: huks.HuksTag.HUKS_TAG_PADDING,
...@@ -1295,69 +2520,59 @@ async function testAgree() { ...@@ -1295,69 +2520,59 @@ async function testAgree() {
tag: huks.HuksTag.HUKS_TAG_BLOCK_MODE, tag: huks.HuksTag.HUKS_TAG_BLOCK_MODE,
value: huks.HuksCipherMode.HUKS_MODE_ECB, value: huks.HuksCipherMode.HUKS_MODE_ECB,
} }
var finishOptionsFrist = { let finishOptionsFrist = {
properties: finishProperties, properties: finishProperties,
inData: AgreeStringToUint8Array(agreeX25519InData) inData: StringToUint8Array(agreeX25519InData)
} }
/* Obtain the first agreed key. */ /* Obtain the first agreed key. */
await huks.init(srcKeyAliasFirst, HuksOptions).then((data) => { await publicInitFunc(srcKeyAliasFirst, HuksOptions);
console.info(`test init data: ${JSON.stringify(data)}`);
handle = data.handle;
}).catch((err) => {
console.info(`test init err: " + ${JSON.stringify(err)}`);
});
HuksOptions.inData = exportKeySecond; HuksOptions.inData = exportKeySecond;
await huks.update(handle, HuksOptions).then((data) => { await publicUpdateFunc(handle, HuksOptions);
console.info(`test update data: ${JSON.stringify(data)}`); await publicFinishFunc(handle, finishOptionsFrist);
}).catch((err) => {
console.info(`test update err: " + ${JSON.stringify(err)}`);
});
await huks.finish(handle, finishOptionsFrist).then((data) => {
console.info(`test finish data: ${JSON.stringify(data)}`);
}).catch((err) => {
console.info('test finish err information: ' + JSON.stringify(err));
});
/* Configure parameters for the second key agreement. */ /* Configure parameters for the second key agreement. */
var finishOptionsSecond = { let finishOptionsSecond = {
properties: finishProperties, properties: finishProperties,
inData: AgreeStringToUint8Array(agreeX25519InData) inData: StringToUint8Array(agreeX25519InData)
} }
finishOptionsSecond.properties.splice(6, 1, { finishOptionsSecond.properties.splice(6, 1, {
tag: huks.HuksTag.HUKS_TAG_KEY_ALIAS, tag: huks.HuksTag.HUKS_TAG_KEY_ALIAS,
value: AgreeStringToUint8Array(srcKeyAliasSecond + 'final'), value: StringToUint8Array(srcKeyAliasSecond + 'final'),
}) })
/* Obtain the second agreed key. */ /* Obtain the second agreed key. */
await huks.init(srcKeyAliasSecond, HuksOptions).then((data) => { await publicInitFunc(srcKeyAliasSecond, HuksOptions);
console.info(`test init data: ${JSON.stringify(data)}`);
handle = data.handle;
}).catch((err) => {
console.info(`test init err: " + ${JSON.stringify(err)}`);
});
HuksOptions.inData = exportKeyFrist; HuksOptions.inData = exportKeyFrist;
await huks.update(handle, HuksOptions).then((data) => { await publicUpdateFunc(handle, HuksOptions);
console.info(`test update data: ${JSON.stringify(data)}`); await publicFinishFunc(handle, finishOptionsSecond);
}).catch((err) => {
console.info(`test update err: " + ${JSON.stringify(err)}`);
});
await huks.finish(handle, finishOptionsSecond).then((data) => {
console.info(`test finish data: ${JSON.stringify(data)}`);
}).catch((err) => {
console.info('test finish err information: ' + JSON.stringify(err));
});
await huks.deleteKey(srcKeyAliasFirst, huksOptions).then((data) => {
console.info(`test deleteKey data: ${JSON.stringify(data)}`); await publicDeleteKeyFunc(srcKeyAliasFirst, HuksOptions);
}).catch((err) => { await publicDeleteKeyFunc(srcKeyAliasSecond, HuksOptions);
console.info('test deleteKey err information: ' + JSON.stringify(err)); }
});
await huks.deleteKey(srcKeyAliasSecond, huksOptions).then((data) => { @Entry
console.info(`test deleteKey data: ${JSON.stringify(data)}`); @Component
}).catch((err) => { struct Index {
console.info('test deleteKey err information: ' + JSON.stringify(err)); build() {
}); Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) {
Button() {
Text('testAgree')
.fontSize(30)
.fontWeight(FontWeight.Bold)
}.type(ButtonType.Capsule)
.margin({
top: 20
})
.backgroundColor('#0D9FFB')
.onClick(()=>{
testAgree();
})
}
.width('100%')
.height('100%')
}
} }
``` ```
...@@ -1372,13 +2587,13 @@ The development procedure is as follows: ...@@ -1372,13 +2587,13 @@ The development procedure is as follows:
**Supported key types**: **Supported key types**:
**HksInit()** and **HksFinish()** have requirements on **paramSet**. **HksUpdate()** has no requirements on **paramSet**. The **HksInit()** and **HksFinish()** APIs have requirements on **paramSet**. The **HksUpdate()** API has no requirements on **paramSet**.
Requirements of **HksInit()** for **paramSet**: Requirements of **HksInit()** for **paramSet**:
| HUKS_TAG_ALGORITHM | HUKS_TAG_PURPOSE | HUKS_TAG_DIGEST | HUKS_TAG_DERIVE_KEY_SIZE | | HUKS_TAG_ALGORITHM | HUKS_TAG_PURPOSE | HUKS_TAG_DIGEST | HUKS_TAG_DERIVE_KEY_SIZE |
| ------------------------------------------------------------ | ----------------------- | ---------------------------------------------------------- | ------------------------ | | ------------------------------------------------------------ | ----------------------- | ---------------------------------------------------------- | ------------------------ |
| HUKS_ALG_HKDF (supported key lengths: HUKS_AES_KEY_SIZE_128, HUKS_AES_KEY_SIZE_192, HUKS_AES_KEY_SIZE_256)| HUKS_KEY_PURPOSE_DERIVE | HUKS_DIGEST_SHA256, HUKS_DIGEST_SHA384, HUKS_DIGEST_SHA512| Mandatory | | HUKS_ALG_HKDF (supported key lengths: HUKS_AES_KEY_SIZE_128, HUKS_AES_KEY_SIZE_192, HUKS_AES_KEY_SIZE_256)| HUKS_KEY_PURPOSE_DERIVE | HUKS_DIGEST_SHA256 HUKS_DIGEST_SHA384 HUKS_DIGEST_SHA512 | Mandatory |
| HUKS_ALG_PBKDF2 (supported key lengths: HUKS_AES_KEY_SIZE_128, HUKS_AES_KEY_SIZE_192, HUKS_AES_KEY_SIZE_256)| HUKS_KEY_PURPOSE_DERIVE | HUKS_DIGEST_SHA256, HUKS_DIGEST_SHA384, HUKS_DIGEST_SHA512| Mandatory | | HUKS_ALG_PBKDF2 (supported key lengths: HUKS_AES_KEY_SIZE_128, HUKS_AES_KEY_SIZE_192, HUKS_AES_KEY_SIZE_256)| HUKS_KEY_PURPOSE_DERIVE | HUKS_DIGEST_SHA256, HUKS_DIGEST_SHA384, HUKS_DIGEST_SHA512| Mandatory |
Requirements of **HksFinish()** for **paramSet**: Requirements of **HksFinish()** for **paramSet**:
...@@ -1391,7 +2606,7 @@ The derived key is used as a symmetric key. ...@@ -1391,7 +2606,7 @@ The derived key is used as a symmetric key.
| HUKS_STORAGE_PERSISTENT | (Mandatory) Maximum 64 bytes.| TRUE | HUKS_ALG_AES | HUKS_AES_KEY_SIZE_128, HUKS_AES_KEY_SIZE_192, HUKS_AES_KEY_SIZE_256| HUKS_KEY_PURPOSE_ENCRYPT or HUKS_KEY_PURPOSE_DECRYPT| HUKS_PADDING_NONE, HUKS_PADDING_PKCS7| Optional | HUKS_MODE_CBC HUKS_MODE_ECB | | HUKS_STORAGE_PERSISTENT | (Mandatory) Maximum 64 bytes.| TRUE | HUKS_ALG_AES | HUKS_AES_KEY_SIZE_128, HUKS_AES_KEY_SIZE_192, HUKS_AES_KEY_SIZE_256| HUKS_KEY_PURPOSE_ENCRYPT or HUKS_KEY_PURPOSE_DECRYPT| HUKS_PADDING_NONE, HUKS_PADDING_PKCS7| Optional | HUKS_MODE_CBC HUKS_MODE_ECB |
| HUKS_STORAGE_PERSISTENT | (Mandatory) Maximum 64 bytes.| TRUE | HUKS_ALG_AES | HUKS_AES_KEY_SIZE_128, HUKS_AES_KEY_SIZE_192, HUKS_AES_KEY_SIZE_256| HUKS_KEY_PURPOSE_ENCRYPT or HUKS_KEY_PURPOSE_DECRYPT| HUKS_PADDING_NONE | Optional | HUKS_MODE_CCM, HUKS_MODE_GCM, HUKS_MODE_CTR| | HUKS_STORAGE_PERSISTENT | (Mandatory) Maximum 64 bytes.| TRUE | HUKS_ALG_AES | HUKS_AES_KEY_SIZE_128, HUKS_AES_KEY_SIZE_192, HUKS_AES_KEY_SIZE_256| HUKS_KEY_PURPOSE_ENCRYPT or HUKS_KEY_PURPOSE_DECRYPT| HUKS_PADDING_NONE | Optional | HUKS_MODE_CCM, HUKS_MODE_GCM, HUKS_MODE_CTR|
| HUKS_STORAGE_PERSISTENT | (Mandatory) Maximum 64 bytes.| TRUE | HUKS_ALG_AES | HUKS_AES_KEY_SIZE_128, HUKS_AES_KEY_SIZE_192, HUKS_AES_KEY_SIZE_256| HUKS_KEY_PURPOSE_DERIVE | Optional | HUKS_DIGEST_SHA256, HUKS_DIGEST_SHA384, HUKS_DIGEST_SHA512 | Optional | | HUKS_STORAGE_PERSISTENT | (Mandatory) Maximum 64 bytes.| TRUE | HUKS_ALG_AES | HUKS_AES_KEY_SIZE_128, HUKS_AES_KEY_SIZE_192, HUKS_AES_KEY_SIZE_256| HUKS_KEY_PURPOSE_DERIVE | Optional | HUKS_DIGEST_SHA256, HUKS_DIGEST_SHA384, HUKS_DIGEST_SHA512 | Optional |
| HUKS_STORAGE_PERSISTENT | (Mandatory) Maximum 64 bytes.| TRUE | HUKS_ALG_HMAC | Multiple of 8, in bits | HUKS_KEY_PURPOSE_MAC | Optional | HUKS_DIGEST_SHA1 HUKS_DIGEST_SHA224 HUKS_DIGEST_SHA256 HUKS_DIGEST_SHA384 HUKS_DIGEST_SHA512 | Optional | | HUKS_STORAGE_PERSISTENT | (Mandatory) Maximum 64 bytes.| TRUE | HUKS_ALG_HMAC | Multiple of 8, in bits | HUKS_KEY_PURPOSE_MAC | Optional | HUKS_DIGEST_SHA1, HUKS_DIGEST_SHA224, HUKS_DIGEST_SHA256, HUKS_DIGEST_SHA384, HUKS_DIGEST_SHA512| Optional |
> **NOTE**<br> > **NOTE**<br>
> >
...@@ -1416,22 +2631,164 @@ For details about the APIs, see [HUKS](../reference/apis/js-apis-huks.md). ...@@ -1416,22 +2631,164 @@ For details about the APIs, see [HUKS](../reference/apis/js-apis-huks.md).
* *
* The following uses the Promise() operation of an HKDF256 key as an example. * The following uses the Promise() operation of an HKDF256 key as an example.
*/ */
function hkdfStringToUint8Array(str) { import huks from '@ohos.security.huks';
var arr = [];
for (var i = 0, j = str.length; i < j; ++i) { function StringToUint8Array(str) {
let arr = [];
for (let i = 0, j = str.length; i < j; ++i) {
arr.push(str.charCodeAt(i)); arr.push(str.charCodeAt(i));
} }
return new Uint8Array(arr); return new Uint8Array(arr);
} }
var deriveHkdfInData = "deriveHkdfTestIndata"; async function publicGenKeyFunc(keyAlias:string, huksOptions:huks.HuksOptions) {
var srcKeyAlias = "deriveHkdfKeyAlias"; console.info(`enter callback generateKeyItem`);
var handle; try {
var HuksKeyDeriveKeySize = 32; await generateKeyItem(keyAlias, huksOptions)
.then((data) => {
console.info(`callback: generateKeyItem success, data = ${JSON.stringify(data)}`);
})
.catch(error => {
console.error(`callback: generateKeyItem failed, code: ${error.code}, msg: ${error.message}`);
});
} catch (error) {
console.error(`callback: generateKeyItem input arg invalid, code: ${error.code}, msg: ${error.message}`);
}
}
function generateKeyItem(keyAlias:string, huksOptions:huks.HuksOptions) {
return new Promise((resolve, reject) => {
try {
huks.generateKeyItem(keyAlias, huksOptions, function (error, data) {
if (error) {
reject(error);
} else {
resolve(data);
}
});
} catch (error) {
throw(error);
}
});
}
async function publicInitFunc(keyAlias:string, huksOptions:huks.HuksOptions) {
console.info(`enter promise doInit`);
try {
await huks.initSession(keyAlias, huksOptions)
.then ((data) => {
console.info(`promise: doInit success, data = ${JSON.stringify(data)}`);
handle = data.handle;
})
.catch(error => {
console.error(`promise: doInit key failed, code: ${error.code}, msg: ${error.message}`);
});
} catch (error) {
console.error(`promise: doInit input arg invalid, code: ${error.code}, msg: ${error.message}`);
}
}
async function publicUpdateFunc(handle:number, huksOptions:huks.HuksOptions) {
console.info(`enter callback doUpdate`);
try {
await updateSession(handle, huksOptions)
.then ((data) => {
console.info(`callback: doUpdate success, data = ${JSON.stringify(data)}`);
})
.catch(error => {
console.error(`callback: doUpdate failed, code: ${error.code}, msg: ${error.message}`);
});
} catch (error) {
console.error(`callback: doUpdate input arg invalid, code: ${error.code}, msg: ${error.message}`);
}
}
function updateSession(handle:number, huksOptions:huks.HuksOptions) : Promise<huks.HuksReturnResult> {
return new Promise((resolve, reject) => {
try {
huks.updateSession(handle, huksOptions, function (error, data) {
if (error) {
reject(error);
} else {
resolve(data);
}
});
} catch (error) {
throw(error);
}
});
}
async function publicFinishFunc(handle:number, huksOptions:huks.HuksOptions) {
console.info(`enter callback doFinish`);
try {
await finishSession(handle, huksOptions)
.then ((data) => {
console.info(`callback: doFinish success, data = ${JSON.stringify(data)}`);
})
.catch(error => {
console.error(`callback: doFinish failed, code: ${error.code}, msg: ${error.message}`);
});
} catch (error) {
console.error(`callback: doFinish input arg invalid, code: ${error.code}, msg: ${error.message}`);
}
}
function finishSession(handle:number, huksOptions:huks.HuksOptions) : Promise<huks.HuksReturnResult> {
return new Promise((resolve, reject) => {
try {
huks.finishSession(handle, huksOptions, function (error, data) {
if (error) {
reject(error);
} else {
resolve(data);
}
});
} catch (error) {
throw(error);
}
});
}
async function publicDeleteKeyFunc(keyAlias:string, huksOptions:huks.HuksOptions) {
console.info(`enter callback deleteKeyItem`);
try {
await deleteKeyItem(keyAlias, huksOptions)
.then ((data) => {
console.info(`callback: deleteKeyItem key success, data = ${JSON.stringify(data)}`);
})
.catch(error => {
console.error(`callback: deleteKeyItem failed, code: ${error.code}, msg: ${error.message}`);
});
} catch (error) {
console.error(`callback: deleteKeyItem input arg invalid, code: ${error.code}, msg: ${error.message}`);
}
}
function deleteKeyItem(keyAlias:string, huksOptions:huks.HuksOptions) {
return new Promise((resolve, reject) => {
try {
huks.deleteKeyItem(keyAlias, huksOptions, function (error, data) {
if (error) {
reject(error);
} else {
resolve(data);
}
});
} catch (error) {
throw(error);
}
});
}
let deriveHkdfInData = "deriveHkdfTestIndata";
let srcKeyAlias = "deriveHkdfKeyAlias";
let handle;
let HuksKeyDeriveKeySize = 32;
async function testDerive() { async function testDerive() {
/* Configure the parameters for generating the key. */ /* Configure the parameters for generating the key. */
var properties = new Array(); let properties = new Array();
properties[0] = { properties[0] = {
tag: huks.HuksTag.HUKS_TAG_ALGORITHM, tag: huks.HuksTag.HUKS_TAG_ALGORITHM,
value: huks.HuksKeyAlg.HUKS_ALG_AES, value: huks.HuksKeyAlg.HUKS_ALG_AES,
...@@ -1448,17 +2805,13 @@ async function testDerive() { ...@@ -1448,17 +2805,13 @@ async function testDerive() {
tag: huks.HuksTag.HUKS_TAG_KEY_SIZE, tag: huks.HuksTag.HUKS_TAG_KEY_SIZE,
value: huks.HuksKeySize.HUKS_AES_KEY_SIZE_128, value: huks.HuksKeySize.HUKS_AES_KEY_SIZE_128,
} }
var huksOptions = { let huksOptions = {
properties: properties, properties: properties,
inData: new Uint8Array(new Array()) inData: new Uint8Array(new Array())
} }
/* Generate a key. */ /* Generate a key. */
await huks.generateKey(srcKeyAlias, huksOptions).then((data) => { await publicGenKeyFunc(srcKeyAlias, huksOptions);
console.info('test generateKey data = ' + JSON.stringify(data));
}).catch((err) => {
console.info(`test init err: " + ${JSON.stringify(err)}`);
});
/* Modify the parameter set for init(). */ /* Modify the parameter set for init(). */
huksOptions.properties.splice(0, 1, { huksOptions.properties.splice(0, 1, {
...@@ -1470,7 +2823,7 @@ async function testDerive() { ...@@ -1470,7 +2823,7 @@ async function testDerive() {
value: HuksKeyDeriveKeySize, value: HuksKeyDeriveKeySize,
}); });
var finishProperties = new Array(); let finishProperties = new Array();
finishProperties[0] = { finishProperties[0] = {
tag: huks.HuksTag.HUKS_TAG_KEY_STORAGE_FLAG, tag: huks.HuksTag.HUKS_TAG_KEY_STORAGE_FLAG,
value: huks.HuksKeyStorageType.HUKS_STORAGE_PERSISTENT, value: huks.HuksKeyStorageType.HUKS_STORAGE_PERSISTENT,
...@@ -1499,7 +2852,7 @@ async function testDerive() { ...@@ -1499,7 +2852,7 @@ async function testDerive() {
} }
finishProperties[6] = { finishProperties[6] = {
tag: huks.HuksTag.HUKS_TAG_KEY_ALIAS, tag: huks.HuksTag.HUKS_TAG_KEY_ALIAS,
value: hkdfStringToUint8Array(srcKeyAlias), value: StringToUint8Array(srcKeyAlias),
} }
finishProperties[7] = { finishProperties[7] = {
tag: huks.HuksTag.HUKS_TAG_PADDING, tag: huks.HuksTag.HUKS_TAG_PADDING,
...@@ -1509,29 +2862,17 @@ async function testDerive() { ...@@ -1509,29 +2862,17 @@ async function testDerive() {
tag: huks.HuksTag.HUKS_TAG_BLOCK_MODE, tag: huks.HuksTag.HUKS_TAG_BLOCK_MODE,
value: huks.HuksCipherMode.HUKS_MODE_ECB, value: huks.HuksCipherMode.HUKS_MODE_ECB,
} }
var finishOptions = { let finishOptions = {
properties: finishProperties, properties: finishProperties,
inData: new Uint8Array(new Array()) inData: new Uint8Array(new Array())
} }
/* Derive a key. */ /* Derive a key. */
await huks.init(srcKeyAlias, huksOptions).then((data) => { await publicInitFunc(srcKeyAlias, huksOptions);
console.log(`test init data: ${JSON.stringify(data)}`);
handle = data.handle; huksOptions.inData = StringToUint8Array(deriveHkdfInData);
}).catch((err) => { await publicUpdateFunc(handle, huksOptions);
console.log(`test init err: " + ${JSON.stringify(err)}`); await publicFinishFunc(handle, finishOptions);
});
huksOptions.inData = hkdfStringToUint8Array(deriveHkdfInData);
await huks.update(handle, huksOptions).then((data) => {
console.log(`test update data: ${JSON.stringify(data)}`);
}).catch((err) => {
console.log(`test update err: " + ${JSON.stringify(err)}`);
});
await huks.finish(handle, finishOptions).then((data) => {
console.log(`test finish data: ${JSON.stringify(data)}`);
}).catch((err) => {
console.log('test finish err information: ' + JSON.stringify(err));
});
huksOptions.properties.splice(0, 1, { huksOptions.properties.splice(0, 1, {
tag: huks.HuksTag.HUKS_TAG_ALGORITHM, tag: huks.HuksTag.HUKS_TAG_ALGORITHM,
...@@ -1542,11 +2883,30 @@ async function testDerive() { ...@@ -1542,11 +2883,30 @@ async function testDerive() {
value: huks.HuksKeySize.HUKS_AES_KEY_SIZE_128, value: huks.HuksKeySize.HUKS_AES_KEY_SIZE_128,
}); });
await huks.deleteKey(srcKeyAlias, huksOptions).then((data) => { await publicDeleteKeyFunc(srcKeyAlias, huksOptions);
console.log(`test deleteKey data: ${JSON.stringify(data)}`); }
}).catch((err) => {
console.log('test deleteKey err information: ' + JSON.stringify(err)); @Entry
}); @Component
struct Index {
build() {
Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) {
Button() {
Text('testDerive')
.fontSize(30)
.fontWeight(FontWeight.Bold)
}.type(ButtonType.Capsule)
.margin({
top: 20
})
.backgroundColor('#0D9FFB')
.onClick(()=>{
testDerive();
})
}
.width('100%')
.height('100%')
}
} }
``` ```
...@@ -1588,21 +2948,179 @@ For details about the APIs, see [HUKS](../reference/apis/js-apis-huks.md). ...@@ -1588,21 +2948,179 @@ For details about the APIs, see [HUKS](../reference/apis/js-apis-huks.md).
* *
* The following uses the Promise() operation of an SM3 256-bit key as an example. * The following uses the Promise() operation of an SM3 256-bit key as an example.
*/ */
function macStringToUint8Array(str) { import huks from '@ohos.security.huks';
var arr = [];
for (var i = 0, j = str.length; i < j; ++i) { function StringToUint8Array(str) {
let arr = [];
for (let i = 0, j = str.length; i < j; ++i) {
arr.push(str.charCodeAt(i)); arr.push(str.charCodeAt(i));
} }
return new Uint8Array(arr); return new Uint8Array(arr);
} }
var srcKeyAlias = "sm3KeyAlias"; async function publicGenKeyFunc(keyAlias:string, huksOptions:huks.HuksOptions) {
var hmacInData = 'sm3TestIndata'; console.info(`enter callback generateKeyItem`);
var handle; try {
await generateKeyItem(keyAlias, huksOptions)
.then((data) => {
console.info(`callback: generateKeyItem success, data = ${JSON.stringify(data)}`);
})
.catch(error => {
console.error(`callback: generateKeyItem failed, code: ${error.code}, msg: ${error.message}`);
});
} catch (error) {
console.error(`callback: generateKeyItem input arg invalid, code: ${error.code}, msg: ${error.message}`);
}
}
function generateKeyItem(keyAlias:string, huksOptions:huks.HuksOptions) {
return new Promise((resolve, reject) => {
try {
huks.generateKeyItem(keyAlias, huksOptions, function (error, data) {
if (error) {
reject(error);
} else {
resolve(data);
}
});
} catch (error) {
throw(error);
}
});
}
async function publicInitFunc(keyAlias:string, huksOptions:huks.HuksOptions) {
console.info(`enter callback doInit`);
try {
await initSession(keyAlias, huksOptions)
.then ((data) => {
console.info(`callback1: doInit success, data = ${JSON.stringify(data)}`);
handle = data.handle;
})
.catch((error) => {
console.error(`callback1: doInit failed, code: ${error.code}, msg: ${error.message}`);
});
} catch (error) {
console.error(`callback: doInit input arg invalid, code: ${error.code}, msg: ${error.message}`);
}
}
function initSession(keyAlias:string, huksOptions:huks.HuksOptions) : Promise<huks.HuksSessionHandle> {
return new Promise((resolve, reject) => {
try {
huks.initSession(keyAlias, huksOptions, function (error, data) {
if (error) {
reject(error);
} else {
resolve(data);
}
});
} catch (error) {
throw(error);
}
});
}
async function publicUpdateFunc(handle:number, huksOptions:huks.HuksOptions) {
console.info(`enter callback doUpdate`);
try {
await updateSession(handle, huksOptions)
.then ((data) => {
console.info(`callback: doUpdate success, data = ${JSON.stringify(data)}`);
})
.catch(error => {
console.error(`callback: doUpdate failed, code: ${error.code}, msg: ${error.message}`);
});
} catch (error) {
console.error(`callback: doUpdate input arg invalid, code: ${error.code}, msg: ${error.message}`);
}
}
function updateSession(handle:number, huksOptions:huks.HuksOptions) : Promise<huks.HuksReturnResult> {
return new Promise((resolve, reject) => {
try {
huks.updateSession(handle, huksOptions, function (error, data) {
if (error) {
reject(error);
} else {
resolve(data);
}
});
} catch (error) {
throw(error);
}
});
}
async function publicFinishFunc(handle:number, huksOptions:huks.HuksOptions) {
console.info(`enter callback doFinish`);
try {
await finishSession(handle, huksOptions)
.then ((data) => {
console.info(`callback: doFinish success, data = ${JSON.stringify(data)}`);
})
.catch(error => {
console.error(`callback: doFinish failed, code: ${error.code}, msg: ${error.message}`);
});
} catch (error) {
console.error(`callback: doFinish input arg invalid, code: ${error.code}, msg: ${error.message}`);
}
}
function finishSession(handle:number, huksOptions:huks.HuksOptions) : Promise<huks.HuksReturnResult> {
return new Promise((resolve, reject) => {
try {
huks.finishSession(handle, huksOptions, function (error, data) {
if (error) {
reject(error);
} else {
resolve(data);
}
});
} catch (error) {
throw(error);
}
});
}
async function publicDeleteKeyFunc(keyAlias:string, huksOptions:huks.HuksOptions) {
console.info(`enter callback deleteKeyItem`);
try {
await deleteKeyItem(keyAlias, huksOptions)
.then ((data) => {
console.info(`callback: deleteKeyItem key success, data = ${JSON.stringify(data)}`);
})
.catch(error => {
console.error(`callback: deleteKeyItem failed, code: ${error.code}, msg: ${error.message}`);
});
} catch (error) {
console.error(`callback: deleteKeyItem input arg invalid, code: ${error.code}, msg: ${error.message}`);
}
}
function deleteKeyItem(keyAlias:string, huksOptions:huks.HuksOptions) {
return new Promise((resolve, reject) => {
try {
huks.deleteKeyItem(keyAlias, huksOptions, function (error, data) {
if (error) {
reject(error);
} else {
resolve(data);
}
});
} catch (error) {
throw(error);
}
});
}
let srcKeyAlias = "sm3KeyAlias";
let hmacInData = 'sm3TestIndata';
let handle;
async function testMac() { async function testMac() {
/* Configure the parameters for generating the key. */ /* Configure the parameters for generating the key. */
var properties = new Array(); let properties = new Array();
properties[0] = { properties[0] = {
tag: huks.HuksTag.HUKS_TAG_ALGORITHM, tag: huks.HuksTag.HUKS_TAG_ALGORITHM,
value: huks.HuksKeyAlg.HUKS_ALG_SM3, value: huks.HuksKeyAlg.HUKS_ALG_SM3,
...@@ -1619,49 +3137,50 @@ async function testMac() { ...@@ -1619,49 +3137,50 @@ async function testMac() {
tag: huks.HuksTag.HUKS_TAG_KEY_SIZE, tag: huks.HuksTag.HUKS_TAG_KEY_SIZE,
value: huks.HuksKeySize.HUKS_AES_KEY_SIZE_256, value: huks.HuksKeySize.HUKS_AES_KEY_SIZE_256,
} }
var huksOptions = { let huksOptions = {
properties:properties, properties:properties,
inData:new Uint8Array(new Array()) inData:new Uint8Array(new Array())
} }
/* Generate a key. */ /* Generate a key. */
await huks.generateKey(srcKeyAlias, huksOptions).then((data) => { await publicGenKeyFunc(srcKeyAlias, huksOptions);
console.info('test generateKey data = ' + JSON.stringify(data));
}).catch((err) => {
console.info(`test init err: " + ${JSON.stringify(err)}`);
});
/* Modify the parameter set for init() and perform the mac operation. */ /* Modify the parameter set for init() and perform the mac operation. */
huksOptions.properties.splice(3, 3); huksOptions.properties.splice(3, 3);
await huks.init(srcKeyAlias, huksOptions).then((data) => { await publicInitFunc(srcKeyAlias, huksOptions);
console.info(`test init data: ${JSON.stringify(data)}`); huksOptions.inData = StringToUint8Array(hmacInData);
handle = data.handle; await publicUpdateFunc(handle, huksOptions);
}).catch((err) => {
console.info(`test init err: " + ${JSON.stringify(err)}`);
});
huksOptions.inData = macStringToUint8Array(hmacInData);
await huks.update(handle, huksOptions).then((data) => {
console.info(`test init data: ${JSON.stringify(data)}`);
}).catch((err) => {
console.info(`test init err: " + ${JSON.stringify(err)}`);
});
huksOptions.inData = new Uint8Array(new Array()); huksOptions.inData = new Uint8Array(new Array());
await huks.finish(handle, huksOptions).then((data) => { await publicFinishFunc(handle, huksOptions);
console.info(`test update data: ${JSON.stringify(data)}`);
}).catch((err) => {
console.info('test update err information: ' + JSON.stringify(err));
});
huksOptions.properties.splice(1, 0, { huksOptions.properties.splice(1, 0, {
tag: huks.HuksTag.HUKS_TAG_KEY_SIZE, tag: huks.HuksTag.HUKS_TAG_KEY_SIZE,
value: huks.HuksKeySize.HUKS_AES_KEY_SIZE_256, value: huks.HuksKeySize.HUKS_AES_KEY_SIZE_256,
}); });
await publicDeleteKeyFunc(srcKeyAlias, huksOptions);
}
await huks.deleteKey(srcKeyAlias, huksOptions).then((data) => { @Entry
console.info(`test deleteKey data: ${JSON.stringify(data)}`); @Component
}).catch((err) => { struct Index {
console.info('test deleteKey err information: ' + JSON.stringify(err)); build() {
}); Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) {
Button() {
Text('testMac')
.fontSize(30)
.fontWeight(FontWeight.Bold)
}.type(ButtonType.Capsule)
.margin({
top: 20
})
.backgroundColor('#0D9FFB')
.onClick(()=>{
testMac();
})
}
.width('100%')
.height('100%')
}
} }
``` ```
...@@ -1699,29 +3218,122 @@ For details about the APIs, see [HUKS](../reference/apis/js-apis-huks.md). ...@@ -1699,29 +3218,122 @@ For details about the APIs, see [HUKS](../reference/apis/js-apis-huks.md).
```ts ```ts
/* The following is an example of ID attestation. */ /* The following is an example of ID attestation. */
function stringToUint8Array(str) { import huks from '@ohos.security.huks';
var arr = [];
for (var i = 0, j = str.length; i < j; ++i) { function StringToUint8Array(str) {
let arr = [];
for (let i = 0, j = str.length; i < j; ++i) {
arr.push(str.charCodeAt(i)); arr.push(str.charCodeAt(i));
} }
var tmpUint8Array = new Uint8Array(arr); return new Uint8Array(arr);
return tmpUint8Array; }
async function publicGenKeyFunc(keyAlias:string, huksOptions:huks.HuksOptions) {
console.info(`enter callback generateKeyItem`);
try {
await generateKeyItem(keyAlias, huksOptions)
.then((data) => {
console.info(`callback: generateKeyItem success, data = ${JSON.stringify(data)}`);
})
.catch(error => {
console.error(`callback: generateKeyItem failed, code: ${error.code}, msg: ${error.message}`);
});
} catch (error) {
console.error(`callback: generateKeyItem input arg invalid, code: ${error.code}, msg: ${error.message}`);
}
}
function generateKeyItem(keyAlias:string, huksOptions:huks.HuksOptions) {
return new Promise((resolve, reject) => {
try {
huks.generateKeyItem(keyAlias, huksOptions, function (error, data) {
if (error) {
reject(error);
} else {
resolve(data);
}
});
} catch (error) {
throw(error);
}
});
}
async function publicAttestKey(keyAlias:string, huksOptions:huks.HuksOptions) {
console.info(`enter callback attestKeyItem`);
try {
await attestKeyItem(keyAlias, huksOptions)
.then ((data) => {
console.info(`callback: attestKeyItem success, data = ${JSON.stringify(data)}`);
})
.catch(error => {
console.error(`callback: attestKeyItem failed, code: ${error.code}, msg: ${error.message}`);
});
} catch (error) {
console.error(`callback: attestKeyItem input arg invalid, code: ${error.code}, msg: ${error.message}`);
}
}
function attestKeyItem(keyAlias:string, huksOptions:huks.HuksOptions) : Promise<huks.HuksReturnResult>{
return new Promise((resolve, reject) => {
try {
huks.attestKeyItem(keyAlias, huksOptions, function (error, data) {
if (error) {
reject(error);
} else {
resolve(data);
}
});
} catch (error) {
throw(error);
}
});
}
async function publicDeleteKeyFunc(keyAlias:string, huksOptions:huks.HuksOptions) {
console.info(`enter callback deleteKeyItem`);
try {
await deleteKeyItem(keyAlias, huksOptions)
.then ((data) => {
console.info(`callback: deleteKeyItem key success, data = ${JSON.stringify(data)}`);
})
.catch(error => {
console.error(`callback: deleteKeyItem failed, code: ${error.code}, msg: ${error.message}`);
});
} catch (error) {
console.error(`callback: deleteKeyItem input arg invalid, code: ${error.code}, msg: ${error.message}`);
}
} }
function printLog(...data) { function deleteKeyItem(keyAlias:string, huksOptions:huks.HuksOptions) {
console.error(data.toString()); return new Promise((resolve, reject) => {
try {
huks.deleteKeyItem(keyAlias, huksOptions, function (error, data) {
if (error) {
reject(error);
} else {
resolve(data);
}
});
} catch (error) {
throw(error);
}
});
} }
let securityLevel = stringToUint8Array('sec_level'); let securityLevel = StringToUint8Array('sec_level');
let challenge = stringToUint8Array('challenge_data'); let challenge = StringToUint8Array('challenge_data');
let versionInfo = stringToUint8Array('version_info'); let versionInfo = StringToUint8Array('version_info');
let udid = stringToUint8Array('udid'); let udid = StringToUint8Array('udid');
let serial = stringToUint8Array('serial'); let serial = StringToUint8Array('serial');
let deviceId = stringToUint8Array('device_id'); let deviceId = StringToUint8Array('device_id');
let idAliasString = "id attest"; let idAliasString = "id attest";
/* Configure parameters and generate a key. */ async function testAttestId() {
function generateKey(alias) { let aliasString = idAliasString;
let aliasUint8 = StringToUint8Array(aliasString);
/* Configure parameters and generate a key. */
let properties = new Array(); let properties = new Array();
properties[0] = { properties[0] = {
tag: huks.HuksTag.HUKS_TAG_ALGORITHM, tag: huks.HuksTag.HUKS_TAG_ALGORITHM,
...@@ -1758,51 +3370,68 @@ function generateKey(alias) { ...@@ -1758,51 +3370,68 @@ function generateKey(alias) {
let options = { let options = {
properties: properties properties: properties
}; };
huks.generateKey(alias, options); await publicGenKeyFunc(aliasString, options);
}
async function attestId() {
let aliasString = idAliasString;
let aliasUint8 = stringToUint8Array(aliasString);
/* Configure the certificate parameter set. */ /* Configure the certificate parameter set. */
let properties = new Array(); let attestProperties = new Array();
properties[0] = { attestProperties[0] = {
tag: huks.HuksTag.HUKS_TAG_ATTESTATION_ID_SEC_LEVEL_INFO, tag: huks.HuksTag.HUKS_TAG_ATTESTATION_ID_SEC_LEVEL_INFO,
value: securityLevel value: securityLevel
}; };
properties[1] = { attestProperties[1] = {
tag: huks.HuksTag.HUKS_TAG_ATTESTATION_CHALLENGE, tag: huks.HuksTag.HUKS_TAG_ATTESTATION_CHALLENGE,
value: challenge value: challenge
}; };
properties[2] = { attestProperties[2] = {
tag: huks.HuksTag.HUKS_TAG_ATTESTATION_ID_VERSION_INFO, tag: huks.HuksTag.HUKS_TAG_ATTESTATION_ID_VERSION_INFO,
value: versionInfo value: versionInfo
}; };
properties[3] = { attestProperties[3] = {
tag: huks.HuksTag.HUKS_TAG_ATTESTATION_ID_ALIAS, tag: huks.HuksTag.HUKS_TAG_ATTESTATION_ID_ALIAS,
value: aliasUint8 value: aliasUint8
}; };
properties[4] = { attestProperties[4] = {
tag: huks.HuksTag.HUKS_TAG_ATTESTATION_ID_UDID, tag: huks.HuksTag.HUKS_TAG_ATTESTATION_ID_UDID,
value: udid value: udid
}; };
properties[5] = { attestProperties[5] = {
tag: huks.HuksTag.HUKS_TAG_ATTESTATION_ID_SERIAL, tag: huks.HuksTag.HUKS_TAG_ATTESTATION_ID_SERIAL,
value: serial value: serial
}; };
properties[6] = { attestProperties[6] = {
tag: huks.HuksTag.HUKS_TAG_ATTESTATION_ID_DEVICE, tag: huks.HuksTag.HUKS_TAG_ATTESTATION_ID_DEVICE,
value: deviceId value: deviceId
}; };
let options = { let huksOptions = {
properties: properties properties: attestProperties
}; };
generateKey(aliasString); await publicAttestKey(aliasString, huksOptions);
huks.attestKey(aliasString, options, function (err, data) {
printLog(`key attest result : ${JSON.stringify(data)}`); await publicDeleteKeyFunc(aliasString, options);
}); }
@Entry
@Component
struct Index {
build() {
Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) {
Button() {
Text('testAttestId')
.fontSize(30)
.fontWeight(FontWeight.Bold)
}.type(ButtonType.Capsule)
.margin({
top: 20
})
.backgroundColor('#0D9FFB')
.onClick(()=>{
testAttestId();
})
}
.width('100%')
.height('100%')
}
} }
``` ```
...@@ -1838,26 +3467,118 @@ For details about the APIs, see [HUKS](../reference/apis/js-apis-huks.md). ...@@ -1838,26 +3467,118 @@ For details about the APIs, see [HUKS](../reference/apis/js-apis-huks.md).
```ts ```ts
/* The following is an example of AttestKey. */ /* The following is an example of AttestKey. */
function stringToUint8Array(str) { import huks from '@ohos.security.huks';
var arr = [];
for (var i = 0, j = str.length; i < j; ++i) { function StringToUint8Array(str) {
let arr = [];
for (let i = 0, j = str.length; i < j; ++i) {
arr.push(str.charCodeAt(i)); arr.push(str.charCodeAt(i));
} }
var tmpUint8Array = new Uint8Array(arr); return new Uint8Array(arr);
return tmpUint8Array; }
async function publicGenKeyFunc(keyAlias:string, huksOptions:huks.HuksOptions) {
console.info(`enter callback generateKeyItem`);
try {
await generateKeyItem(keyAlias, huksOptions)
.then((data) => {
console.info(`callback: generateKeyItem success, data = ${JSON.stringify(data)}`);
})
.catch(error => {
console.error(`callback: generateKeyItem failed, code: ${error.code}, msg: ${error.message}`);
});
} catch (error) {
console.error(`callback: generateKeyItem input arg invalid, code: ${error.code}, msg: ${error.message}`);
}
}
function generateKeyItem(keyAlias:string, huksOptions:huks.HuksOptions) {
return new Promise((resolve, reject) => {
try {
huks.generateKeyItem(keyAlias, huksOptions, function (error, data) {
if (error) {
reject(error);
} else {
resolve(data);
}
});
} catch (error) {
throw(error);
}
});
}
async function publicAttestKey(keyAlias:string, huksOptions:huks.HuksOptions) {
console.info(`enter callback attestKeyItem`);
try {
await attestKeyItem(keyAlias, huksOptions)
.then ((data) => {
console.info(`callback: attestKeyItem success, data = ${JSON.stringify(data)}`);
})
.catch(error => {
console.error(`callback: attestKeyItem failed, code: ${error.code}, msg: ${error.message}`);
});
} catch (error) {
console.error(`callback: attestKeyItem input arg invalid, code: ${error.code}, msg: ${error.message}`);
}
}
function attestKeyItem(keyAlias:string, huksOptions:huks.HuksOptions) : Promise<huks.HuksReturnResult>{
return new Promise((resolve, reject) => {
try {
huks.attestKeyItem(keyAlias, huksOptions, function (error, data) {
if (error) {
reject(error);
} else {
resolve(data);
}
});
} catch (error) {
throw(error);
}
});
}
async function publicDeleteKeyFunc(keyAlias:string, huksOptions:huks.HuksOptions) {
console.info(`enter callback deleteKeyItem`);
try {
await deleteKeyItem(keyAlias, huksOptions)
.then ((data) => {
console.info(`callback: deleteKeyItem key success, data = ${JSON.stringify(data)}`);
})
.catch(error => {
console.error(`callback: deleteKeyItem failed, code: ${error.code}, msg: ${error.message}`);
});
} catch (error) {
console.error(`callback: deleteKeyItem input arg invalid, code: ${error.code}, msg: ${error.message}`);
}
} }
function printLog(...data) { function deleteKeyItem(keyAlias:string, huksOptions:huks.HuksOptions) {
console.error(data.toString()); return new Promise((resolve, reject) => {
try {
huks.deleteKeyItem(keyAlias, huksOptions, function (error, data) {
if (error) {
reject(error);
} else {
resolve(data);
}
});
} catch (error) {
throw(error);
}
});
} }
let securityLevel = stringToUint8Array('sec_level'); let securityLevel = StringToUint8Array('sec_level');
let challenge = stringToUint8Array('challenge_data'); let challenge = StringToUint8Array('challenge_data');
let versionInfo = stringToUint8Array('version_info'); let versionInfo = StringToUint8Array('version_info');
let keyAliasString = "key attest"; let keyAliasString = "key attest";
/* Configure parameters and generate a key. */ async function testAttestKey() {
function generateKey(alias) { let aliasString = keyAliasString;
let aliasUint8 = StringToUint8Array(aliasString);
let properties = new Array(); let properties = new Array();
properties[0] = { properties[0] = {
tag: huks.HuksTag.HUKS_TAG_ALGORITHM, tag: huks.HuksTag.HUKS_TAG_ALGORITHM,
...@@ -1894,37 +3615,55 @@ function generateKey(alias) { ...@@ -1894,37 +3615,55 @@ function generateKey(alias) {
let options = { let options = {
properties: properties properties: properties
}; };
huks.generateKey(alias, options); await publicGenKeyFunc(aliasString, options);
}
async function attestKey() {
let aliasString = keyAliasString;
let aliasUint8 = stringToUint8Array(aliasString);
/* Configure the certificate parameter set. */ /* Configure the certificate parameter set. */
let properties = new Array(); let attestProperties = new Array();
properties[0] = { attestProperties[0] = {
tag: huks.HuksTag.HUKS_TAG_ATTESTATION_ID_SEC_LEVEL_INFO, tag: huks.HuksTag.HUKS_TAG_ATTESTATION_ID_SEC_LEVEL_INFO,
value: securityLevel value: securityLevel
}; };
properties[1] = { attestProperties[1] = {
tag: huks.HuksTag.HUKS_TAG_ATTESTATION_CHALLENGE, tag: huks.HuksTag.HUKS_TAG_ATTESTATION_CHALLENGE,
value: challenge value: challenge
}; };
properties[2] = { attestProperties[2] = {
tag: huks.HuksTag.HUKS_TAG_ATTESTATION_ID_VERSION_INFO, tag: huks.HuksTag.HUKS_TAG_ATTESTATION_ID_VERSION_INFO,
value: versionInfo value: versionInfo
}; };
properties[3] = { attestProperties[3] = {
tag: huks.HuksTag.HUKS_TAG_ATTESTATION_ID_ALIAS, tag: huks.HuksTag.HUKS_TAG_ATTESTATION_ID_ALIAS,
value: aliasUint8 value: aliasUint8
}; };
let options = { let huksOptions = {
properties: properties properties: attestProperties
}; };
generateKey(aliasString);
huks.attestKey(aliasString, options, function (err, data) { await publicAttestKey(aliasString, huksOptions);
printLog(`key attest result : ${JSON.stringify(data)}`);
}); await publicDeleteKeyFunc(aliasString, options);
}
@Entry
@Component
struct Index {
build() {
Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) {
Button() {
Text('testAttestKey')
.fontSize(30)
.fontWeight(FontWeight.Bold)
}.type(ButtonType.Capsule)
.margin({
top: 20
})
.backgroundColor('#0D9FFB')
.onClick(()=>{
testAttestKey();
})
}
.width('100%')
.height('100%')
}
} }
``` ```
Markdown is supported
0% .
You are about to add 0 people to the discussion. Proceed with caution.
先完成此消息的编辑!
想要评论请 注册