huks-guidelines.md 77.3 KB
Newer Older
Z
zengyawen 已提交
1 2 3 4 5 6
# HUKS开发指导

## 场景介绍

 HUKS(OpenHarmony Universal KeyStore,OpenHarmony通用密钥库系统)向应用提供密钥库能力,包括密钥管理及密钥的密码学操作等功能。HUKS所管理的密钥可以由应用导入或者由应用调用HUKS接口生成。 

Z
zhangcheng 已提交
7
## 基于JS的开发指导
Z
zengyawen 已提交
8 9 10 11 12 13 14

1. 引入HUKS模块

   ```js
   import huks from '@ohos.security.huks'
   ```

S
shuyi 已提交
15
2. 使用generateKey接口生成密钥。
Z
zengyawen 已提交
16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42

   keyAlias为生成的密钥别名,options为生成密钥时使用到的参数,需根据具体需要到的算法设定options中的参数。

   generateKey接口会返回密钥的生成是否成功。

   ```js
   var alias = 'testAlias';
   var properties = new Array();
   properties[0] = {
     tag: huks.HuksTag.HUKS_TAG_ALGORITHM,
     value: huks.HuksKeyAlg.HUKS_ALG_ECC
   };
   properties[1] = {
     tag: huks.HuksTag.HUKS_TAG_KEY_SIZE,
     value: huks.HuksKeySize.HUKS_ECC_KEY_SIZE_224
   };
   properties[2] = {
     tag: huks.HuksTag.HUKS_TAG_PURPOSE,
     value: huks.HuksKeyPurpose.HUKS_KEY_PURPOSE_AGREE
   };
   properties[3] = {
     tag: huks.HuksTag.HUKS_TAG_DIGEST,
     value: huks.HuksKeyDigest.HUKS_DIGEST_NONE
   };
   var options = {
     properties: properties
   }
S
shuyi 已提交
43
   var resultA = huks.generateKey(alias, options);
Z
zengyawen 已提交
44 45 46 47 48 49 50 51 52 53 54 55 56
   ```

3. 使用Init接口进行init操作。

   Alias为初始化密钥的别名,options为初始化密钥用的参数集合,需根据具体需要到的算法设定options中的参数。

   init接口会返回init操作是否成功。

   ```js
   var alias = 'test001'
   var properties = new Array();
   properties[0] = {
     tag: huks.HuksTag.HUKS_TAG_ALGORITHM,
S
shuyi 已提交
57
     value: huks.HuksKeyAlg.HUKS_ALG_DH
Z
zengyawen 已提交
58 59
   };
   properties[1] = {
S
shuyi 已提交
60 61
     tag: huks.HuksTag.HUKS_TAG_PURPOSE,
     value: huks.HuksKeyPurpose.HUKS_KEY_PURPOSE_AGREE
Z
zengyawen 已提交
62 63
   };
   properties[2] = {
S
shuyi 已提交
64 65
     tag: huks.HuksTag.HUKS_TAG_KEY_SIZE,
     value: huks.HuksKeySize.HUKS_DH_KEY_SIZE_4096
Z
zengyawen 已提交
66 67 68 69
   };
   var options = {
     properties: properties
   };
S
shuyi 已提交
70 71 72 73 74 75 76
   huks.init(alias, options, function(err, data) {
       if (err.code !== 0) {
           console.log("test init err information: " + JSON.stringify(err));
       } else {
           console.log(`test init data: ${JSON.stringify(data)}`);
       }
   })
Z
zengyawen 已提交
77
   ```
Z
zhangcheng 已提交
78

Z
zengyawen 已提交
79 80 81 82 83 84 85 86 87 88
4. 使用Update接口进行update操作。

   handle为更新密钥的session id,options为更新密钥用的参数集合,需根据具体需要到的算法设定options中的参数。

   update接口会返回update操作是否成功。

   ```js
   var properties = new Array();
   properties[0] = {
     tag: huks.HuksTag.HUKS_TAG_ALGORITHM,
S
shuyi 已提交
89
     value: huks.HuksKeyAlg.HUKS_ALG_DH
Z
zengyawen 已提交
90 91
   };
   properties[1] = {
S
shuyi 已提交
92 93
     tag: huks.HuksTag.HUKS_TAG_PURPOSE,
     value: huks.HuksKeyPurpose.HUKS_KEY_PURPOSE_AGREE
Z
zengyawen 已提交
94 95
   };
   properties[2] = {
S
shuyi 已提交
96 97
     tag: huks.HuksTag.HUKS_TAG_KEY_SIZE,
     value: huks.HuksKeySize.HUKS_DH_KEY_SIZE_4096
Z
zengyawen 已提交
98 99 100 101
   };
   var options = {
     properties: properties
   };
S
shuyi 已提交
102
   var result = huks.update(handle, options)
Z
zengyawen 已提交
103
   ```
Z
zhangcheng 已提交
104

Z
zengyawen 已提交
105 106 107 108 109 110 111 112 113 114
5. 使用Finish接口进行finish操作。

   handle为 结束密钥的session id,options为结束密钥用的参数集合,需根据具体需要到的算法设定options中的参数。

   finish接口会返回finish操作是否成功。

   ```js
   var properties = new Array();
   properties[0] = {
     tag: huks.HuksTag.HUKS_TAG_ALGORITHM,
S
shuyi 已提交
115
     value: huks.HuksKeyAlg.HUKS_ALG_DH
Z
zengyawen 已提交
116 117
   };
   properties[1] = {
S
shuyi 已提交
118 119
     tag: huks.HuksTag.HUKS_TAG_PURPOSE,
     value: huks.HuksKeyPurpose.HUKS_KEY_PURPOSE_AGREE
Z
zengyawen 已提交
120 121
   };
   properties[2] = {
S
shuyi 已提交
122 123
     tag: huks.HuksTag.HUKS_TAG_KEY_SIZE,
     value: huks.HuksKeySize.HUKS_DH_KEY_SIZE_4096
Z
zengyawen 已提交
124 125 126 127
   };
   var options = {
     properties: properties
   };
S
shuyi 已提交
128
   var result = huks.finish(handle, options) 
Z
zengyawen 已提交
129 130
   ```

Z
zhangcheng 已提交
131
## 基于TS的开发指导
Z
zhangcheng 已提交
132

Z
zhangcheng 已提交
133
### 密钥导入导出
Z
zhangcheng 已提交
134

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

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

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

Z
zhangcheng 已提交
141 142 143
1. 生成密钥。
2. 导出密钥。
3. 导入密钥。
Z
zhangcheng 已提交
144

145 146 147 148 149 150 151 152 153 154 155 156
**支持导入的密钥类型:**

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

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

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

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

Z
zhangcheng 已提交
157
在使用示例前,需要先了解几个预先定义的变量: 
Z
zhangcheng 已提交
158 159 160 161 162

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

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

**示例:**

Z
zhangcheng 已提交
170
```ts
Z
zhangcheng 已提交
171 172 173
/* 以生成RSA512密钥为例 */
var srcKeyAlias = 'hukRsaKeyAlias';
var srcKeyAliasSecond = 'huksRsaKeyAliasSecond';
Z
zhangcheng 已提交
174
var exportKey;
Z
zhangcheng 已提交
175

Z
zhangcheng 已提交
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
async function testImportExport() {
    /* 集成生成密钥参数集 */
    var properties = new Array();
    properties[0] = {
        tag: huks.HuksTag.HUKS_TAG_ALGORITHM,
        value: huks.HuksKeyAlg.HUKS_ALG_RSA,
    }
    properties[1] = {
        tag: huks.HuksTag.HUKS_TAG_PURPOSE,
        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_RSA_KEY_SIZE_512,
    }
    properties[3] = {
        tag: huks.HuksTag.HUKS_TAG_BLOCK_MODE,
        value: huks.HuksCipherMode.HUKS_MODE_ECB,
    }
    properties[4] = {
        tag: huks.HuksTag.HUKS_TAG_PADDING,
        value: huks.HuksKeyPadding.HUKS_PADDING_PKCS1_V1_5,
    }
    properties[5] = {
        tag: huks.HuksTag.HUKS_TAG_DIGEST,
        value: huks.HuksKeyDigest.HUKS_DIGEST_SHA256,
    }
    var huksOptions = {
        properties: properties,
        inData: new Uint8Array(new Array())
    }
Z
zhangcheng 已提交
209

Z
zhangcheng 已提交
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
    /* 生成密钥 */
    await huks.generateKey(srcKeyAlias, huksOptions).then((data) => {
        console.info(`test generateKey data: ${JSON.stringify(data)}`);
    }).catch((err) => {
        console.info('test generateKey err information: ' + JSON.stringify(err));
    });

    /* 导出密钥 */
    await huks.exportKey(srcKeyAlias, huksOptions).then((data) => {
        console.info(`test ExportKey data: ${JSON.stringify(data)}`);
        exportKey = data.outData;
    }).catch((err) => {
        console.info('test ImportKey err information: ' + JSON.stringify(err));
    });

    /* 集成导入密钥参数集 */
    var propertiesEncrypt = new Array();
    propertiesEncrypt[0] = {
        tag: huks.HuksTag.HUKS_TAG_ALGORITHM,
        value: huks.HuksKeyAlg.HUKS_ALG_RSA,
    }
    propertiesEncrypt[1] = {
        tag: huks.HuksTag.HUKS_TAG_KEY_SIZE,
        value: huks.HuksKeySize.HUKS_RSA_KEY_SIZE_512,
    }
    propertiesEncrypt[2] = {
        tag: huks.HuksTag.HUKS_TAG_PADDING,
        value: huks.HuksKeyPadding.HUKS_PADDING_PKCS1_V1_5,
    }
    propertiesEncrypt[3] = {
        tag: huks.HuksTag.HUKS_TAG_BLOCK_MODE,
        value: huks.HuksCipherMode.HUKS_MODE_ECB,
    }
    propertiesEncrypt[4] = {
        tag: huks.HuksTag.HUKS_TAG_DIGEST,
        value: huks.HuksKeyDigest.HUKS_DIGEST_SHA256,
    }
    propertiesEncrypt[5] = {
        tag: huks.HuksTag.HUKS_TAG_PURPOSE,
        value: huks.HuksKeyPurpose.HUKS_KEY_PURPOSE_ENCRYPT,
    }
    var encryptOptions = {
        properties: propertiesEncrypt,
        inData: new Uint8Array(new Array())
    }

    /* 导入密钥 */
    encryptOptions.inData = exportKey;
    await huks.importKey(srcKeyAliasSecond, encryptOptions).then((data) => {
        console.info(`test ImportKey data: ${JSON.stringify(data)}`);
    }).catch((err) => {
        console.info('test ImportKey err information: ' + JSON.stringify(err));
    });
Z
zhangcheng 已提交
263
}
Z
zhangcheng 已提交
264 265 266 267
```

