huks-guidelines.md 116.9 KB
Newer Older
Z
zengyawen 已提交
1 2
# HUKS开发指导

Z
zhangcheng 已提交
3 4 5 6 7 8 9 10 11 12 13 14 15
HUKS(OpenHarmony Universal KeyStore,OpenHarmony通用密钥库系统)向应用提供密钥库能力,包括密钥管理及密钥的密码学操作等功能。HUKS所管理的密钥可以由应用导入或者由应用调用HUKS接口生成。 

> **说明**
>
> 本开发指导基于API version 9,仅适用于eTS语言开发

### **前提条件**

在使用HUKS的接口开发前,需要引入HUKS模块

```ts
import huks from '@ohos.security.huks'
```
Z
zhangcheng 已提交
16

Z
zhangcheng 已提交
17
### 密钥导入导出
Z
zhangcheng 已提交
18

19 20 21
HUKS支持非对称密钥的公钥导出能力,开发者可以通过密钥别名导出应用自己密钥对的公钥,只允许导出属于应用自己的密钥对的公钥。

HUKS支持密钥从外部导入的能力。密钥导入后全生命周期存在HUKS中,不能再被导出(非对称密钥的公钥除外)。 如果该别名的密钥已经存在,新导入的密钥将覆盖已经存在的密钥。 
Z
zhangcheng 已提交
22

Z
zhangcheng 已提交
23
开发步骤如下:
Z
zhangcheng 已提交
24

Z
zhangcheng 已提交
25 26 27
1. 生成密钥。
2. 导出密钥。
3. 导入密钥。
Z
zhangcheng 已提交
28

29 30 31 32 33 34 35 36 37 38 39 40
**支持导入的密钥类型:**

AES128, AES192, AES256, RSA512, RSA768, RSA1024, RSA2048, RSA3072, RSA4096, HmacSHA1, HmacSHA224, HmacSHA256, HmacSHA384, HmacSHA512, ECC224, ECC256, ECC384, ECC521, Curve25519, DSA, SM2, SM3, SM4.

**支持导出的密钥类型:**

RSA512, RSA768, RSA1024, RSA2048, RSA3072, RSA4096, ECC224, ECC256, ECC384, ECC521, Curve25519, DSA, SM2.

> **说明**
>
> 存储的 keyAlias 密钥别名最大为64字节

Z
zhangcheng 已提交
41
在使用示例前,需要先了解几个预先定义的变量: 
Z
zhangcheng 已提交
42 43 44 45 46

| 参数名            | 类型        | 必填 | 说明                     |
| ----------------- | ----------- | ---- | ------------------------ |
| srcKeyAlias       | string      | 是   | 生成密钥别名。           |
| srcKeyAliasSecond | string      | 是   | 导入密钥别名。           |
Z
zhangcheng 已提交
47
| huksOptions       | HuksOptions | 是   | 用于存放生成key所需TAG。 |
Z
zhangcheng 已提交
48 49
| encryptOptions    | HuksOptions | 是   | 用于存放导入key所需TAG。 |

Z
zhangcheng 已提交
50
关于接口的具体信息,可在[API参考文档](../reference/apis/js-apis-huks.md)中查看。
Z
zhangcheng 已提交
51 52 53

**示例:**

Z
zhangcheng 已提交
54
```ts
Z
zhangcheng 已提交
55 56 57 58
/* 以导出RSA512密钥及导入ECC256密钥为例 */
import huks from '@ohos.security.huks';

function StringToUint8Array(str) {
Z
zhangcheng 已提交
59 60
    let arr = [];
    for (let i = 0, j = str.length; i < j; ++i) {
Z
zhangcheng 已提交
61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192
        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 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)}`);
                if (data.outData !== null) {
                    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);
        }
    });
}

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

Z
zhangcheng 已提交
193 194 195 196
let srcKeyAlias = 'hukRsaKeyAlias';
let srcKeyAliasSecond = 'huksRsaKeyAliasSecond';
let exportKey;
let inputEccPair = new Uint8Array([
Z
zhangcheng 已提交
197 198 199 200 201 202 203 204
    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]);
Z
zhangcheng 已提交
205

Z
zhangcheng 已提交
206 207
async function testImportExport() {
    /* 集成生成密钥参数集 */
Z
zhangcheng 已提交
208
    let exportProperties = new Array();
Z
zhangcheng 已提交
209
    exportProperties[0] = {
Z
zhangcheng 已提交
210 211 212
        tag: huks.HuksTag.HUKS_TAG_ALGORITHM,
        value: huks.HuksKeyAlg.HUKS_ALG_RSA,
    }
Z
zhangcheng 已提交
213
    exportProperties[1] = {
Z
zhangcheng 已提交
214 215 216 217 218
        tag: huks.HuksTag.HUKS_TAG_PURPOSE,
        value:
        huks.HuksKeyPurpose.HUKS_KEY_PURPOSE_ENCRYPT |
        huks.HuksKeyPurpose.HUKS_KEY_PURPOSE_DECRYPT,
    }
Z
zhangcheng 已提交
219
    exportProperties[2] = {
Z
zhangcheng 已提交
220 221 222
        tag: huks.HuksTag.HUKS_TAG_KEY_SIZE,
        value: huks.HuksKeySize.HUKS_RSA_KEY_SIZE_512,
    }
Z
zhangcheng 已提交
223
    exportProperties[3] = {
Z
zhangcheng 已提交
224 225 226
        tag: huks.HuksTag.HUKS_TAG_BLOCK_MODE,
        value: huks.HuksCipherMode.HUKS_MODE_ECB,
    }
Z
zhangcheng 已提交
227
    exportProperties[4] = {
Z
zhangcheng 已提交
228 229 230
        tag: huks.HuksTag.HUKS_TAG_PADDING,
        value: huks.HuksKeyPadding.HUKS_PADDING_PKCS1_V1_5,
    }
Z
zhangcheng 已提交
231
    exportProperties[5] = {
Z
zhangcheng 已提交
232 233 234
        tag: huks.HuksTag.HUKS_TAG_DIGEST,
        value: huks.HuksKeyDigest.HUKS_DIGEST_SHA256,
    }
Z
zhangcheng 已提交
235
    let huksOptions = {
Z
zhangcheng 已提交
236
        properties: exportProperties,
Z
zhangcheng 已提交
237 238
        inData: new Uint8Array(new Array())
    }
Z
zhangcheng 已提交
239

Z
zhangcheng 已提交
240
    /* 生成密钥 */
Z
zhangcheng 已提交
241
    await publicGenKeyFunc(srcKeyAlias, huksOptions);
Z
zhangcheng 已提交
242 243

    /* 导出密钥 */
Z
zhangcheng 已提交
244
    await publicExportKeyFunc(srcKeyAlias, huksOptions);
Z
zhangcheng 已提交
245 246

    /* 集成导入密钥参数集 */
Z
zhangcheng 已提交
247
    let importProperties = new Array();
Z
zhangcheng 已提交
248
    importProperties[0] = {
Z
zhangcheng 已提交
249
        tag: huks.HuksTag.HUKS_TAG_ALGORITHM,
Z
zhangcheng 已提交
250 251 252
        value: huks.HuksKeyAlg.HUKS_ALG_ECC
    };
    importProperties[1] = {
Z
zhangcheng 已提交
253
        tag: huks.HuksTag.HUKS_TAG_KEY_SIZE,
Z
zhangcheng 已提交
254 255 256
        value: huks.HuksKeySize.HUKS_ECC_KEY_SIZE_256
    };
    importProperties[2] = {
Z
zhangcheng 已提交
257
        tag: huks.HuksTag.HUKS_TAG_PURPOSE,
Z
zhangcheng 已提交
258 259 260 261 262 263 264 265 266 267
        value: huks.HuksKeyPurpose.HUKS_KEY_PURPOSE_UNWRAP
    };
    importProperties[3] = {
        tag: huks.HuksTag.HUKS_TAG_DIGEST,
        value: huks.HuksKeyDigest.HUKS_DIGEST_SHA256
    };
    importProperties[4] = {
        tag: huks.HuksTag.HUKS_TAG_IMPORT_KEY_TYPE,
        value: huks.HuksImportKeyType.HUKS_KEY_TYPE_KEY_PAIR,
    };
Z
zhangcheng 已提交
268
    let importOptions = {
Z
zhangcheng 已提交
269 270 271
        properties: importProperties,
        inData: inputEccPair
    };
Z
zhangcheng 已提交
272 273

    /* 导入密钥 */
Z
zhangcheng 已提交
274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300
    await publicImportKeyFunc(srcKeyAliasSecond, importOptions);

    await publicDeleteKeyFunc(srcKeyAlias, huksOptions);
    await publicDeleteKeyFunc(srcKeyAliasSecond, importOptions);
}

@Entry
@Component
struct Index {
    build() {
        Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) {
            Button() {
                Text('testImportExport')
                    .fontSize(30)
                    .fontWeight(FontWeight.Bold)
            }.type(ButtonType.Capsule)
            .margin({
                top: 20
            })
            .backgroundColor('#0D9FFB')
            .onClick(()=>{
                testImportExport();
            })
        }
        .width('100%')
        .height('100%')
    }
Z
zhangcheng 已提交
301
}
Z
zhangcheng 已提交
302 303 304 305
```

### 安全导入

306
基于密钥协商和中间密钥二次加密的方式,业务调用方和HUKS各自协商出共享的对称密钥来对中间密钥、待导入密钥进行加解密。从而实现密文导入后,在HUKS中对导入密钥进行解密再保存。对明文密钥的处理仅在HUKS 安全环境中,保证密钥明文生命周期内不出安全环境。 
Z
zhangcheng 已提交
307 308 309

开发步骤如下:

310 311 312 313 314 315 316 317 318 319 320 321 322 323 324
1.   huks中生成用于加密导入协商的密钥。
2.  导出该密钥的公钥,协商出共享密钥。
3.  生成中间密钥材料并加密密钥。
4.  导入密钥。 

**支持的密钥类型:**

AES128, AES192, AES256, RSA512, RSA768, RSA1024, RSA2048, RSA3072, RSA4096, HmacSHA1, HmacSHA224, HmacSHA256, HmacSHA384, HmacSHA512, ECC224, ECC256, ECC384, ECC521, Curve25519, DSA, SM2, SM3, SM4.

> **注意**
>
> - 生成公共密钥时,要设置参数HUKS_TAG_PURPOSE = HUKS_KEY_PURPOSE_UNWRAP
> - 参数HUKS_TAG_IMPORT_KEY_TYPE = HUKS_KEY_TYPE_KEY_PAIR
> - 安全导入密钥时,参数集须加上参数HUKS_TAG_UNWRAP_ALGORITHM_SUITE, 值为HUKS_UNWRAP_SUITE_X25519_AES_256_GCM_NOPADDING或者HUKS_UNWRAP_SUITE_ECDH_AES_256_GCM_NOPADDING
> - 存储的 keyAlias 密钥别名最大为64字节
Z
zhangcheng 已提交
325 326 327 328 329 330 331 332 333 334

在使用示例前,需要先了解几个预先定义的变量: 

| 参数名         | 类型        | 必填 | 说明                             |
| -------------- | ----------- | ---- | -------------------------------- |
| importAlias    | string      | 是   | 密钥别名。                       |
| wrapAlias      | string      | 是   | 密钥别名。                       |
| genWrapOptions | HuksOptions | 是   | 用于存放生成加密协商key所需TAG。 |
| importOptions  | HuksOptions | 是   | 用于存放导入加密key所需TAG。     |

Z
zhangcheng 已提交
335
关于接口的具体信息,可在[API参考文档](../reference/apis/js-apis-huks.md)中查看。 
Z
zhangcheng 已提交
336 337 338 339

**示例:**

```ts
Z
zhangcheng 已提交
340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358
import huks from '@ohos.security.huks';

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)}`);
                if (data.outData !== null) {
                    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}`);
    }
}
Z
zhangcheng 已提交
359

