huks-guidelines.md 95.0 KB
Newer Older
Z
zengyawen 已提交
1

W
wKyrong 已提交
2 3 4 5 6 7
# 通用密钥库开发指导

## 生成新密钥

HUKS提供为业务安全随机生成密钥的能力。通过HUKS生成的密钥,密钥的全生命周期明文不会出安全环境,能保证任何人都无法接触获取到密钥的明文。即使生成密钥的业务自身,后续也只能通过HUKS提供的接口请求执行密钥操作,获取操作结果,但无法接触到密钥自身。

Z
zengyawen 已提交
8
**开发步骤**
W
wKyrong 已提交
9 10 11 12 13 14 15

生成密钥时使用[huks.generateKeyItem(keyAlias,options,callback)](../reference/apis/js-apis-huks.md#huksgeneratekeyitem9)方法,传入keyAlias作为密钥别名,传入options包含该密钥的属性集,传入callback用于回调异步结果。关于接口的具体信息,可在[API参考文档](../reference/apis/js-apis-huks.md)中查看。

1. 确定密钥别名;
2. 初始化密钥属性集:通过[HuksParam](../reference/apis/js-apis-huks.md#huksparam)封装密钥属性,搭配Array组成密钥属性集,并赋值给[HuksOptions](../reference/apis/js-apis-huks.md#huksoptions)(properties字段),其中必须包含[HuksKeyAlg](../reference/apis/js-apis-huks.md#hukskeyalg),[HuksKeySize](../reference/apis/js-apis-huks.md#hukskeysize),[HuksKeyPurpose](../reference/apis/js-apis-huks.md#hukskeypurpose)属性;
3. 将密钥别名与密钥参数集作为参数传入,生成密钥。

Z
zhangcheng 已提交
16 17
> **说明**
>
W
wKyrong 已提交
18
> 存储的 keyAlias 密钥别名最大为64字节
Z
zhangcheng 已提交
19

W
wKyrong 已提交
20
**代码示例:**
Z
zhangcheng 已提交
21 22

```ts
W
wKyrong 已提交
23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 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
/*
 * 以下以生成DH密钥的Callback操作使用为例
 */
import huks from '@ohos.security.huks';

/*
 * 确定密钥别名和封装密钥属性参数集
 */
let keyAlias = 'dh_key';
let properties = new Array();
properties[0] = {
    tag: huks.HuksTag.HUKS_TAG_ALGORITHM,
    value: huks.HuksKeyAlg.HUKS_ALG_DH
}
properties[1] = {
    tag: huks.HuksTag.HUKS_TAG_PURPOSE,
    value: huks.HuksKeyPurpose.HUKS_KEY_PURPOSE_AGREE
}
properties[2] = {
    tag: huks.HuksTag.HUKS_TAG_KEY_SIZE,
    value: huks.HuksKeySize.HUKS_DH_KEY_SIZE_2048
}
properties[3] = {
    tag: huks.HuksTag.HUKS_TAG_DIGEST,
    value: huks.HuksKeyDigest.HUKS_DIGEST_SHA256
}
let huksOptions = {
    properties: properties,
    inData: new Uint8Array(new Array())
}

/*
 * 生成密钥
 */
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 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}`);
    }
}


async function TestGenKey() {
    await publicGenKeyFunc(keyAlias, huksOptions);
}
Z
zhangcheng 已提交
92
```
Z
zhangcheng 已提交
93

W
wKyrong 已提交
94 95 96 97
## 导入外部密钥
如果密钥是在HUKS外部生成(比如应用间协商生成、服务器端生成),应用可以将密钥导入到HUKS托管。HUKS支持直接将密钥明文导入到HUKS,但是明文导入会导致密钥暴露在REE内存中,一般适用于轻量级设备或低安业务。对于高安敏感业务,HUKS还提供了安全导入密钥的能力,允许业务自己生成密钥,并通过与处于安全环境中的HUKS建立端到端的加密传输通道,将密钥安全加密导入到HUKS中,确保导入传入过程中密钥不被泄露。

与生成密钥一样,密钥一旦导入到HUKS中,密钥的生命周期明文不出安全环境,同样能保证任何人都无法接触获取到密钥的明文。
J
jianjew 已提交
98

J
--amend  
jianjew 已提交
99

J
jianjew 已提交
100

W
wKyrong 已提交
101
### 明文导入
J
jianjew 已提交
102 103


W
wKyrong 已提交
104
导入明文密钥时使用[huks.importKeyItem(keyAlias,options,callback)](../reference/apis/js-apis-huks.md#huksimportkeyitem9)方法,传入keyAlias作为密钥别名,传入options,其中必须包含密钥材料和密钥属性集,传入callback用于回调异步结果。关于接口的具体信息,可在[API参考文档](../reference/apis/js-apis-huks.md)中查看。
J
jianjew 已提交
105 106


W
wKyrong 已提交
107 108 109 110
1. 确定密钥别名;
2. 封装密钥材料和密钥属性集:密钥材料须符合[HUKS密钥材料格式](./huks-appendix.md#密钥材料格式)并以Uint8Array形式赋值给[HuksOptions](../reference/apis/js-apis-huks.md#huksoptions)的inData字段;另外,通过[HuksParam](../reference/apis/js-apis-huks.md#huksparam)封装密钥属性,搭配Array组成密钥属性集赋值给properties字段,属性集中必须包含[HuksKeyAlg](../reference/apis/js-apis-huks.md#hukskeyalg),[HuksKeySize](../reference/apis/js-apis-huks.md#hukskeysize),[HuksKeyPurpose](../reference/apis/js-apis-huks.md#hukskeypurpose)属性;
3. 导入密钥。

J
jianjew 已提交
111

W
wKyrong 已提交
112 113

**代码示例:**
J
jianjew 已提交
114 115

```ts
W
wKyrong 已提交
116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133
/*
 * 以导入AES256密钥为例
 */
 
/* 密钥 */
let plainTextSize32 = new Uint8Array([
  0xfb, 0x8b, 0x9f, 0x12, 0xa0, 0x83, 0x19, 0xbe, 0x6a, 0x6f, 0x63, 0x2a, 0x7c, 0x86, 0xba, 0xca,
  0x64, 0x0b, 0x88, 0x96, 0xe2, 0xfa, 0x77, 0xbc, 0x71, 0xe3, 0x0f, 0x0f, 0x9e, 0x3c, 0xe5, 0xf9
]);

/*
 * 确定密钥别名
 */
let keyAlias = 'AES256Alias_sample';

/*
 * 封装密钥属性集和密钥材料
 */ 
J
jianjew 已提交
134 135 136
let properties = new Array();
properties[0] = {
    tag: huks.HuksTag.HUKS_TAG_ALGORITHM,
W
wKyrong 已提交
137
    value: huks.HuksKeyAlg.HUKS_ALG_AES
J
jianjew 已提交
138 139 140
};
properties[1] = {
    tag: huks.HuksTag.HUKS_TAG_KEY_SIZE,
W
wKyrong 已提交
141
    value: huks.HuksKeySize.HUKS_AES_KEY_SIZE_256
J
jianjew 已提交
142 143 144 145
};
properties[2] = {
    tag: huks.HuksTag.HUKS_TAG_PURPOSE,
    value:
W
wKyrong 已提交
146
    huks.HuksKeyPurpose.HUKS_KEY_PURPOSE_ENCRYPT | huks.HuksKeyPurpose.HUKS_KEY_PURPOSE_DECRYPT
J
jianjew 已提交
147 148
};
let options = {
W
wKyrong 已提交
149 150
    properties: properties,
    inData: plainTextSize32
J
jianjew 已提交
151
};
W
wKyrong 已提交
152 153 154 155

/*
 * 导入密钥
 */
J
jianjew 已提交
156
try {
W
wKyrong 已提交
157
    huks.importKeyItem(keyAlias, options, function (error, data) {
J
jianjew 已提交
158
        if (error) {
W
wKyrong 已提交
159
            console.error(`callback: importKeyItem failed, code: ${error.code}, msg: ${error.message}`);
J
jianjew 已提交
160
        } else {
W
wKyrong 已提交
161
            console.info(`callback: importKeyItem success`);
J
jianjew 已提交
162 163 164
        }
    });
} catch (error) {
W
wKyrong 已提交
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 193 194 195 196 197 198 199 200 201 202
    console.error(`callback: importKeyItem input arg invalid, code: ${error.code}, msg: ${error.message}`);
}
```

**调测验证**

验证时查询密钥是否存在,如密钥存在即表示生成密钥成功。

**代码示例:**

```ts
import huks from '@ohos.security.huks';

let keyAlias = 'AES256Alias_sample';
let isKeyExist;

let keyProperties = new Array();
keyProperties[0] = {
    tag: huks.HuksTag.HUKS_TAG_ALGORITHM,
    value: huks.HuksKeyAlg.HUKS_ALG_AES,
}
let huksOptions = {
    properties: keyProperties, // 非空填充
    inData: new Uint8Array(new Array()) // 非空填充
}
try {
    huks.isKeyItemExist(keyAlias, huksOptions, function (error, data) {
        if (error) {
            console.error(`callback: isKeyItemExist failed, code: ${error.code}, msg: ${error.message}`);
        } else {
            if (data !== null && data.valueOf() !== null) {
                isKeyExist = data.valueOf();
                console.info(`callback: isKeyItemExist success, isKeyExist = ${isKeyExist}`);
            }
        }
    });
} catch (error) {
    console.error(`callback: isKeyItemExist input arg invalid, code: ${error.code}, msg: ${error.message}`);
J
jianjew 已提交
203 204 205
}
```

W
wKyrong 已提交
206
### 加密导入
J
jianjew 已提交
207

W
wKyrong 已提交
208
相比明文导入,加密导入步骤更多,密钥材料更复杂,此章节将展示开发过程中关键的开发流程和密钥材料数据结构。下图是加密导入的基本开发流程。
J
jianjew 已提交
209

Z
zhangcheng 已提交
210

211

W
wKyrong 已提交
212
**图2** 加密导入开发流程
Z
zhangcheng 已提交
213

W
wKyrong 已提交
214
![huks_import_wrapped_key](figures/huks_import_wrapped_key.png)
Z
zhangcheng 已提交
215 216


217 218


W
wKyrong 已提交
219
**接口说明**
220

W
wKyrong 已提交
221 222 223 224
根据开发流程,在导入加密密钥过程中,需要依次调用HUKS的生成密钥、导出公钥、导入加密密钥、删除密钥接口。
| 接口名                      | 描述                 |
| -------------------------------------- | ----------------------------|
|generateKeyItem(keyAlias: string, options: HuksOptions, callback: AsyncCallback\<void>) : void| 生成新密钥|
Z
zengyawen 已提交
225 226 227
|exportKeyItem(keyAlias: string, options: HuksOptions, callback: AsyncCallback\<HuksReturnResult>) : void| 导出密钥对的公钥|
|importWrappedKeyItem(keyAlias: string, wrappingKeyAlias: string, options: HuksOptions, callback: AsyncCallback\<void>) : void|导入加密密钥|
|deleteKeyItem(keyAlias: string, options: HuksOptions, callback: AsyncCallback\<void>) : void|删除密钥|
228

W
wKyrong 已提交
229 230 231
需要注意的是,导出密钥接口返回的公钥明文材料是按照**X.509**格式封装,导入加密密钥接口中的密钥材料需满足**Length<sub>Data</sub>-Data** 的格式封装。具体,应用需要申请一个Uint8Array按照以下表格中的顺序依次封装。

**表2** 加密密钥材料格式
232

G
gaoshuyang 已提交
233
| 内容 | 业务公钥长度L<sub>pk2</sub> | 业务公钥pk2 | k2加密参数AAD2长度L<sub>AAD2</sub> | k2加密参数AAD2 |  k2加密参数Nonce2长度L<sub>Nonce2</sub> | k2加密参数Nonce2 |
W
wKyrong 已提交
234 235
| :--: |:----:|:----: |:----: | :----:  | :----:|:----:|
|长度| 4字节 |L<sub>pk2</sub>字节| 4字节 | L<sub>AAD2</sub>字节 | 4字节 | L<sub>Nonce2</sub>字节 |
G
gaoshuyang 已提交
236
| 内容 | k2加密参数AEAD2长度L<sub>AEAD2</sub> | k2加密参数AEAD2 | k3密文长度L<sub>k3_enc</sub> | k3密文k3_enc |  k3加密参数AAD3长度L<sub>AAD3</sub> | k3加密参数AAD3 |
W
wKyrong 已提交
237
|长度| 4字节 |L<sub>AEAD2</sub>字节| 4字节 | L<sub>k3_enc</sub>字节 | 4字节 | L<sub>AAD3</sub>字节 |
G
gaoshuyang 已提交
238
| 内容| k3加密参数Nonce3长度L<sub>Nonce3</sub> | k3加密参数Nonce3 | k3加密参数AEAD3长度L<sub>AEAD3</sub> | k3加密参数AEAD3 |  **密钥明文材料长度** 的长度L<sub>k1'_size</sub> | 密钥明文材料长度k1'_size |
W
wKyrong 已提交
239 240 241
|长度| 4字节 |L<sub>Nonce3</sub>字节| 4字节 | L<sub>AEAD3</sub>字节 | 4字节 | L<sub>k1'_size</sub>字节 |
|内容|k1'密文长度L<sub>k1'_enc</sub>| k1'密文k1'_enc| | | | |
|长度| 4字节 |L<sub>k1'_enc</sub>字节| | | | |
Z
zhangcheng 已提交
242

W
wKyrong 已提交
243
**开发步骤**
Z
zhangcheng 已提交
244

W
wKyrong 已提交
245 246 247 248 249 250 251
这里主要展示涉及调用HUKS的开发样例(使用ECDH密钥协商套件),部分在业务本地执行的步骤不在这里展示详细样例。
1. 转换成HUKS格式的密钥材料
2. 生成加密导入用途的密钥
3. 导出公钥材料
4. 封装加密导入密钥材料
5. 导入封装的加密密钥材料
6. 删除用于加密导入的密钥
Z
zhangcheng 已提交
252

W
wKyrong 已提交
253
**代码示例:**
Z
zhangcheng 已提交
254

Z
zhangcheng 已提交
255
```ts
W
wKyrong 已提交
256 257 258
/*
 * 以下以SM2密钥的Callback操作验证为例
 */
Z
zhangcheng 已提交
259 260
import huks from '@ohos.security.huks';

W
wKyrong 已提交
261 262 263 264 265 266
/*
 * 确定密钥别名
 */
let importAlias = "importAlias";
let wrapAlias = "wrappingKeyAlias";
let exportKey;
Z
zhangcheng 已提交
267

W
wKyrong 已提交
268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286
/*
 * 加密导入用途的密钥材料原文:转换成HUKS ECC-P-256密钥对格式的密钥材料
 */
