subsys-security-huks-guide.md 37.2 KB
Newer Older
1
# OpenHarmony通用密钥库开发
scrawman's avatar
scrawman 已提交
2 3 4 5 6

## 概述

### 功能简介

7
在安全领域里,密码系统被攻击通常不是因为选择的加密算法不够安全,而是密钥管理不到位。用户信息的安全取决于密钥的安全,所以失去对密钥的控制将导致密码系统的失败,从而危害到用户信息的安全。Huks提供系统级的密钥管理能力,支撑鸿蒙生态应用和系统应用,实现密钥全生命周期(生成,存储,使用,销毁)的管理和安全使用,对标AndriodKeyStore补充和增强密钥管理相关能力,满足生态应用和上层业务的诉求。通过密钥明文不出可信环境、密钥非明文存储等方式,保护用户密钥安全。
scrawman's avatar
scrawman 已提交
8

9 10 11 12 13 14 15 16 17 18
支持特性:密钥全生命周期管理

1. 密钥生成/导入

2. 密钥存储

3. 密钥使用(加解密,签名验签,密钥派生,密钥协商,哈希,密钥访问控制)

4. 密钥销毁

scrawman's avatar
scrawman 已提交
19 20
### 基本概念

21
- 服务层
scrawman's avatar
scrawman 已提交
22 23 24

  提供密钥管理服务的具体业务功能模块,HUKS Service并不直接处理密钥运算,而是依赖HUKS Core为上层提供服务。

25
- 核心层
scrawman's avatar
scrawman 已提交
26 27 28 29 30 31 32

  提供密钥管理服务的核心功能模块,密钥全生命周期明文不出HUKS Core模块。

- 可信执行环境(Trusted Execution Environment,TEE)

  通过软硬件方法在中央处理器中构建一个安全区域,保证其内部加载的程序和数据在机密性和完整性上得到保护。通过将系统的硬件和软件资源划分为两个执行环境——可信执行环境和普通执行环境,使其有独立的内部数据通路和计算所需存储空间,保证敏感信息不向外泄漏。普通执行环境的应用不能访问TEE的资源,TEE中的应用在没有授权的情况下也无法相互访问。

33
- 三段式(Init-Update-Finish)
34

35
   Init    初始化密钥操作数据。
36

37
   Update  分段操作数据并返回结果,或追加数据。
38

39
   Finish   结束分段操作或追加数据,返回结果。
scrawman's avatar
scrawman 已提交
40

41
### 实现原理
scrawman's avatar
scrawman 已提交
42 43 44 45 46 47 48 49 50 51 52 53 54

以密钥的生成为例:
上层应用通过密钥管理SDK调用到HUKS Service,Huks Service再调用Huks Core,Huks Core会调用密钥管理模块生成密钥。之后Huks Core使用基于RootKey派生的加密密钥对生成的密钥加密再传给Service侧,Service侧再以文件形式存储加密后的密钥。

![image](figures/HUKS-GenrateKey1.png)

![image](figures/HUKS-GenrateKey2.png)


### 约束与限制

1. Huks的实现需要在可信执行环境(TEE)中实现,保证密钥管理和操作的可信可靠。

55
2. HuksHdiAttestKey返回的证书链应该按照业务证书、设备证书、CA证书和根证书的顺序组装,在每项证书之前还需要加上证书的长度。证书链组装完成后添加整个证书链的长度组装成blob格式。证书的具体格式如要自己实现应与服务器侧解析的格式相对应。
56

57 58
![image](figures/CertChain.png)