Z
zhangcheng 已提交
360 361 362 363 364 365 366 367 368 369 370 371 372
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);
        }
Z
zhangcheng 已提交
373 374 375
    });
}

Z
zhangcheng 已提交
376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391
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) {
Z
zhangcheng 已提交
392
    return new Promise((resolve, reject) => {
Z
zhangcheng 已提交
393 394 395 396 397 398 399 400 401 402 403
        try {
            huks.importKeyItem(keyAlias, huksOptions, function (error, data) {
                if (error) {
                    reject(error);
                } else {
                    resolve(data);
                }
            });
        } catch (error) {
            throw(error);
        }
Z
zhangcheng 已提交
404 405 406
    });
}

Z
zhangcheng 已提交
407 408 409 410 411 412 413 414 415 416 417 418 419
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}`);
    }
Z
zhangcheng 已提交
420 421
}

Z
zhangcheng 已提交
422
function importWrappedKeyItem(keyAlias:string, wrappingKeyAlias:string, huksOptions:huks.HuksOptions) {
Z
zhangcheng 已提交
423
    return new Promise((resolve, reject) => {
Z
zhangcheng 已提交
424 425 426 427 428 429 430 431 432 433 434
        try {
            huks.importWrappedKeyItem(keyAlias, wrappingKeyAlias, huksOptions, function (error, data) {
                if (error) {
                    reject(error);
                } else {
                    resolve(data);
                }
            });
        } catch (error) {
            throw(error);
        }
Z
zhangcheng 已提交
435 436 437
    });
}

Z
zhangcheng 已提交
438 439 440 441 442 443 444 445 446 447 448 449
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}`);
Z
zhangcheng 已提交
450
    }
Z
zhangcheng 已提交
451
}
Z
zhangcheng 已提交
452

Z
zhangcheng 已提交
453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468
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);
        }
    });
}

Z
zhangcheng 已提交
469 470 471
let importAlias = "importAlias";
let wrapAlias = "wrappingKeyAlias";
let exportKey;
Z
zhangcheng 已提交
472

Z
zhangcheng 已提交
473
let inputEccPair = new Uint8Array([
Z
zhangcheng 已提交
474 475 476 477 478 479 480 481 482
    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]);

Z
zhangcheng 已提交
483
let properties = new Array();
Z
zhangcheng 已提交
484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503
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,
};
Z
zhangcheng 已提交
504
let huksOptions = {
Z
zhangcheng 已提交
505 506 507 508
    properties: properties,
    inData: inputEccPair
};

Z
zhangcheng 已提交
509
let importProperties = new Array();
Z
zhangcheng 已提交
510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533
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
};
Z
zhangcheng 已提交
534
let importOptions = {
Z
zhangcheng 已提交
535 536 537 538 539 540 541 542 543 544
    properties: importProperties,
    inData: new Uint8Array(new Array())
};

async function importWrappedKeyItemTest() {

    console.info(`enter ImportWrapKey test`);
    await publicImportKeyFunc(wrapAlias, huksOptions);

    await publicExportKeyFunc(wrapAlias, huksOptions);
Z
zhangcheng 已提交
545 546 547 548 549 550 551 552 553 554 555 556 557 558

    /* 以下操作不需要调用HUKS接口,此处不给出具体实现。
     * 假设待导入的密钥为keyA
     * 1.生成ECC公私钥keyB,公钥为keyB_pub, 私钥为keyB_pri
     * 2.使用keyB_pri和wrappingAlias密钥中获取的公钥进行密钥协商,协商出共享密钥share_key
     * 3.随机生成密钥kek,用于加密keyA,采用AES-GCM加密,加密过程中需要记录:nonce1/aad1/加密后的密文keyA_enc/加密后的tag1。
     * 4.使用share_key加密kek,采用AES-GCM加密,加密过程中需要记录:nonce2/aad2/加密后的密文kek_enc/加密后的tag2。
     * 5.拼接importOptions.inData字段,满足以下格式:
     * keyB_pub的长度(4字节) + keyB_pub的数据 + aad2的长度(4字节) + aad2的数据 +
     * nonce2的长度(4字节)   + nonce2的数据   + tag2的长度(4字节) + tag2的数据 +
     * kek_enc的长度(4字节)  + kek_enc的数据  + aad1的长度(4字节) + aad1的数据 +
     * nonce1的长度(4字节)   + nonce1的数据   + tag1的长度(4字节) + tag1的数据 +
     * keyA长度占用的内存长度(4字节)  + keyA的长度     + keyA_enc的长度(4字节) + keyA_enc的数据
     */
Z
zhangcheng 已提交
559
    let inputKey = new Uint8Array([
Z
zhangcheng 已提交
560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579
        0x5b, 0x00, 0x00, 0x00, 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, 0xc0,
        0xfe, 0x1c, 0x67, 0xde, 0x86, 0x0e, 0xfb, 0xaf, 0xb5, 0x85, 0x52, 0xb4, 0x0e, 0x1f, 0x6c, 0x6c,
        0xaa, 0xc5, 0xd9, 0xd2, 0x4d, 0xb0, 0x8a, 0x72, 0x24, 0xa1, 0x99, 0xaf, 0xfc, 0x3e, 0x55, 0x5a,
        0xac, 0x99, 0x3d, 0xe8, 0x34, 0x72, 0xb9, 0x47, 0x9c, 0xa6, 0xd8, 0xfb, 0x00, 0xa0, 0x1f, 0x9f,
        0x7a, 0x41, 0xe5, 0x44, 0x3e, 0xb2, 0x76, 0x08, 0xa2, 0xbd, 0xe9, 0x41, 0xd5, 0x2b, 0x9e, 0x10,
        0x00, 0x00, 0x00, 0xbf, 0xf9, 0x69, 0x41, 0xf5, 0x49, 0x85, 0x31, 0x35, 0x14, 0x69, 0x12, 0x57,
        0x9c, 0xc8, 0xb7, 0x10, 0x00, 0x00, 0x00, 0x2d, 0xb7, 0xf1, 0x5a, 0x0f, 0xb8, 0x20, 0xc5, 0x90,
        0xe5, 0xca, 0x45, 0x84, 0x5c, 0x08, 0x08, 0x10, 0x00, 0x00, 0x00, 0x43, 0x25, 0x1b, 0x2f, 0x5b,
        0x86, 0xd8, 0x87, 0x04, 0x4d, 0x38, 0xc2, 0x65, 0xcc, 0x9e, 0xb7, 0x20, 0x00, 0x00, 0x00, 0xf4,
        0xe8, 0x93, 0x28, 0x0c, 0xfa, 0x4e, 0x11, 0x6b, 0xe8, 0xbd, 0xa8, 0xe9, 0x3f, 0xa7, 0x8f, 0x2f,
        0xe3, 0xb3, 0xbf, 0xaf, 0xce, 0xe5, 0x06, 0x2d, 0xe6, 0x45, 0x5d, 0x19, 0x26, 0x09, 0xe7, 0x10,
        0x00, 0x00, 0x00, 0xf4, 0x1e, 0x7b, 0x01, 0x7a, 0x84, 0x36, 0xa4, 0xa8, 0x1c, 0x0d, 0x3d, 0xde,
        0x57, 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
    ]);
Z
zhangcheng 已提交
580 581

    importOptions.inData = inputKey;
Z
zhangcheng 已提交
582
    await publicImportWrappedKey(importAlias, wrapAlias, importOptions);
Z
zhangcheng 已提交
583

Z
zhangcheng 已提交
584 585
    await publicDeleteKeyFunc(wrapAlias, huksOptions);
    await publicDeleteKeyFunc(importAlias, importOptions);
Z
zhangcheng 已提交
586
}
Z
zhangcheng 已提交
587

Z
zhangcheng 已提交
588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608
@Entry
@Component
struct Index {
    build() {
        Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) {
            Button() {
                Text('importWrappedKeyItemTest')
                    .fontSize(30)
                    .fontWeight(FontWeight.Bold)
            }.type(ButtonType.Capsule)
            .margin({
                top: 20
            })
            .backgroundColor('#0D9FFB')
            .onClick(()=>{
                importWrappedKeyItemTest();
            })
        }
        .width('100%')
        .height('100%')
    }
Z
zhangcheng 已提交
609
}
Z
zhangcheng 已提交
610 611 612 613
```

### 密钥加解密

614
通过指定别名的方式,使用HUKS中存储的对称或非对称密钥对数据进行加密或解密运算,运算过程中密钥明文不出安全环境。
Z
zhangcheng 已提交
615 616

开发步骤如下:
Z
zhangcheng 已提交
617

Z
zhangcheng 已提交
618 619 620
1. 生成密钥。
2. 密钥加密。
3. 密钥解密。
Z
zhangcheng 已提交
621

622 623 624 625 626 627
**支持的密钥类型:**

| HUKS_ALG_ALGORITHM                                           | HUKS_TAG_PURPOSE                                   | HUKS_TAG_DIGEST                                              | HUKS_TAG_PADDING                                             | HUKS_TAG_BLOCK_MODE                         | HUKS_TAG_IV |
| ------------------------------------------------------------ | -------------------------------------------------- | ------------------------------------------------------------ | ------------------------------------------------------------ | ------------------------------------------- | ----------- |
| HUKS_ALG_SM4                  (支持长度:  HUKS_SM4_KEY_SIZE_128) | HUKS_KEY_PURPOSE_ENCRYPT  HUKS_KEY_PURPOSE_DECRYPT | 【非必选】                                                   | HUKS_PADDING_NONE                                            | HUKS_MODE_CTR  HUKS_MODE_ECB  HUKS_MODE_CBC | 【必选】    |
| HUKS_ALG_SM4                  (支持长度:  HUKS_SM4_KEY_SIZE_128) | HUKS_KEY_PURPOSE_ENCRYPT  HUKS_KEY_PURPOSE_DECRYPT | 【非必选】                                                   | HUKS_PADDING_PKCS7                                           | HUKS_MODE_ECB  HUKS_MODE_CBC                | 【必选】    |
Z
zhangcheng 已提交
628
| 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_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                               | 【非必选】  |
629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644

| 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                 (支持长度:  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                | 【必选】    | 【非必选】     | 【非必选】               | 【非必选】      |
| HUKS_ALG_AES                                                 | HUKS_KEY_PURPOSE_ENCRYPT | HUKS_PADDING_NONE                     | HUKS_MODE_CCM  HUKS_MODE_GCM | 【非必选】  | 【必选】       | 【必选】                 | 【非必选】      |
| HUKS_ALG_AES                                                 | HUKS_KEY_PURPOSE_ENCRYPT | HUKS_PADDING_NONE                     | HUKS_MODE_CTR                | 【必选】    | 【非必选】     | 【非必选】               | 【非必选】      |
| HUKS_ALG_AES                                                 | HUKS_KEY_PURPOSE_ENCRYPT | HUKS_PADDING_PKCS7  HUKS_PADDING_NONE | HUKS_MODE_ECB                | 【必选】    | 【非必选】     | 【非必选】               | 【非必选】      |
| HUKS_ALG_AES                                                 | HUKS_KEY_PURPOSE_DECRYPT | HUKS_PADDING_NONE  HUKS_PADDING_PKCS7 | HUKS_MODE_CBC                | 【必选】    | 【非必选】     | 【非必选】               | 【必选】        |
| HUKS_ALG_AES                                                 | HUKS_KEY_PURPOSE_DECRYPT | HUKS_PADDING_NONE                     | HUKS_MODE_CCM  HUKS_MODE_GCM | 【非必选】  | 【必选】       | 【必选】                 | 【非必选】      |
| HUKS_ALG_AES                                                 | HUKS_KEY_PURPOSE_DECRYPT | HUKS_PADDING_NONE                     | HUKS_MODE_CTR                | 【必选】    | 【非必选】     | 【非必选】               | 【非必选】      |
| HUKS_ALG_AES                                                 | HUKS_KEY_PURPOSE_DECRYPT | HUKS_PADDING_NONE  HUKS_PADDING_PKCS7 | HUKS_MODE_ECB                | 【必选】    | 【非必选】     | 【非必选】               | 【非必选】      |

> **说明**
>
> 存储的 keyAlias 密钥别名最大为64字节

Z
zhangcheng 已提交
645
在使用示例前,需要先了解几个预先定义的变量: 
Z
zhangcheng 已提交
646 647 648 649

| 参数名         | 类型        | 必填 | 说明                     |
| -------------- | ----------- | ---- | ------------------------ |
| srcKeyAlias    | string      | 是   | 密钥别名。               |
Z
zhangcheng 已提交
650
| huksOptions    | HuksOptions | 是   | 用于存放生成key所需TAG。 |
Z
zhangcheng 已提交
651 652 653
| encryptOptions | HuksOptions | 是   | 用于存放加密key所需TAG。 |
| decryptOptions | HuksOptions | 是   | 用于存放解密key所需TAG。 |

Z
zhangcheng 已提交
654
关于接口的具体信息,可在[API参考文档](../reference/apis/js-apis-huks.md)中查看。 
Z
zhangcheng 已提交
655

656
**示例1:**
Z
zhangcheng 已提交
657

Z
zhangcheng 已提交
658
```ts
Z
zhangcheng 已提交
659 660 661 662
/* Cipher操作支持RSA、AES、SM4类型的密钥。
 *
 * 以下以SM4 128密钥的Promise操作使用为例
 */