### 安全导入

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

开发步骤如下:

272 273 274 275 276 277 278 279 280 281 282 283 284 285 286
1.   huks中生成用于加密导入协商的密钥。
2.  导出该密钥的公钥,协商出共享密钥。
3.  生成中间密钥材料并加密密钥。
4.  导入密钥。 

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

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

> **注意**
>
> - 生成公共密钥时,要设置参数HUKS_TAG_PURPOSE = HUKS_KEY_PURPOSE_UNWRAP
> - 参数HUKS_TAG_IMPORT_KEY_TYPE = HUKS_KEY_TYPE_KEY_PAIR
> - 安全导入密钥时,参数集须加上参数HUKS_TAG_UNWRAP_ALGORITHM_SUITE, 值为HUKS_UNWRAP_SUITE_X25519_AES_256_GCM_NOPADDING或者HUKS_UNWRAP_SUITE_ECDH_AES_256_GCM_NOPADDING
> - 存储的 keyAlias 密钥别名最大为64字节
Z
zhangcheng 已提交
287 288 289 290 291 292 293 294 295 296

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

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

Z
zhangcheng 已提交
297
关于接口的具体信息,可在[API参考文档](../reference/apis/js-apis-huks.md)中查看。 
Z
zhangcheng 已提交
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 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372

**示例:**

```ts
var inputEccPair = new Uint8Array([
    0x02, 0x00, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x20, 0x00, 0x00,
    0x00, 0x20, 0x00, 0x00, 0x00, 0x20, 0x00, 0x00, 0x00, 0xa5, 0xb8,
    0xa3, 0x78, 0x1d, 0x6d, 0x76, 0xe0, 0xb3, 0xf5, 0x6f, 0x43, 0x9d,
    0xcf, 0x60, 0xf6, 0x0b, 0x3f, 0x64, 0x45, 0xa8, 0x3f, 0x1a, 0x96,
    0xf1, 0xa1, 0xa4, 0x5d, 0x3e, 0x2c, 0x3f, 0x13, 0xd7, 0x81, 0xf7,
    0x2a, 0xb5, 0x8d, 0x19, 0x3d, 0x9b, 0x96, 0xc7, 0x6a, 0x10, 0xf0,
    0xaa, 0xbc, 0x91, 0x6f, 0x4d, 0xa7, 0x09, 0xb3, 0x57, 0x88, 0x19,
    0x6f, 0x00, 0x4b, 0xad, 0xee, 0x34, 0x35, 0xfb, 0x8b, 0x9f, 0x12,
    0xa0, 0x83, 0x19, 0xbe, 0x6a, 0x6f, 0x63, 0x2a, 0x7c, 0x86, 0xba,
    0xca, 0x64, 0x0b, 0x88, 0x96, 0xe2, 0xfa, 0x77, 0xbc, 0x71, 0xe3,
    0x0f, 0x0f, 0x9e, 0x3c, 0xe5, 0xf9]);

var exportWrappingKey;
var importAlias = "importAlias";
var wrapAlias = "wrappingKeyAlias";

async function TestGenFunc(alias, options) {
    await genKey(alias, options).then((data) => {
        console.log(`test genKey data: ${JSON.stringify(data)}`);
    })
    .catch((err) => {
        console.log('test genKey err information: ' + JSON.stringify(err));
    });
}

function genKey(alias, options) {
    return new Promise((resolve, reject) => {
        huks.importKey(alias, options, function (err, data) {
            console.log(`test genKey data: ${JSON.stringify(data)}`);
            if (err.code !== 0) {
                console.log('test genKey err information: ' + JSON.stringify(err));
                reject(err);
            } else {
                resolve(data);
            }
        });
    });
}

async function TestExportFunc(alias, options) {
    await exportKey(alias, options).then((data) => {
        console.log(`test exportKey data: ${JSON.stringify(data)}`);
    })
    .catch((err) => {
        console.log('test exportKey err information: ' + JSON.stringify(err));
    });
}

function exportKey(alias, options) {
    return new Promise((resolve, reject) => {
        huks.exportKey(alias, options, function (err, data) {
            console.log(`test exportKey data: ${JSON.stringify(data)}`);
            if (err.code !== 0) {
                console.log('test exportKey err information: ' + JSON.stringify(err));
                reject(err);
            } else {
                exportWrappingKey = data.outData;
                resolve(data);
            }
        });
    });
}

async function TestImportWrappedFunc(alias, wrappingAlias, options) {
    var result = await huks.importWrappedKey(alias, wrappingAlias, options);
    if (result.errorCode === 0) {
        console.error('test importWrappedKey success');
    } else {
        console.error('test importWrappedKey fail');
    }
Z
zhangcheng 已提交
373
}
Z
zhangcheng 已提交
374 375 376 377 378 379 380 381 382 383 384 385 386 387 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 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456

async function TestImportWrappedKeyFunc(
    importAlias,
    wrappingAlias,
    genOptions,
    importOptions
) {
    await TestGenFunc(wrappingAlias, genOptions);
    await TestExportFunc(wrappingAlias, genOptions);

    /* 以下操作不需要调用HUKS接口,此处不给出具体实现。
     * 假设待导入的密钥为keyA
     * 1.生成ECC公私钥keyB,公钥为keyB_pub, 私钥为keyB_pri
     * 2.使用keyB_pri和wrappingAlias密钥中获取的公钥进行密钥协商,协商出共享密钥share_key
     * 3.随机生成密钥kek,用于加密keyA,采用AES-GCM加密,加密过程中需要记录:nonce1/aad1/加密后的密文keyA_enc/加密后的tag1。
     * 4.使用share_key加密kek,采用AES-GCM加密,加密过程中需要记录:nonce2/aad2/加密后的密文kek_enc/加密后的tag2。
     * 5.拼接importOptions.inData字段,满足以下格式:
     * keyB_pub的长度(4字节) + keyB_pub的数据 + aad2的长度(4字节) + aad2的数据 +
     * nonce2的长度(4字节)   + nonce2的数据   + tag2的长度(4字节) + tag2的数据 +
     * kek_enc的长度(4字节)  + kek_enc的数据  + aad1的长度(4字节) + aad1的数据 +
     * nonce1的长度(4字节)   + nonce1的数据   + tag1的长度(4字节) + tag1的数据 +
     * keyA长度占用的内存长度(4字节)  + keyA的长度     + keyA_enc的长度(4字节) + keyA_enc的数据
     */
    var inputKey = new Uint8Array([
    0x5b, 0x00, 0x00, 0x00, 0x30, 0x59, 0x30, 0x13, 0x06, 0x07, 0x2a,
    0x86, 0x48, 0xce, 0x3d, 0x02, 0x01, 0x06, 0x08, 0x2a, 0x86, 0x48,
    0xce, 0x3d, 0x03, 0x01, 0x07, 0x03, 0x42, 0x00, 0x04, 0xc0, 0xfe,
    0x1c, 0x67, 0xde, 0x86, 0x0e, 0xfb, 0xaf, 0xb5, 0x85, 0x52, 0xb4,
    0x0e, 0x1f, 0x6c, 0x6c, 0xaa, 0xc5, 0xd9, 0xd2, 0x4d, 0xb0, 0x8a,
    0x72, 0x24, 0xa1, 0x99, 0xaf, 0xfc, 0x3e, 0x55, 0x5a, 0xac, 0x99,
    0x3d, 0xe8, 0x34, 0x72, 0xb9, 0x47, 0x9c, 0xa6, 0xd8, 0xfb, 0x00,
    0xa0, 0x1f, 0x9f, 0x7a, 0x41, 0xe5, 0x44, 0x3e, 0xb2, 0x76, 0x08,
    0xa2, 0xbd, 0xe9, 0x41, 0xd5, 0x2b, 0x9e, 0x10, 0x00, 0x00, 0x00,
    0xbf, 0xf9, 0x69, 0x41, 0xf5, 0x49, 0x85, 0x31, 0x35, 0x14, 0x69,
    0x12, 0x57, 0x9c, 0xc8, 0xb7, 0x10, 0x00, 0x00, 0x00, 0x2d, 0xb7,
    0xf1, 0x5a, 0x0f, 0xb8, 0x20, 0xc5, 0x90, 0xe5, 0xca, 0x45, 0x84,
    0x5c, 0x08, 0x08, 0x10, 0x00, 0x00, 0x00, 0x43, 0x25, 0x1b, 0x2f,
    0x5b, 0x86, 0xd8, 0x87, 0x04, 0x4d, 0x38, 0xc2, 0x65, 0xcc, 0x9e,
    0xb7, 0x20, 0x00, 0x00, 0x00, 0xf4, 0xe8, 0x93, 0x28, 0x0c, 0xfa,
    0x4e, 0x11, 0x6b, 0xe8, 0xbd, 0xa8, 0xe9, 0x3f, 0xa7, 0x8f, 0x2f,
    0xe3, 0xb3, 0xbf, 0xaf, 0xce, 0xe5, 0x06, 0x2d, 0xe6, 0x45, 0x5d,
    0x19, 0x26, 0x09, 0xe7, 0x10, 0x00, 0x00, 0x00, 0xf4, 0x1e, 0x7b,
    0x01, 0x7a, 0x84, 0x36, 0xa4, 0xa8, 0x1c, 0x0d, 0x3d, 0xde, 0x57,
    0x66, 0x73, 0x10, 0x00, 0x00, 0x00, 0xe3, 0xff, 0x29, 0x97, 0xad,
    0xb3, 0x4a, 0x2c, 0x50, 0x08, 0xb5, 0x68, 0xe1, 0x90, 0x5a, 0xdc,
    0x10, 0x00, 0x00, 0x00, 0x26, 0xae, 0xdc, 0x4e, 0xa5, 0x6e, 0xb1,
    0x38, 0x14, 0x24, 0x47, 0x1c, 0x41, 0x89, 0x63, 0x11, 0x04, 0x00,
    0x00, 0x00, 0x20, 0x00, 0x00, 0x00, 0x20, 0x00, 0x00, 0x00, 0x0b,
    0xcb, 0xa9, 0xa8, 0x5f, 0x5a, 0x9d, 0xbf, 0xa1, 0xfc, 0x72, 0x74,
    0x87, 0x79, 0xf2, 0xf4, 0x22, 0x0c, 0x8a, 0x4d, 0xd8, 0x7e, 0x10,
    0xc8, 0x44, 0x17, 0x95, 0xab, 0x3b, 0xd2, 0x8f, 0x0a]);

    importOptions.inData = inputKey;
    await TestImportWrappedFunc(importAlias, wrappingAlias, importOptions);
}

function makePubKeyOptions() {
    var properties = new Array();
    properties[0] = {
        tag: huks.HuksTag.HUKS_TAG_ALGORITHM,
        value: huks.HuksKeyAlg.HUKS_ALG_ECC
    };
    properties[1] = {
        tag: huks.HuksTag.HUKS_TAG_KEY_SIZE,
        value: huks.HuksKeySize.HUKS_ECC_KEY_SIZE_256
    };
    properties[2] = {
        tag: huks.HuksTag.HUKS_TAG_PURPOSE,
        value: huks.HuksKeyPurpose.HUKS_KEY_PURPOSE_UNWRAP
    };
    properties[3] = {
        tag: huks.HuksTag.HUKS_TAG_DIGEST,
        value: huks.HuksKeyDigest.HUKS_DIGEST_SHA256
    };
    properties[4] = {
        tag: huks.HuksTag.HUKS_TAG_IMPORT_KEY_TYPE,
        value: huks.HuksImportKeyType.HUKS_KEY_TYPE_KEY_PAIR,
    };
    var options = {
        properties: properties,
        inData: inputEccPair
    };
    return options;
Z
zhangcheng 已提交
457
}
Z
zhangcheng 已提交
458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490

function makeImportOptions() {
    var properties = new Array();
    properties[0] = {
        tag: huks.HuksTag.HUKS_TAG_ALGORITHM,
        value: huks.HuksKeyAlg.HUKS_ALG_AES
    };
    properties[1] = {
        tag: huks.HuksTag.HUKS_TAG_KEY_SIZE,
        value: huks.HuksKeySize.HUKS_AES_KEY_SIZE_256
    };
    properties[2] = {
        tag: huks.HuksTag.HUKS_TAG_PURPOSE,
        value:
        huks.HuksKeyPurpose.HUKS_KEY_PURPOSE_ENCRYPT |
        huks.HuksKeyPurpose.HUKS_KEY_PURPOSE_DECRYPT
    };
    properties[3] = {
        tag: huks.HuksTag.HUKS_TAG_BLOCK_MODE,
        value: huks.HuksCipherMode.HUKS_MODE_CBC
    };
    properties[4] = {
        tag: huks.HuksTag.HUKS_TAG_PADDING,
        value: huks.HuksKeyPadding.HUKS_PADDING_NONE
    };
    properties[5] = {
        tag: huks.HuksTag.HUKS_TAG_UNWRAP_ALGORITHM_SUITE,
        value: huks.HuksUnwrapSuite.HUKS_UNWRAP_SUITE_ECDH_AES_256_GCM_NOPADDING
    };
    var options = {
        properties: properties
    };
    return options;
Z
zhangcheng 已提交
491 492
}

Z
zhangcheng 已提交
493 494 495 496 497 498 499 500 501 502
function huksImportWrappedKey() {
    var genOptions = makePubKeyOptions();
    var importOptions = makeImportOptions();
    TestImportWrappedKeyFunc(
        importAlias,
        wrapAlias,
        genOptions,
        importOptions
    );
}
Z
zhangcheng 已提交
503 504 505 506
```