let inputEccPair = new Uint8Array([
    0x02, 0x00, 0x00, 0x00, // 密钥算法:huks.HuksKeyAlg.HUKS_ALG_ECC = 2
    0x00, 0x01, 0x00, 0x00, // 密钥大小(比特):256
    0x20, 0x00, 0x00, 0x00, // 坐标x长度(字节):32
    0x20, 0x00, 0x00, 0x00, // 坐标y长度(字节):32
    0x20, 0x00, 0x00, 0x00, // 坐标z长度(字节):32
    // 坐标x
    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,
    // 坐标y
    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,
    // 坐标z
    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 已提交
287

W
wKyrong 已提交
288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316
/*
 * 封装密钥属性参数集
 */
// 生成加密导入用途的密钥的属性集
let properties = new Array();
properties[0] = {
    tag: huks.HuksTag.HUKS_TAG_ALGORITHM,
    value: huks.HuksKeyAlg.HUKS_ALG_ECC
};
properties[1] = {
    tag: huks.HuksTag.HUKS_TAG_KEY_SIZE,
    value: huks.HuksKeySize.HUKS_ECC_KEY_SIZE_256
};
properties[2] = {
    tag: huks.HuksTag.HUKS_TAG_PURPOSE,
    value: huks.HuksKeyPurpose.HUKS_KEY_PURPOSE_UNWRAP
};
properties[3] = {
    tag: huks.HuksTag.HUKS_TAG_DIGEST,
    value: huks.HuksKeyDigest.HUKS_DIGEST_SHA256
};
properties[4] = {
    tag: huks.HuksTag.HUKS_TAG_IMPORT_KEY_TYPE,
    value: huks.HuksImportKeyType.HUKS_KEY_TYPE_KEY_PAIR,
};
let huksOptions = {
    properties: properties,
    inData: inputEccPair
};
Z
zhangcheng 已提交
317

W
wKyrong 已提交
318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347
// 待导入密钥的属性集:AES256
let importProperties = new Array();
importProperties[0] = {
    tag: huks.HuksTag.HUKS_TAG_ALGORITHM,
    value: huks.HuksKeyAlg.HUKS_ALG_AES
};
importProperties[1] = {
    tag: huks.HuksTag.HUKS_TAG_KEY_SIZE,
    value: huks.HuksKeySize.HUKS_AES_KEY_SIZE_256
};
importProperties[2] = {
    tag: huks.HuksTag.HUKS_TAG_PURPOSE,
    value: huks.HuksKeyPurpose.HUKS_KEY_PURPOSE_ENCRYPT | huks.HuksKeyPurpose.HUKS_KEY_PURPOSE_DECRYPT
};
importProperties[3] = {
    tag: huks.HuksTag.HUKS_TAG_BLOCK_MODE,
    value: huks.HuksCipherMode.HUKS_MODE_CBC
};
importProperties[4] = {
    tag: huks.HuksTag.HUKS_TAG_PADDING,
    value: huks.HuksKeyPadding.HUKS_PADDING_NONE
};
importProperties[5] = {
    tag: huks.HuksTag.HUKS_TAG_UNWRAP_ALGORITHM_SUITE,
    value: huks.HuksUnwrapSuite.HUKS_UNWRAP_SUITE_ECDH_AES_256_GCM_NOPADDING // 使用“ECDH+AES256GCM”加密导入套件
};
let importOptions = {
    properties: importProperties,
    inData: new Uint8Array(new Array())
};
Z
zhangcheng 已提交
348

W
wKyrong 已提交
349 350
// 导出加密导入用途的公钥
function exportKeyItem(keyAlias:string, huksOptions:huks.HuksOptions, throwObject) : Promise<huks.HuksReturnResult> {
Z
zhangcheng 已提交
351 352
    return new Promise((resolve, reject) => {
        try {
W
wKyrong 已提交
353
            huks.exportKeyItem(keyAlias, huksOptions, function (error, data) {
Z
zhangcheng 已提交
354 355 356 357 358 359 360
                if (error) {
                    reject(error);
                } else {
                    resolve(data);
                }
            });
        } catch (error) {
W
wKyrong 已提交
361 362
            throwObject.isThrow = true;
            throw(error);
Z
zhangcheng 已提交
363 364 365 366
        }
    });
}

W
wKyrong 已提交
367
async function publicExportKeyFunc(keyAlias:string, huksOptions:huks.HuksOptions) {
Z
zhangcheng 已提交
368
    console.info(`enter callback export`);
W
wKyrong 已提交
369
    let throwObject = {isThrow: false};
Z
zhangcheng 已提交
370
    try {
W
wKyrong 已提交
371 372
        await exportKeyItem(keyAlias, huksOptions, throwObject)
            .then ((data) => {
Z
zhangcheng 已提交
373
                console.info(`callback: exportKeyItem success, data = ${JSON.stringify(data)}`);
W
wKyrong 已提交
374
                exportKey = data.outData;
Z
zhangcheng 已提交
375 376
            })
            .catch(error => {
W
wKyrong 已提交
377 378 379 380 381
                if (throwObject.isThrow) {
                    throw(error);
                } else {
                    console.error(`callback: exportKeyItem failed, code: ${error.code}, msg: ${error.message}`);
                }
Z
zhangcheng 已提交
382 383 384 385 386 387
            });
    } catch (error) {
        console.error(`callback: exportKeyItem input arg invalid, code: ${error.code}, msg: ${error.message}`);
    }
}

W
wKyrong 已提交
388 389
// 此处用导入密钥来模拟“生成加密导入用途的密钥”
function importKeyItem(keyAlias:string, huksOptions:huks.HuksOptions, throwObject) {
Z
zhangcheng 已提交
390 391
    return new Promise((resolve, reject) => {
        try {
W
wKyrong 已提交
392
            huks.importKeyItem(keyAlias, huksOptions, function (error, data) {
Z
zhangcheng 已提交
393 394
                if (error) {
                    reject(error);
W
wKyrong 已提交
395
                } else {
Z
zhangcheng 已提交
396 397 398 399
                    resolve(data);
                }
            });
        } catch (error) {
W
wKyrong 已提交
400 401
            throwObject.isThrow = true;
            throw(error);
Z
zhangcheng 已提交
402 403 404 405
        }
    });
}

W
wKyrong 已提交
406
async function publicImportKeyFunc(keyAlias:string, huksOptions:huks.HuksOptions) {
Z
zhangcheng 已提交
407
    console.info(`enter promise importKeyItem`);
W
wKyrong 已提交
408
    let throwObject = {isThrow: false};
Z
zhangcheng 已提交
409
    try {
W
wKyrong 已提交
410 411
        await importKeyItem(keyAlias, huksOptions, throwObject)
            .then ((data) => {
Z
zhangcheng 已提交
412 413 414
                console.info(`callback: importKeyItem success, data = ${JSON.stringify(data)}`);
            })
            .catch(error => {
W
wKyrong 已提交
415 416 417 418 419
                if (throwObject.isThrow) {
                    throw(error);
                } else {
                    console.error(`callback: importKeyItem failed, code: ${error.code}, msg: ${error.message}`);
                }
Z
zhangcheng 已提交
420 421 422 423 424 425
            });
    } catch (error) {
        console.error(`callback: importKeyItem input arg invalid, code: ${error.code}, msg: ${error.message}`);
    }
}

W
wKyrong 已提交
426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447
// 执行加密导入
async function publicImportWrappedKey(keyAlias:string, wrappingKeyAlias:string, huksOptions:huks.HuksOptions) {
    console.info(`enter callback importWrappedKeyItem`);
    var throwObject = {isThrow: false};
    try {
        await importWrappedKeyItem(keyAlias, wrappingKeyAlias, huksOptions, throwObject)
            .then ((data) => {
                console.info(`callback: importWrappedKeyItem success, data = ${JSON.stringify(data)}`);
            })
            .catch(error => {
                if (throwObject.isThrow) {
                    throw(error);
                } else {
                    console.error(`callback: importWrappedKeyItem failed, code: ${error.code}, msg: ${error.message}`);
                }
            });
    } catch (error) {
        console.error(`callback: importWrappedKeyItem input arg invalid, code: ${error.code}, msg: ${error.message}`);
    }
}

function importWrappedKeyItem(keyAlias:string, wrappingKeyAlias:string, huksOptions:huks.HuksOptions, throwObject) {
Z
zhangcheng 已提交
448 449
    return new Promise((resolve, reject) => {
        try {
W
wKyrong 已提交
450
            huks.importWrappedKeyItem(keyAlias, wrappingKeyAlias, huksOptions, function (error, data) {
Z
zhangcheng 已提交
451 452 453
                if (error) {
                    reject(error);
                } else {
W
wKyrong 已提交
454
                    resolve(data);
Z
zhangcheng 已提交
455 456 457
                }
            });
        } catch (error) {
W
wKyrong 已提交
458 459
            throwObject.isThrow = true;
            throw(error);
Z
zhangcheng 已提交
460 461 462 463
        }
    });
}

W
wKyrong 已提交
464 465
// 删除加密导入用途的密钥
function deleteKeyItem(keyAlias:string, huksOptions:huks.HuksOptions, throwObject) {
Z
zhangcheng 已提交
466 467 468 469 470 471 472 473 474 475
    return new Promise((resolve, reject) => {
        try {
            huks.deleteKeyItem(keyAlias, huksOptions, function (error, data) {
                if (error) {
                    reject(error);
                } else {
                    resolve(data);
                }
            });
        } catch (error) {
W
wKyrong 已提交
476 477
            throwObject.isThrow = true;
            throw(error);
Z
zhangcheng 已提交
478 479 480 481
        }
    });
}

W
wKyrong 已提交
482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498
async function publicDeleteKeyFunc(keyAlias:string, huksOptions:huks.HuksOptions) {
    console.info(`enter callback deleteKeyItem`);
    let throwObject = {isThrow: false};
    try {
        await deleteKeyItem(keyAlias, huksOptions, throwObject)
            .then ((data) => {
                console.info(`callback: deleteKeyItem key success, data = ${JSON.stringify(data)}`);
            })
            .catch(error => {
                if (throwObject.isThrow) {
                    throw(error);
                } else {
                    console.error(`callback: deleteKeyItem failed, code: ${error.code}, msg: ${error.message}`);
                }
            });
    } catch (error) {
        console.error(`callback: deletKeeyItem input arg invalid, code: ${error.code}, msg: ${error.message}`);
Z
zhangcheng 已提交
499
    }
W
wKyrong 已提交
500
}
Z
zhangcheng 已提交
501

W
wKyrong 已提交
502 503 504 505 506 507
async function ImportWrappedKeyNormalTest() {
    console.info(`enter ImportWrapKey test`);
    /*
     * 生成加密导入用途的密钥(此处使用导入进行模拟)
     */
    await publicImportKeyFunc(wrapAlias, huksOptions);
Z
zhangcheng 已提交
508

W
wKyrong 已提交
509 510 511 512
    /*
     * 导出加密导入用途密钥的公钥材料
     */
    await publicExportKeyFunc(wrapAlias, huksOptions);
Z
zhangcheng 已提交
513

W
wKyrong 已提交
514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574
    /*----------------------------------------------------------------------------------------------
     * 此处省略业务本地生成ECC密钥对、业务本地ECDH密钥协商、业务本地生成密钥加密密钥K3、业务本地加密K1'和K3的流程
     *----------------------------------------------------------------------------------------------*/

    /* 封装加密导入密钥材料:参考加密导入
     * 拼接importOptions.inData字段,满足以下格式:
     * PK2长度(4字节)     + PK2的数据     + AAD2的长度(4字节) + AAD2的数据 +
     * Nonce2的长度(4字节)+ Nonce2的数据  + AEAD2的长度(4字节) + AEAD2的数据 +
     * K3密文的长度(4字节) + K3密文的数据  + AAD3的长度(4字节) + AAD3的数据 +
     * Nonce3的长度(4字节) + Nonce3的数据  + AEAD3的长度(4字节) + AEAD3的数据 +
     * K1'_size的长度(4字节) + K1'_size   + K1'_enc的长度(4字节) + K1'_enc的数据
     */
    let inputKey = new Uint8Array([
        0x5b, 0x00, 0x00, 0x00, // ECC-P-256 公钥长度(X.509规范DER格式):91
        // ECC-P-256 公钥
        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, // AAD2长度:16
        // AAD2
        0xbf, 0xf9, 0x69, 0x41, 0xf5, 0x49, 0x85, 0x31, 0x35, 0x14, 0x69, 0x12, 0x57, 0x9c, 0xc8, 0xb7,

        0x10, 0x00, 0x00, 0x00, // Nonce2长度:16
        // Nonce2
        0x2d, 0xb7, 0xf1, 0x5a, 0x0f, 0xb8, 0x20, 0xc5, 0x90, 0xe5, 0xca, 0x45, 0x84, 0x5c, 0x08, 0x08,

        0x10, 0x00, 0x00, 0x00, // AEAD2长度:16
        // AEAD2
        0x43, 0x25, 0x1b, 0x2f, 0x5b, 0x86, 0xd8, 0x87, 0x04, 0x4d, 0x38, 0xc2, 0x65, 0xcc, 0x9e, 0xb7,

        0x20, 0x00, 0x00, 0x00, // K3密文长度:32
        // K3密文
        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, // AAD3长度:16
        // AAD3
        0xf4, 0x1e, 0x7b, 0x01, 0x7a, 0x84, 0x36, 0xa4, 0xa8, 0x1c, 0x0d, 0x3d, 0xde, 0x57, 0x66, 0x73,

        0x10, 0x00, 0x00, 0x00, // Nonce3长度:16
        // Nonce3
        0xe3, 0xff, 0x29, 0x97, 0xad, 0xb3, 0x4a, 0x2c, 0x50, 0x08, 0xb5, 0x68, 0xe1, 0x90, 0x5a, 0xdc,

        0x10, 0x00, 0x00, 0x00, // AEAD3长度:16
        // AEAD3
        0x26, 0xae, 0xdc, 0x4e, 0xa5, 0x6e, 0xb1, 0x38, 0x14, 0x24, 0x47, 0x1c, 0x41, 0x89, 0x63, 0x11,

        0x04, 0x00, 0x00, 0x00, // “密钥明文材料长度”的长度(字节):4
        // 密钥明文材料的长度:32字节
        0x20, 0x00, 0x00, 0x00,

        0x20, 0x00, 0x00, 0x00, // 待导入密钥密文长度(字节):32
        // 待导入密钥密文
        0x0b, 0xcb, 0xa9, 0xa8, 0x5f, 0x5a, 0x9d, 0xbf, 0xa1, 0xfc, 0x72, 0x74, 0x87, 0x79, 0xf2, 0xf4,
        0x22, 0x0c, 0x8a, 0x4d, 0xd8, 0x7e, 0x10, 0xc8, 0x44, 0x17, 0x95, 0xab, 0x3b, 0xd2, 0x8f, 0x0a
    ]);
    importOptions.inData = inputKey;
Z
zhangcheng 已提交
575

W
wKyrong 已提交
576 577 578 579
    /*
     * 导入封装的加密密钥材料
     */
    await publicImportWrappedKey(importAlias, wrapAlias, importOptions);
Z
zhangcheng 已提交
580

W
wKyrong 已提交
581 582 583 584
    /*
     * 删除用于加密导入的密钥
     */
    await publicDeleteKeyFunc(wrapAlias, huksOptions);
Z
zhangcheng 已提交
585
}
W
wKyrong 已提交
586
```
Z
zhangcheng 已提交
587

W
wKyrong 已提交
588
**调测验证**
Z
zhangcheng 已提交
589

W
wKyrong 已提交
590
验证时查询密钥是否存在,如密钥存在即表示生成密钥成功。
Z
zhangcheng 已提交
591

W
wKyrong 已提交
592
**代码示例:**
Z
zhangcheng 已提交
593

W
wKyrong 已提交
594 595
```ts
import huks from '@ohos.security.huks';
Z
zhangcheng 已提交
596

W
wKyrong 已提交
597 598 599 600 601
/*
 * 确定密钥别名和封装密钥属性参数集
 */
let keyAlias = 'importAlias';
let isKeyExist;
Z
zhangcheng 已提交
602

W
wKyrong 已提交
603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620
let keyProperties = new Array();
keyProperties[0] = {
    tag: huks.HuksTag.HUKS_TAG_ALGORITHM,
    value: huks.HuksKeyAlg.HUKS_ALG_AES,
}
let huksOptions = {
    properties: keyProperties, // 非空填充
    inData: new Uint8Array(new Array()) // 非空填充
}
try {
    huks.isKeyItemExist(keyAlias, huksOptions, function (error, data) {
        if (error) {
            console.error(`callback: isKeyItemExist failed, code: ${error.code}, msg: ${error.message}`);
        } else {
            if (data !== null && data.valueOf() !== null) {
                isKeyExist = data.valueOf();
                console.info(`callback: isKeyItemExist success, isKeyExist = ${isKeyExist}`);
            }
Z
zhangcheng 已提交
621
        }
W
wKyrong 已提交
622 623 624
    });
} catch (error) {
    console.error(`callback: isKeyItemExist input arg invalid, code: ${error.code}, msg: ${error.message}`);
Z
zhangcheng 已提交
625
}
Z
zhangcheng 已提交
626 627 628
```


W
wKyrong 已提交
629
## 常见密钥操作
Z
zhangcheng 已提交
630

W
wKyrong 已提交
631
**场景概述**
Z
zhangcheng 已提交
632

W
wKyrong 已提交
633
为了实现对数据机密性、完整性等保护,在生成/导入密钥后,需要对数据进行密钥操作,比如加密解密、签名验签、密钥协商、密钥派生等,本章节提供了常用的密钥操作的示例。本章节提供的示例都没有设置二次身份访问控制,如设置了密钥访问控制请参考[密钥访问控制](#密钥访问控制)用法。
634

W
wKyrong 已提交
635
**通用开发流程**
636

W
wKyrong 已提交
637 638 639 640
HUKS基于密钥会话来操作数据,使用密钥时基于以下流程:
1. **初始化密钥会话[huks.initSession()](../reference/apis/js-apis-huks.md#huksinitsession9):** 传入密钥别名和密钥操作参数,初始化一个密钥会话并获取会话句柄。其中密钥操作参数中必须包含对应密码算法所必须的参数,包括密码算法、密钥大小、密钥目的、工作模式、填充模式、散列模式、IV、Nonce、AAD等。如果密钥设置了访问控制属性,还需要其他参数具体[密钥访问控制](#密钥访问控制)。此步骤必选!
2. **分段操作数据[huks.updateSession()](../reference/apis/js-apis-huks.md#huksupdatesession9):** 如数据过大(超过100K)或密码算法的要求需要对数据进行分段操作,反之可跳过此步。此步骤可选!
3. **结束密钥会话[huks.finishSession()](../reference/apis/js-apis-huks.md#huksfinishsession9):** 操作最后一段数据并结束密钥会话,如过程中发生错误或不需要此次密钥操作数据,必须取消会话[huks.abortSession()](../reference/apis/js-apis-huks.md#huksabortsession9)。此步骤必选!
641

W
wKyrong 已提交
642 643 644
### 加密解密
```ts
/*
G
gaoshuyang 已提交
645
 * 以下以AES 128密钥的Callback操作使用为例
W
wKyrong 已提交
646 647
 */
import huks from '@ohos.security.huks';
G
gaoshuyang 已提交
648
import promptAction from '@ohos.promptAction';
W
wKyrong 已提交
649

Z
zhangcheng 已提交
650

G
gaoshuyang 已提交
651 652 653 654 655 656
let aesKeyAlias = 'test_aesKeyAlias';
let handle;
let plainText = '123456';
let IV = '001122334455';
let cipherData:Uint8Array;
let plainData:Uint8Array;
Z
zhangcheng 已提交
657

W
wKyrong 已提交
658
function StringToUint8Array(str) {
G
gaoshuyang 已提交
659 660 661 662 663
  let arr = [];
  for (let i = 0, j = str.length; i < j; ++i) {
    arr.push(str.charCodeAt(i));
  }
  return new Uint8Array(arr);
W
wKyrong 已提交
664
}
Z
zhangcheng 已提交
665

W
wKyrong 已提交
666
function Uint8ArrayToString(fileData) {
G
gaoshuyang 已提交
667 668 669 670 671
  let dataString = '';
  for (let i = 0; i < fileData.length; i++) {
    dataString += String.fromCharCode(fileData[i]);
  }
  return dataString;
W
wKyrong 已提交
672
}
Z
zhangcheng 已提交
673

G
gaoshuyang 已提交
674 675 676 677
function GetAesGenerateProperties() {
  var properties = new Array();
  var index = 0;
  properties[index++] = {
W
wKyrong 已提交
678
    tag: huks.HuksTag.HUKS_TAG_ALGORITHM,
G
gaoshuyang 已提交
679 680 681
    value: huks.HuksKeyAlg.HUKS_ALG_AES
  };
  properties[index++] = {
W
wKyrong 已提交
682
    tag: huks.HuksTag.HUKS_TAG_KEY_SIZE,
G
gaoshuyang 已提交
683 684 685 686 687 688 689 690
    value: huks.HuksKeySize.HUKS_AES_KEY_SIZE_128
  };
  properties[index++] = {
    tag: huks.HuksTag.HUKS_TAG_PURPOSE,
    value: huks.HuksKeyPurpose.HUKS_KEY_PURPOSE_ENCRYPT |
           huks.HuksKeyPurpose.HUKS_KEY_PURPOSE_DECRYPT
  }
  return properties;
W
wKyrong 已提交
691
}
Z
zhangcheng 已提交
692

G
gaoshuyang 已提交
693 694 695 696
function GetAesEncryptProperties() {
  var properties = new Array();
  var index = 0;
  properties[index++] = {
W
wKyrong 已提交
697
    tag: huks.HuksTag.HUKS_TAG_ALGORITHM,
G
gaoshuyang 已提交
698 699 700
    value: huks.HuksKeyAlg.HUKS_ALG_AES
  };
  properties[index++] = {
W
wKyrong 已提交
701
    tag: huks.HuksTag.HUKS_TAG_KEY_SIZE,
G
gaoshuyang 已提交
702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720
    value: huks.HuksKeySize.HUKS_AES_KEY_SIZE_128
  };
  properties[index++] = {
    tag: huks.HuksTag.HUKS_TAG_PURPOSE,
    value: huks.HuksKeyPurpose.HUKS_KEY_PURPOSE_ENCRYPT
  }
  properties[index++] = {
    tag: huks.HuksTag.HUKS_TAG_PADDING,
    value: huks.HuksKeyPadding.HUKS_PADDING_PKCS7
  }
  properties[index++] = {
    tag: huks.HuksTag.HUKS_TAG_BLOCK_MODE,
    value: huks.HuksCipherMode.HUKS_MODE_CBC
  }
  properties[index++] = {
    tag: huks.HuksTag.HUKS_TAG_IV,
    value: StringToUint8Array(IV)
  }
  return properties;
W
wKyrong 已提交
721
}
Z
zhangcheng 已提交
722

G
gaoshuyang 已提交
723 724 725 726
function GetAesDecryptProperties() {
  var properties = new Array();
  var index = 0;
  properties[index++] = {
W
wKyrong 已提交
727
    tag: huks.HuksTag.HUKS_TAG_ALGORITHM,
G
gaoshuyang 已提交
728 729 730
    value: huks.HuksKeyAlg.HUKS_ALG_AES
  };
  properties[index++] = {
W
wKyrong 已提交
731
    tag: huks.HuksTag.HUKS_TAG_KEY_SIZE,
G
gaoshuyang 已提交
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
    value: huks.HuksKeySize.HUKS_AES_KEY_SIZE_128
  };
  properties[index++] = {
    tag: huks.HuksTag.HUKS_TAG_PURPOSE,
    value: huks.HuksKeyPurpose.HUKS_KEY_PURPOSE_DECRYPT
  }
  properties[index++] = {
    tag: huks.HuksTag.HUKS_TAG_PADDING,
    value: huks.HuksKeyPadding.HUKS_PADDING_PKCS7
  }
  properties[index++] = {
    tag: huks.HuksTag.HUKS_TAG_BLOCK_MODE,
    value: huks.HuksCipherMode.HUKS_MODE_CBC
  }
  properties[index++] = {
    tag: huks.HuksTag.HUKS_TAG_IV,
    value: StringToUint8Array(IV)
  }
  return properties;
}

async function GenerateAesKey() {
  var genProperties = GetAesGenerateProperties();
  var options = {
    properties: genProperties
  }
  await huks.generateKeyItem(aesKeyAlias, options).then((data) => {
    promptAction.showToast({
      message: "成功生成了 一个 AES 密钥",
      duration: 2500,
    })
  }).catch((err)=>{
    promptAction.showToast({
      message: "密钥生成失败,错误码是: " + err.code + " 错误吗信息: " + err.message,
      duration: 6500,
    })
  })
}

async function EncryptData() {
    var encryptProperties = GetAesEncryptProperties();
    var options = {
        properties:encryptProperties,
        inData: StringToUint8Array(plainText)
Z
zhangcheng 已提交
776
    }
G
gaoshuyang 已提交
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 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898
    await huks.initSession(aesKeyAlias, options).then((data) => {
      handle = data.handle;
    }).catch((err)=>{
      promptAction.showToast({
        message: "密钥初始化失败,错误码是: " + err.code + " 错误吗信息: " + err.message,
        duration: 6500,
      })
    })
    await huks.finishSession(handle, options).then((data) => {
      promptAction.showToast({
        message: "加密数据成功, 密文是: " + Uint8ArrayToString(data.outData),
        duration: 6500,
      })
      cipherData = data.outData
    }).catch((err)=>{
      promptAction.showToast({
        message: "加密流程捕获了异常,错误码是: " + err.code + " 错误码信息: " + err.message,
        duration: 6500,
      })
    })
}

async function DecryptData() {
   var decryptOptions = GetAesDecryptProperties()
   var options = {
     properties:decryptOptions,
     inData: cipherData
   }
  await huks.initSession(aesKeyAlias, options).then((data) => {
    handle = data.handle;
  }).catch((err)=>{
    promptAction.showToast({
      message: "密钥初始化失败,错误码是: " + err.code + " 错误吗信息: " + err.message,
      duration: 6500,
    })
  })
  await huks.finishSession(handle, options).then((data) => {
    promptAction.showToast({
      message: "解密成功, 解密的明文是: " + Uint8ArrayToString(data.outData),
      duration: 6500,
    })
  }).catch((err)=>{
    promptAction.showToast({
      message: "解密流程捕获了异常,错误码是: " + err.code + " 错误码信息: " + err.message,
      duration: 6500,
    })
  })
}

async function DeleteKey() {
  let emptyOptions = {
    properties:[]
  }
    await huks.deleteKeyItem(aesKeyAlias, emptyOptions).then((data) => {
      promptAction.showToast({
        message: "密钥删除成功!",
        duration: 6500,
      })
    }).catch((err)=>{
      promptAction.showToast({
        message: "密钥删除失败,错误码是: " + err.code + " 错误吗信息: " + err.message,
        duration: 6500,
      })
    })
}

@Entry
@Component
struct Index {
  @State message: string = 'Hello Huks'
  controller: TextInputController = new TextInputController();
  build() {
    Column() {
      Row() {
        Text('输入您要加密得内容').fontSize(20).margin({ left: 2, top: 10 })
      }

      Row() {
        TextInput({ placeholder: '默认加密123456', controller: this.controller })
          .placeholderColor(Color.Grey)
          .placeholderFont({ size: 14, weight: 400 })
          .caretColor(Color.Blue)
          .width(400)
          .height(40)
          .margin(20)
          .fontSize(14)
          .fontColor(Color.Black)
          .type(InputType.Normal)
          .onChange((value: string) => {
            this.message += '您输入得明文是: ' + value + '\n'
            plainText = value
          })
          .margin({ top: 10 })
      }

      Row() {
        Text('加密或解密的结果').fontSize(20).margin({ left: 2, top: 10 })
      }

      Row() {
        TextInput({ placeholder: '这里将会显示加解密的结果', controller: this.controller })
          .placeholderColor(Color.Grey)
          .placeholderFont({ size: 14, weight: 400 })
          .caretColor(Color.Blue)
          .width(400)
          .height(40)
          .margin(20)
          .fontSize(14)
          .fontColor(Color.Black)
          .type(InputType.Normal)
          .onChange((value: string) => {
            this.message += '您输入得明文是: ' + value + '\n'
            plainText = value
          })
          .margin({ top: 10 })
      }

      Row() {
        Button({ type: ButtonType.Normal, stateEffect: true }) {
          Text('generateAesKey')
            .fontColor(Color.White)
            .fontSize(20)
Z
zhangcheng 已提交
899
        }
G
gaoshuyang 已提交
900 901 902 903 904 905 906 907 908 909 910 911 912
        .borderRadius(8)
        .width('45%')
        .height('5%')
        .backgroundColor(0x317aff)
        .onClick(() => {
          GenerateAesKey()
        })
        .margin(10)

        Button({ type: ButtonType.Normal, stateEffect: true }) {
          Text('deleteAesKey')
            .fontColor(Color.White)
            .fontSize(20)
Z
zhangcheng 已提交
913
        }
G
gaoshuyang 已提交
914 915 916 917 918 919 920 921 922 923 924 925 926 927 928
        .borderRadius(8)
        .width('45%')
        .height('5%')
        .backgroundColor(0x317aff)
        .onClick(() => {
          DeleteKey()
        })
        .margin(10)
      }

      Row() {
        Button({ type: ButtonType.Normal, stateEffect: true }) {
          Text('EncryptData')
            .fontColor(Color.White)
            .fontSize(20)
Z
zhangcheng 已提交
929
        }
G
gaoshuyang 已提交
930 931 932 933 934 935 936 937 938 939 940 941 942
        .borderRadius(8)
        .width('45%')
        .height('5%')
        .backgroundColor(0x317aff)
        .onClick(() => {
          EncryptData()
        })
        .margin(10)

        Button({ type: ButtonType.Normal, stateEffect: true }) {
          Text('DecryptData')
            .fontColor(Color.White)
            .fontSize(20)
W
wKyrong 已提交
943
        }
G
gaoshuyang 已提交
944 945 946 947 948 949 950 951 952
        .borderRadius(8)
        .width('45%')
        .height('5%')
        .backgroundColor(0x317aff)
        .onClick(() => {
          DecryptData()
        })
        .margin(10)
      }
Z
zhangcheng 已提交
953
    }
G
gaoshuyang 已提交
954
  }
Z
zhangcheng 已提交
955
}
Z
zhangcheng 已提交
956 957
```

W
wKyrong 已提交
958
### 密钥协商
Z
z00620704 已提交
959 960 961

应用在协商密钥时建议传入[HuksKeyStorageType](https://gitee.com/openharmony/docs/blob/master/zh-cn/application-dev/reference/apis/js-apis-huks.md#hukskeystoragetype)中定义的类型;从API10开始应用只能选择存储(HUKS_STORAGE_ONLY_USED_IN_HUKS),或者选择导出(HUKS_STORAGE_KEY_EXPORT_ALLOWED),若不传入,则默认同时支持存储和导出,存在安全问题,不推荐业务使用。

962
```ts
W
wKyrong 已提交
963 964
/*
 * 以下以X25519 256 TEMP密钥的Callback操作使用为例
965
 */
Z
zhangcheng 已提交
966 967
import huks from '@ohos.security.huks';

W
wKyrong 已提交
968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005
/*
 * 确定密钥别名和封装密钥属性参数集
 */
let srcKeyAliasFirst = "AgreeX25519KeyFirstAlias";
let srcKeyAliasSecond = "AgreeX25519KeySecondAlias";
let agreeX25519InData = 'AgreeX25519TestIndata';
let finishOutData;
let handle;
let exportKey;
let exportKeyFrist;
let exportKeySecond;

/* 集成生成密钥参数集 */
let properties = new Array();
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
z00620704 已提交
1006 1007 1008 1009
properties[6] = {
    tag: huks.HuksTag.HUKS_TAG_DERIVED_AGREED_KEY_STORAGE_FLAG,
    value: huks.HuksKeyStorageType.HUKS_STORAGE_ONLY_USED_IN_HUKS,
}
W
wKyrong 已提交
1010 1011 1012 1013 1014 1015 1016 1017
let HuksOptions = {
    properties: properties,
    inData: new Uint8Array(new Array())
}

/* 集成第一个协商参数集 */
let finishProperties = new Array();
finishProperties[0] = {
Z
z00620704 已提交
1018 1019
    tag: huks.HuksTag.HUKS_TAG_DERIVED_AGREED_KEY_STORAGE_FLAG,
    value: huks.HuksKeyStorageType.HUKS_STORAGE_ONLY_USED_IN_HUKS,
W
wKyrong 已提交
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
}
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,
    value: StringToUint8Array(srcKeyAliasFirst+ 'final'),
}
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,
}
let finishOptionsFrist = {
    properties: finishProperties,
    inData: StringToUint8Array(agreeX25519InData)
}
/* 集成第二个协商参数集 */
let finishOptionsSecond = {
    properties: finishProperties,
    inData: StringToUint8Array(agreeX25519InData)
}
finishOptionsSecond.properties.splice(6, 1, {
    tag: huks.HuksTag.HUKS_TAG_KEY_ALIAS,
    value: StringToUint8Array(srcKeyAliasSecond + 'final'),
})