Z
zhangcheng 已提交
663 664 665
import huks from '@ohos.security.huks';

function StringToUint8Array(str) {
Z
zhangcheng 已提交
666 667
    let arr = [];
    for (let i = 0, j = str.length; i < j; ++i) {
Z
zhangcheng 已提交
668 669 670 671
        arr.push(str.charCodeAt(i));
    }
    return new Uint8Array(arr);
}
Z
zhangcheng 已提交
672 673

function Uint8ArrayToString(fileData) {
Z
zhangcheng 已提交
674 675
    let dataString = '';
    for (let i = 0; i < fileData.length; i++) {
Z
zhangcheng 已提交
676 677 678 679 680
        dataString += String.fromCharCode(fileData[i]);
    }
    return dataString;
}

Z
zhangcheng 已提交
681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822
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 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);
        }
    });
}

Z
zhangcheng 已提交
823 824 825 826 827 828 829
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;
Z
zhangcheng 已提交
830

Z
zhangcheng 已提交
831
async function testSm4Cipher() {
Z
zhangcheng 已提交
832
    /* 集成生成密钥参数集 & 加密参数集 */
Z
zhangcheng 已提交
833
    let properties = new Array();
Z
zhangcheng 已提交
834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855
    properties[0] = {
        tag: huks.HuksTag.HUKS_TAG_ALGORITHM,
        value: huks.HuksKeyAlg.HUKS_ALG_SM4,
    }
    properties[1] = {
        tag: huks.HuksTag.HUKS_TAG_PURPOSE,
        value:
        huks.HuksKeyPurpose.HUKS_KEY_PURPOSE_ENCRYPT |
        huks.HuksKeyPurpose.HUKS_KEY_PURPOSE_DECRYPT,
    }
    properties[2] = {
        tag: huks.HuksTag.HUKS_TAG_KEY_SIZE,
        value: huks.HuksKeySize.HUKS_SM4_KEY_SIZE_128,
    }
    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,
    }
Z
zhangcheng 已提交
856
    let huksOptions = {
Z
zhangcheng 已提交
857 858 859
        properties: properties,
        inData: new Uint8Array(new Array())
    }
Z
zhangcheng 已提交
860

Z
zhangcheng 已提交
861
    let propertiesEncrypt = new Array();
Z
zhangcheng 已提交
862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883
    propertiesEncrypt[0] = {
        tag: huks.HuksTag.HUKS_TAG_ALGORITHM,
        value: huks.HuksKeyAlg.HUKS_ALG_SM4,
    }
    propertiesEncrypt[1] = {
        tag: huks.HuksTag.HUKS_TAG_PURPOSE,
        value: huks.HuksKeyPurpose.HUKS_KEY_PURPOSE_ENCRYPT,
    }
    propertiesEncrypt[2] = {
        tag: huks.HuksTag.HUKS_TAG_KEY_SIZE,
        value: huks.HuksKeySize.HUKS_SM4_KEY_SIZE_128,
    }
    propertiesEncrypt[3] = {
        tag: huks.HuksTag.HUKS_TAG_PADDING,
        value: huks.HuksKeyPadding.HUKS_PADDING_NONE,
    }
    propertiesEncrypt[4] = {
        tag: huks.HuksTag.HUKS_TAG_BLOCK_MODE,
        value: huks.HuksCipherMode.HUKS_MODE_CBC,
    }
    propertiesEncrypt[5] = {
        tag: huks.HuksTag.HUKS_TAG_IV,
Z
zhangcheng 已提交
884
        value: StringToUint8Array(IV),
Z
zhangcheng 已提交
885
    }
Z
zhangcheng 已提交
886
    let encryptOptions = {
Z
zhangcheng 已提交
887 888 889
        properties: propertiesEncrypt,
        inData: new Uint8Array(new Array())
    }
Z
zhangcheng 已提交
890

Z
zhangcheng 已提交
891
    /* 生成密钥 */
Z
zhangcheng 已提交
892
    await publicGenKeyFunc(srcKeyAlias, huksOptions);
Z
zhangcheng 已提交
893 894

    /* 进行密钥加密操作 */
Z
zhangcheng 已提交
895 896 897 898 899 900
    await publicInitFunc(srcKeyAlias, encryptOptions);
    
    encryptOptions.inData = StringToUint8Array(cipherInData);
    await publicUpdateFunc(handle, encryptOptions);
    encryptUpdateResult = updateResult;

Z
zhangcheng 已提交
901
    encryptOptions.inData = new Uint8Array(new Array());
Z
zhangcheng 已提交
902 903 904 905 906 907
    await publicFinishFunc(handle, encryptOptions);
    if (finishOutData === cipherInData) {
        console.info('test finish encrypt err ');
    } else {
        console.info('test finish encrypt success');
    }
Z
zhangcheng 已提交
908 909 910 911 912 913

    /* 修改加密参数集为解密参数集 */
    propertiesEncrypt.splice(1, 1, {
        tag: huks.HuksTag.HUKS_TAG_PURPOSE,
        value: huks.HuksKeyPurpose.HUKS_KEY_PURPOSE_DECRYPT,
    });
Z
zhangcheng 已提交
914
    let decryptOptions = {
Z
zhangcheng 已提交
915 916
        properties: propertiesEncrypt,
        inData: new Uint8Array(new Array())
Z
zhangcheng 已提交
917 918
    }

Z
zhangcheng 已提交
919
    /* 进行解密操作 */
Z
zhangcheng 已提交
920 921
    await publicInitFunc(srcKeyAlias, decryptOptions);

Z
zhangcheng 已提交
922
    decryptOptions.inData = new Uint8Array(encryptUpdateResult);
Z
zhangcheng 已提交
923 924
    await publicUpdateFunc(handle, decryptOptions);

Z
zhangcheng 已提交
925
    decryptOptions.inData = new Uint8Array(new Array());
Z
zhangcheng 已提交
926 927 928 929 930 931
    await publicFinishFunc(handle, decryptOptions);
    if (finishOutData === cipherInData) {
        console.info('test finish decrypt success ');
    } else {
        console.info('test finish decrypt err');
    }
Z
zhangcheng 已提交
932

Z
zhangcheng 已提交
933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956
    await publicDeleteKeyFunc(srcKeyAlias, huksOptions);
}

@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%')
    }
Z
zhangcheng 已提交
957
}
Z
zhangcheng 已提交
958 959
```

960 961 962 963 964 965 966
**示例2:**

```ts
/* Cipher操作支持RSA、AES、SM4类型的密钥。
 *
 * 以下以AES128 GCM密钥的Promise操作使用为例
 */
Z
zhangcheng 已提交
967 968 969
import huks from '@ohos.security.huks';

function StringToUint8Array(str) {
Z
zhangcheng 已提交
970 971
    let arr = [];
    for (let i = 0, j = str.length; i < j; ++i) {
972 973 974 975
        arr.push(str.charCodeAt(i));
    }
    return new Uint8Array(arr);
}
Z
zhangcheng 已提交
976 977

function Uint8ArrayToString(fileData) {
Z
zhangcheng 已提交
978 979
    let dataString = '';
    for (let i = 0; i < fileData.length; i++) {
980 981 982 983 984
        dataString += String.fromCharCode(fileData[i]);
    }
    return dataString;
}

Z
zhangcheng 已提交
985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126
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 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);
        }
    });
}

Z
zhangcheng 已提交
1127 1128 1129 1130 1131 1132 1133 1134 1135 1136
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;
Z
zhangcheng 已提交
1137 1138