### 密钥加解密

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

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

Z
zhangcheng 已提交
511 512 513
1. 生成密钥。
2. 密钥加密。
3. 密钥解密。
Z
zhangcheng 已提交
514

515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537
**支持的密钥类型:**

| HUKS_ALG_ALGORITHM                                           | HUKS_TAG_PURPOSE                                   | HUKS_TAG_DIGEST                                              | HUKS_TAG_PADDING                                             | HUKS_TAG_BLOCK_MODE                         | HUKS_TAG_IV |
| ------------------------------------------------------------ | -------------------------------------------------- | ------------------------------------------------------------ | ------------------------------------------------------------ | ------------------------------------------- | ----------- |
| HUKS_ALG_SM4                  (支持长度:  HUKS_SM4_KEY_SIZE_128) | HUKS_KEY_PURPOSE_ENCRYPT  HUKS_KEY_PURPOSE_DECRYPT | 【非必选】                                                   | HUKS_PADDING_NONE                                            | HUKS_MODE_CTR  HUKS_MODE_ECB  HUKS_MODE_CBC | 【必选】    |
| HUKS_ALG_SM4                  (支持长度:  HUKS_SM4_KEY_SIZE_128) | HUKS_KEY_PURPOSE_ENCRYPT  HUKS_KEY_PURPOSE_DECRYPT | 【非必选】                                                   | HUKS_PADDING_PKCS7                                           | HUKS_MODE_ECB  HUKS_MODE_CBC                | 【必选】    |
| HUKS_ALG_RSA                 (支持长度:  HUKS_SM4_KEY_SIZE_512  HUKS_SM4_KEY_SIZE_768  HUKS_SM4_KEY_SIZE_1024  HUKS_SM4_KEY_SIZE_2048  HUKS_SM4_KEY_SIZE_3072  HUKS_SM4_KEY_SIZE_4096) | HUKS_KEY_PURPOSE_ENCRYPT  HUKS_KEY_PURPOSE_DECRYPT | HUKS_DIGEST_SHA1 HUKS_DIGEST_SHA224  HUKS_DIGEST_SHA256  HUKS_DIGEST_SHA384  HUKS_DIGEST_SHA512 | HUKS_PADDING_NONE  HUKS_PADDING_PKCS1_V1_5  HUKS_PADDING_OAEP | HUKS_MODE_ECB                               | 【非必选】  |

| HUKS_ALG_ALGORITHM                                           | HUKS_TAG_PURPOSE         | HUKS_TAG_PADDING                      | HUKS_TAG_BLOCK_MODE          | HUKS_TAG_IV | HUKS_TAG_NONCE | HUKS_TAG_ASSOCIATED_DATA | HUKS_TAG_AE_TAG |
| ------------------------------------------------------------ | ------------------------ | ------------------------------------- | ---------------------------- | ----------- | -------------- | ------------------------ | --------------- |
| HUKS_ALG_AES                 (支持长度:  HUKS_AES_KEY_SIZE_128  HUKS_AES_KEY_SIZE_192  HUKS_AES_KEY_SIZE_256) | HUKS_KEY_PURPOSE_ENCRYPT | HUKS_PADDING_NONE  HUKS_PADDING_PKCS7 | HUKS_MODE_CBC                | 【必选】    | 【非必选】     | 【非必选】               | 【非必选】      |
| HUKS_ALG_AES                                                 | HUKS_KEY_PURPOSE_ENCRYPT | HUKS_PADDING_NONE                     | HUKS_MODE_CCM  HUKS_MODE_GCM | 【非必选】  | 【必选】       | 【必选】                 | 【非必选】      |
| HUKS_ALG_AES                                                 | HUKS_KEY_PURPOSE_ENCRYPT | HUKS_PADDING_NONE                     | HUKS_MODE_CTR                | 【必选】    | 【非必选】     | 【非必选】               | 【非必选】      |
| HUKS_ALG_AES                                                 | HUKS_KEY_PURPOSE_ENCRYPT | HUKS_PADDING_PKCS7  HUKS_PADDING_NONE | HUKS_MODE_ECB                | 【必选】    | 【非必选】     | 【非必选】               | 【非必选】      |
| HUKS_ALG_AES                                                 | HUKS_KEY_PURPOSE_DECRYPT | HUKS_PADDING_NONE  HUKS_PADDING_PKCS7 | HUKS_MODE_CBC                | 【必选】    | 【非必选】     | 【非必选】               | 【必选】        |
| HUKS_ALG_AES                                                 | HUKS_KEY_PURPOSE_DECRYPT | HUKS_PADDING_NONE                     | HUKS_MODE_CCM  HUKS_MODE_GCM | 【非必选】  | 【必选】       | 【必选】                 | 【非必选】      |
| HUKS_ALG_AES                                                 | HUKS_KEY_PURPOSE_DECRYPT | HUKS_PADDING_NONE                     | HUKS_MODE_CTR                | 【必选】    | 【非必选】     | 【非必选】               | 【非必选】      |
| HUKS_ALG_AES                                                 | HUKS_KEY_PURPOSE_DECRYPT | HUKS_PADDING_NONE  HUKS_PADDING_PKCS7 | HUKS_MODE_ECB                | 【必选】    | 【非必选】     | 【非必选】               | 【非必选】      |

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

Z
zhangcheng 已提交
538
在使用示例前,需要先了解几个预先定义的变量: 
Z
zhangcheng 已提交
539 540 541 542

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

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

549
**示例1:**
Z
zhangcheng 已提交
550