Z
zhangcheng 已提交
1069
function StringToUint8Array(str) {
Z
zhangcheng 已提交
1070 1071
    let arr = [];
    for (let i = 0, j = str.length; i < j; ++i) {
1072 1073 1074 1075
        arr.push(str.charCodeAt(i));
    }
    return new Uint8Array(arr);
}
Z
zhangcheng 已提交
1076

W
wKyrong 已提交
1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091
function generateKeyItem(keyAlias:string, huksOptions:huks.HuksOptions, throwObject) {
    return new Promise((resolve, reject) => {
        try {
            huks.generateKeyItem(keyAlias, huksOptions, function (error, data) {
                if (error) {
                    reject(error);
                } else {
                    resolve(data);
                }
            });
        } catch (error) {
            throwObject.isThrow = true;
            throw(error);
        }
    });
1092 1093
}

Z
zhangcheng 已提交
1094 1095
async function publicGenKeyFunc(keyAlias:string, huksOptions:huks.HuksOptions) {
    console.info(`enter callback generateKeyItem`);
W
wKyrong 已提交
1096
    let throwObject = {isThrow: false};
Z
zhangcheng 已提交
1097
    try {
W
wKyrong 已提交
1098
        await generateKeyItem(keyAlias, huksOptions, throwObject)
Z
zhangcheng 已提交
1099 1100 1101 1102
            .then((data) => {
                console.info(`callback: generateKeyItem success, data = ${JSON.stringify(data)}`);
            })
            .catch(error => {
W
wKyrong 已提交
1103 1104 1105 1106 1107
                if (throwObject.isThrow) {
                    throw(error);
                } else {
                    console.error(`callback: generateKeyItem failed, code: ${error.code}, msg: ${error.message}`);
                }
Z
zhangcheng 已提交
1108 1109 1110 1111 1112 1113
            });
    } catch (error) {
        console.error(`callback: generateKeyItem input arg invalid, code: ${error.code}, msg: ${error.message}`);
    }
}