async function testAesCipher() {
1139
    /* 集成生成密钥参数集 & 加密参数集 */
Z
zhangcheng 已提交
1140
    let properties = new Array();
1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162
    properties[0] = {
        tag: huks.HuksTag.HUKS_TAG_ALGORITHM,
        value: huks.HuksKeyAlg.HUKS_ALG_AES,
    }
    properties[1] = {
        tag: huks.HuksTag.HUKS_TAG_PURPOSE,
        value:
        huks.HuksKeyPurpose.HUKS_KEY_PURPOSE_ENCRYPT |
        huks.HuksKeyPurpose.HUKS_KEY_PURPOSE_DECRYPT,
    }
    properties[2] = {
        tag: huks.HuksTag.HUKS_TAG_KEY_SIZE,
        value: huks.HuksKeySize.HUKS_AES_KEY_SIZE_128,
    }
    properties[3] = {
        tag: huks.HuksTag.HUKS_TAG_BLOCK_MODE,
        value: huks.HuksCipherMode.HUKS_MODE_GCM,
    }
    properties[4] = {
        tag: huks.HuksTag.HUKS_TAG_PADDING,
        value: huks.HuksKeyPadding.HUKS_PADDING_NONE,
    }
Z
zhangcheng 已提交
1163
    let huksOptions = {
1164 1165 1166 1167
        properties: properties,
        inData: new Uint8Array(new Array())
    }

Z
zhangcheng 已提交
1168
    let propertiesEncrypt = new Array();
1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194
    propertiesEncrypt[0] = {
        tag: huks.HuksTag.HUKS_TAG_ALGORITHM,
        value: huks.HuksKeyAlg.HUKS_ALG_AES,
    }
    propertiesEncrypt[1] = {
        tag: huks.HuksTag.HUKS_TAG_PURPOSE,
        value: huks.HuksKeyPurpose.HUKS_KEY_PURPOSE_ENCRYPT,
    }
    propertiesEncrypt[2] = {
        tag: huks.HuksTag.HUKS_TAG_KEY_SIZE,
        value: huks.HuksKeySize.HUKS_AES_KEY_SIZE_128,
    }
    propertiesEncrypt[3] = {
        tag: huks.HuksTag.HUKS_TAG_PADDING,
        value: huks.HuksKeyPadding.HUKS_PADDING_NONE,
    }
    propertiesEncrypt[4] = {
        tag: huks.HuksTag.HUKS_TAG_BLOCK_MODE,
        value: huks.HuksCipherMode.HUKS_MODE_GCM,
    }
    propertiesEncrypt[5] = {
        tag: huks.HuksTag.HUKS_TAG_DIGEST,
        value: huks.HuksKeyDigest.HUKS_DIGEST_NONE,
    }
    propertiesEncrypt[6] = {
        tag: huks.HuksTag.HUKS_TAG_ASSOCIATED_DATA,
Z
zhangcheng 已提交
1195
        value: StringToUint8Array(AAD),
1196 1197 1198
    }
    propertiesEncrypt[7] = {
        tag: huks.HuksTag.HUKS_TAG_NONCE,
Z
zhangcheng 已提交
1199
        value: StringToUint8Array(NONCE),
1200 1201 1202
    }
    propertiesEncrypt[8] = {
        tag: huks.HuksTag.HUKS_TAG_AE_TAG,
Z
zhangcheng 已提交
1203
        value: StringToUint8Array(AEAD),
1204
    }
Z
zhangcheng 已提交
1205
    let encryptOptions = {
1206 1207 1208 1209 1210
        properties: propertiesEncrypt,
        inData: new Uint8Array(new Array())
    }

    /* 生成密钥 */
Z
zhangcheng 已提交
1211
    await publicGenKeyFunc(srcKeyAlias, huksOptions);
1212 1213

    /* 进行密钥加密操作 */
Z
zhangcheng 已提交
1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228
    await publicInitFunc(srcKeyAlias, encryptOptions);

    encryptOptions.inData = StringToUint8Array(cipherInData.slice(0,64));
    await publicUpdateFunc(handle, encryptOptions);
    encryptUpdateResult = updateResult;

    encryptOptions.inData = StringToUint8Array(cipherInData.slice(64,80));
    await publicFinishFunc(handle, encryptOptions);
    encryptUpdateResult = updateResult;
    finishOutData = Uint8ArrayToString(new Uint8Array(encryptUpdateResult));
    if (finishOutData === cipherInData) {
        console.info('test finish encrypt err ');
    } else {
        console.info('test finish encrypt success');
    }
1229 1230 1231 1232 1233 1234 1235 1236 1237 1238

    /* 修改加密参数集为解密参数集 */
    propertiesEncrypt.splice(1, 1, {
        tag: huks.HuksTag.HUKS_TAG_PURPOSE,
        value: huks.HuksKeyPurpose.HUKS_KEY_PURPOSE_DECRYPT,
    });
    propertiesEncrypt.splice(8, 1, {
        tag: huks.HuksTag.HUKS_TAG_AE_TAG,
        value: new Uint8Array(encryptUpdateResult.splice(encryptUpdateResult.length - 16,encryptUpdateResult.length))
    });
Z
zhangcheng 已提交
1239
    let decryptOptions = {
1240 1241 1242 1243 1244
        properties: propertiesEncrypt,
        inData: new Uint8Array(new Array())
    }

    /* 进行解密操作 */
Z
zhangcheng 已提交
1245 1246
    await publicInitFunc(srcKeyAlias, decryptOptions);

1247
    decryptOptions.inData = new Uint8Array(encryptUpdateResult.slice(0,64));
Z
zhangcheng 已提交
1248 1249 1250
    await publicUpdateFunc(handle, decryptOptions);
    decryptUpdateResult = updateResult;

1251
    decryptOptions.inData = new Uint8Array(encryptUpdateResult.slice(64,encryptUpdateResult.length));
Z
zhangcheng 已提交
1252 1253 1254 1255 1256 1257 1258 1259
    await publicFinishFunc(handle, decryptOptions);
    decryptUpdateResult = updateResult;
    finishOutData = Uint8ArrayToString(new Uint8Array(decryptUpdateResult));
    if (finishOutData === cipherInData) {
        console.info('test finish decrypt success ');
    } else {
        console.info('test finish decrypt err');
    }
1260

Z
zhangcheng 已提交
1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284
    await publicDeleteKeyFunc(srcKeyAlias, huksOptions);
}

@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%')
    }
1285 1286 1287
}
```

Z
zhangcheng 已提交
1288 1289
### 密钥签名验签

Z
zhangcheng 已提交
1290
签名:给我们将要发送的数据,做上一个唯一签名;验签: 对发送者发送过来的签名进行验证 。
Z
zhangcheng 已提交
1291

Z
zhangcheng 已提交
1292
开发步骤如下:
Z
zhangcheng 已提交
1293

Z
zhangcheng 已提交
1294 1295 1296 1297 1298 1299
1. 生成密钥。
2. 密钥签名。
3. 导出签名密钥。
4. 导入签名密钥。
5. 密钥验签。

1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322
**支持的密钥类型:**

仅HksInit对paramSet中参数有要求,其他三段式接口对paramSet无要求

| 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_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 | 【非必选】              | 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 | 【非必选】              | HUKS_DIGEST_NONE  HUKS_DIGEST_SHA1  HUKS_DIGEST_SHA224  HUKS_DIGEST_SHA256  HUKS_DIGEST_SHA384  HUKS_DIGEST_SHA512 |

Ed25519的签名验签是在算法引擎中做的HASH操作,因此该算法的三段式接口处理较特殊:

Update过程只将inData发送到Core中记录在ctx中,不进行Hash计算,最后在finish操作时,对inData组合后的数据进行签名、验签计算.

| HUKS_ALG_ALGORITHM | HUKS_ALG_KEY_SIZE            | HUKS_ALG_PURPOSE                                |
| ------------------ | ---------------------------- | ----------------------------------------------- |
| HUKS_ALG_ED25519   | HUKS_CURVE25519_KEY_SIZE_256 | HUKS_KEY_PURPOSE_SIGN   HUKS_KEY_PURPOSE_VERIFY |

> **说明**
>
> 存储的 keyAlias 密钥别名最大为64字节

Z
zhangcheng 已提交
1323
在使用示例前,需要先了解几个预先定义的变量: 
Z
zhangcheng 已提交
1324

Z
zhangcheng 已提交
1325 1326 1327 1328 1329 1330 1331
| 参数名            | 类型        | 必填 | 说明                     |
| ----------------- | ----------- | ---- | ------------------------ |
| generateKeyAlias  | string      | 是   | 生成密钥别名。           |
| importKeyAlias    | string      | 是   | 导入密钥别名。           |
| genrateKeyOptions | HuksOptions | 是   | 用于存放生成key所需TAG。 |
| signOptions       | HuksOptions | 是   | 用于存放签名key所需TAG。 |
| verifyOptions     | HuksOptions | 是   | 用于存放验签key所需TAG。 |
Z
zhangcheng 已提交
1332

Z
zhangcheng 已提交
1333
关于接口的具体信息,可在[API参考文档](../reference/apis/js-apis-huks.md)中查看。
Z
zhangcheng 已提交
1334 1335 1336

**示例:**

Z
zhangcheng 已提交
1337
```ts
Z
zhangcheng 已提交
1338 1339
/* Sign/Verify操作支持RSA、ECC、SM2、ED25519、DSA类型的密钥。
 *
Z
zhangcheng 已提交
1340
 * 以下以SM2密钥的Callback操作使用为例
Z
zhangcheng 已提交
1341
 */
Z
zhangcheng 已提交
1342 1343 1344
import huks from '@ohos.security.huks';

function StringToUint8Array(str) {
Z
zhangcheng 已提交
1345 1346
    let arr = [];
    for (let i = 0, j = str.length; i < j; ++i) {
Z
zhangcheng 已提交
1347 1348 1349 1350 1351
        arr.push(str.charCodeAt(i));
    }
    return new Uint8Array(arr);
}

Z
zhangcheng 已提交
1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363
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}`);
Z
zhangcheng 已提交
1364
    }
Z
zhangcheng 已提交
1365
}
Z
zhangcheng 已提交
1366

Z
zhangcheng 已提交
1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381
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);
        }
    });
}
Z
zhangcheng 已提交
1382

Z
zhangcheng 已提交
1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395
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}`);
Z
zhangcheng 已提交
1396
    }
Z
zhangcheng 已提交
1397
}
Z
zhangcheng 已提交
1398

Z
zhangcheng 已提交
1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411
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);
        }
Z
zhangcheng 已提交
1412
    });
Z
zhangcheng 已提交
1413
}
Z
zhangcheng 已提交
1414

Z
zhangcheng 已提交
1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428
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}`);
    }
}
Z
zhangcheng 已提交
1429

Z
zhangcheng 已提交
1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442
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);
        }
Z
zhangcheng 已提交
1443
    });
Z
zhangcheng 已提交
1444
}
Z
zhangcheng 已提交
1445

Z
zhangcheng 已提交
1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474
async function publicFinishFunc(handle:number, huksOptions:huks.HuksOptions) {
    console.info(`enter callback doFinish`);
    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);
        }
Z
zhangcheng 已提交
1475
    });
Z
zhangcheng 已提交
1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506
}

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

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);
        }
Z
zhangcheng 已提交
1507
    });
Z
zhangcheng 已提交
1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523
}

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}`);
    }
}
Z
zhangcheng 已提交
1524

Z
zhangcheng 已提交
1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537
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);
        }
Z
zhangcheng 已提交
1538
    });
Z
zhangcheng 已提交
1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554
}

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}`);
    }
}
Z
zhangcheng 已提交
1555

Z
zhangcheng 已提交
1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568
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);
        }
Z
zhangcheng 已提交
1569 1570
    });
}
Z
zhangcheng 已提交
1571

Z
zhangcheng 已提交
1572 1573 1574 1575 1576 1577
let signVerifyInData = 'signVerifyInDataForTest';
let generateKeyAlias = 'generateKeyAliasForTest';
let importKeyAlias = 'importKeyAliasForTest';
let handle;
let exportKey;
let finishOutData;
Z
zhangcheng 已提交
1578 1579

/* 集成生成密钥参数集 */
Z
zhangcheng 已提交
1580
let generateKeyProperties = new Array();
Z
zhangcheng 已提交
1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598
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,
}
Z
zhangcheng 已提交
1599
let genrateKeyOptions = {
Z
zhangcheng 已提交
1600 1601 1602 1603 1604
    properties: generateKeyProperties,
    inData: new Uint8Array(new Array())
}

/* 集成签名参数集 */
Z
zhangcheng 已提交
1605
let signProperties = new Array();
Z
zhangcheng 已提交
1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622
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,
}
Z
zhangcheng 已提交
1623
let signOptions = {
Z
zhangcheng 已提交
1624 1625 1626 1627 1628
    properties: signProperties,
    inData: new Uint8Array(new Array())
}

/* 集成验签参数集 */
Z
zhangcheng 已提交
1629
let verifyProperties = new Array();
Z
zhangcheng 已提交
1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645
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,
}
Z
zhangcheng 已提交
1646
let verifyOptions = {
Z
zhangcheng 已提交
1647 1648 1649 1650 1651 1652 1653 1654 1655
    properties: verifyProperties,
    inData: new Uint8Array(new Array())
}

async function testSm2SignVerify() {
    /* 生成密钥 */
    await publicGenKeyFunc(generateKeyAlias, genrateKeyOptions);

    /* 签名 */
Z
zhangcheng 已提交
1656 1657
    let signHandle;
    let signFinishOutData;
Z
zhangcheng 已提交
1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675
    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;

    /* 导出密钥 */
    await publicExportKeyFunc(generateKeyAlias, genrateKeyOptions);

    /* 导入密钥 */
    verifyOptions.inData = exportKey;
    await publicImportKeyFunc(importKeyAlias, verifyOptions);

    /* 验证签名 */
Z
zhangcheng 已提交
1676
    let verifyHandle;
Z
zhangcheng 已提交
1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712
    await publicInitFunc(importKeyAlias, verifyOptions);

    verifyHandle = handle;

    verifyOptions.inData = StringToUint8Array(signVerifyInData)
    await publicUpdateFunc(verifyHandle, verifyOptions);

    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%')
    }
}
Z
zhangcheng 已提交
1713 1714 1715 1716
```

### 密钥协商

Z
zhangcheng 已提交
1717
两个或多个对象生成会话密钥,通过会话密钥进行交流 。
Z
zhangcheng 已提交
1718

Z
zhangcheng 已提交
1719
开发步骤如下:
Z
zhangcheng 已提交
1720

Z
zhangcheng 已提交
1721 1722 1723 1724
1. 生成两个密钥。
2. 分别导出密钥。
3. 交叉进行密钥协商。

1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753
**支持的密钥类型:**

仅HksInit和HksFinish接口对paramSet参数有要求,HksUpdate接口对paramSet无要求

HksInit对paramSet中参数的要求