Z
zhangcheng 已提交
551
```ts
Z
zhangcheng 已提交
552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577
/* Cipher操作支持RSA、AES、SM4类型的密钥。
 *
 * 以下以SM4 128密钥的Promise操作使用为例
 */
function sm4CipherStringToUint8Array(str) {
    var arr = [];
    for (var i = 0, j = str.length; i < j; ++i) {
        arr.push(str.charCodeAt(i));
    }
    return new Uint8Array(arr);
}
function sm4CipherUint8ArrayToString(fileData) {
    var dataString = '';
    for (var i = 0; i < fileData.length; i++) {
        dataString += String.fromCharCode(fileData[i]);
    }
    return dataString;
}

var handle;
var IV = '0000000000000000';
var cipherInData = 'Hks_SM4_Cipher_Test_101010101010101010110_string';
var srcKeyAlias = 'huksCipherSm4SrcKeyAlias';
var encryptUpdateResult = new Array();
var decryptUpdateResult = new Array();

Z
zhangcheng 已提交
578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606
async function testCipher() {
    /* 集成生成密钥参数集 & 加密参数集 */
    var 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,
    }
    var huksOptions = {
        properties: properties,
        inData: new Uint8Array(new Array())
    }
Z
zhangcheng 已提交
607

Z
zhangcheng 已提交
608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636
    var 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: sm4CipherStringToUint8Array(IV),
    }
    var encryptOptions = {
        properties: propertiesEncrypt,
        inData: new Uint8Array(new Array())
    }
Z
zhangcheng 已提交
637

Z
zhangcheng 已提交
638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679
    /* 生成密钥 */
    await huks.generateKey(srcKeyAlias, huksOptions).then((data) => {
        console.info(`test generateKey data: ${JSON.stringify(data)}`);
    }).catch((err) => {
        console.info('test generateKey err information: ' + JSON.stringify(err));
    });

    /* 进行密钥加密操作 */
    await huks.init(srcKeyAlias, encryptOptions).then((data) => {
        console.info(`test init data: ${JSON.stringify(data)}`);
        handle = data.handle;
    }).catch((err) => {
        console.info('test init err information: ' + JSON.stringify(err));
    });
    encryptOptions.inData = sm4CipherStringToUint8Array(cipherInData);
    await huks.update(handle, encryptOptions).then(async (data) => {
        console.info(`test update data ${JSON.stringify(data)}`);
        encryptUpdateResult = Array.from(data.outData);
    }).catch((err) => {
        console.info('test update err information: ' + err);
    });
    encryptOptions.inData = new Uint8Array(new Array());
    await huks.finish(handle, encryptOptions).then((data) => {
        console.info(`test finish data: ${JSON.stringify(data)}`);
        var finishData = sm4CipherUint8ArrayToString(new Uint8Array(encryptUpdateResult));
        if (finishData === cipherInData) {
            console.info('test finish encrypt err ');
        } else {
            console.info('test finish encrypt success');
        }
    }).catch((err) => {
        console.info('test finish err information: ' + JSON.stringify(err));
    });

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

Z
zhangcheng 已提交
682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714
    /* 进行解密操作 */
    await huks.init(srcKeyAlias, decryptOptions).then((data) => {
        console.info(`test init data: ${JSON.stringify(data)}`);
        handle = data.handle;
    }).catch((err) => {
        console.info('test init err information: ' + JSON.stringify(err));
    });
    decryptOptions.inData = new Uint8Array(encryptUpdateResult);
    await huks.update(handle, decryptOptions).then(async (data) => {
        console.info(`test update data ${JSON.stringify(data)}`);
        decryptUpdateResult = Array.from(data.outData);
    }).catch((err) => {
        console.info('test update err information: ' + err);
    });
    decryptOptions.inData = new Uint8Array(new Array());
    await huks.finish(handle, decryptOptions).then((data) => {
        console.info(`test finish data: ${JSON.stringify(data)}`);
        var finishData = sm4CipherUint8ArrayToString(new Uint8Array(decryptUpdateResult));
        if (finishData === cipherInData) {
            console.info('test finish decrypt success ');
        } else {
            console.info('test finish decrypt err');
        }
    }).catch((err) => {
        console.info('test finish err information: ' + JSON.stringify(err));
    });

    await huks.deleteKey(srcKeyAlias, huksOptions).then((data) => {
        console.info(`test deleteKey data: ${JSON.stringify(data)}`);
    }).catch((err) => {
        console.info('test deleteKey err information: ' + JSON.stringify(err));
    });
}
Z
zhangcheng 已提交
715 716
```

717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 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 899 900 901 902 903
**示例2:**

```ts
/* Cipher操作支持RSA、AES、SM4类型的密钥。
 *
 * 以下以AES128 GCM密钥的Promise操作使用为例
 */
function aesCipherStringToUint8Array(str) {
    var arr = [];
    for (var i = 0, j = str.length; i < j; ++i) {
        arr.push(str.charCodeAt(i));
    }
    return new Uint8Array(arr);
}
function aesCipherUint8ArrayToString(fileData) {
    var dataString = '';
    for (var i = 0; i < fileData.length; i++) {
        dataString += String.fromCharCode(fileData[i]);
    }
    return dataString;
}

async function aesCipher() {
    var handle;
    var AAD = '0000000000000000';
    var NONCE = '000000000000';
    var AEAD = '0000000000000000';
    var cipherInData = 'Hks_AES_Cipher_Test_00000000000000000000000000000000000000000000000000000_string';
    var srcKeyAlias = 'huksCipherAesSrcKeyAlias';
    var encryptUpdateResult = new Array();
    var decryptUpdateResult = new Array();
    /* 集成生成密钥参数集 & 加密参数集 */
    var 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_GCM,
    }
    properties[4] = {
        tag: huks.HuksTag.HUKS_TAG_PADDING,
        value: huks.HuksKeyPadding.HUKS_PADDING_NONE,
    }
    var HuksOptions = {
        properties: properties,
        inData: new Uint8Array(new Array())
    }

    var 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_GCM,
    }
    propertiesEncrypt[5] = {
        tag: huks.HuksTag.HUKS_TAG_DIGEST,
        value: huks.HuksKeyDigest.HUKS_DIGEST_NONE,
    }
    propertiesEncrypt[6] = {
        tag: huks.HuksTag.HUKS_TAG_ASSOCIATED_DATA,
        value: aesCipherStringToUint8Array(AAD),
    }
    propertiesEncrypt[7] = {
        tag: huks.HuksTag.HUKS_TAG_NONCE,
        value: aesCipherStringToUint8Array(NONCE),
    }
    propertiesEncrypt[8] = {
        tag: huks.HuksTag.HUKS_TAG_AE_TAG,
        value: aesCipherStringToUint8Array(AEAD),
    }
    var encryptOptions = {
        properties: propertiesEncrypt,
        inData: new Uint8Array(new Array())
    }

    /* 生成密钥 */
    await huks.generateKey(srcKeyAlias, HuksOptions).then((data) => {
        console.info(`test generateKey data: ${JSON.stringify(data)}`);
    }).catch((err) => {
        console.info('test generateKey err information: ' + JSON.stringify(err));
    });

    /* 进行密钥加密操作 */
    await huks.init(srcKeyAlias, encryptOptions).then((data) => {
        console.info(`test init data: ${JSON.stringify(data)}`);
        handle = data.handle;
    }).catch((err) => {
        console.info('test init err information: ' + JSON.stringify(err));
    });
    encryptOptions.inData = aesCipherStringToUint8Array(cipherInData.slice(0,64));
    await huks.update(handle, encryptOptions).then(async (data) => {
        console.info(`test update data ${JSON.stringify(data)}`);
        encryptUpdateResult = Array.from(data.outData);
    }).catch((err) => {
        console.info('test update err information: ' + err);
    });
    encryptOptions.inData = aesCipherStringToUint8Array(cipherInData.slice(64,80));
    await huks.finish(handle, encryptOptions).then((data) => {
        console.info(`test finish data: ${JSON.stringify(data)}`);
        encryptUpdateResult = encryptUpdateResult.concat(Array.from(data.outData));
        var finishData = aesCipherUint8ArrayToString(new Uint8Array(encryptUpdateResult));
        if (finishData === cipherInData) {
            console.info('test finish encrypt err ');
        } else {
            console.info('test finish encrypt success');
        }
    }).catch((err) => {
        console.info('test finish err information: ' + JSON.stringify(err));
    });

    /* 修改加密参数集为解密参数集 */
    propertiesEncrypt.splice(1, 1, {
        tag: huks.HuksTag.HUKS_TAG_PURPOSE,
        value: huks.HuksKeyPurpose.HUKS_KEY_PURPOSE_DECRYPT,
    });
    propertiesEncrypt.splice(8, 1, {
        tag: huks.HuksTag.HUKS_TAG_AE_TAG,
        value: new Uint8Array(encryptUpdateResult.splice(encryptUpdateResult.length - 16,encryptUpdateResult.length))
    });
    var decryptOptions = {
        properties: propertiesEncrypt,
        inData: new Uint8Array(new Array())
    }

    /* 进行解密操作 */
    await huks.init(srcKeyAlias, decryptOptions).then((data) => {
        console.info(`test init data: ${JSON.stringify(data)}`);
        handle = data.handle;
    }).catch((err) => {
        console.info('test init err information: ' + JSON.stringify(err));
    });
    decryptOptions.inData = new Uint8Array(encryptUpdateResult.slice(0,64));
    await huks.update(handle, decryptOptions).then(async (data) => {
        console.info(`test update data ${JSON.stringify(data)}`);
        decryptUpdateResult = Array.from(data.outData);
    }).catch((err) => {
        console.info('test update err information: ' + err);
    });
    decryptOptions.inData = new Uint8Array(encryptUpdateResult.slice(64,encryptUpdateResult.length));
    await huks.finish(handle, decryptOptions).then((data) => {
        console.info(`test finish data: ${JSON.stringify(data)}`);
        decryptUpdateResult = decryptUpdateResult.concat(Array.from(data.outData));
        var finishData = aesCipherUint8ArrayToString(new Uint8Array(decryptUpdateResult));
        if (finishData === cipherInData) {
            console.info('test finish decrypt success ');
        } else {
            console.info('test finish decrypt err');
        }
    }).catch((err) => {
        console.info('test finish err information: ' + JSON.stringify(err));
    });

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

Z
zhangcheng 已提交
904 905
### 密钥签名验签

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

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

Z
zhangcheng 已提交
910 911 912 913 914 915
1. 生成密钥。
2. 密钥签名。
3. 导出签名密钥。
4. 导入签名密钥。
5. 密钥验签。

916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938
**支持的密钥类型:**

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

| HUKS_ALG_ALGORITHM | HUKS_ALG_KEY_SIZE                                            | HUKS_ALG_PURPOSE                               | HUKS_ALG_PADDING        | HUKS_TAG_DIGEST                                              |
| ------------------ | ------------------------------------------------------------ | ---------------------------------------------- | ----------------------- | ------------------------------------------------------------ |
| HUKS_ALG_RSA       | HUKS_RSA_KEY_SIZE_512  HUKS_RSA_KEY_SIZE_768  HUKS_RSA_KEY_SIZE_1024  HUKS_RSA_KEY_SIZE_2048  HUKS_RSA_KEY_SIZE_3072  HUKS_RSA_KEY_SIZE_4096 | HUKS_KEY_PURPOSE_SIGN  HUKS_KEY_PURPOSE_VERIFY | HUKS_PADDING_PKCS1_V1_5 | HUKS_DIGEST_MD5  HUKS_DIGEST_NONE  HUKS_DIGEST_SHA1  HUKS_DIGEST_SHA224  HUKS_DIGEST_SHA384  HUKS_DIGEST_SHA512 |
| HUKS_ALG_RSA       | HUKS_RSA_KEY_SIZE_512  HUKS_RSA_KEY_SIZE_768  HUKS_RSA_KEY_SIZE_1024  HUKS_RSA_KEY_SIZE_2048  HUKS_RSA_KEY_SIZE_3072  HUKS_RSA_KEY_SIZE_4096 | HUKS_KEY_PURPOSE_SIGN  HUKS_KEY_PURPOSE_VERIFY | HUKS_PADDING_PSS        | HUKS_DIGEST_SHA1  HUKS_DIGEST_SHA224  HUKS_DIGEST_SHA256  HUKS_DIGEST_SHA384  HUKS_DIGEST_SHA512 |
| HUKS_ALG_DSA       | HUKS_RSA_KEY_SIZE_1024                                       | HUKS_KEY_PURPOSE_SIGN  HUKS_KEY_PURPOSE_VERIFY | 【非必选】              | HUKS_DIGEST_SHA1  HUKS_DIGEST_SHA224  HUKS_DIGEST_SHA256  HUKS_DIGEST_SHA384  HUKS_DIGEST_SHA512 |
| HUKS_ALG_ECC       | HUKS_ECC_KEY_SIZE_224  HUKS_ECC_KEY_SIZE_256  HUKS_ECC_KEY_SIZE_384  HUKS_ECC_KEY_SIZE_521 | HUKS_KEY_PURPOSE_SIGN  HUKS_KEY_PURPOSE_VERIFY | 【非必选】              | HUKS_DIGEST_NONE  HUKS_DIGEST_SHA1  HUKS_DIGEST_SHA224  HUKS_DIGEST_SHA256  HUKS_DIGEST_SHA384  HUKS_DIGEST_SHA512 |

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

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

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

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

Z
zhangcheng 已提交
939
在使用示例前,需要先了解几个预先定义的变量: 
Z
zhangcheng 已提交
940 941 942 943 944 945 946 947 948

| 参数名               | 类型        | 必填 | 说明                     |
| -------------------- | ----------- | ---- | ------------------------ |
| srcRsaKeyAliasSign   | string      | 是   | 生成密钥别名。           |
| srcRsaKeyAliasVerify | string      | 是   | 导入密钥别名。           |
| rsaSignOptions       | HuksOptions | 是   | 用于存放生成key所需TAG。 |
| rsaSignOptionsSecond | HuksOptions | 是   | 用于存放签名key所需TAG。 |
| rsaVerifyOptions     | HuksOptions | 是   | 用于存放验签key所需TAG。 |

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

**示例:**

Z
zhangcheng 已提交
953
```ts
Z
zhangcheng 已提交
954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972
/* Sign/Verify操作支持RSA、ECC、SM2、ED25519、DSA类型的密钥。
 *
 * 以下以RSA512密钥的Promise操作使用为例
 */