W
wKyrong 已提交
1114
function initSession(keyAlias:string, huksOptions:huks.HuksOptions, throwObject) : Promise<huks.HuksSessionHandle> {
Z
zhangcheng 已提交
1115 1116
    return new Promise((resolve, reject) => {
        try {
W
wKyrong 已提交
1117
            huks.initSession(keyAlias, huksOptions, function (error, data) {
Z
zhangcheng 已提交
1118 1119 1120 1121 1122 1123 1124
                if (error) {
                    reject(error);
                } else {
                    resolve(data);
                }
            });
        } catch (error) {
W
wKyrong 已提交
1125
            throwObject.isThrow = true;
Z
zhangcheng 已提交
1126 1127 1128 1129 1130 1131
            throw(error);
        }
    });
}

async function publicInitFunc(keyAlias:string, huksOptions:huks.HuksOptions) {
W
wKyrong 已提交
1132 1133
    console.info(`enter callback doInit`);
    let throwObject = {isThrow: false};
Z
zhangcheng 已提交
1134
    try {
W
wKyrong 已提交
1135
        await initSession(keyAlias, huksOptions, throwObject)
Z
zhangcheng 已提交
1136
            .then ((data) => {
W
wKyrong 已提交
1137
                console.info(`callback: doInit success, data = ${JSON.stringify(data)}`);
Z
zhangcheng 已提交
1138 1139
                handle = data.handle;
            })
W
wKyrong 已提交
1140 1141 1142 1143 1144 1145
            .catch((error) => {
                if (throwObject.isThrow) {
                    throw(error);
                } else {
                    console.error(`callback: doInit failed, code: ${error.code}, msg: ${error.message}`);
                }
Z
zhangcheng 已提交
1146 1147
            });
    } catch (error) {
W
wKyrong 已提交
1148
        console.error(`callback: doInit input arg invalid, code: ${error.code}, msg: ${error.message}`);
Z
zhangcheng 已提交
1149 1150 1151
    }
}

W
wKyrong 已提交
1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168
function updateSession(handle:number, huksOptions:huks.HuksOptions, throwObject) : 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) {
            throwObject.isThrow = true;
            throw(error);
        }
    });
}

Z
zhangcheng 已提交
1169 1170
async function publicUpdateFunc(handle:number, huksOptions:huks.HuksOptions) {
    console.info(`enter callback doUpdate`);
W
wKyrong 已提交
1171
    let throwObject = {isThrow: false};
Z
zhangcheng 已提交
1172
    try {
W
wKyrong 已提交
1173
        await updateSession(handle, huksOptions, throwObject)
Z
zhangcheng 已提交
1174 1175 1176 1177
            .then ((data) => {
                console.info(`callback: doUpdate success, data = ${JSON.stringify(data)}`);
            })
            .catch(error => {
W
wKyrong 已提交
1178 1179 1180 1181 1182
                if (throwObject.isThrow) {
                    throw(error);
                } else {
                    console.error(`callback: doUpdate failed, code: ${error.code}, msg: ${error.message}`);
                }
Z
zhangcheng 已提交
1183 1184 1185 1186 1187 1188
            });
    } catch (error) {
        console.error(`callback: doUpdate input arg invalid, code: ${error.code}, msg: ${error.message}`);
    }
}

W
wKyrong 已提交
1189
function finishSession(handle:number, huksOptions:huks.HuksOptions, throwObject) : Promise<huks.HuksReturnResult> {
Z
zhangcheng 已提交
1190 1191
    return new Promise((resolve, reject) => {
        try {
W
wKyrong 已提交
1192
            huks.finishSession(handle, huksOptions, function (error, data) {
Z
zhangcheng 已提交
1193 1194 1195 1196 1197 1198 1199
                if (error) {
                    reject(error);
                } else {
                    resolve(data);
                }
            });
        } catch (error) {
W
wKyrong 已提交
1200
            throwObject.isThrow = true;
Z
zhangcheng 已提交
1201 1202 1203 1204 1205 1206 1207
            throw(error);
        }
    });
}

async function publicFinishFunc(handle:number, huksOptions:huks.HuksOptions) {
    console.info(`enter callback doFinish`);
W
wKyrong 已提交
1208
    let throwObject = {isThrow: false};
Z
zhangcheng 已提交
1209
    try {
W
wKyrong 已提交
1210
        await finishSession(handle, huksOptions, throwObject)
Z
zhangcheng 已提交
1211
            .then ((data) => {
W
wKyrong 已提交
1212
                finishOutData = data.outData;
Z
zhangcheng 已提交
1213 1214 1215
                console.info(`callback: doFinish success, data = ${JSON.stringify(data)}`);
            })
            .catch(error => {
W
wKyrong 已提交
1216 1217 1218 1219 1220
                if (throwObject.isThrow) {
                    throw(error);
                } else {
                    console.error(`callback: doFinish failed, code: ${error.code}, msg: ${error.message}`);
                }
Z
zhangcheng 已提交
1221 1222 1223 1224 1225 1226
            });
    } catch (error) {
        console.error(`callback: doFinish input arg invalid, code: ${error.code}, msg: ${error.message}`);
    }
}

W
wKyrong 已提交
1227
function exportKeyItem(keyAlias:string, huksOptions:huks.HuksOptions, throwObject) : Promise<huks.HuksReturnResult> {
Z
zhangcheng 已提交
1228 1229
    return new Promise((resolve, reject) => {
        try {
W
wKyrong 已提交
1230
            huks.exportKeyItem(keyAlias, huksOptions, function (error, data) {
Z
zhangcheng 已提交
1231 1232 1233 1234 1235 1236 1237
                if (error) {
                    reject(error);
                } else {
                    resolve(data);
                }
            });
        } catch (error) {
W
wKyrong 已提交
1238
            throwObject.isThrow = true;
Z
zhangcheng 已提交
1239 1240 1241 1242 1243
            throw(error);
        }
    });
}

W
wKyrong 已提交
1244 1245 1246
async function publicExportKeyFunc(keyAlias:string, huksOptions:huks.HuksOptions) {
    console.info(`enter callback export`);
    let throwObject = {isThrow: false};
Z
zhangcheng 已提交
1247
    try {
W
wKyrong 已提交
1248
        await exportKeyItem(keyAlias, huksOptions, throwObject)
Z
zhangcheng 已提交
1249
            .then ((data) => {
W
wKyrong 已提交
1250 1251
                console.info(`callback: exportKeyItem success, data = ${JSON.stringify(data)}`);
                exportKey = data.outData;
Z
zhangcheng 已提交
1252 1253
            })
            .catch(error => {
W
wKyrong 已提交
1254 1255 1256 1257 1258
                if (throwObject.isThrow) {
                    throw(error);
                } else {
                    console.error(`callback: exportKeyItem failed, code: ${error.code}, msg: ${error.message}`);
                }
Z
zhangcheng 已提交
1259 1260
            });
    } catch (error) {
W
wKyrong 已提交
1261
        console.error(`callback: exportKeyItem input arg invalid, code: ${error.code}, msg: ${error.message}`);
Z
zhangcheng 已提交
1262 1263 1264
    }
}

W
wKyrong 已提交
1265
function deleteKeyItem(keyAlias:string, huksOptions:huks.HuksOptions, throwObject) {
Z
zhangcheng 已提交
1266 1267 1268 1269 1270 1271 1272 1273 1274 1275
    return new Promise((resolve, reject) => {
        try {
            huks.deleteKeyItem(keyAlias, huksOptions, function (error, data) {
                if (error) {
                    reject(error);
                } else {
                    resolve(data);
                }
            });
        } catch (error) {
W
wKyrong 已提交
1276
            throwObject.isThrow = true;
Z
zhangcheng 已提交
1277 1278 1279 1280 1281
            throw(error);
        }
    });
}

W
wKyrong 已提交
1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298
async function publicDeleteKeyFunc(keyAlias:string, huksOptions:huks.HuksOptions) {
    console.info(`enter callback deleteKeyItem`);
    let throwObject = {isThrow: false};
    try {
        await deleteKeyItem(keyAlias, huksOptions, throwObject)
            .then ((data) => {
                console.info(`callback: deleteKeyItem key success, data = ${JSON.stringify(data)}`);
            })
            .catch(error => {
                if (throwObject.isThrow) {
                    throw(error);
                } else {
                    console.error(`callback: deleteKeyItem failed, code: ${error.code}, msg: ${error.message}`);
                }
            });
    } catch (error) {
        console.error(`callback: deletKeeyItem input arg invalid, code: ${error.code}, msg: ${error.message}`);
1299
    }
W
wKyrong 已提交
1300
}
1301

W
wKyrong 已提交
1302 1303 1304 1305
async function testAgree() {
    /* 1.生成两个密钥并导出 */
    await publicGenKeyFunc(srcKeyAliasFirst, HuksOptions);
    await publicGenKeyFunc(srcKeyAliasSecond, HuksOptions);
Z
zhangcheng 已提交
1306

W
wKyrong 已提交
1307 1308 1309 1310
    await publicExportKeyFunc(srcKeyAliasFirst, HuksOptions);
    exportKeyFrist = exportKey;
    await publicExportKeyFunc(srcKeyAliasFirst, HuksOptions);
    exportKeySecond = exportKey;
Z
zhangcheng 已提交
1311

W
wKyrong 已提交
1312 1313 1314 1315 1316
    /* 对第一个密钥进行协商 */
    await publicInitFunc(srcKeyAliasFirst, HuksOptions);
    HuksOptions.inData = exportKeySecond;
    await publicUpdateFunc(handle, HuksOptions);
    await publicFinishFunc(handle, finishOptionsFrist);
1317

W
wKyrong 已提交
1318 1319 1320 1321 1322
    /* 对第二个密钥进行协商 */
    await publicInitFunc(srcKeyAliasSecond, HuksOptions);
    HuksOptions.inData = exportKeyFrist;
    await publicUpdateFunc(handle, HuksOptions);
    await publicFinishFunc(handle, finishOptionsSecond);
Z
zhangcheng 已提交
1323

W
wKyrong 已提交
1324 1325
    await publicDeleteKeyFunc(srcKeyAliasFirst, HuksOptions);
    await publicDeleteKeyFunc(srcKeyAliasSecond, HuksOptions);
1326 1327 1328
}
```

W
wKyrong 已提交
1329
### 密钥派生
Z
z00620704 已提交
1330 1331 1332

应用在派生密钥时建议传入[HuksKeyStorageType](https://gitee.com/openharmony/docs/blob/master/zh-cn/application-dev/reference/apis/js-apis-huks.md#hukskeystoragetype)中定义的类型;从API10开始应用只能选择存储(HUKS_STORAGE_ONLY_USED_IN_HUKS),或者选择导出(HUKS_STORAGE_KEY_EXPORT_ALLOWED),若不传入,则默认同时支持存储和导出,存在安全问题,不推荐业务使用。

W
wKyrong 已提交
1333 1334 1335 1336 1337
```ts
/*
 * 以下以HKDF256密钥的Promise操作使用为例
 */