| HUKS_ALG_ALGORITHM | HUKS_ALG_KEY_SIZE                                            | HUKS_ALG_PURPOSE       |
| ------------------ | ------------------------------------------------------------ | ---------------------- |
| 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 |
| HUKS_ALG_DH        | HUKS_DH_KEY_SIZE_2048 HUKS_DH_KEY_SIZE_3072 HUKS_DH_KEY_SIZE_4096 | HUKS_KEY_PURPOSE_AGREE |
| HUKS_ALG_X25519    | HUKS_CURVE25519_KEY_SIZE_256                                 | HUKS_KEY_PURPOSE_AGREE |

HksFinish对paramSet中参数的要求:

派生后的密钥作为对称密钥进行使用

| HUKS_TAG_KEY_STORAGE_FLAG      | HUKS_TAG_KEY_ALIAS | HUKS_TAG_IS_KEY_ALIAS | HUKS_TAG_ALGORITHM | HUKS_TAG_KEY_SIZE                                            | HUKS_TAG_PURPOSE                                   | HUKS_TAG_PADDING   | HUKS_TAG_DIGEST                                              | HUKS_TAG_BLOCK_MODE                         |
| ------------------------------ | ------------------ | --------------------- | ------------------ | ------------------------------------------------------------ | -------------------------------------------------- | ------------------ | ------------------------------------------------------------ | ------------------------------------------- |
| 未设置 或者  HUKS_STORAGE_TEMP | 不需要             | TRUE                  | 不需要             | 不需要                                                       | 不需要                                             | 不需要             | 不需要                                                       | 不需要                                      |
| HUKS_STORAGE_PERSISTENT        | 【必选】最大64字节 | TRUE                  | 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_PADDING_PKCS7 | 【非必选】                                                   | HUKS_MODE_CCM  HUKS_MODE_GCM  HUKS_MODE_CTP |
| HUKS_STORAGE_PERSISTENT        | 【必选】最大64字节 | TRUE                  | HUKS_ALG_AES       | 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   | 【非必选】                                  |
| HUKS_STORAGE_PERSISTENT        | 【必选】最大64字节 | TRUE                  | HUKS_ALG_HMAC      | 8的倍数(单位:bit)                                         | HUKS_KEY_PURPOSE_MAC                               | 【非必选】         | HUKS_DIGEST_SHA1  HUKS_DIGEST_SHA224  HUKS_DIGEST_SHA256  HUKS_DIGEST_SHA384 HUKS_DIGEST_SHA512 | 【非必选】                                  |

> **说明**
>
> HUKS_ALG_AES的SIZE需要满足:协商后的密钥长度(转换成bit)>=选择的HUKS_TAG_KEY_SIZE
>
> 存储的 keyAlias 密钥别名最大为64字节

Z
zhangcheng 已提交
1754
在使用示例前,需要先了解几个预先定义的变量: 
Z
zhangcheng 已提交
1755 1756 1757 1758 1759

| 参数名              | 类型        | 必填 | 说明                                   |
| ------------------- | ----------- | ---- | -------------------------------------- |
| srcKeyAliasFirst    | string      | 是   | 生成密钥别名。                         |
| srcKeyAliasSecond   | string      | 是   | 生成密钥别名,用于结果对比。           |
Z
zhangcheng 已提交
1760
| huksOptions         | HuksOptions | 是   | 用于存放生成key所需TAG。               |
Z
zhangcheng 已提交
1761 1762 1763
| finishOptionsFrist  | HuksOptions | 是   | 用于存放协商key所需TAG。               |
| finishOptionsSecond | HuksOptions | 是   | 用于存放协商key所需TAG,用于结果对比。 |

Z
zhangcheng 已提交
1764
关于接口的具体信息,可在[API参考文档](../reference/apis/js-apis-huks.md)中查看。
Z
zhangcheng 已提交
1765 1766 1767

**示例:**

Z
zhangcheng 已提交
1768
```ts
Z
zhangcheng 已提交
1769 1770
/* agree操作支持ECDH、DH、X25519类型的密钥。
 *
1771
 * 以下以X25519 256 TEMP密钥的Promise操作使用为例
Z
zhangcheng 已提交
1772
 */
Z
zhangcheng 已提交
1773 1774 1775
import huks from '@ohos.security.huks';

function StringToUint8Array(str) {
Z
zhangcheng 已提交
1776 1777
    let arr = [];
    for (let i = 0, j = str.length; i < j; ++i) {
Z
zhangcheng 已提交
1778 1779 1780 1781 1782
        arr.push(str.charCodeAt(i));
    }
    return new Uint8Array(arr);
}

Z
zhangcheng 已提交
1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958 1959 1960 1961 1962 1963 1964 1965 1966 1967 1968 1969 1970
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}`);
    }
}

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

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

Z
zhangcheng 已提交
1971 1972 1973 1974 1975 1976 1977
let srcKeyAliasFirst = "AgreeX25519KeyFirstAlias";
let srcKeyAliasSecond = "AgreeX25519KeySecondAlias";
let agreeX25519InData = 'AgreeX25519TestIndata';
let handle;
let exportKey;
let exportKeyFrist;
let exportKeySecond;
Z
zhangcheng 已提交
1978

Z
zhangcheng 已提交
1979 1980
async function testAgree() {
    /* 集成生成密钥参数集 */
Z
zhangcheng 已提交
1981
    let properties = new Array();
Z
zhangcheng 已提交
1982 1983 1984 1985 1986 1987 1988 1989 1990 1991 1992 1993 1994 1995 1996 1997 1998 1999 2000 2001 2002 2003 2004 2005
    properties[0] = {
        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_DIGEST,
        value: huks.HuksKeyDigest.HUKS_DIGEST_NONE,
    }
    properties[4] = {
        tag: huks.HuksTag.HUKS_TAG_PADDING,
        value: huks.HuksKeyPadding.HUKS_PADDING_NONE,
    }
    properties[5] = {
        tag: huks.HuksTag.HUKS_TAG_BLOCK_MODE,
        value: huks.HuksCipherMode.HUKS_MODE_CBC,
    }
Z
zhangcheng 已提交
2006
    let HuksOptions = {
Z
zhangcheng 已提交
2007 2008 2009
        properties: properties,
        inData: new Uint8Array(new Array())
    }
Z
zhangcheng 已提交
2010

Z
zhangcheng 已提交
2011
    /* 1.生成两个密钥并导出 */
Z
zhangcheng 已提交
2012 2013 2014 2015 2016 2017 2018
    await publicGenKeyFunc(srcKeyAliasFirst, HuksOptions);
    await publicGenKeyFunc(srcKeyAliasSecond, HuksOptions);

    await publicExportKeyFunc(srcKeyAliasFirst, HuksOptions);
    exportKeyFrist = exportKey;
    await publicExportKeyFunc(srcKeyAliasFirst, HuksOptions);
    exportKeySecond = exportKey;
Z
zhangcheng 已提交
2019 2020

    /* 集成第一个协商参数集 */
Z
zhangcheng 已提交
2021
    let finishProperties = new Array();
Z
zhangcheng 已提交
2022 2023
    finishProperties[0] = {
        tag: huks.HuksTag.HUKS_TAG_KEY_STORAGE_FLAG,
2024
        value: huks.HuksKeyStorageType.HUKS_STORAGE_TEMP,
Z
zhangcheng 已提交
2025 2026 2027 2028 2029 2030 2031 2032 2033 2034 2035 2036 2037 2038 2039 2040 2041 2042 2043 2044 2045 2046 2047 2048 2049
    }
    finishProperties[1] = {
        tag: huks.HuksTag.HUKS_TAG_IS_KEY_ALIAS,
        value: true
    }
    finishProperties[2] = {
        tag: huks.HuksTag.HUKS_TAG_ALGORITHM,
        value: huks.HuksKeyAlg.HUKS_ALG_AES,
    }
    finishProperties[3] = {
        tag: huks.HuksTag.HUKS_TAG_KEY_SIZE,
        value: huks.HuksKeySize.HUKS_AES_KEY_SIZE_256,
    }
    finishProperties[4] = {
        tag: huks.HuksTag.HUKS_TAG_PURPOSE,
        value:
        huks.HuksKeyPurpose.HUKS_KEY_PURPOSE_ENCRYPT |
        huks.HuksKeyPurpose.HUKS_KEY_PURPOSE_DECRYPT,
    }
    finishProperties[5] = {
        tag: huks.HuksTag.HUKS_TAG_DIGEST,
        value: huks.HuksKeyDigest.HUKS_DIGEST_NONE,
    }
    finishProperties[6] = {
        tag: huks.HuksTag.HUKS_TAG_KEY_ALIAS,
Z
zhangcheng 已提交
2050
        value: StringToUint8Array(srcKeyAliasFirst+ 'final'),
Z
zhangcheng 已提交
2051 2052 2053 2054 2055 2056 2057 2058 2059
    }
    finishProperties[7] = {
        tag: huks.HuksTag.HUKS_TAG_PADDING,
        value: huks.HuksKeyPadding.HUKS_PADDING_NONE,
    }
    finishProperties[8] = {
        tag: huks.HuksTag.HUKS_TAG_BLOCK_MODE,
        value: huks.HuksCipherMode.HUKS_MODE_ECB,
    }
Z
zhangcheng 已提交
2060
    let finishOptionsFrist = {
Z
zhangcheng 已提交
2061
        properties: finishProperties,
Z
zhangcheng 已提交
2062
        inData: StringToUint8Array(agreeX25519InData)
Z
zhangcheng 已提交
2063
    }
Z
zhangcheng 已提交
2064

Z
zhangcheng 已提交
2065
    /* 对第一个密钥进行协商 */
Z
zhangcheng 已提交
2066
    await publicInitFunc(srcKeyAliasFirst, HuksOptions);
2067
    HuksOptions.inData = exportKeySecond;
Z
zhangcheng 已提交
2068 2069
    await publicUpdateFunc(handle, HuksOptions);
    await publicFinishFunc(handle, finishOptionsFrist);
Z
zhangcheng 已提交
2070 2071

    /* 集成第二个协商参数集 */
Z
zhangcheng 已提交
2072
    let finishOptionsSecond = {
Z
zhangcheng 已提交
2073
        properties: finishProperties,
Z
zhangcheng 已提交
2074
        inData: StringToUint8Array(agreeX25519InData)
Z
zhangcheng 已提交
2075 2076 2077
    }
    finishOptionsSecond.properties.splice(6, 1, {
        tag: huks.HuksTag.HUKS_TAG_KEY_ALIAS,
Z
zhangcheng 已提交
2078
        value: StringToUint8Array(srcKeyAliasSecond + 'final'),
Z
zhangcheng 已提交
2079
    })
Z
zhangcheng 已提交
2080

2081
    /* 对第二个密钥进行协商 */
Z
zhangcheng 已提交
2082
    await publicInitFunc(srcKeyAliasSecond, HuksOptions);
2083
    HuksOptions.inData = exportKeyFrist;
Z
zhangcheng 已提交
2084 2085
    await publicUpdateFunc(handle, HuksOptions);
    await publicFinishFunc(handle, finishOptionsSecond);
Z
zhangcheng 已提交
2086

Z
zhangcheng 已提交
2087 2088 2089 2090 2091 2092 2093 2094 2095 2096 2097 2098 2099 2100 2101 2102 2103 2104 2105 2106 2107 2108 2109 2110 2111 2112

    await publicDeleteKeyFunc(srcKeyAliasFirst, HuksOptions);
    await publicDeleteKeyFunc(srcKeyAliasSecond, HuksOptions);
}

@Entry
@Component
struct Index {
    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%')
    }