function rsaSignVerifyStringToUint8Array(str) {
    var arr = [];
    for (var i = 0, j = str.length; i < j; ++i) {
        arr.push(str.charCodeAt(i));
    }
    return new Uint8Array(arr);
}

var rsaSignHandle;
var rsaSignVerifyInData = 'signVerifyInData';
var srcRsaKeyAliasSign = 'huksSignVerifySrcKeyAliasSign';
var srcRsaKeyAliasVerify = 'huksSignVerifySrcKeyAliasVerify';
var finishRsaSignData;
var rsaExportSignKey;

Z
zhangcheng 已提交
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
async function testSignVerify() {
    /* 集成生成密钥参数集 & 签名参数集 & 验签参数集 */
    var rsaSignProperties = new Array();
    rsaSignProperties[0] = {
        tag: huks.HuksTag.HUKS_TAG_ALGORITHM,
        value: huks.HuksKeyAlg.HUKS_ALG_RSA,
    }
    rsaSignProperties[1] = {
        tag: huks.HuksTag.HUKS_TAG_PURPOSE,
        value: huks.HuksKeyPurpose.HUKS_KEY_PURPOSE_SIGN,
    }
    rsaSignProperties[2] = {
        tag: huks.HuksTag.HUKS_TAG_KEY_SIZE,
        value: huks.HuksKeySize.HUKS_RSA_KEY_SIZE_512,
    }
    rsaSignProperties[3] = {
        tag: huks.HuksTag.HUKS_TAG_DIGEST,
        value: huks.HuksKeyDigest.HUKS_DIGEST_MD5,
    }
    rsaSignProperties[4] = {
        tag: huks.HuksTag.HUKS_TAG_PADDING,
        value: huks.HuksKeyPadding.HUKS_PADDING_PKCS1_V1_5,
    }
    var rsaSignOptions = {
        properties: rsaSignProperties,
        inData: new Uint8Array(new Array())
    }
Z
zhangcheng 已提交
1000

Z
zhangcheng 已提交
1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026
    var rsaPropertiesSign = new Array();
    rsaPropertiesSign[0] = {
        tag: huks.HuksTag.HUKS_TAG_ALGORITHM,
        value: huks.HuksKeyAlg.HUKS_ALG_RSA,
    }
    rsaPropertiesSign[1] = {
        tag: huks.HuksTag.HUKS_TAG_PURPOSE,
        value:
        huks.HuksKeyPurpose.HUKS_KEY_PURPOSE_SIGN
    }
    rsaPropertiesSign[2] = {
        tag: huks.HuksTag.HUKS_TAG_DIGEST,
        value: huks.HuksKeyDigest.HUKS_DIGEST_MD5,
    }
    rsaPropertiesSign[3] = {
        tag: huks.HuksTag.HUKS_TAG_KEY_SIZE,
        value: huks.HuksKeySize.HUKS_RSA_KEY_SIZE_512,
    }
    rsaPropertiesSign[4] = {
        tag: huks.HuksTag.HUKS_TAG_PADDING,
        value: huks.HuksKeyPadding.HUKS_PADDING_PKCS1_V1_5,
    }
    var rsaSignOptionsSecond = {
        properties: rsaPropertiesSign,
        inData: new Uint8Array(new Array())
    }
Z
zhangcheng 已提交
1027

Z
zhangcheng 已提交
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
    var rsaPropertiesVerify = new Array();
    rsaPropertiesVerify[0] = {
        tag: huks.HuksTag.HUKS_TAG_ALGORITHM,
        value: huks.HuksKeyAlg.HUKS_ALG_RSA,
    }
    rsaPropertiesVerify[1] = {
        tag: huks.HuksTag.HUKS_TAG_PURPOSE,
        value: huks.HuksKeyPurpose.HUKS_KEY_PURPOSE_VERIFY
    }
    rsaPropertiesVerify[2] = {
        tag: huks.HuksTag.HUKS_TAG_DIGEST,
        value: huks.HuksKeyDigest.HUKS_DIGEST_MD5,
    }
    rsaPropertiesVerify[3] = {
        tag: huks.HuksTag.HUKS_TAG_KEY_SIZE,
        value: huks.HuksKeySize.HUKS_RSA_KEY_SIZE_512,
    }
    rsaPropertiesVerify[4] = {
        tag: huks.HuksTag.HUKS_TAG_PADDING,
        value: huks.HuksKeyPadding.HUKS_PADDING_PKCS1_V1_5,
    }
    var rsaVerifyOptions = {
        properties: rsaPropertiesVerify,
        inData: new Uint8Array(new Array())
    }
Z
zhangcheng 已提交
1053

Z
zhangcheng 已提交
1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073
    /* 生成密钥 */
    await huks.generateKey(srcRsaKeyAliasSign, rsaSignOptions).then((data) => {
        console.info(`test generateKey data: ${JSON.stringify(data)}`);
    }).catch((err) => {
        console.info('test generateKey err information: ' + JSON.stringify(err));
    });

    /* 对密钥进行签名操作 */
    await huks.init(srcRsaKeyAliasSign, rsaSignOptionsSecond).then((data) => {
        console.info(`test init data: ${JSON.stringify(data)}`);
        rsaSignHandle = data.handle;
    }).catch((err) => {
        console.info('test init err information: ' + JSON.stringify(err));
    });
    rsaSignOptionsSecond.inData = rsaSignVerifyStringToUint8Array(rsaSignVerifyInData)
    await huks.update(rsaSignHandle, rsaSignOptionsSecond).then(async (data) => {
        console.info(`test update data ${JSON.stringify(data)}`);
    }).catch((err) => {
        console.info('test update err information: ' + err);
    });
Z
zhangcheng 已提交
1074
    rsaSignOptionsSecond.inData = new Uint8Array(new Array());
Z
zhangcheng 已提交
1075 1076
    await huks.finish(rsaSignHandle, rsaSignOptionsSecond).then((data) => {
        console.info(`test finish data: ${JSON.stringify(data)}`);
Z
zhangcheng 已提交
1077
        finishRsaSignData = data.outData;
Z
zhangcheng 已提交
1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127
    }).catch((err) => {
        console.info('test finish err information: ' + JSON.stringify(err));
    });

    /* 通过导出导入模拟获取一段密钥数据 */
    await huks.exportKey(srcRsaKeyAliasSign, rsaSignOptions).then((data) => {
        console.info(`test exportKey data: ${JSON.stringify(data)}`);
        rsaExportSignKey = data.outData;
    }).catch((err) => {
        console.info('test exportKey err information: ' + JSON.stringify(err));
    });
    rsaVerifyOptions.inData = rsaExportSignKey;
    await huks.importKey(srcRsaKeyAliasVerify, rsaVerifyOptions).then((data) => {
        console.info(`test ImportKey data: ${JSON.stringify(data)}`);
    }).catch((err) => {
        console.info('test exportKey err information: ' + JSON.stringify(err));
    });

    /* 对密钥进行验签 */
    await huks.init(srcRsaKeyAliasVerify, rsaVerifyOptions).then((data) => {
        console.info(`test init data: ${JSON.stringify(data)}`);
        rsaSignHandle = data.handle;
    }).catch((err) => {
        console.info('test init err information: ' + JSON.stringify(err));
    });
    rsaVerifyOptions.inData = rsaSignVerifyStringToUint8Array(rsaSignVerifyInData);
    await huks.update(rsaSignHandle, rsaVerifyOptions).then(async (data) => {
        console.info(`test update data ${JSON.stringify(data)}`);
    }).catch((err) => {
        console.info('test update err information: ' + err);
    });
    rsaVerifyOptions.inData = finishRsaSignData;
    await huks.finish(rsaSignHandle, rsaVerifyOptions).then((data) => {
        console.info(`test finish data: ${JSON.stringify(data)}`);
    }).catch((err) => {
        console.info('test finish err information: ' + JSON.stringify(err));
    });

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

    await huks.deleteKey(srcRsaKeyAliasSign, rsaSignOptions).then((data) => {
        console.info(`test deleteKey data: ${JSON.stringify(data)}`);
    }).catch((err) => {
        console.info('test deleteKey err information: ' + JSON.stringify(err));
    });
}
Z
zhangcheng 已提交
1128 1129 1130 1131
```

### 密钥协商

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

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

Z
zhangcheng 已提交
1136 1137 1138 1139
1. 生成两个密钥。
2. 分别导出密钥。
3. 交叉进行密钥协商。

1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168
**支持的密钥类型:**

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

HksInit对paramSet中参数的要求

| HUKS_ALG_ALGORITHM | HUKS_ALG_KEY_SIZE                                            | HUKS_ALG_PURPOSE       |
| ------------------ | ------------------------------------------------------------ | ---------------------- |
| HUKS_ALG_ECDH      | HUKS_ECC_KEY_SIZE_224  HUKS_ECC_KEY_SIZE_256 HUKS_ECC_KEY_SIZE_384 HUKS_ECC_KEY_SIZE_521 | HUKS_KEY_PURPOSE_AGREE |
| HUKS_ALG_DH        | HUKS_DH_KEY_SIZE_2048 HUKS_DH_KEY_SIZE_3072 HUKS_DH_KEY_SIZE_4096 | HUKS_KEY_PURPOSE_AGREE |
| HUKS_ALG_X25519    | HUKS_CURVE25519_KEY_SIZE_256                                 | HUKS_KEY_PURPOSE_AGREE |

HksFinish对paramSet中参数的要求:

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

| HUKS_TAG_KEY_STORAGE_FLAG      | HUKS_TAG_KEY_ALIAS | HUKS_TAG_IS_KEY_ALIAS | HUKS_TAG_ALGORITHM | HUKS_TAG_KEY_SIZE                                            | HUKS_TAG_PURPOSE                                   | HUKS_TAG_PADDING   | HUKS_TAG_DIGEST                                              | HUKS_TAG_BLOCK_MODE                         |
| ------------------------------ | ------------------ | --------------------- | ------------------ | ------------------------------------------------------------ | -------------------------------------------------- | ------------------ | ------------------------------------------------------------ | ------------------------------------------- |
| 未设置 或者  HUKS_STORAGE_TEMP | 不需要             | TRUE                  | 不需要             | 不需要                                                       | 不需要                                             | 不需要             | 不需要                                                       | 不需要                                      |
| HUKS_STORAGE_PERSISTENT        | 【必选】最大64字节 | TRUE                  | HUKS_ALG_AES       | HUKS_AES_KEY_SIZE_128   HUKS_AES_KEY_SIZE_192  HUKS_AES_KEY_SIZE_256 | HUKS_KEY_PURPOSE_ENCRYPT  HUKS_KEY_PURPOSE_DECRYPT | HUKS_PADDING_PKCS7 | 【非必选】                                                   | HUKS_MODE_CCM  HUKS_MODE_GCM  HUKS_MODE_CTP |
| HUKS_STORAGE_PERSISTENT        | 【必选】最大64字节 | TRUE                  | HUKS_ALG_AES       | HUKS_AES_KEY_SIZE_128   HUKS_AES_KEY_SIZE_192  HUKS_AES_KEY_SIZE_256 | HUKS_KEY_PURPOSE_DERIVE                            | 【非必选】         | HUKS_DIGEST_SHA256  HUKS_DIGEST_SHA384  HUKS_DIGEST_SHA512   | 【非必选】                                  |
| HUKS_STORAGE_PERSISTENT        | 【必选】最大64字节 | TRUE                  | HUKS_ALG_HMAC      | 8的倍数(单位:bit)                                         | HUKS_KEY_PURPOSE_MAC                               | 【非必选】         | HUKS_DIGEST_SHA1  HUKS_DIGEST_SHA224  HUKS_DIGEST_SHA256  HUKS_DIGEST_SHA384 HUKS_DIGEST_SHA512 | 【非必选】                                  |

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

Z
zhangcheng 已提交
1169
在使用示例前,需要先了解几个预先定义的变量: 
Z
zhangcheng 已提交
1170 1171 1172 1173 1174

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

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

**示例:**

Z
zhangcheng 已提交
1183
```ts
Z
zhangcheng 已提交
1184 1185
/* agree操作支持ECDH、DH、X25519类型的密钥。
 *
1186
 * 以下以X25519 256 TEMP密钥的Promise操作使用为例
Z
zhangcheng 已提交
1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201
 */