import huks from '@ohos.security.huks';
Z
zhangcheng 已提交
1338

W
wKyrong 已提交
1339 1340 1341 1342 1343 1344 1345 1346
/*
 * 确定密钥别名和封装密钥属性参数集
 */
let srcKeyAlias = "hkdf_Key";
let deriveHkdfInData = "deriveHkdfTestIndata";
let handle;
let finishOutData;
let HuksKeyDeriveKeySize = 32;
Z
zhangcheng 已提交
1347

W
wKyrong 已提交
1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365
/* 集成生成密钥参数集 */
let properties = new Array();
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
z00620704 已提交
1366 1367 1368 1369
properties[4] = {
    tag: huks.HuksTag.HUKS_TAG_DERIVED_AGREED_KEY_STORAGE_FLAG,
    value: huks.HuksKeyStorageType.HUKS_STORAGE_ONLY_USED_IN_HUKS,
}
W
wKyrong 已提交
1370 1371 1372 1373
let huksOptions = {
    properties: properties,
    inData: new Uint8Array(new Array())
}
Z
zhangcheng 已提交
1374

W
wKyrong 已提交
1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396
/* 集成init时密钥参数集 */
let initProperties = new Array();
initProperties[0] = {
    tag: huks.HuksTag.HUKS_TAG_ALGORITHM,
    value: huks.HuksKeyAlg.HUKS_ALG_HKDF,
}
initProperties[1] = {
    tag: huks.HuksTag.HUKS_TAG_PURPOSE,
    value: huks.HuksKeyPurpose.HUKS_KEY_PURPOSE_DERIVE,
}
initProperties[2] = {
    tag: huks.HuksTag.HUKS_TAG_DIGEST,
    value: huks.HuksKeyDigest.HUKS_DIGEST_SHA256,
}
initProperties[3] = {
    tag: huks.HuksTag.HUKS_TAG_DERIVE_KEY_SIZE,
    value: HuksKeyDeriveKeySize,
}
let initOptions = {
    properties: initProperties,
    inData: new Uint8Array(new Array())
}
Z
zhangcheng 已提交
1397

W
wKyrong 已提交
1398 1399 1400
/* 集成finish时密钥参数集 */
let finishProperties = new Array();
finishProperties[0] = {
Z
z00620704 已提交
1401 1402
    tag: huks.HuksTag.HUKS_TAG_DERIVED_AGREED_KEY_STORAGE_FLAG,
    value: huks.HuksKeyStorageType.HUKS_STORAGE_ONLY_USED_IN_HUKS,
W
wKyrong 已提交
1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441
}
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,
    value: StringToUint8Array(srcKeyAlias),
}
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,
}
let finishOptions = {
    properties: finishProperties,
    inData: new Uint8Array(new Array())
}
Z
zhangcheng 已提交
1442 1443

function StringToUint8Array(str) {
Z
zhangcheng 已提交
1444 1445
    let arr = [];
    for (let i = 0, j = str.length; i < j; ++i) {
Z
zhangcheng 已提交
1446 1447 1448 1449 1450
        arr.push(str.charCodeAt(i));
    }
    return new Uint8Array(arr);
}

W
wKyrong 已提交
1451
function generateKeyItem(keyAlias:string, huksOptions:huks.HuksOptions, throwObject) {
Z
zhangcheng 已提交
1452 1453 1454 1455 1456 1457 1458 1459 1460 1461
    return new Promise((resolve, reject) => {
        try {
            huks.generateKeyItem(keyAlias, huksOptions, function (error, data) {
                if (error) {
                    reject(error);
                } else {
                    resolve(data);
                }
            });
        } catch (error) {
W
wKyrong 已提交
1462
            throwObject.isThrow = true;
Z
zhangcheng 已提交
1463 1464 1465 1466
            throw(error);
        }
    });
}
Z
zhangcheng 已提交
1467

W
wKyrong 已提交
1468 1469 1470
async function publicGenKeyFunc(keyAlias:string, huksOptions:huks.HuksOptions) {
    console.info(`enter callback generateKeyItem`);
    let throwObject = {isThrow: false};
Z
zhangcheng 已提交
1471
    try {
W
wKyrong 已提交
1472 1473 1474
        await generateKeyItem(keyAlias, huksOptions, throwObject)
            .then((data) => {
                console.info(`callback: generateKeyItem success, data = ${JSON.stringify(data)}`);
Z
zhangcheng 已提交
1475
            })
W
wKyrong 已提交
1476 1477 1478 1479 1480 1481
            .catch(error => {
                if (throwObject.isThrow) {
                    throw(error);
                } else {
                    console.error(`callback: generateKeyItem failed, code: ${error.code}, msg: ${error.message}`);
                }
Z
zhangcheng 已提交
1482 1483
            });
    } catch (error) {
W
wKyrong 已提交
1484
        console.error(`callback: generateKeyItem input arg invalid, code: ${error.code}, msg: ${error.message}`);
Z
zhangcheng 已提交
1485
    }
Z
zhangcheng 已提交
1486
}
Z
zhangcheng 已提交
1487

W
wKyrong 已提交
1488
function initSession(keyAlias:string, huksOptions:huks.HuksOptions, throwObject) : Promise<huks.HuksSessionHandle> {
Z
zhangcheng 已提交
1489 1490 1491 1492 1493 1494 1495 1496 1497 1498
    return new Promise((resolve, reject) => {
        try {
            huks.initSession(keyAlias, huksOptions, function (error, data) {
                if (error) {
                    reject(error);
                } else {
                    resolve(data);
                }
            });
        } catch (error) {
W
wKyrong 已提交
1499
            throwObject.isThrow = true;
Z
zhangcheng 已提交
1500 1501
            throw(error);
        }
Z
zhangcheng 已提交
1502
    });
Z
zhangcheng 已提交
1503
}
Z
zhangcheng 已提交
1504

W
wKyrong 已提交
1505 1506 1507
async function publicInitFunc(keyAlias:string, huksOptions:huks.HuksOptions) {
    console.info(`enter callback doInit`);
    let throwObject = {isThrow: false};
Z
zhangcheng 已提交
1508
    try {
W
wKyrong 已提交
1509
        await initSession(keyAlias, huksOptions, throwObject)
Z
zhangcheng 已提交
1510
            .then ((data) => {
W
wKyrong 已提交
1511 1512
                console.info(`callback: doInit success, data = ${JSON.stringify(data)}`);
                handle = data.handle;
Z
zhangcheng 已提交
1513
            })
W
wKyrong 已提交
1514 1515 1516 1517 1518 1519
            .catch((error) => {
                if (throwObject.isThrow) {
                    throw(error);
                } else {
                    console.error(`callback: doInit failed, code: ${error.code}, msg: ${error.message}`);
                }
Z
zhangcheng 已提交
1520 1521
            });
    } catch (error) {
W
wKyrong 已提交
1522
        console.error(`callback: doInit input arg invalid, code: ${error.code}, msg: ${error.message}`);
Z
zhangcheng 已提交
1523 1524
    }
}
Z
zhangcheng 已提交
1525

W
wKyrong 已提交
1526
function updateSession(handle:number, huksOptions:huks.HuksOptions, throwObject) : Promise<huks.HuksReturnResult> {
Z
zhangcheng 已提交
1527 1528 1529 1530 1531 1532 1533 1534 1535 1536
    return new Promise((resolve, reject) => {
        try {
            huks.updateSession(handle, huksOptions, function (error, data) {
                if (error) {
                    reject(error);
                } else {
                    resolve(data);
                }
            });
        } catch (error) {
W
wKyrong 已提交
1537
            throwObject.isThrow = true;
Z
zhangcheng 已提交
1538 1539
            throw(error);
        }
Z
zhangcheng 已提交
1540
    });
Z
zhangcheng 已提交
1541
}
Z
zhangcheng 已提交
1542

W
wKyrong 已提交
1543 1544 1545
async function publicUpdateFunc(handle:number, huksOptions:huks.HuksOptions) {
    console.info(`enter callback doUpdate`);
    let throwObject = {isThrow: false};
Z
zhangcheng 已提交
1546
    try {
W
wKyrong 已提交
1547
        await updateSession(handle, huksOptions, throwObject)
Z
zhangcheng 已提交
1548
            .then ((data) => {
W
wKyrong 已提交
1549
                console.info(`callback: doUpdate success, data = ${JSON.stringify(data)}`);
Z
zhangcheng 已提交
1550 1551
            })
            .catch(error => {
W
wKyrong 已提交
1552 1553 1554 1555 1556
                if (throwObject.isThrow) {
                    throw(error);
                } else {
                    console.error(`callback: doUpdate failed, code: ${error.code}, msg: ${error.message}`);
                }
Z
zhangcheng 已提交
1557 1558
            });
    } catch (error) {
W
wKyrong 已提交
1559
        console.error(`callback: doUpdate input arg invalid, code: ${error.code}, msg: ${error.message}`);
Z
zhangcheng 已提交
1560 1561 1562
    }
}

W
wKyrong 已提交
1563
function finishSession(handle:number, huksOptions:huks.HuksOptions, throwObject) : Promise<huks.HuksReturnResult> {
Z
zhangcheng 已提交
1564 1565 1566 1567 1568 1569 1570 1571 1572 1573
    return new Promise((resolve, reject) => {
        try {
            huks.finishSession(handle, huksOptions, function (error, data) {
                if (error) {
                    reject(error);
                } else {
                    resolve(data);
                }
            });
        } catch (error) {
W
wKyrong 已提交
1574
            throwObject.isThrow = true;
Z
zhangcheng 已提交
1575 1576
            throw(error);
        }
Z
zhangcheng 已提交
1577
    });
Z
zhangcheng 已提交
1578 1579
}

W
wKyrong 已提交
1580 1581 1582
async function publicFinishFunc(handle:number, huksOptions:huks.HuksOptions) {
    console.info(`enter callback doFinish`);
    let throwObject = {isThrow: false};
Z
zhangcheng 已提交
1583
    try {
W
wKyrong 已提交
1584
        await finishSession(handle, huksOptions, throwObject)
Z
zhangcheng 已提交
1585
            .then ((data) => {
W
wKyrong 已提交
1586 1587
                finishOutData = data.outData;
                console.info(`callback: doFinish success, data = ${JSON.stringify(data)}`);
Z
zhangcheng 已提交
1588 1589
            })
            .catch(error => {
W
wKyrong 已提交
1590 1591
                if (throwObject.isThrow) {
                    throw(error);
Z
zhangcheng 已提交
1592
                } else {
W
wKyrong 已提交
1593
                    console.error(`callback: doFinish failed, code: ${error.code}, msg: ${error.message}`);
Z
zhangcheng 已提交
1594 1595 1596
                }
            });
    } catch (error) {
W
wKyrong 已提交
1597
        console.error(`callback: doFinish input arg invalid, code: ${error.code}, msg: ${error.message}`);
Z
zhangcheng 已提交
1598 1599
    }
}
Z
zhangcheng 已提交
1600

W
wKyrong 已提交
1601
function deleteKeyItem(keyAlias:string, huksOptions:huks.HuksOptions, throwObject) {
Z
zhangcheng 已提交
1602 1603
    return new Promise((resolve, reject) => {
        try {
W
wKyrong 已提交
1604
            huks.deleteKeyItem(keyAlias, huksOptions, function (error, data) {
Z
zhangcheng 已提交
1605 1606 1607 1608 1609 1610 1611
                if (error) {
                    reject(error);
                } else {
                    resolve(data);
                }
            });
        } catch (error) {
W
wKyrong 已提交
1612
            throwObject.isThrow = true;
Z
zhangcheng 已提交
1613 1614
            throw(error);
        }
Z
zhangcheng 已提交
1615
    });
Z
zhangcheng 已提交
1616 1617 1618 1619
}

async function publicDeleteKeyFunc(keyAlias:string, huksOptions:huks.HuksOptions) {
    console.info(`enter callback deleteKeyItem`);
W
wKyrong 已提交
1620
    let throwObject = {isThrow: false};
Z
zhangcheng 已提交
1621
    try {
W
wKyrong 已提交
1622
        await deleteKeyItem(keyAlias, huksOptions, throwObject)
Z
zhangcheng 已提交
1623 1624 1625 1626
            .then ((data) => {
                console.info(`callback: deleteKeyItem key success, data = ${JSON.stringify(data)}`);
            })
            .catch(error => {
W
wKyrong 已提交
1627 1628 1629 1630 1631
                if (throwObject.isThrow) {
                    throw(error);
                } else {
                    console.error(`callback: deleteKeyItem failed, code: ${error.code}, msg: ${error.message}`);
                }
Z
zhangcheng 已提交
1632 1633
            });
    } catch (error) {
W
wKyrong 已提交
1634
        console.error(`callback: deletKeeyItem input arg invalid, code: ${error.code}, msg: ${error.message}`);
Z
zhangcheng 已提交
1635 1636
    }
}
Z
zhangcheng 已提交
1637