Z
zhangcheng 已提交
2113 2114 2115 2116 2117
}
```

### 密钥派生

Z
zhangcheng 已提交
2118
从一个密钥产生出一个或者多个密钥。 
Z
zhangcheng 已提交
2119

Z
zhangcheng 已提交
2120 2121
开发步骤如下:

2122 2123 2124 2125 2126 2127 2128 2129 2130 2131 2132 2133 2134 2135 2136 2137 2138 2139 2140 2141 2142 2143 2144 2145 2146 2147 2148 2149
1. 生成密钥。
2. 进行密钥派生。

**支持的密钥类型:**

仅HksInit和HksFinish接口对paramSet参数有要求,HksUpdate接口对paramSet无要求

HksInit对paramSet中参数的要求

| HUKS_TAG_ALGORITHM                                           | HUKS_TAG_PURPOSE        | HUKS_TAG_DIGEST                                            | HUKS_TAG_DERIVE_KEY_SIZE |
| ------------------------------------------------------------ | ----------------------- | ---------------------------------------------------------- | ------------------------ |
| HUKS_ALG_HKDF  (支持长度:  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 | 【必选】                 |
| HUKS_ALG_PBKDF2  (支持长度:  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 | 【必选】                 |

HksFinish对paramSet中参数的要求:

派生后的密钥作为对称密钥进行使用

| HUKS_TAG_KEY_STORAGE_FLAG      | HUKS_TAG_KEY_ALIAS | HUKS_TAG_IS_KEY_ALIAS | HUKS_TAG_ALGORITHM | HUKS_TAG_KEY_SIZE                                            | HUKS_TAG_PURPOSE                                   | HUKS_TAG_PADDING                      | HUKS_TAG_DIGEST                                              | HUKS_TAG_BLOCK_MODE                         |
| ------------------------------ | ------------------ | --------------------- | ------------------ | ------------------------------------------------------------ | -------------------------------------------------- | ------------------------------------- | ------------------------------------------------------------ | ------------------------------------------- |
| 未设置 或者  HUKS_STORAGE_TEMP | 不需要             | TRUE                  | 不需要             | 不需要                                                       | 不需要                                             | 不需要                                | 不需要                                                       | 不需要                                      |
| HUKS_STORAGE_PERSISTENT        | 【必选】最大64字节 | TRUE                  | 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_PADDING_NONE  HUKS_PADDING_PKCS7 | 【非必选】                                                   | HUKS_MODE_CBC  HUKS_MODE_ECB                |
| HUKS_STORAGE_PERSISTENT        | 【必选】最大64字节 | TRUE                  | 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_PADDING_NONE                     | 【非必选】                                                   | HUKS_MODE_CCM  HUKS_MODE_GCM  HUKS_MODE_CTR |
| HUKS_STORAGE_PERSISTENT        | 【必选】最大64字节 | TRUE                  | HUKS_ALG_AES       | 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   | 【非必选】                                  |
| HUKS_STORAGE_PERSISTENT        | 【必选】最大64字节 | TRUE                  | HUKS_ALG_HMAC      | 8的倍数(单位:bit)                                         | HUKS_KEY_PURPOSE_MAC                               | 【非必选】                            | HUKS_DIGEST_SHA1  HUKS_DIGEST_SHA224  HUKS_DIGEST_SHA256  HUKS_DIGEST_SHA384  HUKS_DIGEST_SHA512 | 【非必选】                                  |

> **说明**
>
Z
zhangcheng 已提交
2150
> HUKS_ALG_AES的SIZE需要满足:派生后的密钥长度(转换成bit)>=选择的HUKS_TAG_KEY_SIZE
2151 2152
>
> 存储的 keyAlias 密钥别名最大为64字节
Z
zhangcheng 已提交
2153 2154

在使用示例前,需要先了解几个预先定义的变量: 
Z
zhangcheng 已提交
2155 2156 2157 2158

| 参数名        | 类型        | 必填 | 说明             |
| ------------- | ----------- | ---- | ---------------- |
| srcKeyAlias   | string      | 是   | 生成密钥别名。   |
Z
zhangcheng 已提交
2159
| huksOptions   | HuksOptions | 是   | 生成密钥参数集。 |
Z
zhangcheng 已提交
2160 2161
| finishOptions | HuksOptions | 是   | 派生密钥参数集。 |

Z
zhangcheng 已提交
2162
关于接口的具体信息,可在[API参考文档](../reference/apis/js-apis-huks.md)中查看。
Z
zhangcheng 已提交
2163 2164 2165

**示例:**

Z
zhangcheng 已提交
2166
```ts
Z
zhangcheng 已提交
2167 2168 2169 2170
/* derive操作支持HKDF、pbdkf类型的密钥。
 *
 * 以下以HKDF256密钥的Promise操作使用为例
 */
Z
zhangcheng 已提交
2171 2172 2173
import huks from '@ohos.security.huks';

function StringToUint8Array(str) {
Z
zhangcheng 已提交
2174 2175
    let arr = [];
    for (let i = 0, j = str.length; i < j; ++i) {
Z
zhangcheng 已提交
2176 2177 2178 2179 2180
        arr.push(str.charCodeAt(i));
    }
    return new Uint8Array(arr);
}

Z
zhangcheng 已提交
2181 2182 2183 2184 2185 2186 2187 2188 2189 2190 2191 2192 2193 2194 2195 2196 2197 2198 2199 2200 2201 2202 2203 2204 2205 2206 2207 2208 2209 2210 2211 2212 2213 2214 2215 2216 2217 2218 2219 2220 2221 2222 2223 2224 2225 2226 2227 2228 2229 2230 2231 2232 2233 2234 2235 2236 2237 2238 2239 2240 2241 2242 2243 2244 2245 2246 2247 2248 2249 2250 2251 2252 2253 2254 2255 2256 2257 2258 2259 2260 2261 2262 2263 2264 2265 2266 2267 2268 2269 2270 2271 2272 2273 2274 2275 2276 2277 2278 2279 2280 2281 2282 2283 2284 2285 2286 2287 2288 2289 2290 2291 2292 2293 2294 2295 2296 2297 2298 2299 2300 2301 2302 2303 2304 2305 2306 2307 2308 2309 2310 2311 2312 2313 2314 2315 2316 2317 2318 2319 2320
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 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);
        }
    });
}

Z
zhangcheng 已提交
2321 2322 2323 2324
let deriveHkdfInData = "deriveHkdfTestIndata";
let srcKeyAlias = "deriveHkdfKeyAlias";
let handle;
let HuksKeyDeriveKeySize = 32;
Z
zhangcheng 已提交
2325

Z
zhangcheng 已提交
2326 2327
async function testDerive() {
    /* 集成生成密钥参数集 */
Z
zhangcheng 已提交
2328
    let properties = new Array();
Z
zhangcheng 已提交
2329 2330 2331 2332 2333 2334 2335 2336 2337 2338 2339 2340 2341 2342 2343 2344
    properties[0] = {
        tag: huks.HuksTag.HUKS_TAG_ALGORITHM,
        value: huks.HuksKeyAlg.HUKS_ALG_AES,
    }
    properties[1] = {
        tag: huks.HuksTag.HUKS_TAG_PURPOSE,
        value: huks.HuksKeyPurpose.HUKS_KEY_PURPOSE_DERIVE,
    }
    properties[2] = {
        tag: huks.HuksTag.HUKS_TAG_DIGEST,
        value: huks.HuksKeyDigest.HUKS_DIGEST_SHA256,
    }
    properties[3] = {
        tag: huks.HuksTag.HUKS_TAG_KEY_SIZE,
        value: huks.HuksKeySize.HUKS_AES_KEY_SIZE_128,
    }
Z
zhangcheng 已提交
2345
    let huksOptions = {
Z
zhangcheng 已提交
2346 2347 2348
        properties: properties,
        inData: new Uint8Array(new Array())
    }
Z
zhangcheng 已提交
2349

Z
zhangcheng 已提交
2350
    /* 生成密钥 */
Z
zhangcheng 已提交
2351
    await publicGenKeyFunc(srcKeyAlias, huksOptions);
Z
zhangcheng 已提交
2352

Z
zhangcheng 已提交
2353 2354 2355 2356 2357 2358 2359
    /* 调整init时的参数集 */
    huksOptions.properties.splice(0, 1, {
        tag: huks.HuksTag.HUKS_TAG_ALGORITHM,
        value: huks.HuksKeyAlg.HUKS_ALG_HKDF,
    });
    huksOptions.properties.splice(3, 1, {
        tag: huks.HuksTag.HUKS_TAG_DERIVE_KEY_SIZE,
2360
        value: HuksKeyDeriveKeySize,
Z
zhangcheng 已提交
2361 2362
    });

Z
zhangcheng 已提交
2363
    let finishProperties = new Array();
Z
zhangcheng 已提交
2364 2365 2366 2367 2368 2369 2370 2371 2372 2373 2374 2375 2376 2377 2378 2379 2380 2381 2382 2383 2384 2385 2386 2387 2388 2389 2390 2391
    finishProperties[0] = {
        tag: huks.HuksTag.HUKS_TAG_KEY_STORAGE_FLAG,
        value: huks.HuksKeyStorageType.HUKS_STORAGE_PERSISTENT,
    }
    finishProperties[1] = {
        tag: huks.HuksTag.HUKS_TAG_IS_KEY_ALIAS,
        value: true,
    }
    finishProperties[2] = {
        tag: huks.HuksTag.HUKS_TAG_ALGORITHM,
        value: huks.HuksKeyAlg.HUKS_ALG_AES,
    }
    finishProperties[3] = {
        tag: huks.HuksTag.HUKS_TAG_KEY_SIZE,
        value: huks.HuksKeySize.HUKS_AES_KEY_SIZE_256,
    }
    finishProperties[4] = {
        tag: huks.HuksTag.HUKS_TAG_PURPOSE,
        value:
        huks.HuksKeyPurpose.HUKS_KEY_PURPOSE_ENCRYPT |
        huks.HuksKeyPurpose.HUKS_KEY_PURPOSE_DECRYPT,
    }
    finishProperties[5] = {
        tag: huks.HuksTag.HUKS_TAG_DIGEST,
        value: huks.HuksKeyDigest.HUKS_DIGEST_NONE,
    }
    finishProperties[6] = {
        tag: huks.HuksTag.HUKS_TAG_KEY_ALIAS,
Z
zhangcheng 已提交
2392
        value: StringToUint8Array(srcKeyAlias),
Z
zhangcheng 已提交
2393 2394 2395 2396 2397 2398 2399 2400 2401
    }
    finishProperties[7] = {
        tag: huks.HuksTag.HUKS_TAG_PADDING,
        value: huks.HuksKeyPadding.HUKS_PADDING_NONE,
    }
    finishProperties[8] = {
        tag: huks.HuksTag.HUKS_TAG_BLOCK_MODE,
        value: huks.HuksCipherMode.HUKS_MODE_ECB,
    }
Z
zhangcheng 已提交
2402
    let finishOptions = {
Z
zhangcheng 已提交
2403 2404 2405 2406 2407
        properties: finishProperties,
        inData: new Uint8Array(new Array())
    }

    /* 进行派生操作 */
Z
zhangcheng 已提交
2408 2409 2410 2411 2412
    await publicInitFunc(srcKeyAlias, huksOptions);

    huksOptions.inData = StringToUint8Array(deriveHkdfInData);
    await publicUpdateFunc(handle, huksOptions);
    await publicFinishFunc(handle, finishOptions);
Z
zhangcheng 已提交
2413 2414 2415 2416 2417 2418 2419 2420 2421 2422

    huksOptions.properties.splice(0, 1, {
        tag: huks.HuksTag.HUKS_TAG_ALGORITHM,
        value: huks.HuksKeyAlg.HUKS_ALG_AES,
    });
    huksOptions.properties.splice(3, 1, {
        tag: huks.HuksTag.HUKS_TAG_KEY_SIZE,
        value: huks.HuksKeySize.HUKS_AES_KEY_SIZE_128,
    });

Z
zhangcheng 已提交
2423 2424 2425 2426 2427 2428 2429 2430 2431 2432 2433 2434 2435 2436 2437 2438 2439 2440 2441 2442 2443 2444 2445 2446
    await publicDeleteKeyFunc(srcKeyAlias, huksOptions);
}