59
3. 接口返回的密钥必须按照密钥存储态组装成KeyBlob,哪些接口需要遵循该限制请见[接口说明](#接口说明)
scrawman's avatar
scrawman 已提交
60

61
   构造KeyBlob的示例请参见[hks_keyblob.c/HksBuildKeyBlob](https://gitee.com/openharmony/security_huks/blob/master/services/huks_standard/huks_engine/main/core/src/hks_keyblob.c)
scrawman's avatar
scrawman 已提交
62 63 64

#### 密钥存储态

65 66
为了基于密钥属性对密钥的使用进行访问控制,需要在存储密钥的同时存储它的相关信息,存储态下密钥属性和密钥的组合结构如下:

scrawman's avatar
scrawman 已提交
67 68 69 70 71 72
![image](figures/HUKS-KeyBlob.png)

## 开发指导

### 场景介绍

73
HUKS以CORE层为基础向应用提供密钥库能力,包括密钥管理及密钥的密码学操作等功能。如果想要使用自己的实现替换HUKS的CORE层,需要实现以下接口。
scrawman's avatar
scrawman 已提交
74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91

### 接口说明

**表1** 接口功能介绍

| 接口名                                                       | 功能介绍                                  | 约束与限制                     | 对应的js接口                                        |
| ------------------------------------------------------------ | ---------------------------------------- | ----------------------------- | ------------------------------------------------------------ |
| HuksHdiModuleInit()                   | Core的初始化。                            |  无                           | 无 |
| HuksHdiRefresh()                          | 刷新根密钥。                              |  无                            | 无 |
| HuksHdiGenerateKey()                  | 生成密钥。                                |  出参要遵循KeyBlob格式          |generateKey(keyAlias: string, options: HuksOptions)|
| HuksHdiImportKey()                     | 导入明文密钥。                            |  出参要遵循KeyBlob格式           | importKey(keyAlias: string, options: HuksOptions)|
| HuksHdiImportWrappedKey()        |导入加密密钥。                              |  出参要遵循KeyBlob格式          | importWrappedKey(keyAlias: string, wrappingKeyAlias: string, options: HuksOptions)|
| HuksHdiExportPublicKey()         | 导出公钥。                                 |无                             | exportKey(keyAlias: string, options: HuksOptions) |
| HuksHdiInit()                              | 三段式中的Init接口。                       |无                              | init(keyAlias: string, options: HuksOptions) |
| HuksHdiUpdate()                           | 三段式中的Update接口。                     |签名验签时入参是原始数据          | update(handle: number, token?: Uint8Array, options: HuksOptions) |
| HuksHdiFinish()                           | 三段式中的Finish接口。                     |签名验签时入参是签名后数据        | finish(handle: number, options: HuksOptions) |
| HuksHdiAbort()                         | 终止三段式。                               |无                             | abort(handle: number, options: HuksOptions) |
| HuksHdiGetKeyProperties()        | 获取密钥属性。                              |无                            | getKeyProperties(keyAlias: string, options: HuksOptions)|
92
| HuksHdiAttestKey()        | 获取密钥证书。                              |出参要遵循certChain格式                      | attestKey(keyAlias: string, options: HuksOptions)|
scrawman's avatar
scrawman 已提交
93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 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 348 349 350 351 352 353 354 355

- - -

**HuksHdiModuleInit**

**接口描述**

Core的初始化,包括锁,加密算法库,authtoken key和根密钥。

**接口原型**
<pre><code>int32_t HuksHdiModuleInit();</code></pre>

<details>
  <summary><strong>返回值</strong></summary>

  - HKS_SUCCESS:成功

  - 其他:失败
</details>

- - -

**HuksHdiRefresh**

**接口描述**

刷新根密钥。

**接口原型**
<pre><code>int32_t HuksHdiRefresh();</code></pre>

<details>
  <summary><strong>返回值</strong></summary>

  - HKS_SUCCESS:成功

  - 其他:失败
</details>

- - -

**HuksHdiGenerateKey**

**接口描述**

根据paramSet生成密钥。

**接口原型**
<pre><code>int32_t HuksHdiGenerateKey(const struct HksBlob *keyAlias, const struct HksParamSet *paramSet, const struct HksBlob *keyIn, struct HksBlob *keyOut);</code></pre>

<details>
  <summary><strong>参数说明</strong></summary>
  <pre>
  <strong>const struct HksBlob *keyAlias</strong>
  将要生成的密钥的别名,要求:
  1. keyAlias != null
  2. keyAlias -> data != null
  3. keyAlias -> size != 0
  <br></br>
  <strong>const struct HksParamSet *paramSet</strong>
  要生成密钥的参数
  <br></br>
  <strong>const struct HksBlob *keyIn</strong>
  在agree key时使用
  <br></br>
  <strong>struct HksBlob *keyOut</strong>
  出参,将paramset和生成的密钥存放在这里
  </pre>
</details>
<br></br>

<details>
  <summary><strong>约束与限制</strong></summary>

  1. 请在接口内检查上述参数是否符合要求,如是否是空指针、密钥算法是否支持等

  2. keyOut请参照[KeyBlob](#密钥存储态)的结构

</details>
<br></br>

<details>
  <summary><strong>返回值</strong></summary>

  - HKS_SUCCESS:成功

  - 其他:失败
</details>

- - -

**HuksHdiImportKey**

**接口描述**

导入明文密钥。

**接口原型**
<pre><code>int32_t HuksHdiImportKey(const struct HksBlob *keyAlias, const struct HksBlob *key, const struct HksParamSet *paramSet, struct HksBlob *keyOut);</code></pre>

<details>
  <summary><strong>参数说明</strong></summary>
  <pre>
  <strong>const struct HksBlob *msg</strong>
  将要导入的密钥的别名,要求:
  1. keyAlias != null
  2. keyAlias -> data != null
  3. keyAlias -> size != 0
  <br></br>
  <strong>const struct HksBlob *key</strong>
  要导入的密钥,要求:
  1. key != null
  2. key -> data != null
  3. key -> size != 0
  <br></br>
  <strong>const struct HksParamSet *paramSet</strong>
  导入密钥的参数
  <br></br>
  <strong>struct HksBlob *keyOut</strong>
  出参,将paramset和生成的密钥存放在这里
  <br></br>
  </pre>
</details>
<br></br>

<details>
  <summary><strong>约束与限制</strong></summary>

  1. 请在接口内检查上述参数是否符合要求,如是否是空指针、密钥算法是否支持等

  2. keyOut请参照[KeyBlob](#密钥存储态)的结构

</details>
<br></br>

<details>
  <summary><strong>返回值</strong></summary>

  - HKS_SUCCESS:成功

  - 其他:失败
</details>

- - -

**HuksHdiImportWrappedKey**

**接口描述**

导入加密密钥。

**接口原型**
<pre><code>int32_t HuksHdiImportWrappedKey(const struct HksBlob *keyAlias, const struct HksBlob *wrappingUsedkey, const struct HksBlob *wrappedKeyData, const struct HksParamSet *paramSet, struct HksBlob *keyOut);</code></pre>

<details>
  <summary><strong>参数说明</strong></summary>
  <pre>
  <strong>const struct HksBlob *KeyAlias</strong>
  将要导入的密钥的别名,要求:
  1. keyAlias != null
  2. keyAlias -> data != null
  3. keyAlias -> size != 0
  <br></br>
  <strong>const struct HksBlob *key</strong>
  要导入的密钥数据被加密时使用的密钥,要求:
  1. wrappingUsedkey != null
  2. wrappingUsedkey -> data != null
  3. wrappingUsedkey -> size != 0
  <br></br>
  <strong>const struct HksBlob *wrappedKeyData</strong>
  要导入的密钥的加密数据,要求:
  1. wrappedKeyData != null
  2. wrappedKeyData -> data != null
  3. wrappedKeyData -> size != 0
  <br></br>
  <strong>const struct HksParamSet *paramSet</strong>
  导入密钥的参数
  <br></br>
  <strong>struct HksBlob *keyOut</strong>
  出参,将paramset和生成的密钥存放在这里
  </pre>
</details>
<br></br>

<details>
  <summary><strong>约束与限制</strong></summary>

  1. 请在接口内检查上述参数是否符合要求,如是否是空指针、密钥算法是否支持等

  2. keyOut请参照[KeyBlob](#密钥存储态)的结构

</details>
<br></br>

<details>
  <summary><strong>返回值</strong></summary>

  - HKS_SUCCESS:成功

  - 其他:失败
</details>

- - -

**HuksHdiExportPublicKey**

**接口描述**

导出公钥。

**接口原型**
<pre><code>int32_t HuksHdiExportPublicKey(const struct HksBlob *key, const struct HksParamSet *paramSet, struct HksBlob *keyOut);</code></pre>

<details>
  <summary><strong>参数说明</strong></summary>
  <pre>
  <strong>const struct HksBlob *key</strong>
  与要导出的公钥对应的私钥,要求:
  1. key != null
  2. key -> data != null
  3. key -> size != 0
  <br></br>
  <strong>const struct HksParamSet *paramSet</strong>
  空参数
  <br></br>
  <strong>struct HksBlob *keyOut</strong>
  出参,存放导出的公钥
  </pre>
</details>
<br></br>

<details>
  <summary><strong>返回值</strong></summary>

  - HKS_SUCCESS:成功

  - 其他:失败
</details>

- - -

**HuksHdiInit**

**接口描述**

三段式中的Init接口。

**接口原型**
<pre><code>int32_t HuksHdiInit(const struct HksBlob *key, const struct HksParamSet *paramSet, struct HksBlob *handle, struct HksBlob *token);</code></pre>

<details>
  <summary><strong>参数说明</strong></summary>
  <pre>
  <strong>const struct HksBlob *key</strong>
  init操作的密钥,要求:
  1. key != null
  2. key -> data != null
  3. key -> size != 0
  <br></br>
  <strong>const struct HksParamSet *paramSet</strong>
  init操作的参数
  <br></br>
  <strong>struct HksBlob *handle</strong>
356
  三段式的句柄
scrawman's avatar
scrawman 已提交
357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386
  <br></br>
  <strong>struct HksBlob *token</strong>
  存放安全访问控制的challenge
  </pre>
</details>
<br></br>

<details>
  <summary><strong>返回值</strong></summary>

  - HKS_SUCCESS:成功

  - 其他:失败
</details>

- - -

**HuksHdiUpdate**

**接口描述**

三段式中的Update接口。

**接口原型**
<pre><code>int32_t HuksHdiUpdate(const struct HksBlob *handle, const struct HksParamSet *paramSet, const struct HksBlob *inData, struct HksBlob *outData);</code></pre>

<details>
  <summary><strong>参数说明</strong></summary>
  <pre>
  <strong>const struct HksBlob *handle</strong>
387
  三段式的句柄
scrawman's avatar
scrawman 已提交
388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431
  <br></br>
  <strong> const struct HksParamSet *paramSet</strong>
  update操作的参数
  <br></br>
  <strong> const struct HksBlob *inData</strong>
  update操作的输入
  <br></br>
  <strong> struct HksBlob *outData</strong>
  update操作的结果
  </pre>
</details>
<br></br>

<details>
  <summary><strong>约束与限制</strong></summary>

  1. 在进行签名验签时inData要传入原文数据

</details>
<br></br>

<details>
  <summary><strong>返回值</strong></summary>

  - HKS_SUCCESS:成功

  - 其他:失败
</details>

- - -

**HuksHdiFinish**

**接口描述**

三段式中的Finish接口。

**接口原型**
<pre><code>int32_t HuksHdiFinish(const struct HksBlob *handle, const struct HksParamSet *paramSet, const struct HksBlob *inData, struct HksBlob *outData);</code></pre>

<details>
  <summary><strong>参数说明</strong></summary>
  <pre>
  <strong>const struct HksBlob *handle</strong>
432
  三段式的句柄
scrawman's avatar
scrawman 已提交
433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476
  <br></br>
  <strong> const struct HksParamSet *paramSet</strong>
  finish操作的参数
  <br></br>
  <strong> const struct HksBlob *inData</strong>
  finish操作的输入
  <br></br>
  <strong> struct HksBlob *outData</strong>
  finish操作的结果
  </pre>
</details>
<br></br>

<details>
  <summary><strong>约束与限制</strong></summary>

  1. 在进行签名验签时inData要传入需要验证的签名数据,通过返回结果表示验签是否成功

</details>
<br></br>

<details>
  <summary><strong>返回值</strong></summary>

  - HKS_SUCCESS:成功

  - 其他:失败
</details>

- - -

**HuksHdiAbort**

**接口描述**

终止三段式。当init,update和finish操作中的任一阶段发生错误时,都要调用abort来终止密钥的使用。

**接口原型**
<pre><code>int32_t HuksHdiAbort(const struct HksBlob *handle, const struct HksParamSet *paramSet);</code></pre>

<details>
  <summary><strong>参数说明</strong></summary>
  <pre>
  <strong>const struct HksBlob *handle</strong>
477
  三段式的句柄
scrawman's avatar
scrawman 已提交
478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515
  <br></br>
  <strong>const struct HksParamSet *paramSet</strong>
  Abort操作的参数
  </pre>
</details>
<br></br>

<details>
  <summary><strong>返回值</strong></summary>

  - HKS_SUCCESS:成功

  - 其他:失败
</details>

- - -

**HuksHdiGetKeyProperties**

**接口描述**

获取密钥属性。

**接口原型**
<pre><code>int32_t HuksHdiGetKeyProperties(const struct HksParamSet *paramSet, const struct HksBlob *key);</code></pre>

<details>
  <summary><strong>参数说明</strong></summary>
  <pre>
  <strong>const struct HksParamSet *paramSet</strong>
  空对象
  <br></br>
  <strong>const struct HksBlob *key</strong>
  要获取属性的密钥
  </pre>
</details>
<br></br>

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
<details>
  <summary><strong>返回值</strong></summary>

  - HKS_SUCCESS:成功

  - 其他:失败
</details>

- - -

**HuksHdiAttestKey**

**接口描述**

获取密钥证书。

**接口原型**
<pre><code>int32_t (*HuksHdiAttestKey)(const struct HksBlob *key, const struct HksParamSet *paramSet, struct HksBlob *certChain);</code></pre>

<details>
  <summary><strong>参数说明</strong></summary>
  <pre>
  <strong>const struct HksBlob *key</strong>
  要获取证书的密钥
  <br></br>
  <strong>const struct HksParamSet *paramSet</strong>
  获取证书操作的参数
  <br></br>
  <strong>struct HksBlob *certChain</strong>
  出参,存放证书
  </pre>
</details>
<br></br>

<details>
  <summary><strong>约束与限制</strong></summary>

553
  1. certChain的格式需遵循[约束与限制第二点](#约束与限制)
554 555 556 557

</details>
<br></br>

scrawman's avatar
scrawman 已提交
558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586
<details>
  <summary><strong>返回值</strong></summary>

  - HKS_SUCCESS:成功

  - 其他:失败
</details>

- - -

### 开发步骤

Huks Core层接口实例,以下是目录结构及各部分功能简介。

```undefined
// base/security/user_auth/services/huks_standard/huks_engine/main
├── BUILD.gn # 编译脚本
├── core_dependency # 实现依赖
└── core # Core层的软实现
    ├── BUILD.gn # 编译脚本
    ├── include 
    └── src
        ├── hks_core_interfaces.c # Hdi到Core的适配层
        └── hks_core_service.c # 具体实现
        └── ... #其他功能代码
```

1. 关于Core层接口的具体实现,详细代码参见[hks_core_service.c](https://gitee.com/openharmony/security_huks/blob/master/services/huks_standard/huks_engine/main/core/src/hks_core_service.c)文件。

587
```c
scrawman's avatar
scrawman 已提交
588 589 590 591 592 593
   // 导入明文密钥
   int32_t HksCoreImportKey(const struct HksBlob *keyAlias, const struct HksBlob *key,
    const struct HksParamSet *paramSet, struct HksBlob *keyOut)
   {
        struct HksBlob innerKey = { 0, NULL };
        struct HksParam *importKeyTypeParam = NULL;
594
        //在属性里加入IMPORT_KEY
scrawman's avatar
scrawman 已提交
595 596 597 598 599 600 601 602 603 604 605 606
        int32_t ret = HksGetParam(paramSet, HKS_TAG_IMPORT_KEY_TYPE, &importKeyTypeParam);
        if ((ret == HKS_SUCCESS) &&
            ((importKeyTypeParam->uint32Param == HKS_KEY_TYPE_PRIVATE_KEY) ||
            (importKeyTypeParam->uint32Param == HKS_KEY_TYPE_KEY_PAIR))) {
            ret = GetPrivateOrPairInnerFormat(importKeyTypeParam->uint32Param, key, paramSet, &innerKey);
        } else {
            ret = CopyToInnerKey(key, &innerKey);
        }
        if (ret != HKS_SUCCESS) {
            HKS_LOG_E("translate key to inner format failed, ret = %d", ret);
            return ret;
        }
607
        //检查import key的参数
scrawman's avatar
scrawman 已提交
608 609 610 611
        ret = HksCoreCheckImportKeyParams(keyAlias, &innerKey, paramSet, keyOut);
        if (ret != HKS_SUCCESS) {
            return ret;
        }
612
        //构建存储态的密钥
scrawman's avatar
scrawman 已提交
613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641
        ret = HksBuildKeyBlob(keyAlias, HKS_KEY_FLAG_IMPORT_KEY, &innerKey, paramSet, keyOut);
        (void)memset_s(innerKey.data, innerKey.size, 0, innerKey.size);
        HKS_FREE_BLOB(innerKey);
        return ret;
   }
   
   // 三段式init接口
   int32_t HksCoreInit(const struct  HksBlob *key, const struct HksParamSet *paramSet, struct HksBlob *handle,
    struct HksBlob *token)
    {
        HKS_LOG_D("HksCoreInit in Core start");
        uint32_t pur = 0;
        uint32_t alg = 0;

        if (key == NULL || paramSet == NULL || handle == NULL || token == NULL) {
            HKS_LOG_E("the pointer param entered is invalid");
            return HKS_FAILURE;
        }

        if (handle->size < sizeof(uint64_t)) {
            HKS_LOG_E("handle size is too small, size : %u", handle->size);
            return HKS_ERROR_INSUFFICIENT_MEMORY;
        }

        struct HuksKeyNode *keyNode = HksCreateKeyNode(key, paramSet);
        if (keyNode == NULL || handle == NULL) {
            HKS_LOG_E("the pointer param entered is invalid");
            return HKS_ERROR_BAD_STATE;
        }
642
        //初始化handle。通过handle向session中存储信息,供update/finish使用。使得外部可以通过同个handle分多次进行同一密钥操作。
scrawman's avatar
scrawman 已提交
643 644
        handle->size = sizeof(uint64_t);
        (void)memcpy_s(handle->data, handle->size, &(keyNode->handle), handle->size);
645
        //从参数中提取出算法
scrawman's avatar
scrawman 已提交
646 647 648 649 650 651 652 653 654 655 656 657
        int32_t ret = GetPurposeAndAlgorithm(paramSet, &pur, &alg);
        if (ret != HKS_SUCCESS) {
            HksDeleteKeyNode(keyNode->handle);
            return ret;
        }

        ret = HksCoreSecureAccessInitParams(keyNode, paramSet, token);
        if (ret != HKS_SUCCESS) {
            HKS_LOG_E("init secure access params failed");
            HksDeleteKeyNode(keyNode->handle);
            return ret;
        }
658
        
scrawman's avatar
scrawman 已提交
659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683
        uint32_t i;
        uint32_t size = HKS_ARRAY_SIZE(g_hksCoreInitHandler);
        for (i = 0; i < size; i++) {
            if (g_hksCoreInitHandler[i].pur == pur) {
                HKS_LOG_E("Core HksCoreInit [pur] = %d, pur = %d", g_hksCoreInitHandler[i].pur, pur);
                ret = g_hksCoreInitHandler[i].handler(keyNode, paramSet, alg);
                break;
            }
        }

        if (ret != HKS_SUCCESS) {
            HksDeleteKeyNode(keyNode->handle);
            HKS_LOG_E("CoreInit failed, ret : %d", ret);
            return ret;
        }

        if (i == size) {
            HksDeleteKeyNode(keyNode->handle);
            HKS_LOG_E("don't found purpose, pur : %u", pur);
            return HKS_FAILURE;
        }

        HKS_LOG_D("HksCoreInit in Core end");
        return ret;
    }
684 685 686 687
   
   // 三段式update接口
   int32_t HksCoreUpdate(const struct HksBlob *handle, const struct HksParamSet *paramSet, const struct HksBlob *inData,
    struct HksBlob *outData)
688 689 690 691
    {
        HKS_LOG_D("HksCoreUpdate in Core start");
        uint32_t pur = 0;
        uint32_t alg = 0;
692

693 694 695 696
        if (handle == NULL || paramSet == NULL || inData == NULL) {
            HKS_LOG_E("the pointer param entered is invalid");
            return HKS_FAILURE;
        }
697

698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729
        uint64_t sessionId;
        struct HuksKeyNode *keyNode = NULL;
        //根据handle获取本次三段式操作需要的上下文
        int32_t ret = GetParamsForUpdateAndFinish(handle, &sessionId, &keyNode, &pur, &alg);
        if (ret != HKS_SUCCESS) {
            HKS_LOG_E("GetParamsForCoreUpdate failed");
            return ret;
        }
        //校验参数
        ret = HksCoreSecureAccessVerifyParams(keyNode, paramSet);
        if (ret != HKS_SUCCESS) {
            HksDeleteKeyNode(sessionId);
            HKS_LOG_E("HksCoreUpdate secure access verify failed");
            return ret;
        }

        uint32_t i;
        uint32_t size = HKS_ARRAY_SIZE(g_hksCoreUpdateHandler);
        for (i = 0; i < size; i++) {
            //调用对应的密码学处理函数
            if (g_hksCoreUpdateHandler[i].pur == pur) {
                struct HksBlob appendInData = { 0, NULL };
                ret = HksCoreAppendAuthInfoBeforeUpdate(keyNode, pur, paramSet, inData, &appendInData);
                if (ret != HKS_SUCCESS) {
                    HKS_LOG_E("before update: append auth info failed");
                    break;
                }
                ret = g_hksCoreUpdateHandler[i].handler(keyNode, paramSet,
                    appendInData.data == NULL ? inData : &appendInData, outData, alg);
                if (appendInData.data != NULL) {
                    HKS_FREE_BLOB(appendInData);
                }
730 731 732 733
                break;
            }
        }

734 735 736 737 738
        if (ret != HKS_SUCCESS) {
            HksDeleteKeyNode(keyNode->handle);
            HKS_LOG_E("CoreUpdate failed, ret : %d", ret);
            return ret;
        }
739

740 741 742 743 744 745
        if (i == size) {
            HksDeleteKeyNode(sessionId);
            HKS_LOG_E("don't found purpose, pur : %u", pur);
            return HKS_FAILURE;
        }
        return ret;
746
    }
scrawman's avatar
scrawman 已提交
747 748 749 750
   ```

### 调测验证

751
开发完成后,通过[HUKS JS接口](https://gitee.com/openharmony/security_huks/blob/master/interfaces/kits/js/@ohos.security.huks.d.ts)开发JS应用。JS测试代码示例如下:
scrawman's avatar
scrawman 已提交
752

753
AES生成密钥和加密:
scrawman's avatar
scrawman 已提交
754 755

```js
756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799
import huks from '@ohos.security.huks';

export default {
    data: {},
    onInit() {
        console.log(`huks demo cipher_aes init finish`);
    },
    onShow() {
        console.log(`huks demo cipher_aes onshow start`);
        this.start();
        console.log(`huks demo cipher_aes onshow end`);
    },
    async start() {
        let handle;
        let IV = '0000000000000000';
        let cipherInData = 'Hks_AES_Cipher_Test_101010101010101010110_string';
        let srcKeyAlias = 'huksCipherAesSrcKeyAlias';
        let encryptUpdateResult = new Array()
        let decryptUpdateResult = new Array()
        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_ENCRYPT |
            huks.HuksKeyPurpose.HUKS_KEY_PURPOSE_DECRYPT,
        }
        properties[2] = {
            tag: huks.HuksTag.HUKS_TAG_KEY_SIZE,
            value: huks.HuksKeySize.HUKS_AES_KEY_SIZE_128,
        }
        properties[3] = {
            tag: huks.HuksTag.HUKS_TAG_BLOCK_MODE,
            value: huks.HuksCipherMode.HUKS_MODE_CBC,
        }
        properties[4] = {
            tag: huks.HuksTag.HUKS_TAG_PADDING,
            value: huks.HuksKeyPadding.HUKS_PADDING_NONE,
        }
scrawman's avatar
scrawman 已提交
800

801 802 803 804
        let HuksOptions = {
            properties: properties,
            inData: new Uint8Array(new Array())
        }
scrawman's avatar
scrawman 已提交
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
        /* 生成密钥 */
        await huks.generateKey(srcKeyAlias, HuksOptions).then((data) => {
            console.log(`test generateKey data: ${JSON.stringify(data)}`);
        }).catch((err) => {
            console.log('test generateKey err information: ' + JSON.stringify(err));
        });
        let propertiesEncrypt = new Array();
        propertiesEncrypt[0] = {
            tag: huks.HuksTag.HUKS_TAG_ALGORITHM,
            value: huks.HuksKeyAlg.HUKS_ALG_AES,
        }
        propertiesEncrypt[1] = {
            tag: huks.HuksTag.HUKS_TAG_PURPOSE,
            value: huks.HuksKeyPurpose.HUKS_KEY_PURPOSE_ENCRYPT,
        }
        propertiesEncrypt[2] = {
            tag: huks.HuksTag.HUKS_TAG_KEY_SIZE,
            value: huks.HuksKeySize.HUKS_AES_KEY_SIZE_128,
        }
        propertiesEncrypt[3] = {
            tag: huks.HuksTag.HUKS_TAG_PADDING,
            value: huks.HuksKeyPadding.HUKS_PADDING_NONE,
        }
        propertiesEncrypt[4] = {
            tag: huks.HuksTag.HUKS_TAG_BLOCK_MODE,
            value: huks.HuksCipherMode.HUKS_MODE_CBC,
        }
        propertiesEncrypt[5] = {
            tag: huks.HuksTag.HUKS_TAG_DIGEST,
            value: huks.HuksKeyDigest.HUKS_DIGEST_NONE,
        }
        propertiesEncrypt[6] = {
            tag: huks.HuksTag.HUKS_TAG_IV,
            value: this.stringToUint8Array(IV)
        }
        let encryptOptions = {
            properties: propertiesEncrypt,
            inData: new Uint8Array(new Array())
        }
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 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929
        /* 进行密钥加密操作 */
        await huks.init(srcKeyAlias, encryptOptions).then((data) => {
            console.log(`test init data: ${JSON.stringify(data)}`);
            handle = data.handle;
        }).catch((err) => {
            console.log('test init err information: ' + JSON.stringify(err));
        });
        encryptOptions.inData = this.stringToUint8Array(cipherInData)
        await huks.update(handle, encryptOptions).then(async (data) => {
            console.log(`test update data ${JSON.stringify(data)}`);
            encryptUpdateResult = Array.from(data.outData);
        }).catch((err) => {
            console.log('test update err information: ' + err);
        });
        encryptOptions.inData = new Uint8Array(new Array());
        await huks.finish(handle, encryptOptions).then((data) => {
            console.log(`test finish data: ${JSON.stringify(data)}`);
            let finishData = this.uint8ArrayToString(new Uint8Array(encryptUpdateResult));
            if (finishData === cipherInData) {
                console.log('test finish encrypt err ');
            } else {
                console.log('test finish encrypt success');
            }
        }).catch((err) => {
            console.log('test finish err information: ' + JSON.stringify(err));
        });

        /* 修改加密参数集为解密参数集 */
        propertiesEncrypt.splice(1, 1, {
            tag: huks.HuksTag.HUKS_TAG_PURPOSE,
            value: huks.HuksKeyPurpose.HUKS_KEY_PURPOSE_DECRYPT,
        });
        let decryptOptions = {
            properties: propertiesEncrypt,
            inData: new Uint8Array(new Array())
        }
        
        /* 进行解密操作 */
        await huks.init(srcKeyAlias, decryptOptions).then((data) => {
            console.log(`test init data: ${JSON.stringify(data)}`);
            handle = data.handle;
        }).catch((err) => {
            console.log('test init err information: ' + JSON.stringify(err));
        });

        decryptOptions.inData = new Uint8Array(encryptUpdateResult);
        await huks.update(handle, decryptOptions).then(async (data) => {
            console.log(`test update data ${JSON.stringify(data)}`);
            decryptUpdateResult = Array.from(data.outData);
        }).catch((err) => {
            console.log('test update err information: ' + err);
        });
        decryptOptions.inData = new Uint8Array(new Array());
        await huks.finish(handle, decryptOptions).then((data) => {
            console.log(`test finish data: ${JSON.stringify(data)}`);
            let finishData = this.uint8ArrayToString(new Uint8Array(decryptUpdateResult));
            if (finishData === cipherInData) {
                console.log('test finish decrypt success ');
            } else {
                console.log('test finish decrypt err');
            }
        }).catch((err) => {
            console.log('test finish err information: ' + JSON.stringify(err));
        });

        await huks.deleteKey(srcKeyAlias, HuksOptions).then((data) => {
            console.log(`test deleteKey data: ${JSON.stringify(data)}`);
        }).catch((err) => {
            console.log('test deleteKey err information: ' + JSON.stringify(err));
        });
    },
    stringToUint8Array(str) {
        var arr = [];
        for (var i = 0, j = str.length; i < j; ++i) {
            arr.push(str.charCodeAt(i));
        }
        return new Uint8Array(arr);
    },
    uint8ArrayToString(fileData) {
        var dataString = '';
        for (var i = 0; i < fileData.length; i++) {
            dataString += String.fromCharCode(fileData[i]);
        }
        return dataString;
scrawman's avatar
scrawman 已提交
930 931 932 933
    }
}
```

934
RSA512签名验签:
scrawman's avatar
scrawman 已提交
935 936

```js
937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979
import huks from '@ohos.security.huks';

export default {
    data: {},
    onInit() {
        console.log(`huks demo signVerify_rsa init finish`);
    },
    onShow() {
        console.log(`huks demo signVerify_rsa onshow start`);
        this.start();
        console.log(`huks demo signVerify_rsa onshow end`);
    },
    async start() {
        let handle;
        let signVerifyInData = 'signVerifyInData';
        let srcKeyAliasSign = 'huksSignVerifySrcKeyAliasSign';
        let srcKeyAliasVerify = 'huksSignVerifySrcKeyAliasVerify';
        let properties = new Array();
        let finishOutData;
        let exportKey;
        /* 集成生成密钥参数集 & 签名参数集 & 验签参数集 */
        properties[0] = {
            tag: huks.HuksTag.HUKS_TAG_ALGORITHM,
            value: huks.HuksKeyAlg.HUKS_ALG_RSA,
        }
        properties[1] = {
            tag: huks.HuksTag.HUKS_TAG_PURPOSE,
            value:
            huks.HuksKeyPurpose.HUKS_KEY_PURPOSE_SIGN |
            huks.HuksKeyPurpose.HUKS_KEY_PURPOSE_VERIFY,
        }
        properties[2] = {
            tag: huks.HuksTag.HUKS_TAG_KEY_SIZE,
            value: huks.HuksKeySize.HUKS_RSA_KEY_SIZE_512,
        }
        properties[3] = {
            tag: huks.HuksTag.HUKS_TAG_DIGEST,
            value: huks.HuksKeyDigest.HUKS_DIGEST_MD5,
        }
        properties[4] = {
            tag: huks.HuksTag.HUKS_TAG_PADDING,
            value: huks.HuksKeyPadding.HUKS_PADDING_PKCS1_V1_5,
        }
scrawman's avatar
scrawman 已提交
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 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015
        let HuksOptions = {
            properties: properties,
            inData: new Uint8Array(new Array())
        }
        
        /* 生成密钥 */
        await huks.generateKey(srcKeyAliasSign, HuksOptions).then((data) => {
            console.log(`test generateKey data: ${JSON.stringify(data)}`);
        }).catch((err) => {
            console.log('test generateKey err information: ' + JSON.stringify(err));
        });
        let propertiesSign = new Array();

        propertiesSign[0] = {
            tag: huks.HuksTag.HUKS_TAG_ALGORITHM,
            value: huks.HuksKeyAlg.HUKS_ALG_RSA,
        }
        propertiesSign[1] = {
            tag: huks.HuksTag.HUKS_TAG_PURPOSE,
            value:
            huks.HuksKeyPurpose.HUKS_KEY_PURPOSE_SIGN
        }
        propertiesSign[2] = {
            tag: huks.HuksTag.HUKS_TAG_DIGEST,
            value: huks.HuksKeyDigest.HUKS_DIGEST_MD5,
        }
        propertiesSign[3] = {
            tag: huks.HuksTag.HUKS_TAG_KEY_SIZE,
            value: huks.HuksKeySize.HUKS_RSA_KEY_SIZE_512,
        }
        propertiesSign[4] = {
            tag: huks.HuksTag.HUKS_TAG_PADDING,
            value: huks.HuksKeyPadding.HUKS_PADDING_PKCS1_V1_5,
        }
1016

1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063
        let signOptions = {
            properties: propertiesSign,
            inData: new Uint8Array(new Array())
        }
        /* 对密钥进行签名操作 */
        await huks.init(srcKeyAliasSign, signOptions).then((data) => {
            console.log(`test init data: ${JSON.stringify(data)}`);
            handle = data.handle;
        }).catch((err) => {
            console.log('test init err information: ' + JSON.stringify(err));
        });
        signOptions.inData = this.stringToUint8Array(signVerifyInData)
        await huks.update(handle, signOptions).then(async (data) => {
            console.log(`test update data ${JSON.stringify(data)}`);
        }).catch((err) => {
            console.log('test update err information: ' + err);
        });
        signOptions.inData = new Uint8Array(new Array());
        await huks.finish(handle, signOptions).then((data) => {
            console.log(`test finish data: ${JSON.stringify(data)}`);
            finishOutData = data.outData;
        }).catch((err) => {
            console.log('test finish err information: ' + JSON.stringify(err));
        });
        
        /* 通过导出导入模拟获取一段密钥数据 */
        await huks.exportKey(srcKeyAliasSign, HuksOptions).then((data) => {
            console.log(`test exportKey data: ${JSON.stringify(data)}`);
            exportKey = data.outData;
        }).catch((err) => {
            console.log('test exportKey err information: ' + JSON.stringify(err));
        });

        let propertiesVerify = new Array();

        propertiesVerify[0] = {
            tag: huks.HuksTag.HUKS_TAG_ALGORITHM,
            value: huks.HuksKeyAlg.HUKS_ALG_RSA,
        }
        propertiesVerify[1] = {
            tag: huks.HuksTag.HUKS_TAG_PURPOSE,
            value: huks.HuksKeyPurpose.HUKS_KEY_PURPOSE_VERIFY
        }
        propertiesVerify[2] = {
            tag: huks.HuksTag.HUKS_TAG_DIGEST,
            value: huks.HuksKeyDigest.HUKS_DIGEST_MD5,
        }
1064

1065 1066 1067 1068
        propertiesVerify[3] = {
            tag: huks.HuksTag.HUKS_TAG_KEY_SIZE,
            value: huks.HuksKeySize.HUKS_RSA_KEY_SIZE_512,
        }
1069

1070 1071 1072 1073
        propertiesVerify[4] = {
            tag: huks.HuksTag.HUKS_TAG_PADDING,
            value: huks.HuksKeyPadding.HUKS_PADDING_PKCS1_V1_5,
        }
1074

1075 1076 1077 1078
        let verifyOptions = {
            properties: propertiesVerify,
            inData: new Uint8Array(new Array())
        }
1079

1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132
        verifyOptions.inData = exportKey;
        await huks.importKey(srcKeyAliasVerify, verifyOptions).then((data) => {
            console.log(`test ImportKey data: ${JSON.stringify(data)}`);
        }).catch((err) => {
            console.log('test exportKey err information: ' + JSON.stringify(err));
        });
        
        /* 对密钥进行验签 */
        await huks.init(srcKeyAliasVerify, verifyOptions).then((data) => {
            console.log(`test init data: ${JSON.stringify(data)}`);
            handle = data.handle;
        }).catch((err) => {
            console.log('test init err information: ' + JSON.stringify(err));
        });

        verifyOptions.inData = this.stringToUint8Array(signVerifyInData);
        await huks.update(handle, verifyOptions).then(async (data) => {
            console.log(`test update data ${JSON.stringify(data)}`);
        }).catch((err) => {
            console.log('test update err information: ' + err);
        });
        verifyOptions.inData = finishOutData;
        await huks.finish(handle, verifyOptions).then((data) => {
            console.log(`test finish data: ${JSON.stringify(data)}`);
        }).catch((err) => {
            console.log('test finish err information: ' + JSON.stringify(err));
        });

        await huks.deleteKey(srcKeyAliasVerify, HuksOptions).then((data) => {
            console.log(`test deleteKey data: ${JSON.stringify(data)}`);
        }).catch((err) => {
            console.log('test deleteKey err information: ' + JSON.stringify(err));
        });

        await huks.deleteKey(srcKeyAliasSign, HuksOptions).then((data) => {
            console.log(`test deleteKey data: ${JSON.stringify(data)}`);
        }).catch((err) => {
            console.log('test deleteKey err information: ' + JSON.stringify(err));
        });
    },
    stringToUint8Array(str) {
        var arr = [];
        for (var i = 0, j = str.length; i < j; ++i) {
            arr.push(str.charCodeAt(i));
        }
        return new Uint8Array(arr);
    },
    uint8ArrayToString(fileData) {
        var dataString = '';
        for (var i = 0; i < fileData.length; i++) {
            dataString += String.fromCharCode(fileData[i]);
        }
        return dataString;
1133 1134 1135
    }
}
```