W
wKyrong 已提交
1638 1639 1640
async function testDerive() {
    /* 生成密钥 */
    await publicGenKeyFunc(srcKeyAlias, huksOptions);
Z
zhangcheng 已提交
1641

W
wKyrong 已提交
1642 1643
    /* 进行派生操作 */
    await publicInitFunc(srcKeyAlias, initOptions);
Z
zhangcheng 已提交
1644

W
wKyrong 已提交
1645 1646 1647 1648 1649
    initOptions.inData = StringToUint8Array(deriveHkdfInData);
    await publicUpdateFunc(handle, initOptions);
    await publicFinishFunc(handle, finishOptions);

    await publicDeleteKeyFunc(srcKeyAlias, huksOptions);
Z
zhangcheng 已提交
1650
}
W
wKyrong 已提交
1651
```
Z
zhangcheng 已提交
1652

W
wKyrong 已提交
1653
## 密钥访问控制
Z
zhangcheng 已提交
1654

W
wKyrong 已提交
1655
HUKS提供了全面完善的密钥访问控制能力,确保存储在HUKS中的密钥被合法正确的访问。
Z
zhangcheng 已提交
1656

W
wKyrong 已提交
1657 1658 1659
首先,业务只能访问属于自己的密钥,即只能访问通过HUKS生成或导入的密钥。
其次,支持密钥的用户身份认证访问控制,对于高安敏感的业务密钥,需要在使用密钥的时候,再次要求用户即时的验证锁屏密码或生物特征,验证通过后,才能使用业务密钥。
除此之外,HUKS还支持严格限制密钥的使用用途,如支持只允许AES密钥进行加密解密,只允许RSA密钥进行签名验签。
Z
zhangcheng 已提交
1660

Z
z00620704 已提交
1661
### 用户身份认证访问控制
Z
zhangcheng 已提交
1662

W
wKyrong 已提交
1663
生成或导入密钥时,可以指定密钥必须经过用户身份认证后才能使用。您可以指定用于解锁设备锁屏的凭据(锁屏密码、指纹、人脸)的子集进行身份认证。在生成/导入密钥后,即使应用进程被攻击也不会导致未经用户授权的密钥访问,一般用于高敏感且高级别安全保护的场景,比如免密登录、免密支付、自动填充密码保护场景。
Z
zhangcheng 已提交
1664

W
wKyrong 已提交
1665 1666 1667
除用户身份认证外,应用还须将密钥的授权访问类型(即失效条件)设置为以下两种类型之一:
- **清除锁屏密码后密钥永久无效。** 设置此模式的前提是当前用户已经设置了锁屏密码,在生成/导入密钥后,一旦清除了锁屏密码,此类密钥将永久失效。注意,修改密码不会导致失效情况发生。此模式适合那些需要锁屏密码授权访问或用户强相关的数据保护的场景。
- **用户新录入生物特征后永久无效。** 此模式需要当前用户至少录入了一个生物特征(如指纹)才能生效,在生成/导入密钥后,一旦录入新的生物特征,这些密钥将永久失效。注意,仅删除生物特征不会导致失效情况发生。如果您不希望新录入的生物特征后,用户还可以授权访问原有数据(密钥保护的数据),那么可以使用此模式,如免密登录,免密支付等场景。
Z
zhangcheng 已提交
1668

W
wKyrong 已提交
1669
此外,为了保证密钥使用时用户认证结果的有效性(不可重放),HUKS支持挑战值校验:在身份认证前,需要从HUKS获取挑战值(调用[huks.initSession()](../reference/apis/js-apis-huks.md#huksinitsession9)返回的[HuksSessionHandle](../reference/apis/js-apis-huks.md#hukssessionhandle9)中)传给用户身份认证方法([userIAM_userAuth.getAuthInstance](../reference/apis/js-apis-useriam-userauth.md#authinstance9)),然后在密钥操作时校验认证令牌的挑战值。
Z
zhangcheng 已提交
1670

W
wKyrong 已提交
1671
**开发流程**
Z
zhangcheng 已提交
1672

W
wKyrong 已提交
1673
设置了二次用户身份认证的密钥,需要先初始化密钥会话并获取挑战值,然后将HUKS生成的挑战值传至用户身份认证方法进行用户身份认证,认证通过后获取一个认证令牌,将认证令牌传至HUKS进行密钥操作。
Z
zhangcheng 已提交
1674

W
wKyrong 已提交
1675
![huks_key_user_auth_work_flow](./figures/huks_key_user_auth_work_flow.png)
Z
zhangcheng 已提交
1676

W
wKyrong 已提交
1677
**接口说明**
Z
zhangcheng 已提交
1678

W
wKyrong 已提交
1679
1. 生成或导入密钥时,在密钥属性集中需指定三个参数:用户认证类型[HuksUserAuthType](../reference/apis/js-apis-huks.md#huksuserauthtype9)、授权访问类型[HuksAuthAccessType](../reference/apis/js-apis-huks.md#huksauthaccesstype9)、挑战值类型[HuksChallengeType](../reference/apis/js-apis-huks.md#hukschallengetype9)
Z
zhangcheng 已提交
1680

W
wKyrong 已提交
1681 1682 1683 1684 1685 1686
	**表3** 用户认证类型:三种类型的子集
	| 名称            | 值  | 说明                      |
	| ------------------------------- |---|------------------------ |
	| HUKS_USER_AUTH_TYPE_FINGERPRINT |0x0001  | 用户认证类型为指纹,允许和人脸、锁屏密码同时设置  |
	| HUKS_USER_AUTH_TYPE_FACE     |0x0002   | 用户认证类型为人脸 ,允许和指纹、锁屏密码同时设置 |
	| HUKS_USER_AUTH_TYPE_PIN      |0x0004  | 用户认证类型为锁屏密码,允许和人脸、指纹同时设置 |
Z
zhangcheng 已提交
1687

W
wKyrong 已提交
1688 1689 1690 1691 1692
	**表4** 安全访问类型:二选一
	| 名称                                    | 值   | 说明             |
	| --------------------------------------- | ---- | ------------------------------------------------ |
	| HUKS_AUTH_ACCESS_INVALID_CLEAR_PASSWORD | 1    | 清除锁屏密码后密钥无法访问。       |
	| HUKS_AUTH_ACCESS_INVALID_NEW_BIO_ENROLL | 2    | 新录入生物特征后密钥无法访问,用户认证类型须包含生物认证类型。 |
Z
zhangcheng 已提交
1693

W
wKyrong 已提交
1694 1695 1696 1697 1698 1699
	**表5** 挑战值类型:三选一
	| 名称                            | 值   | 说明                        |
	| ------------------------------- | ---- | ------------------------------ |
	| HUKS_CHALLENGE_TYPE_NORMAL | 0    | 普通类型,每次密钥的使用需要独立的一次用户认证 |
	| HUKS_CHALLENGE_TYPE_CUSTOM        | 1    | 自定义类型,支持和多个密钥共享一次用户认证|
	| HUKS_CHALLENGE_TYPE_NONE         | 2    | 无挑战值类型,用户认证时不需要挑战值 |
1700

W
wKyrong 已提交
1701 1702 1703
	> **注意**
	> 
	> 当指定挑战值类型为**HUKS_CHALLENGE_TYPE_NONE** 时,不需要传递挑战值,但是存在新的限制:在用户身份认证后,一段时间内允许访问该密钥,超时后不能访问,需要重新认证才能访问。因此应用需要额外指定超时时间**HUKS_TAG_AUTH_TIMEOUT**属性(最大60秒)。
1704 1705


W
wKyrong 已提交
1706 1707 1708
2. 使用密钥时,先初始化密钥会话,然后根据密钥生成/导入阶段指定的挑战值类型属性是否需要获取挑战值,或组装新的挑战值。
        
    **表6** 使用密钥的接口介绍
1709

W
wKyrong 已提交
1710 1711 1712 1713 1714
	| 接口名                      | 描述                 |
	| -------------------------------------- | ----------------------------|
	|initSession(keyAlias: string, options: HuksOptions, callback: AsyncCallback\<HuksSessionHandle>) : void| 初始化密钥会话,获取挑战值|
	|updateSession(handle: number, options: HuksOptions, token: Uint8Array, callback: AsyncCallback\<HuksReturnResult>) : void| 分段操作数据,传递认证令牌|
	|finishSession(handle: number, options: HuksOptions, token: Uint8Array, callback: AsyncCallback\<HuksReturnResult>) : void| 结束密钥会话,传递认证令牌|
Z
zhangcheng 已提交
1715 1716 1717



W
wKyrong 已提交
1718
**开发步骤**
Z
zhangcheng 已提交
1719

W
wKyrong 已提交
1720
1. 生成密钥并指定指纹访问控制和相关属性
Z
zhangcheng 已提交
1721
```ts
Z
zhangcheng 已提交
1722 1723
import huks from '@ohos.security.huks';

W
wKyrong 已提交
1724 1725 1726 1727 1728 1729 1730 1731
/*
 * 确定密钥别名和封装密钥属性参数集
 */
let keyAlias = 'dh_key_fingerprint_access';
let properties = new Array();
properties[0] = {
  tag: huks.HuksTag.HUKS_TAG_ALGORITHM,
  value: huks.HuksKeyAlg.HUKS_ALG_SM4,
Z
zhangcheng 已提交
1732
}
W
wKyrong 已提交
1733 1734 1735
properties[1] = {
  tag: huks.HuksTag.HUKS_TAG_PURPOSE,
  value: huks.HuksKeyPurpose.HUKS_KEY_PURPOSE_ENCRYPT | huks.HuksKeyPurpose.HUKS_KEY_PURPOSE_DECRYPT,
Z
zhangcheng 已提交
1736
}
W
wKyrong 已提交
1737 1738 1739
properties[2] = {
  tag: huks.HuksTag.HUKS_TAG_KEY_SIZE,
  value: huks.HuksKeySize.HUKS_SM4_KEY_SIZE_128,
Z
zhangcheng 已提交
1740
}
W
wKyrong 已提交
1741 1742 1743
properties[3] = {
  tag: huks.HuksTag.HUKS_TAG_BLOCK_MODE,
  value: huks.HuksCipherMode.HUKS_MODE_CBC,
Z
zhangcheng 已提交
1744
}
W
wKyrong 已提交
1745 1746 1747
properties[4] = {
  tag: huks.HuksTag.HUKS_TAG_PADDING,
  value: huks.HuksKeyPadding.HUKS_PADDING_NONE,
Z
zhangcheng 已提交
1748
}
W
wKyrong 已提交
1749 1750 1751 1752
// 指定密钥身份认证的类型:指纹
properties[5] = {
  tag: huks.HuksTag.HUKS_TAG_USER_AUTH_TYPE,
  value: huks.HuksUserAuthType.HUKS_USER_AUTH_TYPE_FINGERPRINT
Z
zhangcheng 已提交
1753
}
W
wKyrong 已提交
1754 1755 1756 1757
// 指定密钥安全授权的类型(失效类型):新录入生物特征(指纹)后无效
properties[6] = {
  tag: huks.HuksTag.HUKS_TAG_KEY_AUTH_ACCESS_TYPE,
  value: huks.HuksAuthAccessType.HUKS_AUTH_ACCESS_INVALID_NEW_BIO_ENROLL
Z
zhangcheng 已提交
1758
}
W
wKyrong 已提交
1759 1760 1761 1762
// 指定挑战值的类型:默认类型
properties[7] = {
  tag: huks.HuksTag.HUKS_TAG_CHALLENGE_TYPE,
  value: huks.HuksChallengeType.HUKS_CHALLENGE_TYPE_NORMAL
Z
zhangcheng 已提交
1763
}
W
wKyrong 已提交
1764 1765 1766
let huksOptions = {
  properties: properties,
  inData: new Uint8Array(new Array())
Z
zhangcheng 已提交
1767 1768
}

W
wKyrong 已提交
1769 1770 1771 1772 1773
/*
 * 生成密钥
 */
function generateKeyItem(keyAlias:string, huksOptions:huks.HuksOptions, throwObject) {
  return new Promise((resolve, reject) => {
Z
zhangcheng 已提交
1774
    try {
W
wKyrong 已提交
1775 1776 1777 1778 1779
      huks.generateKeyItem(keyAlias, huksOptions, function (error, data) {
        if (error) {
          reject(error);
        } else {
          resolve(data);
Z
zhangcheng 已提交
1780
        }
W
wKyrong 已提交
1781 1782 1783 1784
      });
    } catch (error) {
      throwObject.isThrow = true;
      throw(error);
Z
zhangcheng 已提交
1785
    }
W
wKyrong 已提交
1786
  });
Z
zhangcheng 已提交
1787
}
Z
zhangcheng 已提交
1788