@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%')
    }
Z
zhangcheng 已提交
2447
}
Z
zhangcheng 已提交
2448 2449 2450 2451
```

### 密钥mac

Z
zhangcheng 已提交
2452
基于密钥数据进行mac摘要所获得的一个哈希值。 
Z
zhangcheng 已提交
2453

Z
zhangcheng 已提交
2454
开发步骤如下:
Z
zhangcheng 已提交
2455

Z
zhangcheng 已提交
2456 2457
1. 生成密钥。
2. 密钥mac。
Z
zhangcheng 已提交
2458

2459 2460 2461 2462 2463 2464 2465 2466 2467 2468 2469 2470 2471
**支持的密钥类型:**

HksInit对paramSet中参数的要求,其他三段式接口对paramSet无要求

| HUKS_TAG_ALGORITHM | HUKS_TAG_KEY_SIZE | HUKS_TAG_PURPOSE    | HUKS_TAG_DIGEST                                              | HUKS_TAG_PADDING | HUKS_TAG_BLOCK_MODE |
| ------------ | ---------- | ------------------- | ------------------------------------------------------------ | ---------- | ---------- |
| HUKS_ALG_HMAC | 【非必选】 | HUKS_KEY_PURPOSE_MAC | HUKS_DIGEST_SHA1  HUKS_DIGEST_SHA224  HUKS_DIGEST_SHA256  HUKS_DIGEST_SHA384  HUKS_DIGEST_SHA512 | 【非必选】 | 【非必选】 |
| HUKS_ALG_SM3 | 【非必选】 | HUKS_KEY_PURPOSE_MAC | HUKS_DIGEST_SM3                                              | 【非必选】 | 【非必选】 |

> **说明**
>
> 存储的 keyAlias 密钥别名最大为64字节

Z
zhangcheng 已提交
2472
在使用示例前,需要先了解几个预先定义的变量: 
Z
zhangcheng 已提交
2473 2474 2475 2476

| 参数名      | 类型        | 必填 | 说明           |
| ----------- | ----------- | ---- | -------------- |
| srcKeyAlias | string      | 是   | 生成密钥别名。 |
Z
zhangcheng 已提交
2477
| huksOptions | HuksOptions | 是   | 密钥参数集。   |
Z
zhangcheng 已提交
2478

Z
zhangcheng 已提交
2479
关于接口的具体信息,可在[API参考文档](../reference/apis/js-apis-huks.md)中查看。
Z
zhangcheng 已提交
2480 2481 2482

**示例:**

Z
zhangcheng 已提交
2483
```ts
Z
zhangcheng 已提交
2484 2485 2486 2487
/* mac操作支持HMAC、SM3类型的密钥。
 *
 * 以下以SM3 256密钥的Promise操作使用为例
 */
Z
zhangcheng 已提交
2488 2489 2490
import huks from '@ohos.security.huks';

function StringToUint8Array(str) {
Z
zhangcheng 已提交
2491 2492
    let arr = [];
    for (let i = 0, j = str.length; i < j; ++i) {
Z
zhangcheng 已提交
2493 2494 2495 2496 2497
        arr.push(str.charCodeAt(i));
    }
    return new Uint8Array(arr);
}

Z
zhangcheng 已提交
2498 2499 2500 2501 2502 2503 2504 2505 2506 2507 2508 2509 2510 2511 2512 2513 2514 2515 2516 2517 2518 2519 2520 2521 2522 2523 2524 2525 2526 2527 2528 2529 2530 2531 2532 2533 2534 2535 2536 2537 2538 2539 2540 2541 2542 2543 2544 2545 2546 2547 2548 2549 2550 2551 2552 2553 2554 2555 2556 2557 2558 2559 2560 2561 2562 2563 2564 2565 2566 2567 2568 2569 2570 2571 2572 2573 2574 2575 2576 2577 2578 2579 2580 2581 2582 2583 2584 2585 2586 2587 2588 2589 2590 2591 2592 2593 2594 2595 2596 2597 2598 2599 2600 2601 2602 2603 2604 2605 2606 2607 2608 2609 2610 2611 2612 2613 2614 2615 2616 2617 2618 2619 2620 2621 2622 2623 2624 2625 2626 2627 2628 2629 2630 2631 2632 2633 2634 2635 2636 2637 2638 2639 2640 2641 2642 2643 2644 2645 2646 2647 2648 2649 2650 2651 2652 2653
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}`);
    }
}

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

Z
zhangcheng 已提交
2654 2655 2656
let srcKeyAlias = "sm3KeyAlias";
let hmacInData = 'sm3TestIndata';
let handle;
Z
zhangcheng 已提交
2657

Z
zhangcheng 已提交
2658 2659
async function testMac() {
    /* 集成生成密钥参数集 */
Z
zhangcheng 已提交
2660
    let properties = new Array();
Z
zhangcheng 已提交
2661 2662 2663 2664 2665 2666 2667 2668 2669 2670 2671 2672 2673 2674 2675 2676
    properties[0] = {
        tag: huks.HuksTag.HUKS_TAG_ALGORITHM,
        value: huks.HuksKeyAlg.HUKS_ALG_SM3,
    }
    properties[1] = {
        tag: huks.HuksTag.HUKS_TAG_PURPOSE,
        value: huks.HuksKeyPurpose.HUKS_KEY_PURPOSE_MAC,
    }
    properties[2] = {
        tag: huks.HuksTag.HUKS_TAG_DIGEST,
        value: huks.HuksKeyDigest.HUKS_DIGEST_SM3,
    }
    properties[3] = {
        tag: huks.HuksTag.HUKS_TAG_KEY_SIZE,
        value: huks.HuksKeySize.HUKS_AES_KEY_SIZE_256,
    }
Z
zhangcheng 已提交
2677
    let huksOptions = {
Z
zhangcheng 已提交
2678 2679 2680
        properties:properties,
        inData:new Uint8Array(new Array())
    }
Z
zhangcheng 已提交
2681

Z
zhangcheng 已提交
2682
    /* 生成密钥 */
Z
zhangcheng 已提交
2683
    await publicGenKeyFunc(srcKeyAlias, huksOptions);
Z
zhangcheng 已提交
2684 2685 2686

    /* 修改init时的参数集并进行mac操作 */
    huksOptions.properties.splice(3, 3);
Z
zhangcheng 已提交
2687 2688 2689
    await publicInitFunc(srcKeyAlias, huksOptions);
    huksOptions.inData = StringToUint8Array(hmacInData);
    await publicUpdateFunc(handle, huksOptions);
Z
zhangcheng 已提交
2690
    huksOptions.inData = new Uint8Array(new Array());
Z
zhangcheng 已提交
2691 2692
    await publicFinishFunc(handle, huksOptions);
    
Z
zhangcheng 已提交
2693 2694 2695 2696
    huksOptions.properties.splice(1, 0, {
        tag: huks.HuksTag.HUKS_TAG_KEY_SIZE,
        value: huks.HuksKeySize.HUKS_AES_KEY_SIZE_256,
    });
Z
zhangcheng 已提交
2697 2698
    await publicDeleteKeyFunc(srcKeyAlias, huksOptions);
}
Z
zhangcheng 已提交
2699

Z
zhangcheng 已提交
2700 2701 2702 2703 2704 2705 2706 2707 2708 2709 2710 2711 2712 2713 2714 2715 2716 2717 2718 2719 2720
@Entry
@Component
struct Index {
    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%')
    }
Z
zhangcheng 已提交
2721
}
Z
zhangcheng 已提交
2722 2723 2724 2725
```

### AttestID

2726 2727 2728 2729 2730
应用生成非对称密钥后,可以通过id attestation获取证书链,ID Attestation包含支持如下设备信息: BRAND, DEVICE, PRODUCT, SERIAL, IMEI, MEID, MANUFACTURER, MODEL, SOCID, UDID。

应用还可以通过key attestation获取证书链。

ID Attestation和Key Attestation只有拥有TEE环境的设备才具备该功能。
Z
zhangcheng 已提交
2731 2732

开发步骤如下:
Z
zhangcheng 已提交
2733

Z
zhangcheng 已提交
2734 2735
1. 生成证书。
2. 获取证书信息。
Z
zhangcheng 已提交
2736

2737 2738 2739 2740 2741 2742 2743 2744
**支持的密钥类型:**

RSA512, RSA768, RSA1024, RSA2048, RSA3072, RSA4096, ECC224, ECC256, ECC384, ECC521, X25519

> **说明**
>
> 存储的 keyAlias 密钥别名最大为64字节

Z
zhangcheng 已提交
2745
在使用示例前,需要先了解几个预先定义的变量: 
Z
zhangcheng 已提交
2746 2747 2748 2749 2750 2751

| 参数名   | 类型        | 必填 | 说明                                 |
| -------- | ----------- | ---- | ------------------------------------ |
| keyAlias | string      | 是   | 密钥别名,存放待获取证书密钥的别名。 |
| options  | HuksOptions | 是   | 用于获取证书时指定所需参数与数据。   |

Z
zhangcheng 已提交
2752
关于接口的具体信息,可在[API参考文档](../reference/apis/js-apis-huks.md)中查看。
Z
zhangcheng 已提交
2753 2754 2755

**示例:**

Z
zhangcheng 已提交
2756
```ts
Z
zhangcheng 已提交
2757
/* 证书AttestID操作示例如下*/
Z
zhangcheng 已提交
2758 2759 2760
import huks from '@ohos.security.huks';

function StringToUint8Array(str) {
Z
zhangcheng 已提交
2761 2762
    let arr = [];
    for (let i = 0, j = str.length; i < j; ++i) {
Z
zhangcheng 已提交
2763
        arr.push(str.charCodeAt(i));
Z
zhangcheng 已提交
2764
    }
Z
zhangcheng 已提交
2765 2766 2767 2768 2769 2770 2771 2772 2773 2774 2775 2776 2777 2778 2779 2780 2781 2782 2783 2784 2785 2786 2787 2788 2789 2790 2791 2792 2793 2794 2795 2796 2797 2798 2799 2800 2801 2802 2803 2804 2805 2806 2807 2808 2809 2810 2811 2812 2813 2814 2815 2816 2817 2818 2819 2820 2821 2822 2823 2824 2825 2826 2827 2828 2829 2830 2831 2832 2833 2834 2835 2836 2837 2838 2839 2840 2841 2842
    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 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}`);
    }
Z
zhangcheng 已提交
2843 2844
}

Z
zhangcheng 已提交
2845 2846 2847 2848 2849 2850 2851 2852 2853 2854 2855 2856 2857 2858
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);
        }
    });
Z
zhangcheng 已提交
2859 2860
}

Z
zhangcheng 已提交
2861 2862 2863 2864 2865 2866 2867
let securityLevel = StringToUint8Array('sec_level');
let challenge = StringToUint8Array('challenge_data');
let versionInfo = StringToUint8Array('version_info');
let udid = StringToUint8Array('udid');
let serial = StringToUint8Array('serial');
let deviceId = StringToUint8Array('device_id');
let idAliasString = "id attest";
Z
zhangcheng 已提交
2868 2869