function AgreeStringToUint8Array(str) {
    var arr = [];
    for (var i = 0, j = str.length; i < j; ++i) {
        arr.push(str.charCodeAt(i));
    }
    return new Uint8Array(arr);
}

var srcKeyAliasFirst = "AgreeX25519KeyFirstAlias";
var srcKeyAliasSecond = "AgreeX25519KeySecondAlias";
var agreeX25519InData = 'AgreeX25519TestIndata';
var exportKeyFrist;
var exportKeySecond;

Z
zhangcheng 已提交
1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228
async function testAgree() {
    /* 集成生成密钥参数集 */
    var 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,
    }
1229
    var HuksOptions = {
Z
zhangcheng 已提交
1230 1231 1232
        properties: properties,
        inData: new Uint8Array(new Array())
    }
Z
zhangcheng 已提交
1233

Z
zhangcheng 已提交
1234
    /* 1.生成两个密钥并导出 */
1235
    await huks.generateKey(srcKeyAliasFirst, HuksOptions).then((data) => {
Z
zhangcheng 已提交
1236 1237 1238 1239
        console.info('test generateKey data = ' + JSON.stringify(data));
    }).catch((err) => {
        console.info(`test generateKey err: " + ${JSON.stringify(err)}`);
    });
1240
    await huks.generateKey(srcKeyAliasSecond, HuksOptions).then((data) => {
Z
zhangcheng 已提交
1241 1242 1243 1244
        console.info('test generateKey data = ' + JSON.stringify(data));
    }).catch((err) => {
        console.info(`test generateKey err: " + ${JSON.stringify(err)}`);
    });
1245
    await huks.exportKey(srcKeyAliasFirst, HuksOptions).then((data) => {
Z
zhangcheng 已提交
1246 1247 1248 1249 1250
        console.info('test exportKey data = ' + JSON.stringify(data));
        exportKeyFrist = data.outData;
    }).catch((err) => {
        console.info(`test exportKey err: " + ${JSON.stringify(err)}`);
    });
1251
    await huks.exportKey(srcKeyAliasSecond, HuksOptions).then((data) => {
Z
zhangcheng 已提交
1252 1253 1254 1255 1256 1257 1258 1259 1260 1261
        console.info('test exportKey data = ' + JSON.stringify(data));
        exportKeySecond = data.outData;
    }).catch((err) => {
        console.info(`test exportKey err: " + ${JSON.stringify(err)}`);
    });

    /* 集成第一个协商参数集 */
    var finishProperties = new Array();
    finishProperties[0] = {
        tag: huks.HuksTag.HUKS_TAG_KEY_STORAGE_FLAG,
1262
        value: huks.HuksKeyStorageType.HUKS_STORAGE_TEMP,
Z
zhangcheng 已提交
1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301
    }
    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: AgreeStringToUint8Array(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,
    }
    var finishOptionsFrist = {
        properties: finishProperties,
        inData: AgreeStringToUint8Array(agreeX25519InData)
    }
1302
    
Z
zhangcheng 已提交
1303
    /* 对第一个密钥进行协商 */
1304
    await huks.init(srcKeyAliasFirst, HuksOptions).then((data) => {
Z
zhangcheng 已提交
1305 1306 1307 1308 1309
        console.info(`test init data: ${JSON.stringify(data)}`);
        handle = data.handle;
    }).catch((err) => {
        console.info(`test init err: " + ${JSON.stringify(err)}`);
    });
1310 1311
    HuksOptions.inData = exportKeySecond;
    await huks.update(handle, HuksOptions).then((data) => {
Z
zhangcheng 已提交
1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330
        console.info(`test update data: ${JSON.stringify(data)}`);
    }).catch((err) => {
        console.info(`test update err: " + ${JSON.stringify(err)}`);
    });
    await huks.finish(handle, finishOptionsFrist).then((data) => {
        console.info(`test finish data: ${JSON.stringify(data)}`);
    }).catch((err) => {
        console.info('test finish err information: ' + JSON.stringify(err));
    });

    /* 集成第二个协商参数集 */
    var finishOptionsSecond = {
        properties: finishProperties,
        inData: AgreeStringToUint8Array(agreeX25519InData)
    }
    finishOptionsSecond.properties.splice(6, 1, {
        tag: huks.HuksTag.HUKS_TAG_KEY_ALIAS,
        value: AgreeStringToUint8Array(srcKeyAliasSecond + 'final'),
    })
1331 1332 1333
    
    /* 对第二个密钥进行协商 */
    await huks.init(srcKeyAliasSecond, HuksOptions).then((data) => {
Z
zhangcheng 已提交
1334 1335 1336 1337 1338
        console.info(`test init data: ${JSON.stringify(data)}`);
        handle = data.handle;
    }).catch((err) => {
        console.info(`test init err: " + ${JSON.stringify(err)}`);
    });