W
wKyrong 已提交
1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807
async function publicGenKeyFunc(keyAlias:string, huksOptions:huks.HuksOptions) {
  console.info(`enter callback generateKeyItem`);
  let throwObject = {isThrow: false};
  try {
    await generateKeyItem(keyAlias, huksOptions, throwObject)
      .then((data) => {
        console.info(`callback: generateKeyItem success, data = ${JSON.stringify(data)}`);
      })
      .catch(error => {
        if (throwObject.isThrow) {
          throw(error);
        } else {
          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 已提交
1808

W
wKyrong 已提交
1809 1810 1811 1812
async function TestGenKeyForFingerprintAccessControl() {
  await publicGenKeyFunc(keyAlias, huksOptions);
}
```
Z
zhangcheng 已提交
1813 1814


W
wKyrong 已提交
1815
2. 初始化密钥会话获取挑战值并发起指纹认证获取认证令牌
Z
zhangcheng 已提交
1816
```ts
Z
zhangcheng 已提交
1817
import huks from '@ohos.security.huks';
W
wKyrong 已提交
1818
import userIAM_userAuth from '@ohos.userIAM.userAuth';
Z
zhangcheng 已提交
1819

W
wKyrong 已提交
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
/*
 * 确定密钥别名和封装密钥属性参数集
 */
let srcKeyAlias = 'sm4_key_fingerprint_access';
let handle;
let challenge;
let fingerAuthToken;
let authType = userIAM_userAuth.UserAuthType.FINGERPRINT;
let authTrustLevel = userIAM_userAuth.AuthTrustLevel.ATL1;

/* 集成生成密钥参数集 & 加密参数集 */
let properties = new Array();
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,
}
let huksOptions = {
  properties: properties,
  inData: new Uint8Array(new Array())
Z
zhangcheng 已提交
1855 1856
}

W
wKyrong 已提交
1857 1858
function initSession(keyAlias:string, huksOptions:huks.HuksOptions, throwObject) : Promise<huks.HuksSessionHandle> {
  return new Promise((resolve, reject) => {
Z
zhangcheng 已提交
1859
    try {
W
wKyrong 已提交
1860 1861 1862 1863 1864 1865 1866
      huks.initSession(keyAlias, huksOptions, function (error, data) {
        if (error) {
          reject(error);
        } else {
          resolve(data);
        }
      });
Z
zhangcheng 已提交
1867
    } catch (error) {
W
wKyrong 已提交
1868 1869
      throwObject.isThrow = true;
      throw(error);
Z
zhangcheng 已提交
1870
    }
W
wKyrong 已提交
1871
  });
Z
zhangcheng 已提交
1872 1873
}

W
wKyrong 已提交
1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888
async function publicInitFunc(keyAlias:string, huksOptions:huks.HuksOptions) {
  console.info(`enter callback doInit`);
  let throwObject = {isThrow: false};
  try {
    await initSession(keyAlias, huksOptions, throwObject)
      .then ((data) => {
        console.info(`callback: doInit success, data = ${JSON.stringify(data)}`);
        handle = data.handle;
        challenge = data.challenge;
      })
      .catch((error) => {
        if (throwObject.isThrow) {
          throw(error);
        } else {
          console.error(`callback: doInit failed, code: ${error.code}, msg: ${error.message}`);
Z
zhangcheng 已提交
1889
        }
W
wKyrong 已提交
1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912
      });
  } catch (error) {
    console.error(`callback: doInit input arg invalid, code: ${error.code}, msg: ${error.message}`);
  }
}

function userIAMAuthFinger(huksChallenge:Uint8Array) {
  // 获取认证对象
  let auth;
  try {
    auth = userIAM_userAuth.getAuthInstance(huksChallenge, authType, authTrustLevel);
    console.log("get auth instance success");
  } catch (error) {
    console.log("get auth instance failed" + error);
  }

  // 订阅认证结果
  try {
    auth.on("result", {
      callback: (result: userIAM_userAuth.AuthResultInfo) => {
        /* 认证成功获取认证令牌 */
        fingerAuthToken = result.token;
      }
Z
zhangcheng 已提交
1913
    });
W
wKyrong 已提交
1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932
    console.log("subscribe authentication event success");
  } catch (error) {
    console.log("subscribe authentication event failed " + error);
  }

  // 开始认证
  try {
    auth.start();
    console.info("authV9 start auth success");
  } catch (error) {
    console.info("authV9 start auth failed, error = " + error);
  }
}

async function testInitAndAuthFinger() {
  /* 初始化密钥会话获取挑战值 */
  await publicInitFunc(srcKeyAlias, huksOptions);
  /* 调用userIAM进行身份认证 */
  userIAMAuthFinger(challenge);
Z
zhangcheng 已提交
1933
}
W
wKyrong 已提交
1934
```
Z
zhangcheng 已提交
1935

W
wKyrong 已提交
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 1971 1972 1973 1974 1975 1976 1977 1978 1979 1980 1981 1982
3. 传入认证令牌进行数据操作
```ts
/*
 * 以下以SM4 128密钥的Callback操作使用为例
 */
import huks from '@ohos.security.huks';

/*
 * 确定密钥别名和封装密钥属性参数集
 */
let srcKeyAlias = 'sm4_key_fingerprint_access';
let IV = '1234567890123456';
let cipherInData = 'Hks_SM4_Cipher_Test_101010101010101010110_string';
let handle;
let fingerAuthToken;
let updateResult = new Array();
let finishOutData;

/* 集成生成密钥参数集 & 加密参数集 */
let propertiesEncrypt = new Array();
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,
  value: StringToUint8Array(IV),
}
let encryptOptions = {
  properties: propertiesEncrypt,
  inData: new Uint8Array(new Array())
Z
zhangcheng 已提交
1983 1984
}

W
wKyrong 已提交
1985 1986 1987 1988 1989 1990
function StringToUint8Array(str) {
  let arr = [];
  for (let i = 0, j = str.length; i < j; ++i) {
    arr.push(str.charCodeAt(i));
  }
  return new Uint8Array(arr);
Z
zhangcheng 已提交
1991 1992
}

W
wKyrong 已提交
1993 1994
function updateSession(handle:number, huksOptions:huks.HuksOptions, token:Uint8Array, throwObject) : Promise<huks.HuksReturnResult> {
  return new Promise((resolve, reject) => {
Z
zhangcheng 已提交
1995
    try {
W
wKyrong 已提交
1996 1997 1998 1999 2000 2001 2002
      huks.updateSession(handle, huksOptions, token, function (error, data) {
        if (error) {
          reject(error);
        } else {
          resolve(data);
        }
      });
Z
zhangcheng 已提交
2003
    } catch (error) {
W
wKyrong 已提交
2004 2005 2006 2007 2008 2009 2010 2011 2012 2013 2014 2015 2016 2017 2018 2019 2020 2021 2022 2023 2024 2025 2026 2027
      throwObject.isThrow = true;
      throw(error);
    }
  });
}

async function publicUpdateFunc(handle:number, token:Uint8Array, huksOptions:huks.HuksOptions) {
  console.info(`enter callback doUpdate`);
  let throwObject = {isThrow: false};
  try {
    await updateSession(handle, huksOptions, token, throwObject)
      .then ((data) => {
        console.info(`callback: doUpdate success, data = ${JSON.stringify(data)}`);
      })
      .catch(error => {
        if (throwObject.isThrow) {
          throw(error);
        } else {
          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 已提交
2028 2029
}

W
wKyrong 已提交
2030 2031 2032 2033 2034 2035 2036 2037
function finishSession(handle:number, huksOptions:huks.HuksOptions, token:Uint8Array, throwObject) : Promise<huks.HuksReturnResult> {
  return new Promise((resolve, reject) => {
    try {
      huks.finishSession(handle, huksOptions, token, function (error, data) {
        if (error) {
          reject(error);
        } else {
          resolve(data);
Z
zhangcheng 已提交
2038
        }
W
wKyrong 已提交
2039 2040 2041 2042 2043 2044 2045 2046 2047 2048 2049 2050 2051 2052 2053 2054 2055 2056 2057 2058 2059 2060 2061 2062 2063 2064 2065
      });
    } catch (error) {
      throwObject.isThrow = true;
      throw(error);
    }
  });
}

async function publicFinishFunc(handle:number, token:Uint8Array, huksOptions:huks.HuksOptions) {
  console.info(`enter callback doFinish`);
  let throwObject = {isThrow: false};
  try {
    await finishSession(handle, huksOptions, token, throwObject)
      .then ((data) => {
        finishOutData = data.outData;
        console.info(`callback: doFinish success, data = ${JSON.stringify(data)}`);
      })
      .catch(error => {
        if (throwObject.isThrow) {
          throw(error);
        } else {
          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}`);
  }
Z
zhangcheng 已提交
2066 2067
}

W
wKyrong 已提交
2068 2069 2070 2071 2072 2073 2074 2075 2076 2077 2078 2079 2080 2081
async function testSm4Cipher() {
  encryptOptions.inData = StringToUint8Array(cipherInData);
  /* 传入认证令牌 */
  await publicUpdateFunc(handle, fingerAuthToken, encryptOptions);
  encryptUpdateResult = updateResult;

  encryptOptions.inData = new Uint8Array(new Array());
  /* 传入认证令牌 */
  await publicFinishFunc(handle, fingerAuthToken, encryptOptions);
  if (finishOutData === cipherInData) {
    console.info('test finish encrypt err ');
  } else {
    console.info('test finish encrypt success');
  }
Z
zhangcheng 已提交
2082 2083 2084
}
```

Z
z00620704 已提交
2085 2086 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 2113 2114 2115 2116 2117 2118 2119 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 2150 2151 2152 2153 2154 2155 2156 2157 2158 2159 2160 2161 2162 2163 2164 2165 2166 2167 2168 2169 2170 2171 2172 2173 2174 2175 2176 2177 2178 2179 2180 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 2321 2322 2323 2324 2325 2326 2327 2328 2329 2330 2331 2332 2333 2334 2335 2336 2337 2338 2339 2340 2341 2342 2343 2344 2345 2346 2347 2348 2349 2350 2351 2352 2353 2354 2355 2356 2357 2358 2359 2360 2361 2362 2363 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 2392 2393 2394 2395 2396 2397 2398 2399 2400 2401 2402 2403 2404 2405 2406 2407 2408 2409 2410 2411 2412 2413 2414 2415 2416 2417 2418 2419 2420 2421 2422 2423 2424 2425 2426 2427 2428 2429 2430 2431 2432 2433 2434 2435 2436 2437 2438 2439 2440 2441 2442 2443 2444 2445 2446 2447 2448 2449 2450 2451 2452 2453 2454 2455 2456 2457 2458 2459 2460 2461 2462 2463 2464 2465 2466 2467 2468 2469 2470 2471 2472 2473 2474 2475 2476 2477 2478 2479 2480 2481 2482 2483 2484 2485 2486 2487 2488 2489 2490 2491 2492 2493 2494 2495 2496 2497 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
### 细粒度用户身份认证访问控制

该功能是基于已有[密钥访问控制](https://gitee.com/openharmony/docs/blob/master/zh-cn/application-dev/security/huks-guidelines.md#%E5%AF%86%E9%92%A5%E8%AE%BF%E9%97%AE%E6%8E%A7%E5%88%B6)能力的扩展,提供了基于生物特征和锁屏密码二次身份认证的细粒度访问控制能力,允许设置密钥在加密、解密、签名、验签、密钥协商、密钥派生的单个或多个场景时是否需要进行身份验证。比如,业务需要使用HUKS密钥加密保存账号密码信息等数据,要求在加密的时候不进行指纹等身份认证,解密的时候需要进行指纹等身份认证,这是就需要依赖HUKS提供细粒度的二次身份认证访问控制机制。

**开发流程**
1. 基于用户身份认证访问控制的流程,在密钥生成阶段,通过额外指定用于细粒度用户身份认证访问控制的HuksTag:[HUKS_TAG_KEY_AUTH_PURPOSE](https://gitee.com/openharmony/docs/blob/master/zh-cn/application-dev/reference/apis/js-apis-huks.md#hukstag)值,来指定在某种算法用途的情况下需要使用用户身份认证访问控制能力。
2. 基于用户身份认证访问控制的流程,在密钥使用阶段,业务无需再次指定HUKS_TAG_KEY_AUTH_PURPOSE值,同用户身份认证访问控制的开发流程。

**接口说明**

新增用于细粒度用户身份认证访问控制的HuksTag:[HUKS_TAG_KEY_AUTH_PURPOSE](https://gitee.com/openharmony/docs/blob/master/zh-cn/application-dev/reference/apis/js-apis-huks.md#hukstag),该Tag值取值范围为枚举类[HuksKeyAlg](https://gitee.com/openharmony/docs/blob/master/zh-cn/application-dev/reference/apis/js-apis-huks.md#hukskeyalg)

**表8** 细粒度用户身份认证访问控制Tag类型介绍
| 名称                      | 描述                 |
| -------------------------------------- | ----------------------------|
|HUKS_TAG_KEY_AUTH_PURPOSE| 表示密钥认证用途的tag,用于设置某种算法用途下需要用户身份认证访问控制|

**注意**
1. 当业务未指定用户认证类型[HuksUserAuthType](../reference/apis/js-apis-huks.md#huksuserauthtype9)时表示默认都不需要用户身份认证访问控制能力,则此时设置HUKS_TAG_KEY_AUTH_PURPOSE是默认无效的; 当业务指定了[HuksUserAuthType](../reference/apis/js-apis-huks.md#huksuserauthtype9)时表示需要用户身份认证访问控制能力,此时若不设置HUKS_TAG_KEY_AUTH_PURPOSE值,则生成密钥阶段指定的算法用途在密钥使用时都默认需要进行用户身份认证访问控制。
2. 当指定的算法是对称算法AES和SM4时,且同时指定用于加解密用途,则只允许设置CBC模式,其它模式不支持细粒度用户身份认证访问控制能力。

**开发步骤**

示例场景:密钥生成阶段,生成用于加解密的密钥并指定只有解密的时候需要用户身份认证访问控制;密钥使用阶段,加密时不需要用户身份认证访问控制,解密时需要用户身份认证访问控制

1. 生成密钥并指定指纹访问控制和相关属性,以及HUKS_TAG_KEY_AUTH_PURPOSE值
```ts
import huks from '@ohos.security.huks';

/*
 * 确定密钥别名和封装密钥属性参数集
 */
let keyAlias = 'dh_key_fingerprint_access';
let properties = new Array();
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,
}
// 指定密钥身份认证的类型:指纹
properties[5] = {
  tag: huks.HuksTag.HUKS_TAG_USER_AUTH_TYPE,
  value: huks.HuksUserAuthType.HUKS_USER_AUTH_TYPE_FINGERPRINT
}
// 指定密钥安全授权的类型(失效类型):新录入生物特征(指纹)后无效
properties[6] = {
  tag: huks.HuksTag.HUKS_TAG_KEY_AUTH_ACCESS_TYPE,
  value: huks.HuksAuthAccessType.HUKS_AUTH_ACCESS_INVALID_NEW_BIO_ENROLL
}
// 指定挑战值的类型:默认类型
properties[7] = {
  tag: huks.HuksTag.HUKS_TAG_CHALLENGE_TYPE,
  value: huks.HuksChallengeType.HUKS_CHALLENGE_TYPE_NORMAL
}
// 指定某种算法用途时需要用户身份认证访问控制:比如解密需要
properties[8] = {
  tag: huks.HuksTag.HUKS_TAG_KEY_AUTH_PURPOSE,
  value: huks.HuksKeyPurpose.HUKS_KEY_PURPOSE_DECRYPT
}
let huksOptions = {
  properties: properties,
  inData: new Uint8Array(new Array())
}

/*
 * 生成密钥
 */
async function generateKeyItem(keyAlias:string, huksOptions:huks.HuksOptions, throwObject) {
  return new Promise((resolve, reject) => {
    try {
      huks.generateKeyItem(keyAlias, huksOptions, function (error, data) {
        if (error) {
          reject(error);
        } else {
          resolve(data);
        }
      });
    } catch (error) {
      throwObject.isThrow = true;
      throw(error);
    }
  });
}

async function publicGenKeyFunc(keyAlias:string, huksOptions:huks.HuksOptions) {
  console.info(`enter callback generateKeyItem`);
  let throwObject = {isThrow: false};
  try {
    await generateKeyItem(keyAlias, huksOptions, throwObject)
      .then((data) => {
        console.info(`callback: generateKeyItem success, data = ${JSON.stringify(data)}`);
      })
      .catch(error => {
        if (throwObject.isThrow) {
          throw(error);
        } else {
          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}`);
  }
}

async function TestGenKeyForFingerprintAccessControl() {
  await publicGenKeyFunc(keyAlias, huksOptions);
}
```

2. 使用密钥-加密场景-加密时不需要进行用户身份认证访问控制
```ts
import huks from '@ohos.security.huks';

/*
 * 确定密钥别名和封装密钥属性参数集
 */
let srcKeyAlias = 'sm4_key_fingerprint_access';
let cipherInData = 'Hks_SM4_Cipher_Test_101010101010101010110_string'; // 明文数据
let IV = '1234567890123456';
let handle;
let cipherText; // 加密后的密文数据

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

/* 集成生成密钥参数集 & 加密参数集 */
let propertiesEncrypt = new Array();
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,
  value: StringToUint8Array(IV),
}
let encryptOptions = {
  properties: propertiesEncrypt,
  inData: new Uint8Array(new Array())
}

function initSession(keyAlias:string, huksOptions:huks.HuksOptions, throwObject) : 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) {
      throwObject.isThrow = true;
      throw(error);
    }
  });
}

async function publicInitFunc(keyAlias:string, huksOptions:huks.HuksOptions) {
  console.info(`enter callback doInit`);
  let throwObject = {isThrow: false};
  try {
    await initSession(keyAlias, huksOptions, throwObject)
      .then ((data) => {
        console.info(`callback: doInit success, data = ${JSON.stringify(data)}`);
        handle = data.handle;
      })
      .catch((error) => {
        if (throwObject.isThrow) {
          throw(error);
        } else {
          console.error(`callback: doInit failed, code: ${error.code}, msg: ${error.message}`);
        }
      });
  } catch (error) {
    console.error(`callback: doInit input arg invalid, code: ${error.code}, msg: ${error.message}`);
  }
}

function finishSession(handle:number, huksOptions:huks.HuksOptions, throwObject) : 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) {
      throwObject.isThrow = true;
      throw(error);
    }
  });
}

async function publicFinishFunc(handle:number, huksOptions:huks.HuksOptions) {
  console.info(`enter callback doFinish`);
  let throwObject = {isThrow: false};
  try {
    await finishSession(handle, huksOptions, throwObject)
      .then ((data) => {
        cipherText = data.outData;
        console.info(`callback: doFinish success, data = ${JSON.stringify(data)}`);
      })
      .catch(error => {
        if (throwObject.isThrow) {
          throw(error);
        } else {
          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}`);
  }
}

async function testSm4Cipher() {
  /* 初始化密钥会话获取挑战值 */
  await publicInitFunc(srcKeyAlias, encryptOptions);

  /* 加密 */
  encryptOptions.inData = StringToUint8Array(cipherInData);
  await publicFinishFunc(handle, encryptOptions);
}
```

3. 使用密钥-解密场景-解密时需要进行用户身份认证访问控制
```ts
import huks from '@ohos.security.huks';
import userIAM_userAuth from '@ohos.userIAM.userAuth';

/*
 * 确定密钥别名和封装密钥属性参数集
 */
let srcKeyAlias = 'sm4_key_fingerprint_access';
let cipherText = 'r56ywtTJUQC6JFJ2VV2kZw=='; // 加密时得到的密文数据, 业务需根据实际加密结果修改
let IV = '1234567890123456';
let handle;
let finishOutData; // 解密后的明文数据
let fingerAuthToken;
let authType = userIAM_userAuth.UserAuthType.FINGERPRINT;
let authTrustLevel = userIAM_userAuth.AuthTrustLevel.ATL1;

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

/* 集成生成密钥参数集 & 加密参数集 */
let propertiesDecrypt = new Array();
propertiesDecrypt[0] = {
  tag: huks.HuksTag.HUKS_TAG_ALGORITHM,
  value: huks.HuksKeyAlg.HUKS_ALG_SM4,
}
propertiesDecrypt[1] = {
  tag: huks.HuksTag.HUKS_TAG_PURPOSE,
  value: huks.HuksKeyPurpose.HUKS_KEY_PURPOSE_DECRYPT,
}
propertiesDecrypt[2] = {
  tag: huks.HuksTag.HUKS_TAG_KEY_SIZE,
  value: huks.HuksKeySize.HUKS_SM4_KEY_SIZE_128,
}
propertiesDecrypt[3] = {
  tag: huks.HuksTag.HUKS_TAG_PADDING,
  value: huks.HuksKeyPadding.HUKS_PADDING_NONE,
}
propertiesDecrypt[4] = {
  tag: huks.HuksTag.HUKS_TAG_BLOCK_MODE,
  value: huks.HuksCipherMode.HUKS_MODE_CBC,
}
propertiesDecrypt[5] = {
  tag: huks.HuksTag.HUKS_TAG_IV,
  value: StringToUint8Array(IV),
}
let decryptOptions = {
  properties: propertiesDecrypt,
  inData: new Uint8Array(new Array())
}

function initSession(keyAlias:string, huksOptions:huks.HuksOptions, throwObject) : 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) {
      throwObject.isThrow = true;
      throw(error);
    }
  });
}

async function publicInitFunc(keyAlias:string, huksOptions:huks.HuksOptions) {
  console.info(`enter callback doInit`);
  let throwObject = {isThrow: false};
  try {
    await initSession(keyAlias, huksOptions, throwObject)
      .then ((data) => {
        console.info(`callback: doInit success, data = ${JSON.stringify(data)}`);
        handle = data.handle;
        challenge = data.challenge;
      })
      .catch((error) => {
        if (throwObject.isThrow) {
          throw(error);
        } else {
          console.error(`callback: doInit failed, code: ${error.code}, msg: ${error.message}`);
        }
      });
  } catch (error) {
    console.error(`callback: doInit input arg invalid, code: ${error.code}, msg: ${error.message}`);
  }
}

function userIAMAuthFinger(huksChallenge:Uint8Array) {
  // 获取认证对象
  let auth;
  try {
    auth = userIAM_userAuth.getAuthInstance(huksChallenge, authType, authTrustLevel);
    console.log("get auth instance success");
  } catch (error) {
    console.log("get auth instance failed" + error);
  }

  // 订阅认证结果
  try {
    auth.on("result", {
      callback: (result: userIAM_userAuth.AuthResultInfo) => {
        /* 认证成功获取认证令牌 */
        fingerAuthToken = result.token;
      }
    });
    console.log("subscribe authentication event success");
  } catch (error) {
    console.log("subscribe authentication event failed " + error);
  }

  // 开始认证
  try {
    auth.start();
    console.info("authV9 start auth success");
  } catch (error) {
    console.info("authV9 start auth failed, error = " + error);
  }
}

function finishSession(handle:number, huksOptions:huks.HuksOptions, token:Uint8Array, throwObject) : Promise<huks.HuksReturnResult> {
  return new Promise((resolve, reject) => {
    try {
      huks.finishSession(handle, huksOptions, token, function (error, data) {
        if (error) {
          reject(error);
        } else {
          resolve(data);
        }
      });
    } catch (error) {
      throwObject.isThrow = true;
      throw(error);
    }
  });
}

async function publicFinishFunc(handle:number, token:Uint8Array, huksOptions:huks.HuksOptions) {
  console.info(`enter callback doFinish`);
  let throwObject = {isThrow: false};
  try {
    await finishSession(handle, huksOptions, token, throwObject)
      .then ((data) => {
        finishOutData = data.outData;
        console.info(`callback: doFinish success, data = ${JSON.stringify(data)}`);
      })
      .catch(error => {
        if (throwObject.isThrow) {
          throw(error);
        } else {
          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}`);
  }
}

async function testSm4Cipher() {
  /* 初始化密钥会话获取挑战值 */
  await publicInitFunc(srcKeyAlias, decryptOptions);

  /* 调用userIAM进行身份认证 */
  userIAMAuthFinger(challenge);

  /* 认证成功后进行解密, 需要传入Auth获取到的authToken值 */
  decryptOptions.inData = StringToUint8Array(cipherText);
  await publicFinishFunc(handle, fingerAuthToken, decryptOptions);
}
```

W
wKyrong 已提交
2525
## 密钥证明
Z
zhangcheng 已提交
2526

W
wKyrong 已提交
2527
HUKS为密钥提供合法性证明能力,主要应用于非对称密钥的公钥的证明。基于PKI证书链技术,HUKS可以为存储在HUKS中的非对称密钥对的公钥签发证书,证明其公钥的合法性。业务可以通过OpenHarmony提供的根CA证书,逐级验证HUKS签发的密钥证明证书,来确保证书中的公钥以及对应的私钥,确实来自合法的硬件设备,且存储管理在HUKS中。
Z
zhangcheng 已提交
2528

W
wKyrong 已提交
2529 2530 2531 2532
**开发流程**
1. 指定密钥别名和需要证明的密钥属性的标签传入HUKS。
2. 调用HUKS为应用生成一个依次由根CA证书、设备CA证书、设备证书、密钥证书组成的X.509证书链。
3. 将证书链传输至受信任的服务器,并在服务器上解析和验证证书链的有效性和单个证书是否吊销。
2533

W
wKyrong 已提交
2534
**接口说明**
2535

Z
z00620704 已提交
2536
**表8** 密钥认证接口介绍
W
wKyrong 已提交
2537 2538 2539
| 接口名                      | 描述                 |
| -------------------------------------- | ----------------------------|
|attestKeyItem(keyAlias: string, options: HuksOptions, callback: AsyncCallback\<HuksReturnResult>) : void| 密钥认证|
2540

W
wKyrong 已提交
2541
**开发步骤**
Z
zhangcheng 已提交
2542

W
wKyrong 已提交
2543 2544 2545 2546 2547
```ts
/*
 * 以下以attestKey Callback接口操作验证为例
 */
import huks from '@ohos.security.huks';
Z
zhangcheng 已提交
2548

W
wKyrong 已提交
2549 2550 2551 2552 2553 2554 2555 2556 2557 2558
/*
 * 确定密钥别名和封装密钥属性参数集
 */
let keyAliasString = "key attest";
let aliasString = keyAliasString;
let aliasUint8 = StringToUint8Array(keyAliasString);
let securityLevel = StringToUint8Array('sec_level');
let challenge = StringToUint8Array('challenge_data');
let versionInfo = StringToUint8Array('version_info');
let attestCertChain;
Z
zhangcheng 已提交
2559

W
wKyrong 已提交
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
let genKeyProperties = new Array();
genKeyProperties[0] = {
    tag: huks.HuksTag.HUKS_TAG_ALGORITHM,
    value: huks.HuksKeyAlg.HUKS_ALG_RSA
};
genKeyProperties[1] = {
    tag: huks.HuksTag.HUKS_TAG_KEY_STORAGE_FLAG,
    value: huks.HuksKeyStorageType.HUKS_STORAGE_PERSISTENT
};
genKeyProperties[2] = {
    tag: huks.HuksTag.HUKS_TAG_KEY_SIZE,
    value: huks.HuksKeySize.HUKS_RSA_KEY_SIZE_2048
};
genKeyProperties[3] = {
    tag: huks.HuksTag.HUKS_TAG_PURPOSE,
    value: huks.HuksKeyPurpose.HUKS_KEY_PURPOSE_VERIFY
};
genKeyProperties[4] = {
    tag: huks.HuksTag.HUKS_TAG_DIGEST,
    value: huks.HuksKeyDigest.HUKS_DIGEST_SHA256
};
genKeyProperties[5] = {
    tag: huks.HuksTag.HUKS_TAG_PADDING,
    value: huks.HuksKeyPadding.HUKS_PADDING_PSS
};
genKeyProperties[6] = {
    tag: huks.HuksTag.HUKS_TAG_KEY_GENERATE_TYPE,
    value: huks.HuksKeyGenerateType.HUKS_KEY_GENERATE_TYPE_DEFAULT
};
genKeyProperties[7] = {
    tag: huks.HuksTag.HUKS_TAG_BLOCK_MODE,
    value: huks.HuksCipherMode.HUKS_MODE_ECB
};
let genOptions = {
    properties: genKeyProperties
};
Z
zhangcheng 已提交
2596

W
wKyrong 已提交
2597 2598 2599 2600 2601 2602 2603 2604 2605 2606 2607 2608 2609 2610 2611 2612 2613 2614 2615 2616
let attestKeyproperties = new Array();
attestKeyproperties[0] = {
    tag: huks.HuksTag.HUKS_TAG_ATTESTATION_ID_SEC_LEVEL_INFO,
    value: securityLevel
};
attestKeyproperties[1] = {
    tag: huks.HuksTag.HUKS_TAG_ATTESTATION_CHALLENGE,
    value: challenge
};
attestKeyproperties[2] = {
    tag: huks.HuksTag.HUKS_TAG_ATTESTATION_ID_VERSION_INFO,
    value: versionInfo
};
attestKeyproperties[3] = {
    tag: huks.HuksTag.HUKS_TAG_ATTESTATION_ID_ALIAS,
    value: aliasUint8
};
let huksOptions = {
    properties: attestKeyproperties
};
Z
zhangcheng 已提交
2617 2618

function StringToUint8Array(str) {
Z
zhangcheng 已提交
2619 2620
    let arr = [];
    for (let i = 0, j = str.length; i < j; ++i) {
Z
zhangcheng 已提交
2621
        arr.push(str.charCodeAt(i));
Z
zhangcheng 已提交
2622
    }
Z
zhangcheng 已提交
2623 2624 2625
    return new Uint8Array(arr);
}

W
wKyrong 已提交
2626
function generateKeyItem(keyAlias:string, huksOptions:huks.HuksOptions, throwObject) {
Z
zhangcheng 已提交
2627 2628 2629 2630 2631 2632 2633 2634 2635 2636
    return new Promise((resolve, reject) => {
        try {
            huks.generateKeyItem(keyAlias, huksOptions, function (error, data) {
                if (error) {
                    reject(error);
                } else {
                    resolve(data);
                }
            });
        } catch (error) {
W
wKyrong 已提交
2637
            throwObject.isThrow = true;
Z
zhangcheng 已提交
2638 2639 2640 2641 2642
            throw(error);
        }
    });
}

W
wKyrong 已提交
2643 2644 2645
async function publicGenKeyFunc(keyAlias:string, huksOptions:huks.HuksOptions) {
    console.info(`enter callback generateKeyItem`);
    let throwObject = {isThrow: false};
Z
zhangcheng 已提交
2646
    try {
W
wKyrong 已提交
2647 2648 2649
        await generateKeyItem(keyAlias, huksOptions, throwObject)
            .then((data) => {
                console.info(`callback: generateKeyItem success, data = ${JSON.stringify(data)}`);
Z
zhangcheng 已提交
2650 2651
            })
            .catch(error => {
W
wKyrong 已提交
2652 2653 2654 2655 2656
                if (throwObject.isThrow) {
                    throw(error);
                } else {
                    console.error(`callback: generateKeyItem failed, code: ${error.code}, msg: ${error.message}`);
                }
Z
zhangcheng 已提交
2657 2658
            });
    } catch (error) {
W
wKyrong 已提交
2659
        console.error(`callback: generateKeyItem input arg invalid, code: ${error.code}, msg: ${error.message}`);
Z
zhangcheng 已提交
2660 2661 2662
    }
}

W
wKyrong 已提交
2663
function attestKeyItem(keyAlias:string, huksOptions:huks.HuksOptions, throwObject) : Promise<huks.HuksReturnResult>{
Z
zhangcheng 已提交
2664 2665 2666 2667 2668 2669 2670 2671 2672 2673
    return new Promise((resolve, reject) => {
        try {
            huks.attestKeyItem(keyAlias, huksOptions, function (error, data) {
                if (error) {
                    reject(error);
                } else {
                    resolve(data);
                }
            });
        } catch (error) {
W
wKyrong 已提交
2674
            throwObject.isThrow = true;
Z
zhangcheng 已提交
2675 2676 2677 2678 2679
            throw(error);
        }
    });
}

W
wKyrong 已提交
2680 2681 2682
async function publicAttestKey(keyAlias:string, huksOptions:huks.HuksOptions) {
    console.info(`enter callback attestKeyItem`);
    let throwObject = {isThrow: false};
Z
zhangcheng 已提交
2683
    try {
W
wKyrong 已提交
2684
        await attestKeyItem(keyAlias, huksOptions, throwObject)
Z
zhangcheng 已提交
2685
            .then ((data) => {
W
wKyrong 已提交
2686 2687 2688 2689
                console.info(`callback: attestKeyItem success, data = ${JSON.stringify(data)}`);
                if (data !== null && data.certChains !== null) {
                    attestCertChain = data.certChains;
                }
Z
zhangcheng 已提交
2690 2691
            })
            .catch(error => {
W
wKyrong 已提交
2692 2693 2694 2695 2696
                if (throwObject.isThrow) {
                    throw(error);
                } else {
                    console.error(`callback: attestKeyItem failed, code: ${error.code}, msg: ${error.message}`);
                }
Z
zhangcheng 已提交
2697 2698
            });
    } catch (error) {
W
wKyrong 已提交
2699
        console.error(`callback: attestKeyItem input arg invalid, code: ${error.code}, msg: ${error.message}`);
Z
zhangcheng 已提交
2700
    }
Z
zhangcheng 已提交
2701 2702
}

W
wKyrong 已提交
2703 2704 2705 2706 2707
async function AttestKeyTest() {
    await publicGenKeyFunc(aliasString, genOptions);

    await publicAttestKey(aliasString, huksOptions);
    console.info('attest certChain data: ' + attestCertChain)
Z
zhangcheng 已提交
2708
}
W
wKyrong 已提交
2709
```
Z
zhangcheng 已提交
2710

W
wKyrong 已提交
2711
> 常见问题
Z
zhangcheng 已提交
2712

W
wKyrong 已提交
2713
1. Cannot find name 'huks'.
Z
zhangcheng 已提交
2714

W
wKyrong 已提交
2715
   不能找到huks,使用了接口函数但没导入security.huks.d.ts,添加import huks from '@ohos.security.huks';即可。
Z
zhangcheng 已提交
2716

W
wKyrong 已提交
2717
2. Property 'finishSession' does not exist on type 'typeof huks'. Did you mean 'finish'?
Z
zengyawen 已提交
2718

W
wKyrong 已提交
2719
   不能在huks库中找到finishSession,finishSession是API9版本的,请更新SDK版本或替换新版本的security.huks.d.ts文件。