async function testAttestId() {
Z
zhangcheng 已提交
2870 2871
    let aliasString = idAliasString;
    let aliasUint8 = StringToUint8Array(aliasString);
Z
zhangcheng 已提交
2872

Z
zhangcheng 已提交
2873
    /* 集成生成密钥参数集 & 生成密钥 */
Z
zhangcheng 已提交
2874
    let properties = new Array();
Z
zhangcheng 已提交
2875 2876 2877 2878
    properties[0] = {
        tag: huks.HuksTag.HUKS_TAG_ALGORITHM,
        value: huks.HuksKeyAlg.HUKS_ALG_RSA
    };
Z
zhangcheng 已提交
2879
    properties[1] = {
Z
zhangcheng 已提交
2880 2881
        tag: huks.HuksTag.HUKS_TAG_KEY_STORAGE_FLAG,
        value: huks.HuksKeyStorageType.HUKS_STORAGE_PERSISTENT
Z
zhangcheng 已提交
2882 2883 2884
    };
    properties[2] = {
        tag: huks.HuksTag.HUKS_TAG_KEY_SIZE,
Z
zhangcheng 已提交
2885 2886 2887 2888 2889 2890 2891 2892 2893 2894 2895 2896 2897 2898 2899 2900 2901 2902 2903 2904 2905 2906
        value: huks.HuksKeySize.HUKS_RSA_KEY_SIZE_2048
    };
    properties[3] = {
        tag: huks.HuksTag.HUKS_TAG_PURPOSE,
        value: huks.HuksKeyPurpose.HUKS_KEY_PURPOSE_VERIFY
    };
    properties[4] = {
        tag: huks.HuksTag.HUKS_TAG_DIGEST,
        value: huks.HuksKeyDigest.HUKS_DIGEST_SHA256
    };
    properties[5] = {
        tag: huks.HuksTag.HUKS_TAG_PADDING,
        value: huks.HuksKeyPadding.HUKS_PADDING_PSS
    };
    properties[6] = {
        tag: huks.HuksTag.HUKS_TAG_KEY_GENERATE_TYPE,
        value: huks.HuksKeyGenerateType.HUKS_KEY_GENERATE_TYPE_DEFAULT
    };
    properties[7] = {
        tag: huks.HuksTag.HUKS_TAG_BLOCK_MODE,
        value: huks.HuksCipherMode.HUKS_MODE_ECB
    };
Z
zhangcheng 已提交
2907
    let options = {
Z
zhangcheng 已提交
2908 2909
        properties: properties
    };
Z
zhangcheng 已提交
2910
    await publicGenKeyFunc(aliasString, options);
Z
zhangcheng 已提交
2911 2912

    /* 集成证书参数集 */
Z
zhangcheng 已提交
2913
    let attestProperties = new Array();
Z
zhangcheng 已提交
2914
    attestProperties[0] = {
Z
zhangcheng 已提交
2915 2916 2917
        tag: huks.HuksTag.HUKS_TAG_ATTESTATION_ID_SEC_LEVEL_INFO,
        value: securityLevel
    };
Z
zhangcheng 已提交
2918
    attestProperties[1] = {
Z
zhangcheng 已提交
2919 2920 2921
        tag: huks.HuksTag.HUKS_TAG_ATTESTATION_CHALLENGE,
        value: challenge
    };
Z
zhangcheng 已提交
2922
    attestProperties[2] = {
Z
zhangcheng 已提交
2923 2924 2925
        tag: huks.HuksTag.HUKS_TAG_ATTESTATION_ID_VERSION_INFO,
        value: versionInfo
    };
Z
zhangcheng 已提交
2926
    attestProperties[3] = {
Z
zhangcheng 已提交
2927 2928 2929
        tag: huks.HuksTag.HUKS_TAG_ATTESTATION_ID_ALIAS,
        value: aliasUint8
    };
Z
zhangcheng 已提交
2930
    attestProperties[4] = {
Z
zhangcheng 已提交
2931 2932 2933
        tag: huks.HuksTag.HUKS_TAG_ATTESTATION_ID_UDID,
        value: udid
    };
Z
zhangcheng 已提交
2934
    attestProperties[5] = {
Z
zhangcheng 已提交
2935 2936 2937
        tag: huks.HuksTag.HUKS_TAG_ATTESTATION_ID_SERIAL,
        value: serial
    };
Z
zhangcheng 已提交
2938
    attestProperties[6] = {
Z
zhangcheng 已提交
2939 2940 2941
        tag: huks.HuksTag.HUKS_TAG_ATTESTATION_ID_DEVICE,
        value: deviceId
    };
Z
zhangcheng 已提交
2942
    let huksOptions = {
Z
zhangcheng 已提交
2943
        properties: attestProperties
Z
zhangcheng 已提交
2944 2945
    };

Z
zhangcheng 已提交
2946 2947 2948 2949 2950 2951 2952 2953 2954 2955 2956 2957 2958 2959 2960 2961 2962 2963 2964 2965 2966 2967 2968 2969 2970 2971
    await publicAttestKey(aliasString, huksOptions);

    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%')
    }
Z
zhangcheng 已提交
2972 2973 2974 2975 2976
}
```

### AttestKey

2977 2978 2979
应用生成非对称密钥后,可以通过Key attestation获取证书链。应用还可以通过id attestation获取证书链,其中公证书带有设备id等信息。

ID Attestation和Key Attestation只有拥有TEE环境的设备才具备该功能。
Z
zhangcheng 已提交
2980

Z
zhangcheng 已提交
2981
开发步骤如下:
Z
zhangcheng 已提交
2982

Z
zhangcheng 已提交
2983 2984 2985
1. 生成证书。
2. 获取证书信息。

2986 2987 2988 2989 2990 2991 2992 2993
**支持的密钥类型:**

RSA512, RSA768, RSA1024, RSA2048, RSA3072, RSA4096, ECC224, ECC256, ECC384, ECC521, X25519

> **说明**
>
> 存储的 keyAlias 密钥别名最大为64字节

Z
zhangcheng 已提交
2994
在使用示例前,需要先了解几个预先定义的变量: 
Z
zhangcheng 已提交
2995 2996 2997 2998 2999 3000

| 参数名   | 类型        | 必填 | 说明                                 |
| -------- | ----------- | ---- | ------------------------------------ |
| keyAlias | string      | 是   | 密钥别名,存放待获取证书密钥的别名。 |
| options  | HuksOptions | 是   | 用于获取证书时指定所需参数与数据。   |

Z
zhangcheng 已提交
3001
关于接口的具体信息,可在[API参考文档](../reference/apis/js-apis-huks.md)中查看。
Z
zhangcheng 已提交
3002 3003 3004

**示例:**

Z
zhangcheng 已提交
3005
```ts
Z
zhangcheng 已提交
3006
/* 证书AttestKey操作示例如下*/
Z
zhangcheng 已提交
3007 3008 3009
import huks from '@ohos.security.huks';

function StringToUint8Array(str) {
Z
zhangcheng 已提交
3010 3011
    let arr = [];
    for (let i = 0, j = str.length; i < j; ++i) {
Z
zhangcheng 已提交
3012
        arr.push(str.charCodeAt(i));
Z
zhangcheng 已提交
3013
    }
Z
zhangcheng 已提交
3014 3015 3016 3017 3018 3019 3020 3021 3022 3023 3024 3025 3026 3027 3028 3029 3030 3031 3032 3033 3034 3035 3036 3037 3038 3039 3040 3041 3042 3043 3044 3045 3046 3047 3048 3049 3050 3051 3052 3053 3054 3055 3056 3057 3058 3059 3060 3061 3062 3063 3064 3065 3066 3067 3068 3069 3070 3071 3072 3073 3074 3075 3076 3077 3078 3079 3080 3081 3082 3083 3084 3085 3086 3087 3088 3089 3090 3091
    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 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}`);
    }
Z
zhangcheng 已提交
3092 3093
}

Z
zhangcheng 已提交
3094 3095 3096 3097 3098 3099 3100 3101 3102 3103 3104 3105 3106 3107
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);
        }
    });
Z
zhangcheng 已提交
3108 3109
}

Z
zhangcheng 已提交
3110 3111 3112 3113
let securityLevel = StringToUint8Array('sec_level');
let challenge = StringToUint8Array('challenge_data');
let versionInfo = StringToUint8Array('version_info');
let keyAliasString = "key attest";
Z
zhangcheng 已提交
3114

Z
zhangcheng 已提交
3115
async function testAttestKey() {
Z
zhangcheng 已提交
3116 3117
    let aliasString = keyAliasString;
    let aliasUint8 = StringToUint8Array(aliasString);
Z
zhangcheng 已提交
3118

Z
zhangcheng 已提交
3119
    let properties = new Array();
Z
zhangcheng 已提交
3120
    properties[0] = {
Z
zhangcheng 已提交
3121 3122
        tag: huks.HuksTag.HUKS_TAG_ALGORITHM,
        value: huks.HuksKeyAlg.HUKS_ALG_RSA
Z
zhangcheng 已提交
3123 3124
    };
    properties[1] = {
Z
zhangcheng 已提交
3125 3126
        tag: huks.HuksTag.HUKS_TAG_KEY_STORAGE_FLAG,
        value: huks.HuksKeyStorageType.HUKS_STORAGE_PERSISTENT
Z
zhangcheng 已提交
3127 3128 3129
    };
    properties[2] = {
        tag: huks.HuksTag.HUKS_TAG_KEY_SIZE,
Z
zhangcheng 已提交
3130
        value: huks.HuksKeySize.HUKS_RSA_KEY_SIZE_2048
Z
zhangcheng 已提交
3131 3132
    };
    properties[3] = {
Z
zhangcheng 已提交
3133 3134
        tag: huks.HuksTag.HUKS_TAG_PURPOSE,
        value: huks.HuksKeyPurpose.HUKS_KEY_PURPOSE_VERIFY
Z
zhangcheng 已提交
3135 3136
    };
    properties[4] = {
Z
zhangcheng 已提交
3137 3138 3139 3140 3141 3142 3143 3144 3145 3146 3147 3148 3149 3150 3151
        tag: huks.HuksTag.HUKS_TAG_DIGEST,
        value: huks.HuksKeyDigest.HUKS_DIGEST_SHA256
    };
    properties[5] = {
        tag: huks.HuksTag.HUKS_TAG_PADDING,
        value: huks.HuksKeyPadding.HUKS_PADDING_PSS
    };
    properties[6] = {
        tag: huks.HuksTag.HUKS_TAG_KEY_GENERATE_TYPE,
        value: huks.HuksKeyGenerateType.HUKS_KEY_GENERATE_TYPE_DEFAULT
    };
    properties[7] = {
        tag: huks.HuksTag.HUKS_TAG_BLOCK_MODE,
        value: huks.HuksCipherMode.HUKS_MODE_ECB
    };
Z
zhangcheng 已提交
3152
    let options = {
Z
zhangcheng 已提交
3153 3154
        properties: properties
    };
Z
zhangcheng 已提交
3155
    await publicGenKeyFunc(aliasString, options);
Z
zhangcheng 已提交
3156 3157

    /* 集成证书参数集 */
Z
zhangcheng 已提交
3158
    let attestProperties = new Array();
Z
zhangcheng 已提交
3159
    attestProperties[0] = {
Z
zhangcheng 已提交
3160 3161 3162
        tag: huks.HuksTag.HUKS_TAG_ATTESTATION_ID_SEC_LEVEL_INFO,
        value: securityLevel
    };
Z
zhangcheng 已提交
3163
    attestProperties[1] = {
Z
zhangcheng 已提交
3164 3165 3166
        tag: huks.HuksTag.HUKS_TAG_ATTESTATION_CHALLENGE,
        value: challenge
    };
Z
zhangcheng 已提交
3167
    attestProperties[2] = {
Z
zhangcheng 已提交
3168 3169 3170
        tag: huks.HuksTag.HUKS_TAG_ATTESTATION_ID_VERSION_INFO,
        value: versionInfo
    };
Z
zhangcheng 已提交
3171
    attestProperties[3] = {
Z
zhangcheng 已提交
3172 3173 3174
        tag: huks.HuksTag.HUKS_TAG_ATTESTATION_ID_ALIAS,
        value: aliasUint8
    };
Z
zhangcheng 已提交
3175
    let huksOptions = {
Z
zhangcheng 已提交
3176
        properties: attestProperties
Z
zhangcheng 已提交
3177
    };
Z
zhangcheng 已提交
3178 3179 3180 3181 3182 3183 3184 3185 3186 3187 3188 3189 3190 3191 3192 3193 3194 3195 3196 3197 3198 3199 3200 3201 3202 3203 3204

    await publicAttestKey(aliasString, huksOptions);

    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%')
    }
Z
zhangcheng 已提交
3205 3206
}
```
Z
zengyawen 已提交
3207 3208