1339 1340
    HuksOptions.inData = exportKeyFrist;
    await huks.update(handle, HuksOptions).then((data) => {
Z
zhangcheng 已提交
1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360
        console.info(`test update data: ${JSON.stringify(data)}`);
    }).catch((err) => {
        console.info(`test update err: " + ${JSON.stringify(err)}`);
    });
    await huks.finish(handle, finishOptionsSecond).then((data) => {
        console.info(`test finish data: ${JSON.stringify(data)}`);
    }).catch((err) => {
        console.info('test finish err information: ' + JSON.stringify(err));
    });

    await huks.deleteKey(srcKeyAliasFirst, huksOptions).then((data) => {
        console.info(`test deleteKey data: ${JSON.stringify(data)}`);
    }).catch((err) => {
        console.info('test deleteKey err information: ' + JSON.stringify(err));
    });
    await huks.deleteKey(srcKeyAliasSecond, huksOptions).then((data) => {
        console.info(`test deleteKey data: ${JSON.stringify(data)}`);
    }).catch((err) => {
        console.info('test deleteKey err information: ' + JSON.stringify(err));
    });
Z
zhangcheng 已提交
1361 1362 1363 1364 1365
}
```

### 密钥派生

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

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

1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400
1. 生成密钥。
2. 进行密钥派生。

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

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

HksInit对paramSet中参数的要求

| HUKS_TAG_ALGORITHM                                           | HUKS_TAG_PURPOSE        | HUKS_TAG_DIGEST                                            | HUKS_TAG_DERIVE_KEY_SIZE |
| ------------------------------------------------------------ | ----------------------- | ---------------------------------------------------------- | ------------------------ |
| HUKS_ALG_HKDF  (支持长度:  HUKS_AES_KEY_SIZE_128 HUKS_AES_KEY_SIZE_192 HUKS_AES_KEY_SIZE_256) | HUKS_KEY_PURPOSE_DERIVE | HUKS_DIGEST_SHA256  HUKS_DIGEST_SHA384  HUKS_DIGEST_SHA512 | 【必选】                 |
| HUKS_ALG_PBKDF2  (支持长度:  HUKS_AES_KEY_SIZE_128 HUKS_AES_KEY_SIZE_192 HUKS_AES_KEY_SIZE_256) | HUKS_KEY_PURPOSE_DERIVE | HUKS_DIGEST_SHA256  HUKS_DIGEST_SHA384  HUKS_DIGEST_SHA512 | 【必选】                 |

HksFinish对paramSet中参数的要求:

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

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

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

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

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

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

**示例:**

Z
zhangcheng 已提交
1414
```ts
Z
zhangcheng 已提交
1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428
/* derive操作支持HKDF、pbdkf类型的密钥。
 *
 * 以下以HKDF256密钥的Promise操作使用为例
 */
function hkdfStringToUint8Array(str) {
    var arr = [];
    for (var i = 0, j = str.length; i < j; ++i) {
        arr.push(str.charCodeAt(i));
    }
    return new Uint8Array(arr);
}

var deriveHkdfInData = "deriveHkdfTestIndata";
var srcKeyAlias = "deriveHkdfKeyAlias";
Z
zhangcheng 已提交
1429
var handle;
1430
var HuksKeyDeriveKeySize = 32;
Z
zhangcheng 已提交
1431

Z
zhangcheng 已提交
1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454
async function testDerive() {
    /* 集成生成密钥参数集 */
    var 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,
    }
    var huksOptions = {
        properties: properties,
        inData: new Uint8Array(new Array())
    }
Z
zhangcheng 已提交
1455

Z
zhangcheng 已提交
1456 1457 1458 1459
    /* 生成密钥 */
    await huks.generateKey(srcKeyAlias, huksOptions).then((data) => {
        console.info('test generateKey data = ' + JSON.stringify(data));
    }).catch((err) => {
Z
zhangcheng 已提交
1460
        console.info(`test init err: " + ${JSON.stringify(err)}`);
Z
zhangcheng 已提交
1461
    });
Z
zhangcheng 已提交
1462

Z
zhangcheng 已提交
1463 1464 1465 1466 1467 1468 1469
    /* 调整init时的参数集 */
    huksOptions.properties.splice(0, 1, {
        tag: huks.HuksTag.HUKS_TAG_ALGORITHM,
        value: huks.HuksKeyAlg.HUKS_ALG_HKDF,
    });
    huksOptions.properties.splice(3, 1, {
        tag: huks.HuksTag.HUKS_TAG_DERIVE_KEY_SIZE,
1470
        value: HuksKeyDeriveKeySize,
Z
zhangcheng 已提交
1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501
    });

    var finishProperties = new Array();
    finishProperties[0] = {
        tag: huks.HuksTag.HUKS_TAG_KEY_STORAGE_FLAG,
        value: huks.HuksKeyStorageType.HUKS_STORAGE_PERSISTENT,
    }
    finishProperties[1] = {
        tag: huks.HuksTag.HUKS_TAG_IS_KEY_ALIAS,
        value: true,
    }
    finishProperties[2] = {
        tag: huks.HuksTag.HUKS_TAG_ALGORITHM,
        value: huks.HuksKeyAlg.HUKS_ALG_AES,
    }
    finishProperties[3] = {
        tag: huks.HuksTag.HUKS_TAG_KEY_SIZE,
        value: huks.HuksKeySize.HUKS_AES_KEY_SIZE_256,
    }
    finishProperties[4] = {
        tag: huks.HuksTag.HUKS_TAG_PURPOSE,
        value:
        huks.HuksKeyPurpose.HUKS_KEY_PURPOSE_ENCRYPT |
        huks.HuksKeyPurpose.HUKS_KEY_PURPOSE_DECRYPT,
    }
    finishProperties[5] = {
        tag: huks.HuksTag.HUKS_TAG_DIGEST,
        value: huks.HuksKeyDigest.HUKS_DIGEST_NONE,
    }
    finishProperties[6] = {
        tag: huks.HuksTag.HUKS_TAG_KEY_ALIAS,
Z
zhangcheng 已提交
1502
        value: hkdfStringToUint8Array(srcKeyAlias),
Z
zhangcheng 已提交
1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550
    }
    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,
    }
    var finishOptions = {
        properties: finishProperties,
        inData: new Uint8Array(new Array())
    }

    /* 进行派生操作 */
    await huks.init(srcKeyAlias, huksOptions).then((data) => {
        console.log(`test init data: ${JSON.stringify(data)}`);
        handle = data.handle;
    }).catch((err) => {
        console.log(`test init err: " + ${JSON.stringify(err)}`);
    });
    huksOptions.inData = hkdfStringToUint8Array(deriveHkdfInData);
    await huks.update(handle, huksOptions).then((data) => {
        console.log(`test update data: ${JSON.stringify(data)}`);
    }).catch((err) => {
        console.log(`test update err: " + ${JSON.stringify(err)}`);
    });
    await huks.finish(handle, finishOptions).then((data) => {
        console.log(`test finish data: ${JSON.stringify(data)}`);
    }).catch((err) => {
        console.log('test finish err information: ' + JSON.stringify(err));
    });

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

    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));
    });
}
Z
zhangcheng 已提交
1551 1552 1553 1554
```

### 密钥mac

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

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

Z
zhangcheng 已提交
1559 1560
1. 生成密钥。
2. 密钥mac。
Z
zhangcheng 已提交
1561

1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574
**支持的密钥类型:**

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

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

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

Z
zhangcheng 已提交
1575
在使用示例前,需要先了解几个预先定义的变量: 
Z
zhangcheng 已提交
1576 1577 1578 1579

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

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

**示例:**

Z
zhangcheng 已提交
1586
```ts
Z
zhangcheng 已提交
1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602
/* mac操作支持HMAC、SM3类型的密钥。
 *
 * 以下以SM3 256密钥的Promise操作使用为例
 */
function macStringToUint8Array(str) {
    var arr = [];
    for (var i = 0, j = str.length; i < j; ++i) {
        arr.push(str.charCodeAt(i));
    }
    return new Uint8Array(arr);
}

var srcKeyAlias = "sm3KeyAlias";
var hmacInData = 'sm3TestIndata';
var handle;

Z
zhangcheng 已提交
1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625
async function testMac() {
    /* 集成生成密钥参数集 */
    var properties = new Array();
    properties[0] = {
        tag: huks.HuksTag.HUKS_TAG_ALGORITHM,
        value: huks.HuksKeyAlg.HUKS_ALG_SM3,
    }
    properties[1] = {
        tag: huks.HuksTag.HUKS_TAG_PURPOSE,
        value: huks.HuksKeyPurpose.HUKS_KEY_PURPOSE_MAC,
    }
    properties[2] = {
        tag: huks.HuksTag.HUKS_TAG_DIGEST,
        value: huks.HuksKeyDigest.HUKS_DIGEST_SM3,
    }
    properties[3] = {
        tag: huks.HuksTag.HUKS_TAG_KEY_SIZE,
        value: huks.HuksKeySize.HUKS_AES_KEY_SIZE_256,
    }
    var huksOptions = {
        properties:properties,
        inData:new Uint8Array(new Array())
    }
Z
zhangcheng 已提交
1626

Z
zhangcheng 已提交
1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665
    /* 生成密钥 */
    await huks.generateKey(srcKeyAlias, huksOptions).then((data) => {
        console.info('test generateKey data = ' + JSON.stringify(data));
    }).catch((err) => {
        console.info(`test init err: " + ${JSON.stringify(err)}`);
    });

    /* 修改init时的参数集并进行mac操作 */
    huksOptions.properties.splice(3, 3);
    await huks.init(srcKeyAlias, huksOptions).then((data) => {
        console.info(`test init data: ${JSON.stringify(data)}`);
        handle = data.handle;
    }).catch((err) => {
        console.info(`test init err: " + ${JSON.stringify(err)}`);
    });
    huksOptions.inData = macStringToUint8Array(hmacInData);
    await huks.update(handle, huksOptions).then((data) => {
        console.info(`test init data: ${JSON.stringify(data)}`);
    }).catch((err) => {
        console.info(`test init err: " + ${JSON.stringify(err)}`);
    });
    huksOptions.inData = new Uint8Array(new Array());
    await huks.finish(handle, huksOptions).then((data) => {
        console.info(`test update data: ${JSON.stringify(data)}`);
    }).catch((err) => {
        console.info('test update err information: ' + JSON.stringify(err));
    });

    huksOptions.properties.splice(1, 0, {
        tag: huks.HuksTag.HUKS_TAG_KEY_SIZE,
        value: huks.HuksKeySize.HUKS_AES_KEY_SIZE_256,
    });

    await huks.deleteKey(srcKeyAlias, huksOptions).then((data) => {
        console.info(`test deleteKey data: ${JSON.stringify(data)}`);
    }).catch((err) => {
        console.info('test deleteKey err information: ' + JSON.stringify(err));
    });
}
Z
zhangcheng 已提交
1666 1667 1668 1669
```

### AttestID

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

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

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

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

Z
zhangcheng 已提交
1678 1679
1. 生成证书。
2. 获取证书信息。
Z
zhangcheng 已提交
1680

1681 1682 1683 1684 1685 1686 1687 1688
**支持的密钥类型:**

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

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

Z
zhangcheng 已提交
1689
在使用示例前,需要先了解几个预先定义的变量: 
Z
zhangcheng 已提交
1690 1691 1692 1693 1694 1695

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

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

**示例:**

Z
zhangcheng 已提交
1700
```ts
Z
zhangcheng 已提交
1701 1702 1703
/* 证书AttestID操作示例如下*/
function stringToUint8Array(str) {
    var arr = [];
Z
zhangcheng 已提交
1704
    for (var i = 0, j = str.length; i < j; ++i) {
Z
zhangcheng 已提交
1705
        arr.push(str.charCodeAt(i));
Z
zhangcheng 已提交
1706 1707 1708
    }
    var tmpUint8Array = new Uint8Array(arr);
    return tmpUint8Array;
Z
zhangcheng 已提交
1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729
}

function printLog(...data) {
    console.error(data.toString());
}

let securityLevel = stringToUint8Array('sec_level');
let challenge = stringToUint8Array('challenge_data');
let versionInfo = stringToUint8Array('version_info');
let udid = stringToUint8Array('udid');
let serial = stringToUint8Array('serial');
let deviceId = stringToUint8Array('device_id');
let idAliasString = "id attest";

/* 集成生成密钥参数集 & 生成密钥 */
function generateKey(alias) {
    let properties = new Array();
    properties[0] = {
        tag: huks.HuksTag.HUKS_TAG_ALGORITHM,
        value: huks.HuksKeyAlg.HUKS_ALG_RSA
    };
Z
zhangcheng 已提交
1730
    properties[1] = {
Z
zhangcheng 已提交
1731 1732
        tag: huks.HuksTag.HUKS_TAG_KEY_STORAGE_FLAG,
        value: huks.HuksKeyStorageType.HUKS_STORAGE_PERSISTENT
Z
zhangcheng 已提交
1733 1734 1735
    };
    properties[2] = {
        tag: huks.HuksTag.HUKS_TAG_KEY_SIZE,
Z
zhangcheng 已提交
1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802
        value: huks.HuksKeySize.HUKS_RSA_KEY_SIZE_2048
    };
    properties[3] = {
        tag: huks.HuksTag.HUKS_TAG_PURPOSE,
        value: huks.HuksKeyPurpose.HUKS_KEY_PURPOSE_VERIFY
    };
    properties[4] = {
        tag: huks.HuksTag.HUKS_TAG_DIGEST,
        value: huks.HuksKeyDigest.HUKS_DIGEST_SHA256
    };
    properties[5] = {
        tag: huks.HuksTag.HUKS_TAG_PADDING,
        value: huks.HuksKeyPadding.HUKS_PADDING_PSS
    };
    properties[6] = {
        tag: huks.HuksTag.HUKS_TAG_KEY_GENERATE_TYPE,
        value: huks.HuksKeyGenerateType.HUKS_KEY_GENERATE_TYPE_DEFAULT
    };
    properties[7] = {
        tag: huks.HuksTag.HUKS_TAG_BLOCK_MODE,
        value: huks.HuksCipherMode.HUKS_MODE_ECB
    };
    let options = {
        properties: properties
    };
    huks.generateKey(alias, options);
}

async function attestId() {
    let aliasString = idAliasString;
    let aliasUint8 = stringToUint8Array(aliasString);

    /* 集成证书参数集 */
    let properties = new Array();
    properties[0] = {
        tag: huks.HuksTag.HUKS_TAG_ATTESTATION_ID_SEC_LEVEL_INFO,
        value: securityLevel
    };
    properties[1] = {
        tag: huks.HuksTag.HUKS_TAG_ATTESTATION_CHALLENGE,
        value: challenge
    };
    properties[2] = {
        tag: huks.HuksTag.HUKS_TAG_ATTESTATION_ID_VERSION_INFO,
        value: versionInfo
    };
    properties[3] = {
        tag: huks.HuksTag.HUKS_TAG_ATTESTATION_ID_ALIAS,
        value: aliasUint8
    };
    properties[4] = {
        tag: huks.HuksTag.HUKS_TAG_ATTESTATION_ID_UDID,
        value: udid
    };
    properties[5] = {
        tag: huks.HuksTag.HUKS_TAG_ATTESTATION_ID_SERIAL,
        value: serial
    };
    properties[6] = {
        tag: huks.HuksTag.HUKS_TAG_ATTESTATION_ID_DEVICE,
        value: deviceId
    };
    let options = {
    properties: properties
    };

    generateKey(aliasString);
Z
zhangcheng 已提交
1803
    huks.attestKey(aliasString, options, function (err, data) {
Z
zhangcheng 已提交
1804
        printLog(`key attest result : ${JSON.stringify(data)}`);
Z
zhangcheng 已提交
1805
    });
Z
zhangcheng 已提交
1806 1807 1808 1809 1810
}
```

### AttestKey

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

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

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

Z
zhangcheng 已提交
1817 1818 1819
1. 生成证书。
2. 获取证书信息。

1820 1821 1822 1823 1824 1825 1826 1827
**支持的密钥类型:**

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

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

Z
zhangcheng 已提交
1828
在使用示例前,需要先了解几个预先定义的变量: 
Z
zhangcheng 已提交
1829 1830 1831 1832 1833 1834

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

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

**示例:**

Z
zhangcheng 已提交
1839
```ts
Z
zhangcheng 已提交
1840 1841 1842 1843 1844
/* 证书AttestKey操作示例如下*/
function stringToUint8Array(str) {
    var arr = [];
    for (var i = 0, j = str.length; i < j; ++i) {
        arr.push(str.charCodeAt(i));
Z
zhangcheng 已提交
1845 1846 1847
    }
    var tmpUint8Array = new Uint8Array(arr);
    return tmpUint8Array;
Z
zhangcheng 已提交
1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860
}

function printLog(...data) {
    console.error(data.toString());
}

let securityLevel = stringToUint8Array('sec_level');
let challenge = stringToUint8Array('challenge_data');
let versionInfo = stringToUint8Array('version_info');
let keyAliasString = "key attest";

/* 集成生成密钥参数集 & 生成密钥 */
function generateKey(alias) {
Z
zhangcheng 已提交
1861 1862
    let properties = new Array();
    properties[0] = {
Z
zhangcheng 已提交
1863 1864
        tag: huks.HuksTag.HUKS_TAG_ALGORITHM,
        value: huks.HuksKeyAlg.HUKS_ALG_RSA
Z
zhangcheng 已提交
1865 1866
    };
    properties[1] = {
Z
zhangcheng 已提交
1867 1868
        tag: huks.HuksTag.HUKS_TAG_KEY_STORAGE_FLAG,
        value: huks.HuksKeyStorageType.HUKS_STORAGE_PERSISTENT
Z
zhangcheng 已提交
1869 1870 1871
    };
    properties[2] = {
        tag: huks.HuksTag.HUKS_TAG_KEY_SIZE,
Z
zhangcheng 已提交
1872
        value: huks.HuksKeySize.HUKS_RSA_KEY_SIZE_2048
Z
zhangcheng 已提交
1873 1874
    };
    properties[3] = {
Z
zhangcheng 已提交
1875 1876
        tag: huks.HuksTag.HUKS_TAG_PURPOSE,
        value: huks.HuksKeyPurpose.HUKS_KEY_PURPOSE_VERIFY
Z
zhangcheng 已提交
1877 1878
    };
    properties[4] = {
Z
zhangcheng 已提交
1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925
        tag: huks.HuksTag.HUKS_TAG_DIGEST,
        value: huks.HuksKeyDigest.HUKS_DIGEST_SHA256
    };
    properties[5] = {
        tag: huks.HuksTag.HUKS_TAG_PADDING,
        value: huks.HuksKeyPadding.HUKS_PADDING_PSS
    };
    properties[6] = {
        tag: huks.HuksTag.HUKS_TAG_KEY_GENERATE_TYPE,
        value: huks.HuksKeyGenerateType.HUKS_KEY_GENERATE_TYPE_DEFAULT
    };
    properties[7] = {
        tag: huks.HuksTag.HUKS_TAG_BLOCK_MODE,
        value: huks.HuksCipherMode.HUKS_MODE_ECB
    };
    let options = {
        properties: properties
    };
    huks.generateKey(alias, options);
}

async function attestKey() {
    let aliasString = keyAliasString;
    let aliasUint8 = stringToUint8Array(aliasString);

    /* 集成证书参数集 */
    let properties = new Array();
    properties[0] = {
        tag: huks.HuksTag.HUKS_TAG_ATTESTATION_ID_SEC_LEVEL_INFO,
        value: securityLevel
    };
    properties[1] = {
        tag: huks.HuksTag.HUKS_TAG_ATTESTATION_CHALLENGE,
        value: challenge
    };
    properties[2] = {
        tag: huks.HuksTag.HUKS_TAG_ATTESTATION_ID_VERSION_INFO,
        value: versionInfo
    };
    properties[3] = {
        tag: huks.HuksTag.HUKS_TAG_ATTESTATION_ID_ALIAS,
        value: aliasUint8
    };
        let options = {
        properties: properties
    };
    generateKey(aliasString);
Z
zhangcheng 已提交
1926
    huks.attestKey(aliasString, options, function (err, data) {
Z
zhangcheng 已提交
1927
        printLog(`key attest result : ${JSON.stringify(data)}`);
Z
zhangcheng 已提交
1928
    });
Z
zhangcheng 已提交
1929 1930
}
```
Z
zengyawen 已提交
1931 1932