• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1# @ohos.security.cryptoFramework (加解密算法库框架)
2
3为屏蔽底层硬件和算法库,向上提供统一的密码算法库加解密相关接口。
4
5> **说明:**
6>
7> - 本模块首批接口从API version 9开始支持。后续版本的新增接口,采用上角标单独标记接口的起始版本。
8> - 以下示例代码片段仅适用于JS语言开发。
9
10## 导入模块
11
12```ts
13import cryptoFramework from "@ohos.security.cryptoFramework";
14```
15
16## Result
17
18 表示执行结果的枚举。
19
20 **系统能力:** SystemCapability.Security.CryptoFramework
21
22| 名称                                  |    值   |   说明                         |
23| ------------------------------------- | -------- | ---------------------------- |
24| INVALID_PARAMS                        | 401      | 非法入参。                   |
25| NOT_SUPPORT                           | 801      | 操作不支持。                 |
26| ERR_OUT_OF_MEMORY                     | 17620001 | 内存错误。                   |
27| ERR_RUNTIME_ERROR                     | 17620002 | 运行时外部错误。             |
28| ERR_CRYPTO_OPERATION                  | 17630001 | 调用三方算法库API出错。     |
29
30## DataBlob
31
32buffer数组,提供blob数据类型。
33
34 **系统能力:** SystemCapability.Security.CryptoFramework
35
36| 名称 | 类型       | 可读 | 可写 | 说明   |
37| ---- | ---------- | ---- | ---- | ------ |
38| data | Uint8Array | 是   | 是   | 数据。 |
39
40## ParamsSpec
41
42加解密参数,在进行对称加解密时需要构造其子类对象,并将子类对象传入[init()](#init-2)方法。
43
44适用于需要iv等参数的对称加解密模式(对于无iv等参数的模式如ECB模式,无需构造,在[init()](#init-2)中传入null即可)。
45
46**系统能力:** SystemCapability.Security.CryptoFramework
47
48| 名称    | 类型   | 可读 | 可写 | 说明                                                         |
49| ------- | ------ | ---- | ---- | ------------------------------------------------------------ |
50| algName | string | 是   | 是   | 指明对称加解密参数的算法模式。可选值如下:<br/> - "IvParamsSpec": 适用于CBC\|CTR\|OFB\|CFB模式<br/> - "GcmParamsSpec": 适用于GCM模式<br/> - "CcmParamsSpec": 适用于CCM模式 |
51
52> **说明:**
53>
54> 由于[init()](#init-2)的params参数是ParamsSpec类型(父类),而实际需要传入具体的子类对象(如IvParamsSpec),因此在构造子类对象时应设置其父类ParamsSpec的algName参数,使算法库在init()时知道传入的是哪种子类对象。
55
56## IvParamsSpec
57
58加解密参数[ParamsSpec](#paramsspec)的子类,用于在对称加解密时作为[init()](#init-2)方法的参数。
59
60适用于CBC、CTR、OFB、CFB这些仅使用iv作为参数的加解密模式。
61
62**系统能力:** SystemCapability.Security.CryptoFramework
63
64| 名称 | 类型                  | 可读 | 可写 | 说明                                                         |
65| ---- | --------------------- | ---- | ---- | ------------------------------------------------------------ |
66| iv   | [DataBlob](#datablob) | 是   | 是   | 指明加解密参数iv。常见取值如下:<br/>- AES的CBC\|CTR\|OFB\|CFB模式:iv长度为16字节<br/>- 3DES的CBC\|OFB\|CFB模式:iv长度为8字节<br/>- SM4<sup>10+</sup>的CBC\|CTR\|OFB\|CFB模式:iv长度为16字节。 |
67
68> **说明:**
69>
70> 传入[init()](#init-2)方法前需要指定其algName属性(来源于父类[ParamsSpec](#paramsspec))。
71
72## GcmParamsSpec
73
74加解密参数[ParamsSpec](#paramsspec)的子类,用于在对称加解密时作为[init()](#init-2)方法的参数。
75
76适用于GCM模式。
77
78**系统能力:** SystemCapability.Security.CryptoFramework
79
80| 名称    | 类型                  | 可读 | 可写 | 说明                                                         |
81| ------- | --------------------- | ---- | ---- | ------------------------------------------------------------ |
82| iv      | [DataBlob](#datablob) | 是   | 是   | 指明加解密参数iv,长度为12字节。                             |
83| aad     | [DataBlob](#datablob) | 是   | 是   | 指明加解密参数aad,长度为8字节。                             |
84| authTag | [DataBlob](#datablob) | 是   | 是   | 指明加解密参数authTag,长度为16字节。<br/>采用GCM模式加密时,需要获取[doFinal()](#dofinal-2)输出的[DataBlob](#datablob),取出其末尾16字节作为解密时[init()](#init-2)方法的入参[GcmParamsSpec](#gcmparamsspec)中的的authTag。 |
85
86> **说明:**
87>
88> 传入[init()](#init-2)方法前需要指定其algName属性(来源于父类[ParamsSpec](#paramsspec))。
89
90## CcmParamsSpec
91
92加解密参数[ParamsSpec](#paramsspec)的子类,用于在对称加解密时作为[init()](#init-2)方法的参数。
93
94适用于CCM模式。
95
96**系统能力:** SystemCapability.Security.CryptoFramework
97
98| 名称    | 类型                  | 可读 | 可写 | 说明                                                         |
99| ------- | --------------------- | ---- | ---- | ------------------------------------------------------------ |
100| iv      | [DataBlob](#datablob) | 是   | 是   | 指明加解密参数iv,长度为7字节。                              |
101| aad     | [DataBlob](#datablob) | 是   | 是   | 指明加解密参数aad,长度为8字节。                             |
102| authTag | [DataBlob](#datablob) | 是   | 是   | 指明加解密参数authTag,长度为12字节。<br/>采用CCM模式加密时,需要获取[doFinal()](#dofinal-2)输出的[DataBlob](#datablob),取出其末尾12字节作为解密时[init()](#init-2)方法的入参[CcmParamsSpec](#ccmparamsspec)中的authTag。 |
103
104> **说明:**
105>
106> 传入[init()](#init-2)方法前需要指定其algName属性(来源于父类[ParamsSpec](#paramsspec))。
107
108## CryptoMode
109
110表示加解密操作的枚举。
111
112**系统能力:** SystemCapability.Security.CryptoFramework
113
114| 名称         | 值   | 说明               |
115| ------------ | ---- | ------------------ |
116| ENCRYPT_MODE | 0    | 表示进行加密操作。 |
117| DECRYPT_MODE | 1    | 表示进行解密操作。 |
118
119## AsyKeySpecItem<sup>10+</sup>
120
121表示密钥参数的枚举。
122
123**系统能力:** SystemCapability.Security.CryptoFramework
124
125| 名称         | 值   | 说明             |
126| ------------ | ---- | ---------------- |
127| DSA_P_BN | 101 | DSA算法的素模数p。 |
128| DSA_Q_BN | 102 | DSA算法中密钥参数q(p-1的素因子)。 |
129| DSA_G_BN | 103 | DSA算法的参数g。 |
130| DSA_SK_BN | 104 | DSA算法的私钥sk。 |
131| DSA_PK_BN | 105 | DSA算法的公钥pk。 |
132| ECC_FP_P_BN | 201 | DSA算法中表示椭圆曲线Fp域的素数p。 |
133| ECC_A_BN | 202 | DSA算法中椭圆曲线的第一个系数a。 |
134| ECC_B_BN | 203 | DSA算法中椭圆曲线的第二个系数b。 |
135| ECC_G_X_BN | 204 | ECC算法中基点g的x坐标。 |
136| ECC_G_Y_BN | 205 | ECC算法中基点g的y坐标。 |
137| ECC_N_BN | 206 | ECC算法中基点g的阶n。 |
138| ECC_H_NUM | 207 | ECC算法中的余因子h。 |
139| ECC_SK_BN | 208 | ECC算法中的私钥sk。 |
140| ECC_PK_X_BN | 209 | ECC算法中,公钥pk(椭圆曲线上的一个点)的x坐标。 |
141| ECC_PK_Y_BN | 210 | ECC算法中,公钥pk(椭圆曲线上的一个点)的y坐标。 |
142| ECC_FIELD_TYPE_STR | 211 | ECC算法中,椭圆曲线的域类型(当前只支持Fp域)。 |
143| ECC_FIELD_SIZE_NUM | 212 | ECC算法中域的大小,单位为bits(注:对于Fp域,域的大小为素数p的bits长度)。 |
144| ECC_CURVE_NAME_STR | 213 | ECC算法中的SECG曲线名称。 |
145| RSA_N_BN | 301 | RSA算法中的模数n。 |
146| RSA_SK_BN | 302 | RSA算法中的私钥sk(即私钥指数d)。 |
147| RSA_PK_BN | 303 | RSA算法中的公钥pk(即公钥指数e)。 |
148
149## AsyKeySpecType<sup>10+</sup>
150
151表示密钥参数类型的枚举。
152
153**系统能力:** SystemCapability.Security.CryptoFramework
154
155| 名称         | 值   | 说明             |
156| ------------ | ---- | ---------------- |
157| COMMON_PARAMS_SPEC | 0 | 表示公私钥中包含的公共参数。使用此类型的参数可以调用[generateKeyPair](#generatekeypair-2)随机生成密钥对。 |
158| PRIVATE_KEY_SPEC | 1 | 表示私钥中包含的参数。使用此类型的参数可以调用[generatePriKey](#generateprikey)生成指定的私钥。 |
159| PUBLIC_KEY_SPEC | 2 | 表示公钥中包含的参数。使用此类型的参数可以调用[generatePubKey](#generatepubkey)生成指定的公钥。 |
160| KEY_PAIR_SPEC | 3 | 表示公私钥中包含的全量参数。使用此类型的参数可以调用[generateKeyPair](#generatekeypair-2)生成指定的密钥对。 |
161
162## CipherSpecItem<sup>10+</sup>
163
164表示加解密参数的枚举,这些加解密参数支持通过[setCipherSpec](#setcipherspec10)接口设置/通过[getCipherSpec](#getcipherspec10)接口获取。
165
166当前只支持RSA算法,详细规格请参考框架概述[加解密规格](../../security/cryptoFramework-overview.md#加解密规格)
167
168**系统能力:** SystemCapability.Security.CryptoFramework
169
170| 名称         | 值   | 说明             |
171| ------------ | ---- | ---------------- |
172| OAEP_MD_NAME_STR | 100 | 表示RSA算法中,使用PKCS1_OAEP模式时,消息摘要功能的算法名。 |
173| OAEP_MGF_NAME_STR | 101 | 表示RSA算法中,使用PKCS1_OAEP模式时,掩码生成算法(目前仅支持MGF1)。 |
174| OAEP_MGF1_MD_STR | 102 | 表示RSA算法中,使用PKCS1_OAEP模式时,MGF1掩码生成功能的消息摘要算法。 |
175| OAEP_MGF1_PSRC_UINT8ARR | 103 | 表示RSA算法中,使用PKCS1_OAEP模式时,pSource的字节流。 |
176
177## SignSpecItem<sup>10+</sup>
178
179表示签名验签参数的枚举,这些签名验签参数支持通过[setSignSpec](#setsignspec10)、[setVerifySpec](#setverifyspec10)接口设置/通过[getSignSpec](#getsignspec10)、[getVerifySpec](#getverifyspec10)接口获取。
180
181当前只支持RSA算法,详细规格请参考框架概述[加解密规格](../../security/cryptoFramework-overview.md#加解密规格)
182
183**系统能力:** SystemCapability.Security.CryptoFramework
184
185| 名称         | 值   | 说明             |
186| ------------ | ---- | ---------------- |
187| PSS_MD_NAME_STR | 100 | 表示RSA算法中,使用PSS模式时,消息摘要功能的算法名。 |
188| PSS_MGF_NAME_STR | 101 | 表示RSA算法中,使用PSS模式时,掩码生成算法(目前仅支持MGF1)。 |
189| PSS_MGF1_MD_STR | 102 | 表示RSA算法中,使用PSS模式时,MGF1掩码生成功能的消息摘要参数。 |
190| PSS_SALT_LEN_NUM | 103 | 表示RSA算法中,使用PSS模式时,盐值的长度,长度以字节为单位。 |
191| PSS_TRAILER_FIELD_NUM | 104 | 表示RSA算法中,使用PSS模式时,用于编码操作的整数,值为1。 |
192
193## AsyKeySpec<sup>10+</sup>
194
195指定非对称密钥参数的基本接口,用于创建密钥生成器。在指定非对称密钥参数时需要构造其子类对象,并将子类对象传入[createAsyKeyGeneratorBySpec()](#cryptoframeworkcreateasykeygeneratorbyspec10)方法创建密钥生成器。构造子类对象时,所有bigint类型的密钥参数均采用大端写法,并使用正数。
196
197**系统能力:** SystemCapability.Security.CryptoFramework
198
199| 名称    | 类型   | 可读 | 可写 | 说明                                                         |
200| ------- | ------ | ---- | ---- | ------------------------------------------------------------ |
201| algName | string | 是   | 是   | 指定非对称密钥的算法名称,比如"RSA"、"DSA"、"ECC"。 |
202| specType | [AsyKeySpecType](#asykeyspectype10) | 是   | 是 | 指定密钥参数类型,用于区分公/私钥参数。 |
203
204## DSACommonParamsSpec<sup>10+</sup>
205
206密钥参数[AsyKeySpec](#asykeyspec10)的子类,用于指定DSA算法中公私钥包含的公共参数,随机生成公/私钥。
207
208在使用密钥参数生成密钥时,将其传入[createAsyKeyGeneratorBySpec()](#cryptoframeworkcreateasykeygeneratorbyspec10)方法创建密钥生成器。
209
210**系统能力:** SystemCapability.Security.CryptoFramework
211
212| 名称    | 类型   | 可读 | 可写 | 说明                                                         |
213| ------- | ------ | ---- | ---- | ------------------------------------------------------------ |
214| p | bigint | 是   | 是   | 指定DSA算法的素模数p。 |
215| q | bigint | 是   | 是   | 指定DSA算法中密钥参数q(p-1的素因子)。 |
216| g | bigint | 是   | 是   | 指定DSA算法的参数g。 |
217
218## DSAPubKeySpec<sup>10+</sup>
219
220密钥参数[AsyKeySpec](#asykeyspec10)的子类,用于指定DSA算法中公钥包含的参数。
221
222在使用密钥参数生成密钥时,将其传入[createAsyKeyGeneratorBySpec()](#cryptoframeworkcreateasykeygeneratorbyspec10)方法创建密钥生成器。
223
224**系统能力:** SystemCapability.Security.CryptoFramework
225
226| 名称    | 类型   | 可读 | 可写 | 说明                                                         |
227| ------- | ------ | ---- | ---- | ------------------------------------------------------------ |
228| params | [DSACommonParamsSpec](#dsacommonparamsspec10) | 是   | 是   | 指定DSA算法中公私钥都包含的公共参数。 |
229| pk | bigint | 是   | 是   | 指定DSA算法的公钥。 |
230
231## DSAKeyPairSpec<sup>10+</sup>
232
233密钥参数[AsyKeySpec](#asykeyspec10)的子类,用于指定DSA算法中公私钥包含的全量参数。
234
235在使用密钥参数生成密钥时,将其传入[createAsyKeyGeneratorBySpec()](#cryptoframeworkcreateasykeygeneratorbyspec10)方法创建密钥生成器。
236
237**系统能力:** SystemCapability.Security.CryptoFramework
238
239| 名称    | 类型   | 可读 | 可写 | 说明                                                         |
240| ------- | ------ | ---- | ---- | ------------------------------------------------------------ |
241| params | [DSACommonParamsSpec](#dsacommonparamsspec10) | 是   | 是   | 指定DSA算法中公私钥都包含的公共参数。 |
242| sk | bigint | 是   | 是   | 指定DSA算法的私钥sk。 |
243| pk | bigint | 是   | 是   | 指定DSA算法的公钥pk。 |
244
245## ECField<sup>10+</sup>
246
247指定椭圆曲线的域。当前只支持Fp域。
248
249**系统能力:** SystemCapability.Security.CryptoFramework
250
251| 名称    | 类型   | 可读 | 可写 | 说明                                                         |
252| ------- | ------ | ---- | ---- | ------------------------------------------------------------ |
253| fieldType | string | 是   | 是   | 指定椭圆曲线域的类型,当前只支持"Fp"。 |
254
255## ECFieldFp<sup>10+</sup>
256
257指定椭圆曲线素数域。是[ECField](#ecfield10)的子类。
258
259**系统能力:** SystemCapability.Security.CryptoFramework
260
261| 名称    | 类型   | 可读 | 可写 | 说明                                                         |
262| ------- | ------ | ---- | ---- | ------------------------------------------------------------ |
263| p | bigint | 是   | 是   | 指定素数p。 |
264
265## Point<sup>10+</sup>
266
267指定椭圆曲线上的一个点。
268
269**系统能力:** SystemCapability.Security.CryptoFramework
270
271| 名称    | 类型   | 可读 | 可写 | 说明                                                         |
272| ------- | ------ | ---- | ---- | ------------------------------------------------------------ |
273| x | bigint | 是   | 是   | 指定椭圆曲线上,点的x坐标。 |
274| y | bigint | 是   | 是   | 指定椭圆曲线上,点的y坐标。 |
275
276## ECCCommonParamsSpec<sup>10+</sup>
277
278密钥参数[AsyKeySpec](#asykeyspec10)的子类,用于指定ECC算法中公私钥包含的公共参数,随机生成公/私钥。
279
280在使用密钥参数生成密钥时,将其传入[createAsyKeyGeneratorBySpec()](#cryptoframeworkcreateasykeygeneratorbyspec10)方法创建密钥生成器。
281
282**系统能力:** SystemCapability.Security.CryptoFramework
283
284| 名称    | 类型   | 可读 | 可写 | 说明                                                         |
285| ------- | ------ | ---- | ---- | ------------------------------------------------------------ |
286| field | [ECField](#ecfield10) | 是   | 是   | 指定椭圆曲线的域(当前只支持Fp域)。 |
287| a | bigint | 是   | 是   | 指定椭圆曲线的第一个系数a。 |
288| b | bigint | 是   | 是   | 指定椭圆曲线的第二个系数b。 |
289| g | [Point](#point10) | 是   | 是   | 指定基点g。 |
290| n | bigint | 是   | 是   | 指定基点g的阶数n。 |
291| h | number | 是   | 是   | 指定余因子h。 |
292
293## ECCPriKeySpec<sup>10+</sup>
294
295密钥参数[AsyKeySpec](#asykeyspec10)的子类,用于指定ECC算法中私钥包含的参数。
296
297在使用密钥参数生成密钥时,将其传入[createAsyKeyGeneratorBySpec()](#cryptoframeworkcreateasykeygeneratorbyspec10)方法创建密钥生成器。
298
299**系统能力:** SystemCapability.Security.CryptoFramework
300
301| 名称    | 类型   | 可读 | 可写 | 说明                                                         |
302| ------- | ------ | ---- | ---- | ------------------------------------------------------------ |
303| params | [ECCCommonParamsSpec](#ecccommonparamsspec10) | 是   | 是   | 指定ECC算法中公私钥都包含的公共参数。 |
304| sk | bigint | 是   | 是   | 指定ECC算法的私钥sk。 |
305
306## ECCPubKeySpec<sup>10+</sup>
307
308密钥参数[AsyKeySpec](#asykeyspec10)的子类,用于指定ECC算法中公钥包含的参数。
309
310在使用密钥参数生成密钥时,将其传入[createAsyKeyGeneratorBySpec()](#cryptoframeworkcreateasykeygeneratorbyspec10)方法创建密钥生成器。
311
312**系统能力:** SystemCapability.Security.CryptoFramework
313
314| 名称    | 类型   | 可读 | 可写 | 说明                                                         |
315| ------- | ------ | ---- | ---- | ------------------------------------------------------------ |
316| params | [ECCCommonParamsSpec](#ecccommonparamsspec10) | 是   | 是   | 指定ECC算法中公私钥都包含的公共参数。 |
317| pk | [Point](#point10) | 是   | 是   | 指定ECC算法的公钥pk。 |
318
319## ECCKeyPairSpec<sup>10+</sup>
320
321密钥参数[AsyKeySpec](#asykeyspec10)的子类,用于指定ECC算法中公私钥包含的全量参数。
322
323在使用密钥参数生成密钥时,将其传入[createAsyKeyGeneratorBySpec()](#cryptoframeworkcreateasykeygeneratorbyspec10)方法创建密钥生成器。
324
325**系统能力:** SystemCapability.Security.CryptoFramework
326
327| 名称    | 类型   | 可读 | 可写 | 说明                                                         |
328| ------- | ------ | ---- | ---- | ------------------------------------------------------------ |
329| params | [ECCCommonParamsSpec](#ecccommonparamsspec10) | 是   | 是   | 指定ECC算法中公私钥都包含的公共参数。 |
330| sk | bigint | 是   | 是   | 指定ECC算法的私钥sk。 |
331| pk | [Point](#point10) | 是   | 是   | 指定ECC算法的公钥pk。 |
332
333## RSACommonParamsSpec<sup>10+</sup>
334
335密钥参数[AsyKeySpec](#asykeyspec10)的子类,用于指定RSA算法中公私钥包含的公共参数,随机生成公/私钥。
336
337在使用密钥参数生成密钥时,将其传入[createAsyKeyGeneratorBySpec()](#cryptoframeworkcreateasykeygeneratorbyspec10)方法创建密钥生成器。
338
339**系统能力:** SystemCapability.Security.CryptoFramework
340
341| 名称    | 类型   | 可读 | 可写 | 说明                                                         |
342| ------- | ------ | ---- | ---- | ------------------------------------------------------------ |
343| n | bigint | 是   | 是   | 指定模数n。 |
344
345## RSAPubKeySpec<sup>10+</sup>
346
347密钥参数[AsyKeySpec](#asykeyspec10)的子类,用于指定RSA算法中公钥包含的参数。
348
349在使用密钥参数生成密钥时,将其传入[createAsyKeyGeneratorBySpec()](#cryptoframeworkcreateasykeygeneratorbyspec10)方法创建密钥生成器。
350
351**系统能力:** SystemCapability.Security.CryptoFramework
352
353| 名称    | 类型   | 可读 | 可写 | 说明                                                         |
354| ------- | ------ | ---- | ---- | ------------------------------------------------------------ |
355| params | [RSACommonParamsSpec](#rsacommonparamsspec10) | 是   | 是   | 指定RSA算法中公私钥都包含的公共参数。 |
356| pk | bigint | 是   | 是   | 指定RSA算法的公钥pk。 |
357
358## RSAKeyPairSpec<sup>10+</sup>
359
360密钥参数[AsyKeySpec](#asykeyspec10)的子类,用于指定RSA算法中公私钥包含的全量参数。
361
362在使用密钥参数生成密钥时,将其传入[createAsyKeyGeneratorBySpec()](#cryptoframeworkcreateasykeygeneratorbyspec10)方法创建密钥生成器。
363
364**系统能力:** SystemCapability.Security.CryptoFramework
365
366| 名称    | 类型   | 可读 | 可写 | 说明                                                         |
367| ------- | ------ | ---- | ---- | ------------------------------------------------------------ |
368| params | [RSACommonParamsSpec](#rsacommonparamsspec10) | 是   | 是   | 指定RSA算法中公私钥都包含的公共参数。 |
369| sk | bigint | 是   | 是   | 指定RSA算法的私钥sk。 |
370| pk | bigint | 是   | 是   | 指定RSA算法的公钥pk。 |
371
372## Key
373
374密钥(父类),在运行密码算法(如加解密)时需要提前生成其子类对象,并传入[Cipher](#cipher)实例的[init()](#init-2)方法。
375
376密钥可以通过密钥生成器来生成。
377
378### 属性
379
380**系统能力:** SystemCapability.Security.CryptoFramework
381
382| 名称    | 类型   | 可读 | 可写 | 说明                         |
383| ------- | ------ | ---- | ---- | ---------------------------- |
384| format  | string | 是   | 否   | 密钥的格式。                 |
385| algName | string | 是   | 否   | 密钥对应的算法名(含长度)。 |
386
387### getEncoded
388
389getEncoded(): DataBlob
390
391同步方法,获取密钥数据的字节流。密钥可以为对称密钥,公钥或者私钥。其中,公钥格式满足ASN.1语法、X.509规范、DER编码格式;私钥格式满足ASN.1语法,PKCS#8规范、DER编码方式。
392
393> **说明:**
394>
395> RSA算法使用密钥参数生成私钥时,私钥对象不支持getEncoded。
396
397**系统能力:** SystemCapability.Security.CryptoFramework
398
399**返回值:**
400
401| 类型                  | 说明                     |
402| --------------------- | ------------------------ |
403| [DataBlob](#datablob) | 用于查看密钥的具体内容。 |
404
405**错误码:**
406以下错误码的详细介绍请参见[crypto framework错误码](../errorcodes/errorcode-crypto-framework.md)
407
408| 错误码ID | 错误信息               |
409| -------- | ---------------------- |
410| 801 | this operation is not supported. |
411| 17620001 | memory error. |
412| 17630001 | crypto operation error. |
413
414**示例:**
415
416```ts
417let key: cryptoFramework.SymKey;    // The key is generated by a key generator. The generation process is omitted here.
418let encodedKey = key.getEncoded();
419console.info("key blob:" + encodedKey.data);
420```
421
422## SymKey
423
424对称密钥,是[Key](#key)的子类,在对称加解密时需要将其对象传入[Cipher](#cipher)实例的[init()](#init-2)方法使用。
425
426对称密钥可以通过对称密钥生成器[SymKeyGenerator](#symkeygenerator)来生成。
427
428### clearMem
429
430clearMem(): void
431
432同步方法,将系统底层内存中的的密钥内容清零。建议在不再使用对称密钥实例时,调用本函数,避免内存中密钥数据存留过久。
433
434**系统能力:** SystemCapability.Security.CryptoFramework
435
436**示例:**
437
438```ts
439let key: cryptoFramework.SymKey;    // The key is generated by a symKeyGenerator. The generation process is omitted here.
440let encodedKey = key.getEncoded();
441console.info("key blob: "+ encodedKey.data);    // Display key content.
442key.clearMem();
443encodedKey = key.getEncoded();
444console.info("key blob:" + encodedKey.data);    // Display all 0s.
445```
446
447## PubKey
448
449公钥,是[Key](#key)的子类,在非对称加解密、验签、密钥协商时需要将其对象作为输入使用。
450
451公钥可以通过非对称密钥生成器[AsyKeyGenerator](#asykeygenerator)、[AsyKeyGeneratorBySpec](#asykeygeneratorbyspec10)来生成。
452
453### getAsyKeySpec<sup>10+</sup>
454
455getAsyKeySpec(itemType: AsyKeySpecItem): bigint | string | number
456
457同步方法,获取密钥参数。
458
459**系统能力:** SystemCapability.Security.CryptoFramework
460
461**参数:**
462
463| 参数名 | 类型                  | 必填 | 说明                 |
464| ---- | --------------------- | ---- | -------------------- |
465| item  | [AsyKeySpecItem](#asykeyspecitem10) | 是   | 指定的密钥参数。 |
466
467**返回值:**
468
469| 类型                        | 说明                              |
470| --------------------------- | --------------------------------- |
471| bigint\|string\|number | 用于查看密钥参数的具体内容。 |
472
473**错误码:**
474以下错误码的详细介绍请参见[crypto framework错误码](../errorcodes/errorcode-crypto-framework.md)
475
476| 错误码ID | 错误信息               |
477| -------- | ---------------------- |
478| 401 | invalid parameters. |
479| 17620001 | memory error. |
480| 17630001 | crypto operation error. |
481
482**示例:**
483
484```ts
485let key: cryptoFramework.PubKey; // key is a public key object. The generation process is omitted here.
486let p = key.getAsyKeySpec(cryptoFramework.AsyKeySpecItem.ECC_FP_P_BN);
487console.info("ecc item --- p: " + p.toString(16));
488```
489
490## PriKey
491
492私钥,是[Key](#key)的子类,在非对称加解密、签名、密钥协商时需要将其作为输入使用。
493
494私钥可以通过非对称密钥生成器[AsyKeyGenerator](#asykeygenerator)、[AsyKeyGeneratorBySpec](#asykeygeneratorbyspec10)来生成。
495
496### clearMem
497
498clearMem(): void
499
500同步方法,将系统底层内存中的的密钥内容清零。
501
502**系统能力:** SystemCapability.Security.CryptoFramework
503
504**示例:**
505
506```ts
507let key: cryptoFramework.PriKey; // The key is a private key generated by the asymmetric key generator. The generation process is omitted here.
508key.clearMem(); // For the asymmetric private key, clearMem() releases the internal key struct. After clearMem is executed, getEncoded() is not supported.
509```
510
511### getAsyKeySpec<sup>10+</sup>
512
513getAsyKeySpec(itemType: AsyKeySpecItem): bigint | string | number
514
515同步方法,获取密钥参数。
516
517**系统能力:** SystemCapability.Security.CryptoFramework
518
519**参数:**
520
521| 参数名 | 类型                  | 必填 | 说明                 |
522| ---- | --------------------- | ---- | -------------------- |
523| item  | [AsyKeySpecItem](#asykeyspecitem10) | 是   | 指定的密钥参数类型。 |
524
525**返回值:**
526
527| 类型                        | 说明                              |
528| --------------------------- | --------------------------------- |
529| bigint\|string\|number | 用于查看密钥参数的具体内容。 |
530
531**错误码:**
532以下错误码的详细介绍请参见[crypto framework错误码](../errorcodes/errorcode-crypto-framework.md)
533
534| 错误码ID | 错误信息               |
535| -------- | ---------------------- |
536| 401 | invalid parameters. |
537| 17620001 | memory error. |
538| 17630001 | crypto operation error. |
539
540**示例:**
541
542```ts
543let key: cryptoFramework.PriKey; // key is a private key object. The generation process is omitted here.
544let p = key.getAsyKeySpec(cryptoFramework.AsyKeySpecItem.ECC_FP_P_BN);
545console.info("ecc item --- p: " + p.toString(16));
546```
547
548## KeyPair
549
550非对称密钥对,包含:公钥与私钥。
551
552可以通过非对称密钥生成器[AsyKeyGenerator](#asykeygenerator)、[AsyKeyGeneratorBySpec](#asykeygeneratorbyspec10)来生成。
553
554> **说明:**
555>
556> KeyPair对象中的pubKey对象和priKey对象,作为KeyPair对象中的一个参数存在,当离开KeyPair对象作用域时,其内部对象可能被析构。
557>
558> 业务方使用时应持有KeyPair对象的引用,而非内部pubKey或priKey对象的引用。
559
560### 属性
561
562**系统能力:** SystemCapability.Security.CryptoFramework
563
564| 名称    | 类型   | 可读 | 可写 | 说明           |
565| ------- | ------ | ---- | ---- | ------------ |
566| priKey  | [PriKey](#prikey) | 是   | 否   | 私钥。      |
567| pubKey | [PubKey](#pubkey) | 是   | 否   | 公钥。       |
568
569## cryptoFramework.createSymKeyGenerator
570
571createSymKeyGenerator(algName: string): SymKeyGenerator
572
573通过指定算法名称的字符串,获取相应的对称密钥生成器实例。
574
575支持的规格详见框架概述“[密钥生成规格](../../security/cryptoFramework-overview.md#密钥生成规格)”一节。
576
577**系统能力:** SystemCapability.Security.CryptoFramework
578
579**参数:**
580
581| 参数名  | 类型   | 必填 | 说明                                                         |
582| ------- | ------ | ---- | ------------------------------------------------------------ |
583| algName | string | 是   | 待生成对称密钥生成器的算法名称。<br/>具体取值详见框架概述“[密钥生成规格](../../security/cryptoFramework-overview.md#密钥生成规格)”一节中的“字符串参数”。 |
584
585**返回值:**
586
587| 类型                                | 说明                       |
588| ----------------------------------- | -------------------------- |
589| [SymKeyGenerator](#symkeygenerator) | 返回对称密钥生成器的对象。 |
590
591以下错误码的详细介绍请参见[crypto framework错误码](../errorcodes/errorcode-crypto-framework.md)
592| 错误码ID | 错误信息               |
593| -------- | ---------------------- |
594| 401 | invalid parameters. |
595| 801 | this operation is not supported. |
596
597**示例:**
598
599```ts
600let symKeyGenerator = cryptoFramework.createSymKeyGenerator('3DES192');
601```
602
603## SymKeyGenerator
604
605对称密钥生成器。
606
607在使用该类的方法前,需要先使用[createSymKeyGenerator](#cryptoframeworkcreatesymkeygenerator)方法构建一个symKeyGenerator实例。
608
609### 属性
610
611**系统能力:** SystemCapability.Security.CryptoFramework
612
613| 名称    | 类型   | 可读 | 可写 | 说明                           |
614| ------- | ------ | ---- | ---- | ------------------------------ |
615| algName | string | 是   | 否   | 对称密钥生成器指定的算法名称。 |
616
617### generateSymKey
618
619generateSymKey(callback: AsyncCallback\<SymKey>): void
620
621异步获取对称密钥生成器随机生成的密钥,通过注册回调函数获取结果。
622
623必须在使用[createSymKeyGenerator](#cryptoframeworkcreatesymkeygenerator)创建对称密钥生成器后,才能使用本函数。
624
625目前支持使用OpenSSL的RAND_priv_bytes()作为底层能力生成随机密钥。
626
627**系统能力:** SystemCapability.Security.CryptoFramework
628
629**参数:**
630
631| 参数名     | 类型                              | 必填 | 说明                                                         |
632| -------- | --------------------------------- | ---- | ------------------------------------------------------------ |
633| callback | AsyncCallback\<[SymKey](#symkey)> | 是   | 回调函数。当生成对称密钥成功,err为undefined,data为获取到的SymKey;否则为错误对象。 |
634
635**错误码:**
636以下错误码的详细介绍请参见[crypto framework错误码](../errorcodes/errorcode-crypto-framework.md)
637
638| 错误码ID | 错误信息      |
639| -------- | ------------- |
640| 17620001 | memory error. |
641
642**示例:**
643
644```ts
645import { BusinessError } from '@ohos.base';
646
647let symAlgName = '3DES192';
648let symKeyGenerator = cryptoFramework.createSymKeyGenerator(symAlgName);
649symKeyGenerator.generateSymKey((err, symKey) => {
650  if (err) {
651    console.error(`Generate symKey failed, ${err.code}, ${err.message}`);
652  } else {
653    console.info(`Generate symKey success, algName: ${symKey.algName}`);
654  }
655})
656```
657
658### generateSymKey
659
660generateSymKey(): Promise\<SymKey>
661
662异步获取该对称密钥生成器随机生成的密钥,通过Promise获取结果。
663
664必须在使用[createSymKeyGenerator](#cryptoframeworkcreatesymkeygenerator)创建对称密钥生成器后,才能使用本函数。
665
666目前支持使用OpenSSL的RAND_priv_bytes()作为底层能力生成随机密钥。
667
668**系统能力:** SystemCapability.Security.CryptoFramework
669
670**返回值:**
671
672| 类型                        | 说明                              |
673| --------------------------- | --------------------------------- |
674| Promise\<[SymKey](#symkey)> | Promise对象,返回对称密钥SymKey。 |
675
676**错误码:**
677以下错误码的详细介绍请参见[crypto framework错误码](../errorcodes/errorcode-crypto-framework.md)
678
679| 错误码ID | 错误信息      |
680| -------- | ------------- |
681| 17620001 | memory error. |
682
683**示例:**
684
685```ts
686import { BusinessError } from '@ohos.base';
687
688let symAlgName = 'AES128';
689let symKeyGenerator = cryptoFramework.createSymKeyGenerator(symAlgName);
690symKeyGenerator.generateSymKey()
691  .then(symKey => {
692    console.info(`Generate symKey success, algName: ${symKey.algName}`);
693  }, (error: BusinessError) => {
694    console.error(`Generate symKey failed, ${error.code}, ${error.message}`);
695  })
696```
697
698### convertKey
699
700convertKey(key: DataBlob, callback: AsyncCallback\<SymKey>): void
701
702异步根据指定数据生成对称密钥,通过注册回调函数获取结果。
703
704必须在使用[createSymKeyGenerator](#cryptoframeworkcreatesymkeygenerator)创建对称密钥生成器后,才能使用本函数。
705
706**系统能力:** SystemCapability.Security.CryptoFramework
707
708**参数:**
709
710| 参数名     | 类型          | 必填 | 说明                       |
711| -------- | ------------------- | ---- | ---------------------|
712| key      | [DataBlob](#datablob)             | 是   | 指定的对称密钥材料。                                         |
713| callback | AsyncCallback\<[SymKey](#symkey)> | 是   | 回调函数。当生成对称密钥成功,err为undefined,data为获取到的SymKey;否则为错误对象。 |
714
715**错误码:**
716以下错误码的详细介绍请参见[crypto framework错误码](../errorcodes/errorcode-crypto-framework.md)
717
718| 错误码ID | 错误信息                                               |
719| -------- | --------------------------------------------------- |
720| 401 | invalid parameters.          |
721| 17620001 | memory error.                                       |
722
723**示例:**
724
725```ts
726import { BusinessError } from '@ohos.base';
727
728function genKeyMaterialBlob(): cryptoFramework.DataBlob {
729  let arr = [
730    0xba, 0x3d, 0xc2, 0x71, 0x21, 0x1e, 0x30, 0x56,
731    0xad, 0x47, 0xfc, 0x5a, 0x46, 0x39, 0xee, 0x7c,
732    0xba, 0x3b, 0xc2, 0x71, 0xab, 0xa0, 0x30, 0x72]; // keyLen = 192 (24 bytes)
733  let keyMaterial = new Uint8Array(arr);
734  return { data: keyMaterial };
735}
736
737let symAlgName = '3DES192';
738let symKeyGenerator = cryptoFramework.createSymKeyGenerator(symAlgName);
739let keyMaterialBlob = genKeyMaterialBlob();
740symKeyGenerator.convertKey(keyMaterialBlob, (err, symKey) => {
741  if (err) {
742    console.error(`Convert symKey failed, ${err.code}, ${err.message}`);
743  } else {
744    console.info(`Convert symKey success, algName: ${symKey.algName}`);
745  }
746})
747```
748
749### convertKey
750
751convertKey(key: DataBlob): Promise\<SymKey>
752
753异步根据指定数据生成对称密钥,通过Promise获取结果。
754
755必须在使用[createSymKeyGenerator](#cryptoframeworkcreatesymkeygenerator)创建对称密钥生成器后,才能使用本函数。
756
757**系统能力:** SystemCapability.Security.CryptoFramework
758
759**参数:**
760
761| 参数名 | 类型                  | 必填 | 说明                 |
762| ---- | --------------------- | ---- | -------------------- |
763| key  | [DataBlob](#datablob) | 是   | 指定的密钥材料数据。 |
764
765**返回值:**
766
767| 类型                        | 说明                              |
768| --------------------------- | --------------------------------- |
769| Promise\<[SymKey](#symkey)> | Promise对象,返回对称密钥SymKey。 |
770
771**错误码:**
772以下错误码的详细介绍请参见[crypto framework错误码](../errorcodes/errorcode-crypto-framework.md)
773
774| 错误码ID | 错误信息                                          |
775| -------- | --------------------------------------------- |
776| 401 | invalid parameters.          |
777| 17620001 | memory error.                                |
778
779**示例:**
780
781```ts
782import { BusinessError } from '@ohos.base';
783
784function genKeyMaterialBlob(): cryptoFramework.DataBlob {
785  let arr = [
786    0xba, 0x3d, 0xc2, 0x71, 0x21, 0x1e, 0x30, 0x56,
787    0xad, 0x47, 0xfc, 0x5a, 0x46, 0x39, 0xee, 0x7c,
788    0xba, 0x3b, 0xc2, 0x71, 0xab, 0xa0, 0x30, 0x72]; // keyLen = 192 (24 bytes)
789  let keyMaterial = new Uint8Array(arr);
790  return { data: keyMaterial };
791}
792
793let symAlgName = '3DES192';
794let symKeyGenerator = cryptoFramework.createSymKeyGenerator(symAlgName);
795let keyMaterialBlob = genKeyMaterialBlob();
796symKeyGenerator.convertKey(keyMaterialBlob)
797  .then(symKey => {
798    console.info(`Convert symKey success, algName: ${symKey.algName}`);
799  }, (error: BusinessError) => {
800    console.error(`Convert symKey failed, ${error.code}, ${error.message}`);
801  })
802```
803
804## cryptoFramework.createAsyKeyGenerator
805
806createAsyKeyGenerator(algName: string): AsyKeyGenerator
807
808通过指定算法名称的字符串,获取相应的非对称密钥生成器实例。
809
810支持的规格详见框架概述“[密钥生成规格](../../security/cryptoFramework-overview.md#密钥生成规格)”一节。
811
812**系统能力:** SystemCapability.Security.CryptoFramework
813
814**参数:**
815
816| 参数名  | 类型   | 必填 | 说明                             |
817| ------- | ------ | ---- | -------------------------------- |
818| algName | string | 是   | 待生成对称密钥生成器的算法名称。 |
819
820**返回值:**
821
822| 类型            | 说明                         |
823| --------------- | ---------------------------- |
824| [AsyKeyGenerator](#asykeygenerator) | 返回非对称密钥生成器的对象。 |
825
826**错误码:**
827以下错误码的详细介绍请参见[crypto framework错误码](../errorcodes/errorcode-crypto-framework.md)
828
829| 错误码ID | 错误信息               |
830| -------- | ---------------------- |
831| 401 | invalid parameters. |
832| 801 | this operation is not supported. |
833| 17620001 | memory error. |
834
835**示例:**
836
837```ts
838let asyKeyGenerator = cryptoFramework.createAsyKeyGenerator("ECC256");
839```
840
841## AsyKeyGenerator
842
843非对称密钥生成器。在使用该类的方法前,需要先使用createAsyKeyGenerator()方法构建一个AsyKeyGenerator实例。
844
845### 属性
846
847**系统能力:** SystemCapability.Security.CryptoFramework
848
849| 名称    | 类型   | 可读 | 可写 | 说明                             |
850| ------- | ------ | ---- | ---- | -------------------------------- |
851| algName | string | 是   | 否   | 非对称密钥生成器指定的算法名称。 |
852
853### generateKeyPair
854
855generateKeyPair(callback: AsyncCallback\<KeyPair>): void
856
857异步获取非对称密钥生成器随机生成的密钥,通过注册回调函数获取结果。
858
859**系统能力:** SystemCapability.Security.CryptoFramework
860
861**参数:**
862
863| 参数名     | 类型                    | 必填 | 说明                           |
864| -------- | ----------------------- | ---- | ------------------------------ |
865| callback | AsyncCallback\<[KeyPair](#keypair)> | 是   | 回调函数,用于获取非对称密钥。 |
866
867**错误码:**
868以下错误码的详细介绍请参见[crypto framework错误码](../errorcodes/errorcode-crypto-framework.md)
869
870| 错误码ID | 错误信息               |
871| -------- | ---------------------- |
872| 401 | invalid parameters.          |
873| 17620001 | memory error.          |
874| 17630001 | crypto operation error.          |
875
876**示例:**
877
878```ts
879import { BusinessError } from '@ohos.base';
880
881let asyKeyGenerator = cryptoFramework.createAsyKeyGenerator("ECC256");
882asyKeyGenerator.generateKeyPair((err, keyPair) => {
883  if (err) {
884    console.error("generateKeyPair: error.");
885    return;
886  }
887  console.info("generateKeyPair: success.");
888})
889```
890
891### generateKeyPair
892
893generateKeyPair(): Promise\<KeyPair>
894
895异步获取该非对称密钥生成器随机生成的密钥,通过Promise获取结果。
896
897**系统能力:** SystemCapability.Security.CryptoFramework
898
899**返回值:**
900
901| 类型              | 说明                              |
902| ----------------- | --------------------------------- |
903| Promise\<[KeyPair](#keypair)> | 使用Promise的方式获取非对称密钥。 |
904
905**错误码:**
906以下错误码的详细介绍请参见[crypto framework错误码](../errorcodes/errorcode-crypto-framework.md)
907
908| 错误码ID | 错误信息               |
909| -------- | ---------------------- |
910| 401 | invalid parameters.          |
911| 17620001 | memory error.          |
912| 17630001 | crypto operation error.          |
913
914**示例:**
915
916```ts
917import { BusinessError } from '@ohos.base';
918
919let asyKeyGenerator = cryptoFramework.createAsyKeyGenerator("ECC256");
920let keyGenPromise = asyKeyGenerator.generateKeyPair();
921keyGenPromise.then( keyPair => {
922  console.info("generateKeyPair success.");
923}).catch((error: BusinessError) => {
924  console.error("generateKeyPair error.");
925});
926```
927
928### convertKey
929
930convertKey(pubKey: DataBlob | null, priKey: DataBlob | null, callback: AsyncCallback\<KeyPair\>): void
931
932异步获取指定数据生成非对称密钥,通过注册回调函数获取结果。详情请看下方**密钥转换说明**。
933
934**系统能力:** SystemCapability.Security.CryptoFramework
935
936**参数:**
937
938| 参数名     | 类型       | 必填 | 说明                           |
939| -------- | ----------- | ---- | ------------------------------ |
940| pubKey   | [DataBlob](#datablob) \| null<sup>10+</sup>    | 是   | 指定的公钥材料。如果公钥不需要转换,可直接传入null。API 10之前只支持DataBlob, API 10之后增加支持null。        |
941| priKey   | [DataBlob](#datablob) \| null<sup>10+</sup>   | 是   | 指定的私钥材料。如果私钥不需要转换,可直接传入null。API 10之前只支持DataBlob, API 10之后增加支持null。        |
942| callback | AsyncCallback\<[KeyPair](#keypair)> | 是   | 回调函数,用于获取非对称密钥。 |
943
944**错误码:**
945以下错误码的详细介绍请参见[crypto framework错误码](../errorcodes/errorcode-crypto-framework.md)
946
947| 错误码ID | 错误信息               |
948| -------- | ---------------------- |
949| 401 | invalid parameters.          |
950| 17620001 | memory error.          |
951| 17630001 | crypto operation error.          |
952
953**示例:**
954
955```ts
956import { BusinessError } from '@ohos.base';
957
958let pubKeyArray = new Uint8Array([48, 89, 48, 19, 6, 7, 42, 134, 72, 206, 61, 2, 1, 6, 8, 42, 134, 72, 206, 61, 3, 1, 7, 3, 66, 0, 4, 83, 96, 142, 9, 86, 214, 126, 106, 247, 233, 92, 125, 4, 128, 138, 105, 246, 162, 215, 71, 81, 58, 202, 121, 26, 105, 211, 55, 130, 45, 236, 143, 55, 16, 248, 75, 167, 160, 167, 106, 2, 152, 243, 44, 68, 66, 0, 167, 99, 92, 235, 215, 159, 239, 28, 106, 124, 171, 34, 145, 124, 174, 57, 92]);
959let priKeyArray = new Uint8Array([48, 49, 2, 1, 1, 4, 32, 115, 56, 137, 35, 207, 0, 60, 191, 90, 61, 136, 105, 210, 16, 27, 4, 171, 57, 10, 61, 123, 40, 189, 28, 34, 207, 236, 22, 45, 223, 10, 189, 160, 10, 6, 8, 42, 134, 72, 206, 61, 3, 1, 7]);
960let pubKeyBlob: cryptoFramework.DataBlob = {data: pubKeyArray}; // Data of the public key.
961let priKeyBlob: cryptoFramework.DataBlob = {data: priKeyArray}; // Data of the private key.
962let asyKeyGenerator = cryptoFramework.createAsyKeyGenerator("ECC256");
963asyKeyGenerator.convertKey(pubKeyBlob, priKeyBlob, (err, keyPair) => {
964  if (err) {
965    console.error("convertKey: error.");
966    return;
967  }
968  console.info("convertKey: success.");
969})
970```
971
972### convertKey
973
974convertKey(pubKey: DataBlob | null, priKey: DataBlob | null): Promise\<KeyPair>
975
976异步获取指定数据生成非对称密钥,通过Promise获取结果。详情请看下方**密钥转换说明**。
977
978**系统能力:** SystemCapability.Security.CryptoFramework
979
980**参数:**
981
982| 参数名   | 类型    | 必填 | 说明             |
983| ------ | -------- | ---- | ---------------- |
984| pubKey | [DataBlob](#datablob) \| null<sup>10+</sup> | 是   | 指定的公钥材料。如果公钥不需要转换,可直接传入null。API 10之前只支持DataBlob, API 10之后增加支持null。 |
985| priKey | [DataBlob](#datablob) \| null<sup>10+</sup> | 是   | 指定的私钥材料。如果私钥不需要转换,可直接传入null。API 10之前只支持DataBlob, API 10之后增加支持null。 |
986
987**返回值:**
988
989| 类型              | 说明                              |
990| ----------------- | --------------------------------- |
991| Promise\<[KeyPair](#keypair)> | 使用Promise的方式获取非对称密钥。 |
992
993**错误码:**
994以下错误码的详细介绍请参见[crypto framework错误码](../errorcodes/errorcode-crypto-framework.md)
995
996| 错误码ID | 错误信息               |
997| -------- | ---------------------- |
998| 401 | invalid parameters.          |
999| 17620001 | memory error.          |
1000| 17630001 | crypto operation error.          |
1001
1002**示例:**
1003
1004```ts
1005import { BusinessError } from '@ohos.base';
1006
1007let pubKeyArray = new Uint8Array([48, 89, 48, 19, 6, 7, 42, 134, 72, 206, 61, 2, 1, 6, 8, 42, 134, 72, 206, 61, 3, 1, 7, 3, 66, 0, 4, 83, 96, 142, 9, 86, 214, 126, 106, 247, 233, 92, 125, 4, 128, 138, 105, 246, 162, 215, 71, 81, 58, 202, 121, 26, 105, 211, 55, 130, 45, 236, 143, 55, 16, 248, 75, 167, 160, 167, 106, 2, 152, 243, 44, 68, 66, 0, 167, 99, 92, 235, 215, 159, 239, 28, 106, 124, 171, 34, 145, 124, 174, 57, 92]);
1008let priKeyArray = new Uint8Array([48, 49, 2, 1, 1, 4, 32, 115, 56, 137, 35, 207, 0, 60, 191, 90, 61, 136, 105, 210, 16, 27, 4, 171, 57, 10, 61, 123, 40, 189, 28, 34, 207, 236, 22, 45, 223, 10, 189, 160, 10, 6, 8, 42, 134, 72, 206, 61, 3, 1, 7]);
1009let pubKeyBlob: cryptoFramework.DataBlob = {data: pubKeyArray}; // Data of the public key.
1010let priKeyBlob: cryptoFramework.DataBlob = {data: priKeyArray}; // Data of the private key.
1011let asyKeyGenerator = cryptoFramework.createAsyKeyGenerator("ECC256");
1012let keyGenPromise = asyKeyGenerator.convertKey(pubKeyBlob, priKeyBlob);
1013keyGenPromise.then( keyPair => {
1014  console.info("convertKey success.");
1015}).catch((error: BusinessError) => {
1016  console.error("convertKey error.");
1017});
1018```
1019
1020**密钥转换说明**
1021
10221. 非对称密钥(RSA、ECC、DSA)的公钥和私钥调用getEncoded()方法后,分别返回X.509格式和PKCS#8格式的二进制数据,此数据可用于跨应用传输或持久化存储。
10232. 当调用convertKey方法将外来二进制数据转换为算法库非对称密钥对象时,公钥应满足ASN.1语法、X.509规范、DER编码格式,私钥应满足ASN.1语法、PKCS#8规范、DER编码格式。
10243. convertKey方法中,公钥和密钥二进制数据非必选项,可单独传入公钥或私钥的数据,生成对应只包含公钥或私钥的KeyPair对象。
1025
1026## cryptoFramework.createAsyKeyGeneratorBySpec<sup>10+</sup>
1027
1028createAsyKeyGeneratorBySpec(asyKeySpec: AsyKeySpec): AsyKeyGeneratorBySpec
1029
1030通过指定密钥参数,获取相应的非对称密钥生成器实例。
1031
1032支持的规格详见框架概述“[密钥生成规格](../../security/cryptoFramework-overview.md#密钥生成规格)”一节。
1033
1034**系统能力:** SystemCapability.Security.CryptoFramework
1035
1036**参数:**
1037
1038| 参数名  | 类型   | 必填 | 说明                             |
1039| ------- | ------ | ---- | -------------------------------- |
1040| asyKeySpec | [AsyKeySpec](#asykeyspec10) | 是   | 密钥参数。非对称密钥生成器根据指定的这些参数生成公/私钥。 |
1041
1042**返回值:**
1043
1044| 类型                                            | 说明                       |
1045| ----------------------------------------------- | -------------------------- |
1046| [AsyKeyGeneratorBySpec](#asykeygeneratorbyspec10) | 返回非对称密钥生成器实例。 |
1047
1048**错误码:**
1049以下错误码的详细介绍请参见[crypto framework错误码](../errorcodes/errorcode-crypto-framework.md)
1050
1051| 错误码ID | 错误信息               |
1052| -------- | ---------------------- |
1053| 401 | invalid parameters. |
1054| 801 | this operation is not supported. |
1055| 17620001 | memory error. |
1056
1057**示例:**
1058
1059```ts
1060// Set the common parameters contained in both the DSA1024 public and private keys.
1061function genDsa1024CommonSpecBigE() {
1062  let dsaCommonSpec: cryptoFramework.DSACommonParamsSpec = {
1063    algName : "DSA",
1064    specType : cryptoFramework.AsyKeySpecType.COMMON_PARAMS_SPEC,
1065    p : BigInt("0xed1501551b8ab3547f6355ffdc2913856ddeca198833dbd04f020e5f25e47c50e0b3894f7690a0d2ea5ed3a7be25c54292a698e1f086eb3a97deb4dbf04fcad2dafd94a9f35c3ae338ab35477e16981ded6a5b13d5ff20bf55f1b262303ad3a80af71aa6aa2354d20e9c82647664bdb6b333b7bea0a5f49d55ca40bc312a1729"),
1066    q : BigInt("0xd23304044019d5d382cfeabf351636c7ab219694ac845051f60b047b"),
1067    g : BigInt("0x2cc266d8bd33c3009bd67f285a257ba74f0c3a7e12b722864632a0ac3f2c17c91c2f3f67eb2d57071ef47aaa8f8e17a21ad2c1072ee1ce281362aad01dcbcd3876455cd17e1dd55d4ed36fa011db40f0bbb8cba01d066f392b5eaa9404bfcb775f2196a6bc20eeec3db32d54e94d87ecdb7a0310a5a017c5cdb8ac78597778bd"),
1068  }
1069  return dsaCommonSpec;
1070}
1071// Set full parameters contained in the DSA1024 public and private keys.
1072function genDsa1024KeyPairSpecBigE() {
1073  let dsaCommonSpec = genDsa1024CommonSpecBigE();
1074  let dsaKeyPairSpec: cryptoFramework.DSAKeyPairSpec = {
1075    algName : "DSA",
1076    specType : cryptoFramework.AsyKeySpecType.KEY_PAIR_SPEC,
1077    params : dsaCommonSpec,
1078    sk : BigInt("0xa2dd2adb2d11392c2541930f61f1165c370aabd2d78d00342e0a2fd9"),
1079    pk : BigInt("0xae6b5d5042e758f3fc9a02d009d896df115811a75b5f7b382d8526270dbb3c029403fafb8573ba4ef0314ea86f09d01e82a14d1ebb67b0c331f41049bd6b1842658b0592e706a5e4d20c14b67977e17df7bdd464cce14b5f13bae6607760fcdf394e0b73ac70aaf141fa4dafd736bd0364b1d6e6c0d7683a5de6b9221e7f2d6b"),
1080  }
1081  return dsaKeyPairSpec;
1082}
1083
1084let asyKeyPairSpec = genDsa1024KeyPairSpecBigE(); // The JS input must be a positive number in big-endian format.
1085let asyKeyGeneratorBySpec = cryptoFramework.createAsyKeyGeneratorBySpec(asyKeyPairSpec);
1086```
1087
1088## AsyKeyGeneratorBySpec<sup>10+</sup>
1089
1090非对称密钥生成器。在使用该类的方法前,需要先使用[createAsyKeyGeneratorBySpec()](#cryptoframeworkcreateasykeygeneratorbyspec10)方法构建一个AsyKeyGeneratorBySpec实例。
1091
1092### 属性
1093
1094**系统能力:** SystemCapability.Security.CryptoFramework
1095
1096| 名称    | 类型   | 可读 | 可写 | 说明                       |
1097| ------- | ------ | ---- | ---- | -------------------------- |
1098| algName | string | 是   | 否   | 非对称密钥生成器的算法名。 |
1099
1100### generateKeyPair
1101
1102generateKeyPair(callback: AsyncCallback\<KeyPair>): void
1103
1104异步获取非对称密钥生成器生成的密钥,通过注册回调函数获取结果。
1105
1106当使用[COMMON_PARAMS_SPEC](#asykeyspectype10)类型的密钥参数来创建密钥生成器时,可以得到随机生成的密钥对;当使用[KEY_PAIR_SPEC](#asykeyspectype10)类型的密钥参数来创建密钥生成器时,可以得到各项数据与密钥参数一致的密钥对。
1107
1108**系统能力:** SystemCapability.Security.CryptoFramework
1109
1110**参数:**
1111
1112| 参数名     | 类型                    | 必填 | 说明                           |
1113| -------- | ----------------------- | ---- | ------------------------------ |
1114| callback | AsyncCallback\<[KeyPair](#keypair)> | 是   | 回调函数,用于获取非对称密钥。 |
1115
1116**错误码:**
1117以下错误码的详细介绍请参见[crypto framework错误码](../errorcodes/errorcode-crypto-framework.md)
1118
1119| 错误码ID | 错误信息                |
1120| -------- | ----------------------- |
1121| 401 | invalid parameters.          |
1122| 17620001 | memory error.           |
1123| 17630001 | crypto operation error. |
1124
1125**示例:**
1126
1127```ts
1128import { BusinessError } from '@ohos.base';
1129
1130let asyKeyPairSpec: cryptoFramework.DSAKeyPairSpec; // dsa as example, asyKeyPairSpec specifies full parameters contained in the private and public keys. The generation process is omitted here.
1131let asyKeyGeneratorBySpec = cryptoFramework.createAsyKeyGeneratorBySpec(asyKeyPairSpec);
1132asyKeyGeneratorBySpec.generateKeyPair((err, keyPair) => {
1133  if (err) {
1134    console.error("generateKeyPair: error.");
1135    return;
1136  }
1137  console.info("generateKeyPair: success.");
1138})
1139```
1140
1141### generateKeyPair
1142
1143generateKeyPair(): Promise\<KeyPair>
1144
1145异步获取该非对称密钥生成器生成的密钥,通过Promise获取结果。
1146
1147当使用[COMMON_PARAMS_SPEC](#asykeyspectype10)类型的密钥参数来创建密钥生成器时,可以得到随机生成的密钥对;当使用[KEY_PAIR_SPEC](#asykeyspectype10)类型的密钥参数来创建密钥生成器时,可以得到各项数据与密钥参数一致的密钥对。
1148
1149**系统能力:** SystemCapability.Security.CryptoFramework
1150
1151**返回值:**
1152
1153| 类型              | 说明                              |
1154| ----------------- | --------------------------------- |
1155| Promise\<[KeyPair](#keypair)> | 使用Promise的方式获取非对称密钥。 |
1156
1157**错误码:**
1158以下错误码的详细介绍请参见[crypto framework错误码](../errorcodes/errorcode-crypto-framework.md)
1159
1160| 错误码ID | 错误信息               |
1161| -------- | ---------------------- |
1162| 401 | invalid parameters.          |
1163| 17620001 | memory error.          |
1164| 17630001 | crypto operation error. |
1165
1166**示例:**
1167
1168```ts
1169import { BusinessError } from '@ohos.base';
1170
1171let asyKeyPairSpec: cryptoFramework.DSAKeyPairSpec; // dsa as example, asyKeyPairSpec specifies full parameters contained in the private and public keys. The generation process is omitted here.
1172let asyKeyGeneratorBySpec = cryptoFramework.createAsyKeyGeneratorBySpec(asyKeyPairSpec);
1173let keyGenPromise = asyKeyGeneratorBySpec.generateKeyPair();
1174keyGenPromise.then( keyPair => {
1175  console.info("generateKeyPair success.");
1176}).catch((error: BusinessError) => {
1177  console.error("generateKeyPair error.");
1178});
1179```
1180
1181### generatePriKey
1182
1183generatePriKey(callback: AsyncCallback\<PriKey>): void
1184
1185异步获取非对称密钥生成器生成的密钥,通过注册回调函数获取结果。
1186
1187当使用[PRIVATE_KEY_SPEC](#asykeyspectype10)类型的密钥参数来创建密钥生成器时,可以得到指定的私钥;当使用[KEY_PAIR_SPEC](#asykeyspectype10)类型的密钥参数来创建密钥生成器时,可以从生成的密钥对中获取指定的私钥。
1188
1189**系统能力:** SystemCapability.Security.CryptoFramework
1190
1191**参数:**
1192
1193| 参数名     | 类型                    | 必填 | 说明                           |
1194| -------- | ----------------------- | ---- | ------------------------------ |
1195| callback | AsyncCallback\<[PriKey](#prikey)> | 是   | 回调函数,用于获取非对称密钥。 |
1196
1197**错误码:**
1198以下错误码的详细介绍请参见[crypto framework错误码](../errorcodes/errorcode-crypto-framework.md)
1199
1200| 错误码ID | 错误信息               |
1201| -------- | ---------------------- |
1202| 401 | invalid parameters.          |
1203| 17620001 | memory error.          |
1204| 17630001 | crypto operation error. |
1205
1206**示例:**
1207
1208```ts
1209import { BusinessError } from '@ohos.base';
1210
1211let asyKeyPairSpec: cryptoFramework.DSAKeyPairSpec; // dsa as example, asyKeyPairSpec specifies full parameters contained in the private and public keys.
1212let asyKeyGeneratorBySpec = cryptoFramework.createAsyKeyGeneratorBySpec(asyKeyPairSpec);
1213asyKeyGeneratorBySpec.generatePriKey((err, prikey) => {
1214  if (err) {
1215    console.error("generatePriKey: error.");
1216    return;
1217  }
1218  console.info("generatePriKey: success.");
1219})
1220```
1221
1222### generatePriKey
1223
1224generatePriKey(): Promise\<PriKey>
1225
1226异步获取该非对称密钥生成器生成的密钥,通过Promise获取结果。
1227
1228当使用[PRIVATE_KEY_SPEC](#asykeyspectype10)类型的密钥参数来创建密钥生成器时,可以得到指定的私钥;当使用[KEY_PAIR_SPEC](#asykeyspectype10)类型的密钥参数来创建密钥生成器时,可以从生成的密钥对中获取指定的私钥。
1229
1230**系统能力:** SystemCapability.Security.CryptoFramework
1231
1232**返回值:**
1233
1234| 类型              | 说明                              |
1235| ----------------- | --------------------------------- |
1236| Promise\<[PriKey](#prikey)> | 使用Promise的方式获取非对称密钥。 |
1237
1238**错误码:**
1239以下错误码的详细介绍请参见[crypto framework错误码](../errorcodes/errorcode-crypto-framework.md)
1240
1241| 错误码ID | 错误信息               |
1242| -------- | ---------------------- |
1243| 401 | invalid parameters.          |
1244| 17620001 | memory error.          |
1245| 17630001 | crypto operation error. |
1246
1247**示例:**
1248
1249```ts
1250import { BusinessError } from '@ohos.base';
1251
1252let asyKeyPairSpec: cryptoFramework.DSAKeyPairSpec; // dsa as example, asyKeyPairSpec specifies full parameters contained in the private and public keys.
1253let asyKeyGeneratorBySpec = cryptoFramework.createAsyKeyGeneratorBySpec(asyKeyPairSpec);
1254let keyGenPromise = asyKeyGeneratorBySpec.generatePriKey();
1255keyGenPromise.then( priKey => {
1256  console.info("generatePriKey success.");
1257}).catch((error: BusinessError) => {
1258  console.error("generatePriKey error.");
1259});
1260```
1261
1262### generatePubKey
1263
1264generatePubKey(callback: AsyncCallback\<PubKey>): void
1265
1266异步获取非对称密钥生成器生成的密钥,通过注册回调函数获取结果。
1267
1268当使用[PUBLIC_KEY_SPEC](#asykeyspectype10)类型的密钥参数来创建密钥生成器时,可以得到指定的公钥;当使用[KEY_PAIR_SPEC](#asykeyspectype10)类型的密钥参数来创建密钥生成器时,可以从生成的密钥对中获取指定的公钥。
1269
1270**系统能力:** SystemCapability.Security.CryptoFramework
1271
1272**参数:**
1273
1274| 参数名     | 类型                    | 必填 | 说明                           |
1275| -------- | ----------------------- | ---- | ------------------------------ |
1276| callback | AsyncCallback\<[PubKey](#pubkey)> | 是   | 回调函数,用于获取非对称密钥。 |
1277
1278**错误码:**
1279以下错误码的详细介绍请参见[crypto framework错误码](../errorcodes/errorcode-crypto-framework.md)
1280
1281| 错误码ID | 错误信息               |
1282| -------- | ---------------------- |
1283| 401 | invalid parameters.          |
1284| 17620001 | memory error.          |
1285| 17630001 | crypto operation error. |
1286
1287**示例:**
1288
1289```ts
1290import { BusinessError } from '@ohos.base';
1291
1292let asyKeyPairSpec: cryptoFramework.DSAKeyPairSpec; // dsa as example, asyKeyPairSpec specifies full parameters contained in the private and public keys. The generation process is omitted here.
1293let asyKeyGeneratorBySpec = cryptoFramework.createAsyKeyGeneratorBySpec(asyKeyPairSpec);
1294asyKeyGeneratorBySpec.generatePubKey((err, pubKey) => {
1295  if (err) {
1296    console.error("generatePubKey: error.");
1297    return;
1298  }
1299  console.info("generatePubKey: success.");
1300})
1301```
1302
1303### generatePubKey
1304
1305generatePubKey(): Promise\<PubKey>
1306
1307异步获取该非对称密钥生成器生成的密钥,通过Promise获取结果。
1308
1309当使用[PUBLIC_KEY_SPEC](#asykeyspectype10)类型的密钥参数来创建密钥生成器时,可以得到指定的公钥;当使用[KEY_PAIR_SPEC](#asykeyspectype10)类型的密钥参数来创建密钥生成器时,可以从生成的密钥对中获取指定的公钥。
1310
1311**系统能力:** SystemCapability.Security.CryptoFramework
1312
1313**返回值:**
1314
1315| 类型              | 说明                              |
1316| ----------------- | --------------------------------- |
1317| Promise\<[PubKey](#pubkey)> | 使用Promise的方式获取非对称密钥。 |
1318
1319**错误码:**
1320以下错误码的详细介绍请参见[crypto framework错误码](../errorcodes/errorcode-crypto-framework.md)
1321
1322| 错误码ID | 错误信息               |
1323| -------- | ---------------------- |
1324| 401 | invalid parameters.          |
1325| 17620001 | memory error.          |
1326| 17630001 | crypto operation error. |
1327
1328**示例:**
1329
1330```ts
1331import { BusinessError } from '@ohos.base';
1332
1333let asyKeyPairSpec: cryptoFramework.DSAKeyPairSpec; // dsa as example, asyKeyPairSpec specifies full parameters contained in the private and public keys. The generation process is omitted here.
1334let asyKeyGeneratorBySpec = cryptoFramework.createAsyKeyGeneratorBySpec(asyKeyPairSpec);
1335let keyGenPromise = asyKeyGeneratorBySpec.generatePubKey();
1336keyGenPromise.then( pubKey => {
1337  console.info("generatePubKey success.");
1338}).catch((error: BusinessError) => {
1339  console.error("generatePubKey error.");
1340});
1341```
1342
1343## cryptoFramework.createCipher
1344
1345createCipher(transformation: string): Cipher
1346
1347通过指定算法名称,获取相应的[Cipher](#cipher)实例。
1348
1349支持的规格详见框架概述“[加解密规格](../../security/cryptoFramework-overview.md#加解密规格)”一节。
1350
1351**系统能力:** SystemCapability.Security.CryptoFramework
1352
1353**参数:**
1354
1355| 参数名         | 类型   | 必填 | 说明                                                         |
1356| -------------- | ------ | ---- | ------------------------------------------------------------ |
1357| transformation | string | 是   | 待生成Cipher的算法名称(含密钥长度)、加密模式以及填充方法的组合。<br/>具体取值详见框架概述“[加解密规格](../../security/cryptoFramework-overview.md#加解密规格)”一节中的“字符串参数”。 |
1358
1359> **说明:**
1360>
1361> 1. 目前对称加解密中,PKCS5和PKCS7的实现相同,其padding长度和分组长度保持一致(即PKCS5和PKCS7在3DES中均按照8字节填充,在AES中均按照16字节填充),另有NoPadding表示不填充。
1362> <br/>开发者需要自行了解密码学不同分组模式的差异,以便选择合适的参数规格。例如选择ECB和CBC模式时,建议启用填充,否则必须确保明文长度是分组大小的整数倍;选择其他模式时,可以不启用填充,此时密文长度和明文长度一致(即可能不是分组大小的整数倍)。
1363> 2. 使用RSA、SM2进行非对称加解密时,必须创建两个Cipher对象分别进行加密和解密操作,而不能对同一个Cipher对象进行加解密。对称加解密没有此要求(即只要算法规格一样,可以对同一个Cipher对象进行加解密操作)。
1364
1365**返回值:**
1366
1367| 类型              | 说明                     |
1368| ----------------- | ------------------------ |
1369| [Cipher](#cipher) | 返回加解密生成器的对象。 |
1370
1371**错误码:**
1372以下错误码的详细介绍请参见[crypto framework错误码](../errorcodes/errorcode-crypto-framework.md)
1373
1374| 错误码ID | 错误信息               |
1375| -------- | ---------------------- |
1376| 401 | invalid parameters.          |
1377| 801 | this operation is not supported. |
1378| 17620001 | memory error.          |
1379
1380**示例:**
1381
1382```ts
1383import { BusinessError } from '@ohos.base';
1384
1385let cipherAlgName = '3DES192|ECB|PKCS7';
1386try {
1387  let cipher = cryptoFramework.createCipher(cipherAlgName);
1388  console.info(`cipher algName: ${cipher.algName}`);
1389} catch (error) {
1390  let e: BusinessError = error as BusinessError;
1391  console.error(`sync error, ${e.code}, ${e.message}`);
1392}
1393```
1394
1395## Cipher
1396
1397提供加解密的算法操作功能,按序调用本类中的[init()](#init-1)、[update()](#update)、[doFinal()](#dofinal)方法,可以实现对称加密/对称解密/非对称加密/非对称解密。
1398
1399完整的加解密流程示例可参考开发指导中的“[使用加解密操作](../../security/cryptoFramework-guidelines.md#使用加解密操作)”一节。
1400
1401一次完整的加/解密流程在对称加密和非对称加密中略有不同:
1402
1403- 对称加解密:init为必选,update为可选(且允许多次update加/解密大数据),doFinal为必选;doFinal结束后可以重新init开始新一轮加/解密流程。
1404- RSA、SM2非对称加解密:init为必选,不支持update操作,doFinal为必选(允许连续多次doFinal加/解密大数据);RSA不支持重复init,切换加解密模式或填充方式时,需要重新创建Cipher对象。
1405
1406### 属性
1407
1408**系统能力:** SystemCapability.Security.CryptoFramework
1409
1410| 名称    | 类型   | 可读 | 可写 | 说明                         |
1411| ------- | ------ | ---- | ---- | ---------------------------- |
1412| algName | string | 是   | 否   | 加解密生成器指定的算法名称。 |
1413
1414### init
1415
1416init(opMode: CryptoMode, key: Key, params: ParamsSpec | null, callback: AsyncCallback\<void>): void
1417
1418初始化加解密的[cipher](#cipher)对象,通过注册回调函数获取结果。
1419
1420必须在使用[createCipher](#cryptoframeworkcreatecipher)创建[Cipher](#cipher)实例后,才能使用本函数。
1421
1422**系统能力:** SystemCapability.Security.CryptoFramework
1423
1424**参数:**
1425
1426| 参数名     | 类型                      | 必填 | 说明                                                         |
1427| -------- | ------------------------- | ---- | ------------------------------------------------------------ |
1428| opMode   | [CryptoMode](#cryptomode) | 是   | 加密或者解密模式。                                           |
1429| key      | [Key](#key)               | 是   | 指定加密或解密的密钥。                                       |
1430| params   | [ParamsSpec](#paramsspec) \| null<sup>10+</sup> | 是   | 指定加密或解密的参数,对于ECB等没有参数的算法模式,可以传入null。API 10之前只支持ParamsSpec, API 10之后增加支持null。 |
1431| callback | AsyncCallback\<void>      | 是   | 回调函数。当加解密初始化成功,err为undefined,否则为错误对象。 |
1432
1433**错误码:**
1434以下错误码的详细介绍请参见[crypto framework错误码](../errorcodes/errorcode-crypto-framework.md)
1435
1436| 错误码ID | 错误信息                                                 |
1437| -------- | --------------------------------------------------------- |
1438| 401 | invalid parameters.          |
1439| 17620001 | memory error.                                            |
1440| 17620002 | runtime error.                                           |
1441| 17630001 | crypto operation error.|
1442
1443**示例:**
1444
1445```ts
1446import { BusinessError } from '@ohos.base';
1447
1448let symKey: cryptoFramework.SymKey;     // The process of generating the symmetric key is omitted here.
1449let cipher: cryptoFramework.Cipher;        // The process of creating a Cipher instance is omitted here.
1450
1451cipher.init(cryptoFramework.CryptoMode.ENCRYPT_MODE, symKey, null, (err, ) => {
1452  if (err) {
1453    console.error(`Failed to init cipher, ${err.code}, ${err.message}`);
1454  } else {
1455    console.info(`Init cipher success`);
1456    // Perform subsequent operations such as update.
1457  }
1458})
1459```
1460
1461### init
1462
1463init(opMode: CryptoMode, key: Key, params: ParamsSpec | null): Promise\<void>
1464
1465初始化加解密的cipher对象,通过Promise获取结果。
1466
1467必须在使用[createCipher](#cryptoframeworkcreatecipher)创建[Cipher](#cipher)实例后,才能使用本函数。
1468
1469**系统能力:** SystemCapability.Security.CryptoFramework
1470
1471**参数:**
1472
1473| 参数名   | 类型                      | 必填 | 说明                                                         |
1474| ------ | ------------------------- | ---- | ------------------------------------------------------------ |
1475| opMode | [CryptoMode](#cryptomode) | 是   | 加密或者解密模式。                                           |
1476| key    | [Key](#key)               | 是   | 指定加密或解密的密钥。                                       |
1477| params | [ParamsSpec](#paramsspec) \| null<sup>10+</sup> | 是   | 指定加密或解密的参数,对于ECB等没有参数的算法模式,可以传入null。API 10之前只支持ParamsSpec, API 10之后增加支持null。 |
1478
1479**返回值:**
1480
1481| 类型           | 说明                                   |
1482| -------------- | -------------------------------------- |
1483| Promise\<void> | 无返回结果的Promise对象。 |
1484
1485**错误码:**
1486以下错误码的详细介绍请参见[crypto framework错误码](../errorcodes/errorcode-crypto-framework.md)
1487
1488| 错误码ID | 错误信息                                          |
1489| -------- | ------------------------------------------------- |
1490| 401 | invalid parameters.          |
1491| 17620001 | memory error.                                     |
1492| 17620002 | runtime error.                                    |
1493| 17630001 | crypto operation error.|
1494
1495**示例:**
1496
1497```ts
1498import { BusinessError } from '@ohos.base';
1499
1500let symKey: cryptoFramework.SymKey;     // The process of generating the symmetric key is omitted here.
1501let cipher: cryptoFramework.Cipher;        // The process of creating a Cipher instance is omitted here.
1502cipher.init(cryptoFramework.CryptoMode.ENCRYPT_MODE, symKey, null)
1503  .then(() => {
1504    console.info(`Init cipher success`);
1505    // Perform subsequent operations such as update.
1506  }, (error: BusinessError) => {
1507    console.error(`Failed to init cipher, ${error.code}, ${error.message}`);
1508  })
1509```
1510
1511### update
1512
1513update(data: DataBlob, callback: AsyncCallback\<DataBlob>): void
1514
1515分段更新加密或者解密数据操作,通过注册回调函数获取加/解密数据。
1516
1517必须在对[Cipher](#cipher)实例使用[init()](init-1)初始化后,才能使用本函数。
1518
1519> **说明:**
1520>
1521> 1. 在进行对称加解密操作的时候,如果开发者对各个分组模式不够熟悉,建议对每次update和doFinal的结果都判断是否为null,并在结果不为null时取出其中的数据进行拼接,形成完整的密文/明文。这是因为选择的分组模式等各项规格都可能对update和doFinal结果产生影响。<br/>(例如对于ECB和CBC模式,不论update传入的数据是否为分组长度的整数倍,都会以分组作为基本单位进行加/解密,并输出本次update新产生的加/解密分组结果。<br/>可以理解为,update只要凑满一个新的分组就会有输出,如果没有凑满则此次update输出为null,把当前还没被加/解密的数据留着,等下一次update/doFinal传入数据的时候,拼接起来继续凑分组。<br/>最后doFinal的时候,会把剩下的还没加/解密的数据,根据[createCipher](#cryptoframeworkcreatecipher)时设置的padding模式进行填充,补齐到分组的整数倍长度,再输出剩余加解密结果。<br/>而对于可以将分组密码转化为流模式实现的模式,还可能出现密文长度和明文长度相同的情况等。)
1522> 2. 根据数据量,可以不调用update(即init完成后直接调用doFinal)或多次调用update。<br/>
1523>    算法库目前没有对update(单次或累计)的数据量设置大小限制,建议对于大数据量的对称加解密,采用多次update的方式传入数据。<br/>
1524>    AES使用多次update操作的示例代码详见开发指导“[使用加解密操作](../../security/cryptoFramework-guidelines.md#使用加解密操作)”。
1525> 3. RSA、SM2非对称加解密不支持update操作。
1526
1527**系统能力:** SystemCapability.Security.CryptoFramework
1528
1529**参数:**
1530
1531| 参数名     | 类型                                  | 必填 | 说明                                                         |
1532| -------- | ------------------------------------- | ---- | ------------------------------------------------------------ |
1533| data     | [DataBlob](#datablob)                 | 是   | 加密或者解密的数据。data不能为null,也不允许传入{data: Uint8Array(空) }。           |
1534| callback | AsyncCallback\<[DataBlob](#datablob)> | 是   | 回调函数。当更新加/解密数据成功,err为undefined,data为此次更新的加/解密结果DataBlob;否则为错误对象。 |
1535
1536**错误码:**
1537以下错误码的详细介绍请参见[crypto framework错误码](../errorcodes/errorcode-crypto-framework.md)
1538
1539| 错误码ID | 错误信息                                    |
1540| -------- | ------------------------------------------- |
1541| 401 | invalid parameters.          |
1542| 17620001 | memory error.                               |
1543| 17620002 | runtime error.                              |
1544| 17630001 | crypto operation error.                     |
1545
1546**示例:**
1547
1548```ts
1549import { BusinessError } from '@ohos.base';
1550
1551function stringToUint8Array(str: string) {
1552  let arr = new Uint8Array(str.length);
1553  for (let i = 0, j = str.length; i < j; ++i) {
1554    arr[i] = str.charCodeAt(i);
1555  }
1556  return arr;
1557}
1558
1559let cipher: cryptoFramework.Cipher;        // The process of creating a Cipher instance is omitted here.
1560// The init() process is omitted here.
1561let plainText: cryptoFramework.DataBlob = {data: stringToUint8Array('this is test!')};
1562cipher.update(plainText, (err, output) => {       // Example of the encryption process.
1563  if (err) {
1564    console.error(`Failed to update cipher`);
1565  } else {
1566    console.info(`Update cipher success`);
1567    if (output != null) {
1568      // Concatenate output.data to the ciphertext.
1569    }
1570    // Perform subsequent operations such as doFinal().
1571  }
1572})
1573```
1574
1575### update
1576
1577update(data: DataBlob): Promise\<DataBlob>
1578
1579分段更新加密或者解密数据操作,通过Promise获取加/解密数据。
1580
1581必须在对[Cipher](#cipher)实例使用[init()](init-2)初始化后,才能使用本函数。
1582
1583> **说明:**
1584>
1585> 1. 在进行对称加解密操作的时候,如果开发者对各个分组模式不够熟悉,建议对每次update和doFinal的结果都判断是否为null,并在结果不为null时取出其中的数据进行拼接,形成完整的密文/明文。这是因为选择的分组模式等各项规格都可能对update和doFinal结果产生影响。
1586> <br/>(例如对于ECB和CBC模式,不论update传入的数据是否为分组长度的整数倍,都会以分组作为基本单位进行加/解密,并输出本次update新产生的加/解密分组结果。<br/>可以理解为,update只要凑满一个新的分组就会有输出,如果没有凑满则此次update输出为null,把当前还没被加/解密的数据留着,等下一次update/doFinal传入数据的时候,拼接起来继续凑分组。<br/>最后doFinal的时候,会把剩下的还没加/解密的数据,根据[createCipher](#cryptoframeworkcreatecipher)时设置的padding模式进行填充,补齐到分组的整数倍长度,再输出剩余加解密结果。<br/>而对于可以将分组密码转化为流模式实现的模式,还可能出现密文长度和明文长度相同的情况等。)
1587> 2. 根据数据量,可以不调用update(即init完成后直接调用doFinal)或多次调用update。<br/>
1588>    算法库目前没有对update(单次或累计)的数据量设置大小限制,建议对于大数据量的对称加解密,可以采用多次update的方式传入数据。<br/>
1589>    AES使用多次update操作的示例代码详见开发指导“[使用加解密操作](../../security/cryptoFramework-guidelines.md#使用加解密操作)”。
1590> 3. RSA、SM2非对称加解密不支持update操作。
1591
1592**系统能力:** SystemCapability.Security.CryptoFramework
1593
1594**参数:**
1595
1596| 参数名 | 类型                  | 必填 | 说明                 |
1597| ---- | --------------------- | ---- | -------------------- |
1598| data | [DataBlob](#datablob) | 是   | 加密或者解密的数据。data不能为null,也不允许传入{data: Uint8Array(空) }。 |
1599
1600**返回值:**
1601
1602| 类型                            | 说明                                             |
1603| ------------------------------- | ------------------------------------------------ |
1604| Promise\<[DataBlob](#datablob)> | Promise对象,返回此次更新的加/解密结果DataBlob。 |
1605
1606**错误码:**
1607以下错误码的详细介绍请参见[crypto framework错误码](../errorcodes/errorcode-crypto-framework.md)
1608
1609| 错误码ID | 错误信息                                     |
1610| -------- | -------------------------------------------- |
1611| 401 | invalid parameters.          |
1612| 17620001 | memory error.                                |
1613| 17620002 | runtime error.                               |
1614| 17630001 | crypto operation error.                      |
1615
1616**示例:**
1617
1618```ts
1619import { BusinessError } from '@ohos.base';
1620
1621function stringToUint8Array(str: string) {
1622  let arr = new Uint8Array(str.length);
1623  for (let i = 0, j = str.length; i < j; ++i) {
1624    arr[i] = str.charCodeAt(i);
1625  }
1626  return arr;
1627}
1628
1629let cipher: cryptoFramework.Cipher;        // The process of creating a Cipher instance is omitted here.
1630// The init() process is omitted here.
1631let plainText: cryptoFramework.DataBlob = {data: stringToUint8Array('this is test!')};
1632cipher.update(plainText)
1633  .then((output) => {
1634    console.info(`Update cipher success.`);
1635    if (output != null) {
1636      // Concatenate output.data to the ciphertext.
1637    }
1638    // Perform subsequent operations such as doFinal().
1639  }, (error: BusinessError) => {
1640    console.info(`Update cipher failed.`);
1641  })
1642```
1643
1644### doFinal
1645
1646doFinal(data: DataBlob | null, callback: AsyncCallback\<DataBlob>): void
1647
1648(1)在对称加解密中,doFinal加/解密(分组模式产生的)剩余数据和本次传入的数据,最后结束加密或者解密数据操作,通过注册回调函数获取加密或者解密数据。<br/>如果数据量较小,可以在doFinal中一次性传入数据,而不使用update;如果在本次加解密流程中,已经使用[update](#update-4)传入过数据,可以在doFinal的data参数处传入null。<br/>根据对称加解密的模式不同,doFinal的输出有如下区别:
1649
1650- 对于GCM和CCM模式的对称加密:一次加密流程中,如果将每一次update和doFinal的结果拼接起来,会得到“密文+authTag”,即末尾的16字节(GCM模式)或12字节(CCM模式)是authTag,而其余部分均为密文。(也就是说,如果doFinal的data参数传入null,则doFinal的结果就是authTag)<br/>authTag需要填入解密时的[GcmParamsSpec](#gcmparamsspec)或[CcmParamsSpec](#ccmparamsspec);密文则作为解密时的入参data。
1651- 对于其他模式的对称加解密、GCM和CCM模式的对称解密:一次加/解密流程中,每一次update和doFinal的结果拼接起来,得到完整的明文/密文。
1652
1653(2)在RSA、SM2非对称加解密中,doFinal加/解密本次传入的数据,通过注册回调函数获取加密或者解密数据。如果数据量较大,可以多次调用doFinal,拼接结果得到完整的明文/密文。
1654
1655> **说明:**
1656>
1657>  1. 对称加解密中,调用doFinal标志着一次加解密流程已经完成,即[Cipher](#cipher)实例的状态被清除,因此当后续开启新一轮加解密流程时,需要重新调用init()并传入完整的参数列表进行初始化<br/>(比如即使是对同一个Cipher实例,采用同样的对称密钥,进行加密然后解密,则解密中调用init的时候仍需填写params参数,而不能直接省略为null)。
1658>  2. 如果遇到解密失败,需检查加解密数据和init时的参数是否匹配,包括GCM模式下加密得到的authTag是否填入解密时的GcmParamsSpec等。
1659>  3. doFinal的结果可能为null,因此使用.data字段访问doFinal结果的具体数据前,请记得先判断结果是否为null,避免产生异常。
1660>  4. RSA、SM2非对称加解密时多次doFinal操作的示例代码详见开发指导“[使用加解密操作](../../security/cryptoFramework-guidelines.md#使用加解密操作)”。
1661
1662**系统能力:** SystemCapability.Security.CryptoFramework
1663
1664**参数:**
1665
1666| 参数名     | 类型                                  | 必填 | 说明                                                         |
1667| -------- | ------------------------------------- | ---- | ------------------------------------------------------------ |
1668| data     | [DataBlob](#datablob) \| null<sup>10+</sup>                 | 是   | 加密或者解密的数据。在对称加解密中允许为null,但不允许传入{data: Uint8Array(空) }。API 10之前只支持DataBlob, API 10之后增加支持null。       |
1669| callback | AsyncCallback\<[DataBlob](#datablob)> | 是   | 回调函数。当最终加/解密数据成功,err为undefined,data为剩余数据的加/解密结果DataBlob;否则为错误对象。 |
1670
1671**错误码:**
1672以下错误码的详细介绍请参见[crypto framework错误码](../errorcodes/errorcode-crypto-framework.md)
1673
1674| 错误码ID | 错误信息                |
1675| -------- | ----------------------- |
1676| 401 | invalid parameters.          |
1677| 17620001 | memory error.           |
1678| 17620002 | runtime error.          |
1679| 17630001 | crypto operation error. |
1680
1681**示例:**
1682
1683```ts
1684import { BusinessError } from '@ohos.base';
1685
1686let cipher: cryptoFramework.Cipher;        // The process of creating a Cipher instance is omitted here.
1687let data: cryptoFramework.DataBlob;           // The process of preparing the data to encrypt or decrypt is omitted here.
1688// The init() and update() processes are omitted here.
1689cipher.doFinal(data, (err, output) => {
1690  if (err) {
1691    console.error(`Failed to finalize cipher, ${err.code}, ${err.message}`);
1692  } else {
1693    console.info(`Finalize cipher success`);
1694    if (output != null) {
1695      // Concatenate output.data to obtain the complete plaintext/ciphertext (and authTag).
1696    }
1697  }
1698})
1699```
1700
1701### doFinal
1702
1703doFinal(data: DataBlob | null): Promise\<DataBlob>
1704
1705(1)在对称加解密中,doFinal加/解密(分组模式产生的)剩余数据和本次传入的数据,最后结束加密或者解密数据操作,通过Promise获取加密或者解密数据。<br/>如果数据量较小,可以在doFinal中一次性传入数据,而不使用update;如果在本次加解密流程中,已经使用update传入过数据,可以在doFinal的data参数处传入null。<br/>根据对称加解密的模式不同,doFinal的输出有如下区别:
1706
1707- 对于GCM和CCM模式的对称加密:一次加密流程中,如果将每一次update和doFinal的结果拼接起来,会得到“密文+authTag”,即末尾的16字节(GCM模式)或12字节(CCM模式)是authTag,而其余部分均为密文。(也就是说,如果doFinal的data参数传入null,则doFinal的结果就是authTag)<br/>authTag需要填入解密时的[GcmParamsSpec](#gcmparamsspec)或[CcmParamsSpec](#ccmparamsspec);密文则作为解密时的入参data。
1708- 对于其他模式的对称加解密、GCM和CCM模式的对称解密:一次加/解密流程中,每一次update和doFinal的结果拼接起来,得到完整的明文/密文。
1709
1710(2)在RSA、SM2非对称加解密中,doFinal加/解密本次传入的数据,通过Promise获取加密或者解密数据。如果数据量较大,可以多次调用doFinal,拼接结果得到完整的明文/密文。
1711
1712> **说明:**
1713>
1714>  1. 对称加解密中,调用doFinal标志着一次加解密流程已经完成,即[Cipher](#cipher)实例的状态被清除,因此当后续开启新一轮加解密流程时,需要重新调用init()并传入完整的参数列表进行初始化<br/>(比如即使是对同一个Cipher实例,采用同样的对称密钥,进行加密然后解密,则解密中调用init的时候仍需填写params参数,而不能直接省略为null)。
1715>  2. 如果遇到解密失败,需检查加解密数据和init时的参数是否匹配,包括GCM模式下加密得到的authTag是否填入解密时的GcmParamsSpec等。
1716>  3. doFinal的结果可能为null,因此使用.data字段访问doFinal结果的具体数据前,请记得先判断结果是否为null,避免产生异常。
1717>  4. RSA、SM2非对称加解密时多次doFinal操作的示例代码详见开发指导“[使用加解密操作](../../security/cryptoFramework-guidelines.md#使用加解密操作)”。
1718
1719**系统能力:** SystemCapability.Security.CryptoFramework
1720
1721**参数:**
1722
1723| 参数名 | 类型                  | 必填 | 说明                 |
1724| ---- | --------------------- | ---- | -------------------- |
1725| data | [DataBlob](#datablob) \| null<sup>10+</sup> | 是   | 加密或者解密的数据。data参数允许为null,但不允许传入{data: Uint8Array(空) }。API 10之前只支持DataBlob, API 10之后增加支持null。 |
1726
1727**返回值:**
1728
1729| 类型                            | 说明                                             |
1730| ------------------------------- | ------------------------------------------------ |
1731| Promise\<[DataBlob](#datablob)> | Promise对象,返回剩余数据的加/解密结果DataBlob。 |
1732
1733**错误码:**
1734以下错误码的详细介绍请参见[crypto framework错误码](../errorcodes/errorcode-crypto-framework.md)
1735
1736| 错误码ID | 错误信息                                     |
1737| -------- | -------------------------------------------- |
1738| 401 | invalid parameters.          |
1739| 17620001 | memory error.                                |
1740| 17620002 | runtime error.                               |
1741| 17630001 | crypto operation error.                      |
1742
1743**示例:**
1744
1745```ts
1746import { BusinessError } from '@ohos.base';
1747
1748let cipher: cryptoFramework.Cipher;        // The process of creating a Cipher instance is omitted here.
1749let data: cryptoFramework.DataBlob;           // The process of preparing the data to encrypt or decrypt is omitted here.
1750// The init() and update() processes are omitted here.
1751cipher.doFinal(data)
1752  .then(output => {
1753    console.info(`Finalize cipher success`);
1754    if (output != null) {
1755      // Concatenate output.data to obtain the complete plaintext/ciphertext (and authTag).
1756    }
1757  }, (error: BusinessError) => {
1758    console.error(`Failed to finalize cipher, ${error.code}, ${error.message}`);
1759  })
1760```
1761
1762**使用RSA加密的callback完整示例:**
1763
1764```ts
1765function stringToUint8Array(str: string) {
1766  let arr = new Uint8Array(str.length);
1767  for (let i = 0, j = str.length; i < j; ++i) {
1768    arr[i] = str.charCodeAt(i);
1769  }
1770  return arr;
1771}
1772
1773let rsaGenerator = cryptoFramework.createAsyKeyGenerator("RSA1024|PRIMES_2");
1774let cipher = cryptoFramework.createCipher("RSA1024|PKCS1");
1775rsaGenerator.generateKeyPair((err, keyPair) => {
1776  let pubKey = keyPair.pubKey;
1777  cipher.init(cryptoFramework.CryptoMode.ENCRYPT_MODE, pubKey, null, (err, data) => {
1778    let plainText = "this is cipher text";
1779    let input: cryptoFramework.DataBlob = {data: stringToUint8Array(plainText) };
1780    cipher.doFinal(input, (err, data) => {
1781      AlertDialog.show({ message: "EncryptOutPut is " + data.data} );
1782    });
1783  });
1784});
1785```
1786
1787**使用RSA加密的Promise完整示例:**
1788
1789```ts
1790function stringToUint8Array(str: string) {
1791  let arr = new Uint8Array(str.length);
1792  for (let i = 0, j = str.length; i < j; ++i) {
1793    arr[i] = str.charCodeAt(i);
1794  }
1795  return arr;
1796}
1797
1798let rsaGenerator = cryptoFramework.createAsyKeyGenerator("RSA1024|PRIMES_2");
1799let cipher = cryptoFramework.createCipher("RSA1024|PKCS1");
1800let keyGenPromise = rsaGenerator.generateKeyPair();
1801keyGenPromise.then((rsaKeyPair: cryptoFramework.KeyPair): Promise<void> => {
1802  let pubKey = rsaKeyPair.pubKey;
1803  return cipher.init(cryptoFramework.CryptoMode.ENCRYPT_MODE, pubKey, null); // Pass in the private key and DECRYPT_MODE to initialize the decryption mode.
1804}).then(() => {
1805  let plainText = "this is cipher text";
1806  let input: cryptoFramework.DataBlob = { data: stringToUint8Array(plainText) };
1807  return cipher.doFinal(input);
1808}).then(dataBlob => {
1809  console.info("EncryptOutPut is " + dataBlob.data);
1810});
1811```
1812
1813> **说明:**
1814>
1815> 更多加解密流程的完整示例可参考开发指导中的“[使用加解密操作](../../security/cryptoFramework-guidelines.md#使用加解密操作)”一节。
1816
1817### setCipherSpec<sup>10+</sup>
1818
1819setCipherSpec(itemType: CipherSpecItem, itemValue: Uint8Array): void
1820
1821设置加解密参数。常用的加解密参数可以直接通过[createCipher](#cryptoframeworkcreatecipher) 来指定,剩余参数可以通过本接口指定。当前只支持RSA算法。
1822
1823**系统能力:** SystemCapability.Security.CryptoFramework
1824
1825**参数:**
1826
1827| 参数名   | 类型                 | 必填 | 说明       |
1828| -------- | -------------------- | ---- | ---------- |
1829| itemType     | [CipherSpecItem](#cipherspecitem10)           | 是   | 用于指定需要设置的加解密参数。 |
1830| itemValue | Uint8Array | 是   | 用于指定加解密参数的具体值。 |
1831
1832**错误码:**
1833以下错误码的详细介绍请参见[crypto framework错误码](../errorcodes/errorcode-crypto-framework.md)
1834
1835| 错误码ID | 错误信息               |
1836| -------- | ---------------------- |
1837| 401 | invalid parameters.          |
1838| 801 | this operation is not supported.          |
1839| 17620001 | memory error.          |
1840| 17630001 | crypto operation error. |
1841
1842**示例:**
1843
1844```ts
1845let cipher: cryptoFramework.Cipher; // The process of generating the Cipher instance is omitted here.
1846let pSource = new Uint8Array([1,2,3,4]);
1847cipher.setCipherSpec(cryptoFramework.CipherSpecItem.OAEP_MGF1_PSRC_UINT8ARR, pSource);
1848```
1849
1850### getCipherSpec<sup>10+</sup>
1851
1852getCipherSpec(itemType: CipherSpecItem): string | Uint8Array
1853
1854获取加解密参数。当前只支持RSA算法。
1855
1856**系统能力:** SystemCapability.Security.CryptoFramework
1857
1858**参数:**
1859
1860| 参数名 | 类型     | 必填 | 说明       |
1861| ------ | -------- | ---- | ---------- |
1862| itemType   | [CipherSpecItem](#cipherspecitem10) | 是   | 用于指定需要获取的加解密参数。 |
1863
1864**返回值:**
1865
1866| 类型           | 说明        |
1867| -------------- | ----------- |
1868| string\|Uint8Array | 获取的加解密参数的具体值。 |
1869
1870**错误码:**
1871以下错误码的详细介绍请参见[crypto framework错误码](../errorcodes/errorcode-crypto-framework.md)
1872
1873| 错误码ID | 错误信息               |
1874| -------- | ---------------------- |
1875| 401 | invalid parameters.          |
1876| 801 | this operation is not supported.          |
1877| 17620001 | memory error.          |
1878| 17630001 | crypto operation error. |
1879
1880**示例:**
1881
1882```ts
1883let cipher: cryptoFramework.Cipher; // The process of generating the Cipher instance is omitted here.
1884let mdName = cipher.getCipherSpec(cryptoFramework.CipherSpecItem.OAEP_MD_NAME_STR);
1885```
1886
1887## cryptoFramework.createSign
1888
1889createSign(algName: string): Sign
1890
1891Sign实例生成。
1892
1893支持的规格详见框架概述“[签名验签规格](../../security/cryptoFramework-overview.md#签名验签规格)”一节。
1894
1895**系统能力:** SystemCapability.Security.CryptoFramework
1896
1897**参数:**
1898
1899| 参数名  | 类型   | 必填 | 说明                                                         |
1900| ------- | ------ | ---- | ------------------------------------------------------------ |
1901| algName | string | 是   | 指定签名算法:RSA,ECC,DSA或SM2<sup>10+</sup>。使用RSA PKCS1模式时需要设置摘要,使用RSA PSS模式时需要设置摘要和掩码摘要。 |
1902
1903**返回值**:
1904
1905| 类型 | 说明                               |
1906| ---- | ---------------------------------- |
1907| Sign | 返回由输入算法指定生成的Sign对象。 |
1908
1909**错误码:**
1910以下错误码的详细介绍请参见[crypto framework错误码](../errorcodes/errorcode-crypto-framework.md)
1911
1912| 错误码ID | 错误信息               |
1913| -------- | ---------------------- |
1914| 401 | invalid parameters.          |
1915| 801 | this operation is not supported.          |
1916| 17620001 | memory error.          |
1917
1918**示例:**
1919
1920```ts
1921let signer1 = cryptoFramework.createSign("RSA1024|PKCS1|SHA256");
1922
1923let signer2 = cryptoFramework.createSign("RSA1024|PSS|SHA256|MGF1_SHA256");
1924
1925let signer3 = cryptoFramework.createSign("ECC224|SHA256");
1926
1927let signer4 = cryptoFramework.createSign("DSA2048|SHA256");
1928```
1929
1930## Sign
1931
1932Sign类,使用Sign方法之前需要创建该类的实例进行操作,通过[createSign(algName: string): Sign](#cryptoframeworkcreatesign)方法构造此实例。按序调用本类中的init、update、sign方法完成签名操作。签名操作的示例代码详见开发指导“[使用签名验签操作](../../security/cryptoFramework-guidelines.md#使用签名验签操作)”。
1933
1934Sign类不支持重复初始化,当业务方需要使用新密钥签名时,需要重新创建新Sign对象并调用init初始化。
1935
1936业务方使用时,在createSign时确定签名的模式,调用init接口设置密钥。
1937
1938当待签名数据较短时,可在init初始化后,(无需update)直接调用sign接口传入原文数据进行签名。
1939
1940当待签名数据较长时,可通过update接口分段传入切分后的原文数据,最后调用sign接口对整体原文数据进行签名。
1941
1942当使用update分段传入原文时,sign接口API 10之前只支持传入DataBlob, API 10之后增加支持null。业务方可在循环中调用update接口,循环结束后调用sign进行签名。
1943
1944### 属性
1945
1946**系统能力:** SystemCapability.Security.CryptoFramework
1947
1948| 名称    | 类型   | 可读 | 可写 | 说明                         |
1949| ------- | ------ | ---- | ---- | ---------------------------- |
1950| algName | string | 是   | 否   | 签名指定的算法名称。 |
1951
1952### init
1953
1954init(priKey: PriKey, callback: AsyncCallback\<void>): void
1955
1956使用私钥初始化Sign对象,通过注册回调函数获取结果。
1957
1958Sign类暂不支持重复init。
1959
1960**系统能力:** SystemCapability.Security.CryptoFramework
1961
1962**参数:**
1963
1964| 参数名   | 类型                 | 必填 | 说明             |
1965| -------- | -------------------- | ---- | ---------------- |
1966| priKey   | [PriKey](#prikey)    | 是   | 用于Sign的初始化。 |
1967| callback | AsyncCallback\<void> | 是   | 回调函数。当签名初始化成功,err为undefined,否则为错误对象。 |
1968
1969**错误码:**
1970以下错误码的详细介绍请参见[crypto framework错误码](../errorcodes/errorcode-crypto-framework.md)
1971
1972| 错误码ID | 错误信息               |
1973| -------- | ---------------------- |
1974| 401 | invalid parameters.          |
1975| 17620001 | memory error.          |
1976| 17620002 | runtime error.          |
1977| 17630001 | crypto operation error. |
1978
1979### init
1980
1981init(priKey: PriKey): Promise\<void>
1982
1983使用私钥初始化Sign对象,通过Promise获取结果。
1984
1985Sign类暂不支持重复init。
1986
1987**系统能力:** SystemCapability.Security.CryptoFramework
1988
1989**参数:**
1990
1991| 参数名 | 类型 | 必填 | 说明             |
1992| ------ | ---- | ---- | ---------------- |
1993| priKey | [PriKey](#prikey)  | 是   | 用于Sign的初始化。 |
1994
1995**返回值:**
1996
1997| 类型           | 说明          |
1998| -------------- | ------------- |
1999| Promise\<void> | 无返回结果的Promise对象。 |
2000
2001**错误码:**
2002以下错误码的详细介绍请参见[crypto framework错误码](../errorcodes/errorcode-crypto-framework.md)
2003
2004| 错误码ID | 错误信息               |
2005| -------- | ---------------------- |
2006| 401 | invalid parameters.          |
2007| 17620001 | memory error.          |
2008| 17620002 | runtime error.          |
2009| 17630001 | crypto operation error. |
2010
2011### update
2012
2013update(data: DataBlob, callback: AsyncCallback\<void>): void
2014
2015追加待签名数据,通过注册回调函数完成更新。
2016
2017必须在对[Sign](#sign)实例使用[init()](#init-2)初始化后,才能使用本函数。
2018
2019> **说明:**
2020>
2021> 根据数据量,可以不调用update(即[init](#init-2)完成后直接调用[sign](#sign-1))或多次调用update。<br/>
2022> 算法库目前没有对update(单次或累计)的数据量设置大小限制,建议对于大数据量的签名操作,采用多次update的方式传入数据,避免一次性申请过大内存。<br/>
2023> 签名使用多次update操作的示例代码详见开发指导“[使用签名验签操作](../../security/cryptoFramework-guidelines.md#使用签名验签操作)”。
2024
2025**系统能力:** SystemCapability.Security.CryptoFramework
2026
2027**参数:**
2028
2029| 参数名   | 类型                  | 必填 | 说明         |
2030| -------- | --------------------- | ---- | ------------ |
2031| data     | [DataBlob](#datablob) | 是   | 传入的消息。 |
2032| callback | AsyncCallback\<void>  | 是   | 回调函数。当签名更新成功,err为undefined,否则为错误对象。 |
2033
2034**错误码:**
2035以下错误码的详细介绍请参见[crypto framework错误码](../errorcodes/errorcode-crypto-framework.md)
2036
2037| 错误码ID | 错误信息               |
2038| -------- | ---------------------- |
2039| 401 | invalid parameters.          |
2040| 17620001 | memory error.          |
2041| 17620002 | runtime error.          |
2042| 17630001 | crypto operation error. |
2043
2044### update
2045
2046update(data: DataBlob): Promise\<void>
2047
2048追加待签名数据,通过Promise方式完成更新。
2049
2050必须在对[Sign](#sign)实例使用[init()](#init-3)初始化后,才能使用本函数。
2051
2052> **说明:**
2053>
2054> 根据数据量,可以不调用update(即[init](#init-3)完成后直接调用[sign](#sign-2))或多次调用update。<br/>
2055> 算法库目前没有对update(单次或累计)的数据量设置大小限制,建议对于大数据量的签名操作,采用多次update的方式传入数据,避免一次性申请过大内存。<br/>
2056> 签名使用多次update操作的示例代码详见开发指导“[使用签名验签操作](../../security/cryptoFramework-guidelines.md#使用签名验签操作)”。
2057
2058**系统能力:** SystemCapability.Security.CryptoFramework
2059
2060**参数:**
2061
2062| 参数名 | 类型     | 必填 | 说明       |
2063| ------ | -------- | ---- | ---------- |
2064| data   | [DataBlob](#datablob)  | 是   | 传入的消息。 |
2065
2066**返回值:**
2067
2068| 类型           | 说明          |
2069| -------------- | ------------- |
2070| Promise\<void> | 无返回结果的Promise对象。 |
2071
2072**错误码:**
2073以下错误码的详细介绍请参见[crypto framework错误码](../errorcodes/errorcode-crypto-framework.md)
2074
2075| 错误码ID | 错误信息               |
2076| -------- | ---------------------- |
2077| 401 | invalid parameters.          |
2078| 17620001 | memory error.          |
2079| 17620002 | runtime error.          |
2080| 17630001 | crypto operation error. |
2081
2082### sign
2083
2084sign(data: DataBlob | null, callback: AsyncCallback\<DataBlob>): void
2085
2086对数据进行签名,通过注册回调函数获取签名结果。
2087
2088**系统能力:** SystemCapability.Security.CryptoFramework
2089
2090**参数:**
2091
2092| 参数名   | 类型                 | 必填 | 说明       |
2093| -------- | -------------------- | ---- | ---------- |
2094| data     | [DataBlob](#datablob) \| null<sup>10+</sup>              | 是   | 传入的消息。API 10之前只支持DataBlob, API 10之后增加支持null。 |
2095| callback | AsyncCallback\<[DataBlob](#datablob)> | 是   | 回调函数,用于获取DataBlob数据。 |
2096
2097**错误码:**
2098以下错误码的详细介绍请参见[crypto framework错误码](../errorcodes/errorcode-crypto-framework.md)
2099
2100| 错误码ID | 错误信息               |
2101| -------- | ---------------------- |
2102| 401 | invalid parameters.          |
2103| 17620001 | memory error.          |
2104| 17620002 | runtime error.          |
2105| 17630001 | crypto operation error. |
2106
2107### sign
2108
2109sign(data: DataBlob | null): Promise\<DataBlob>
2110
2111对数据进行签名,通过Promise方式返回签名结果。
2112
2113**系统能力:** SystemCapability.Security.CryptoFramework
2114
2115**参数:**
2116
2117| 参数名 | 类型     | 必填 | 说明       |
2118| ------ | -------- | ---- | ---------- |
2119| data   | [DataBlob](#datablob) \| null<sup>10+</sup>  | 是   | 传入的消息。 |
2120
2121**返回值:**
2122
2123| 类型           | 说明          |
2124| -------------- | ------------- |
2125| Promise\<void> | 无返回结果的Promise对象。 |
2126
2127**错误码:**
2128以下错误码的详细介绍请参见[crypto framework错误码](../errorcodes/errorcode-crypto-framework.md)
2129
2130| 错误码ID | 错误信息               |
2131| -------- | ---------------------- |
2132| 401 | invalid parameters.          |
2133| 17620001 | memory error.          |
2134| 17620002 | runtime error.          |
2135| 17630001 | crypto operation error. |
2136
2137**callback示例:**
2138
2139```ts
2140function stringToUint8Array(str: string) {
2141  let arr = new Uint8Array(str.length);
2142  for (let i = 0, j = str.length; i < j; ++i) {
2143    arr[i] = str.charCodeAt(i);
2144  }
2145  return arr;
2146}
2147
2148let globalKeyPair: cryptoFramework.KeyPair;
2149let signMessageBlob: cryptoFramework.DataBlob;
2150let plan1 = "This is Sign test plan1"; // The first segment of the data.
2151let plan2 = "This is Sign test plan2"; // The second segment of the data.
2152let input1: cryptoFramework.DataBlob = { data: stringToUint8Array(plan1) };
2153let input2: cryptoFramework.DataBlob = { data: stringToUint8Array(plan2) };
2154
2155function signMessageCallback() {
2156  let rsaGenerator = cryptoFramework.createAsyKeyGenerator("RSA1024|PRIMES_2");
2157  let signer = cryptoFramework.createSign("RSA1024|PKCS1|SHA256");
2158  rsaGenerator.generateKeyPair((err, keyPair) => {
2159    globalKeyPair = keyPair;
2160    let priKey = globalKeyPair.priKey;
2161    signer.init(priKey, err => {
2162      signer.update(input1, err => { // add first segment of data
2163        signer.sign(input2, (err, data) => { // add second segment of data, sign input1 and input2
2164          signMessageBlob = data;
2165          AlertDialog.show({message: "res" +  signMessageBlob.data});
2166        });
2167      });
2168    });
2169  });
2170}
2171```
2172
2173**Promise示例:**
2174
2175```ts
2176function stringToUint8Array(str: string) {
2177  let arr = new Uint8Array(str.length);
2178  for (let i = 0, j = str.length; i < j; ++i) {
2179    arr[i] = str.charCodeAt(i);
2180  }
2181  return arr;
2182}
2183
2184let globalKeyPair: cryptoFramework.KeyPair;
2185let signMessageBlob: cryptoFramework.DataBlob;
2186let plan1 = "This is Sign test plan1"; // The first segment of the data.
2187let plan2 = "This is Sign test plan2"; // The second segment of the data.
2188let input1: cryptoFramework.DataBlob = { data: stringToUint8Array(plan1) };
2189let input2: cryptoFramework.DataBlob = { data: stringToUint8Array(plan2) };
2190
2191function signMessagePromise() {
2192  let rsaGenerator = cryptoFramework.createAsyKeyGenerator("RSA1024|PRIMES_2");
2193  let signer = cryptoFramework.createSign("RSA1024|PKCS1|SHA256"); // From API version 10, a Sign instance can be created by specifying a string parameter defining the key specifications.
2194  let keyGenPromise = rsaGenerator.generateKeyPair();
2195  keyGenPromise.then(keyPair => {
2196    globalKeyPair = keyPair;
2197    let priKey = globalKeyPair.priKey;
2198    return signer.init(priKey);
2199  }).then(() => {
2200    return signer.update(input1);
2201  }).then(() => {
2202    return signer.sign(input2);
2203  }).then(dataBlob => {
2204    signMessageBlob = dataBlob;
2205    console.info("sign output is " + signMessageBlob.data);
2206  });
2207}
2208```
2209
2210### setSignSpec<sup>10+</sup>
2211
2212setSignSpec(itemType: SignSpecItem, itemValue: number): void
2213
2214设置签名参数。常用的签名参数可以直接通过[createSign](#cryptoframeworkcreatesign) 来指定,剩余参数可以通过本接口指定。
2215
2216当前只支持RSA算法。
2217
2218**系统能力:** SystemCapability.Security.CryptoFramework
2219
2220**参数:**
2221
2222| 参数名   | 类型                 | 必填 | 说明       |
2223| -------- | -------------------- | ---- | ---------- |
2224| itemType     | [SignSpecItem](#signspecitem10)              | 是   | 用于指定需要设置的签名参数。 |
2225| itemValue | number | 是   | 用于指定签名参数的具体值。 |
2226
2227**错误码:**
2228以下错误码的详细介绍请参见[crypto framework错误码](../errorcodes/errorcode-crypto-framework.md)
2229
2230| 错误码ID | 错误信息               |
2231| -------- | ---------------------- |
2232| 401 | invalid parameters.          |
2233| 801 | this operation is not supported.          |
2234| 17620001 | memory error.          |
2235| 17630001 | crypto operation error. |
2236
2237**示例:**
2238
2239```ts
2240let signer: cryptoFramework.Sign; // The process of generating the Sign instance is omitted here.
2241let setN = 20;
2242signer.setSignSpec(cryptoFramework.SignSpecItem.PSS_SALT_LEN_NUM, setN);
2243```
2244
2245### getSignSpec<sup>10+</sup>
2246
2247getSignSpec(itemType: SignSpecItem): string | number
2248
2249获取签名参数。当前只支持RSA算法。
2250
2251**系统能力:** SystemCapability.Security.CryptoFramework
2252
2253**参数:**
2254
2255| 参数名 | 类型     | 必填 | 说明       |
2256| ------ | -------- | ---- | ---------- |
2257| itemType | [SignSpecItem](#signspecitem10)  | 是   | 用于指定需要获取的签名参数。 |
2258
2259**返回值:**
2260
2261| 类型           | 说明        |
2262| -------------- | ----------- |
2263| string\|number | 获取的签名参数的具体值。 |
2264
2265**错误码:**
2266以下错误码的详细介绍请参见[crypto framework错误码](../errorcodes/errorcode-crypto-framework.md)
2267
2268| 错误码ID | 错误信息               |
2269| -------- | ---------------------- |
2270| 401 | invalid parameters.          |
2271| 801 | this operation is not supported.          |
2272| 17620001 | memory error.          |
2273| 17630001 | crypto operation error. |
2274
2275**示例:**
2276
2277```ts
2278let signer: cryptoFramework.Sign; // The process of generating the Sign instance is omitted here.
2279let saltLen = signer.getSignSpec(cryptoFramework.SignSpecItem.PSS_SALT_LEN_NUM);
2280```
2281
2282## cryptoFramework.createVerify
2283
2284createVerify(algName: string): Verify
2285
2286Verify实例生成。
2287
2288支持的规格详见框架概述“[签名验签规格](../../security/cryptoFramework-overview.md#签名验签规格)”一节。
2289
2290**系统能力:** SystemCapability.Security.CryptoFramework
2291
2292**参数:**
2293
2294| 参数名  | 类型   | 必填 | 说明                                                         |
2295| ------- | ------ | ---- | ------------------------------------------------------------ |
2296| algName | string | 是   | 指定签名算法:RSA,ECC,DSA或SM2<sup>10+</sup>,。使用RSA PKCS1模式时需要设置摘要,使用RSA PSS模式时需要设置摘要和掩码摘要。 |
2297
2298**返回值**:
2299
2300| 类型   | 说明                                 |
2301| ------ | ------------------------------------ |
2302| Verify | 返回由输入算法指定生成的Verify对象。 |
2303
2304**错误码:**
2305以下错误码的详细介绍请参见[crypto framework错误码](../errorcodes/errorcode-crypto-framework.md)
2306
2307| 错误码ID | 错误信息               |
2308| -------- | ---------------------- |
2309| 401 | invalid parameters.          |
2310| 801 | this operation is not supported.          |
2311| 17620001 | memory error.          |
2312
2313**示例:**
2314
2315```ts
2316let verifyer1 = cryptoFramework.createVerify("RSA1024|PKCS1|SHA256");
2317
2318let verifyer2 = cryptoFramework.createVerify("RSA1024|PSS|SHA256|MGF1_SHA256")
2319```
2320
2321## Verify
2322
2323Verify类,使用Verify方法之前需要创建该类的实例进行操作,通过[createVerify(algName: string): Verify](#cryptoframeworkcreateverify)方法构造此实例。按序调用本类中的init、update、verify方法完成签名操作。验签操作的示例代码详见开发指导“[使用签名验签操作](../../security/cryptoFramework-guidelines.md#使用签名验签操作)”。
2324
2325Verify类不支持重复初始化,当业务方需要使用新密钥验签时,需要重新创建新Verify对象并调用init初始化。
2326
2327业务方使用时,在createVerify时确定验签的模式,调用init接口设置密钥。
2328
2329当被签名的消息较短时,可在init初始化后,(无需update)直接调用verify接口传入被签名的消息和签名(signatureData)进行验签。
2330
2331当被签名的消息较长时,可通过update接口分段传入被签名的消息,最后调用verify接口对消息全文进行验签。verify接口的data入参在API 10之前只支持DataBlob, API 10之后增加支持null。业务方可在循环中调用update接口,循环结束后调用verify传入签名(signatureData)进行验签。
2332
2333### 属性
2334
2335**系统能力:** SystemCapability.Security.CryptoFramework
2336
2337| 名称    | 类型   | 可读 | 可写 | 说明                         |
2338| ------- | ------ | ---- | ---- | ---------------------------- |
2339| algName | string | 是   | 否   | 验签指定的算法名称。 |
2340
2341### init
2342
2343init(pubKey: PubKey, callback: AsyncCallback\<void>): void
2344
2345传入公钥初始化Verify对象,通过注册回调函数获取结果。
2346
2347**系统能力:** SystemCapability.Security.CryptoFramework
2348
2349**参数:**
2350
2351| 参数名   | 类型                 | 必填 | 说明                           |
2352| -------- | -------------------- | ---- | ------------------------------ |
2353| pubKey   | [PubKey](#pubkey)    | 是   | 公钥对象,用于Verify的初始化。 |
2354| callback | AsyncCallback\<void> | 是   | 回调函数。当验签初始化成功,err为undefined,否则为错误对象。 |
2355
2356**错误码:**
2357以下错误码的详细介绍请参见[crypto framework错误码](../errorcodes/errorcode-crypto-framework.md)
2358
2359| 错误码ID | 错误信息               |
2360| -------- | ---------------------- |
2361| 401 | invalid parameters.          |
2362| 17620001 | memory error.          |
2363| 17620002 | runtime error.          |
2364| 17630001 | crypto operation error. |
2365
2366### init
2367
2368init(pubKey: PubKey): Promise\<void>
2369
2370传入公钥初始化Verify对象,通过Promise获取结果。
2371
2372**系统能力:** SystemCapability.Security.CryptoFramework
2373
2374**参数:**
2375
2376| 参数名 | 类型 | 必填 | 说明                         |
2377| ------ | ---- | ---- | ---------------------------- |
2378| pubKey | [PubKey](#pubkey)  | 是   | 公钥对象,用于Verify的初始化。 |
2379
2380**返回值:**
2381
2382| 类型           | 说明          |
2383| -------------- | ------------- |
2384| Promise\<void> | 无返回结果的Promise对象。 |
2385
2386**错误码:**
2387以下错误码的详细介绍请参见[crypto framework错误码](../errorcodes/errorcode-crypto-framework.md)
2388
2389| 错误码ID | 错误信息               |
2390| -------- | ---------------------- |
2391| 401 | invalid parameters.          |
2392| 17620001 | memory error.          |
2393| 17620002 | runtime error.          |
2394| 17630001 | crypto operation error. |
2395
2396### update
2397
2398update(data: DataBlob, callback: AsyncCallback\<void>): void
2399
2400追加待验签数据,通过注册回调函数完成更新。
2401
2402必须在对[Verify](#verify)实例使用[init()](#init-4)初始化后,才能使用本函数。
2403
2404> **说明:**
2405>
2406> 根据数据量,可以不调用update(即[init](#init-4)完成后直接调用[verify](#verify-1))或多次调用update。<br/>
2407> 算法库目前没有对update(单次或累计)的数据量设置大小限制,建议对于大数据量的验签操作,采用多次update的方式传入数据,避免一次性申请过大内存。<br/>
2408> 验签使用多次update操作的示例代码详见开发指导“[使用签名验签操作](../../security/cryptoFramework-guidelines.md#使用签名验签操作)”。
2409
2410**系统能力:** SystemCapability.Security.CryptoFramework
2411
2412**参数:**
2413
2414| 参数名   | 类型                  | 必填 | 说明         |
2415| -------- | --------------------- | ---- | ------------ |
2416| data     | [DataBlob](#datablob) | 是   | 传入的消息。 |
2417| callback | AsyncCallback\<void>  | 是   | 回调函数。当验签更新成功,err为undefined,否则为错误对象。 |
2418
2419**错误码:**
2420以下错误码的详细介绍请参见[crypto framework错误码](../errorcodes/errorcode-crypto-framework.md)
2421
2422| 错误码ID | 错误信息               |
2423| -------- | ---------------------- |
2424| 401 | invalid parameters.          |
2425| 17620001 | memory error.          |
2426| 17620002 | runtime error.          |
2427| 17630001 | crypto operation error. |
2428
2429### update
2430
2431update(data: DataBlob): Promise\<void>
2432
2433追加待验签数据,通过Promise方式完成更新。
2434
2435必须在对[Verify](#verify)实例使用[init()](#init-5)初始化后,才能使用本函数。
2436
2437> **说明:**
2438>
2439> 根据数据量,可以不调用update(即[init](#init-5)完成后直接调用[verify](#verify-2))或多次调用update。<br/>
2440> 算法库目前没有对update(单次或累计)的数据量设置大小限制,建议对于大数据量的验签操作,采用多次update的方式传入数据,避免一次性申请过大内存。<br/>
2441> 验签使用多次update操作的示例代码详见开发指导“[使用签名验签操作](../../security/cryptoFramework-guidelines.md#使用签名验签操作)”。
2442
2443**系统能力:** SystemCapability.Security.CryptoFramework
2444
2445**参数:**
2446
2447| 参数名 | 类型     | 必填 | 说明       |
2448| ------ | -------- | ---- | ---------- |
2449| data   | [DataBlob](#datablob)  | 是   | 传入的消息。 |
2450
2451**返回值:**
2452
2453| 类型           | 说明          |
2454| -------------- | ------------- |
2455| Promise\<void> | 无返回结果的Promise对象。 |
2456
2457**错误码:**
2458以下错误码的详细介绍请参见[crypto framework错误码](../errorcodes/errorcode-crypto-framework.md)
2459
2460| 错误码ID | 错误信息               |
2461| -------- | ---------------------- |
2462| 401 | invalid parameters.          |
2463| 17620001 | memory error.          |
2464| 17620002 | runtime error.          |
2465| 17630001 | crypto operation error. |
2466
2467### verify
2468
2469verify(data: DataBlob | null, signatureData: DataBlob, callback: AsyncCallback\<boolean>): void
2470
2471对数据进行验签,通过注册回调函数返回返回验签结果。
2472
2473**系统能力:** SystemCapability.Security.CryptoFramework
2474
2475**参数:**
2476
2477| 参数名        | 类型                 | 必填 | 说明       |
2478| ------------- | -------------------- | ---- | ---------- |
2479| data          | [DataBlob](#datablob) \| null<sup>10+</sup>             | 是   | 传入的消息。API 10之前只支持DataBlob, API 10之后增加支持null。 |
2480| signatureData | [DataBlob](#datablob)              | 是   | 签名数据。  |
2481| callback      | AsyncCallback\<boolean> | 是   | 回调函数,用于获取以boolean值表示的验签结果。 |
2482
2483**错误码:**
2484以下错误码的详细介绍请参见[crypto framework错误码](../errorcodes/errorcode-crypto-framework.md)
2485
2486| 错误码ID | 错误信息               |
2487| -------- | ---------------------- |
2488| 401 | invalid parameters.          |
2489| 17620001 | memory error.          |
2490| 17620002 | runtime error.          |
2491| 17630001 | crypto operation error. |
2492
2493### verify
2494
2495verify(data: DataBlob | null, signatureData: DataBlob): Promise\<boolean>
2496
2497对数据进行验签,通过Promise返回验签结果。
2498
2499**系统能力:** SystemCapability.Security.CryptoFramework
2500
2501**参数:**
2502
2503| 参数名        | 类型     | 必填 | 说明       |
2504| ------------- | -------- | ---- | ---------- |
2505| data          | [DataBlob](#datablob) \| null<sup>10+</sup>  | 是   | 传入的消息。API 10之前只支持DataBlob, API 10之后增加支持null。 |
2506| signatureData | [DataBlob](#datablob)  | 是   | 签名数据。  |
2507
2508**返回值:**
2509
2510| 类型              | 说明                           |
2511| ----------------- | ------------------------------ |
2512| Promise\<boolean> | 异步返回值,代表验签是否通过。 |
2513
2514**错误码:**
2515以下错误码的详细介绍请参见[crypto framework错误码](../errorcodes/errorcode-crypto-framework.md)
2516
2517| 错误码ID | 错误信息               |
2518| -------- | ---------------------- |
2519| 401 | invalid parameters.          |
2520| 17620001 | memory error.          |
2521| 17620002 | runtime error.          |
2522| 17630001 | crypto operation error. |
2523
2524**callback示例:**
2525
2526```ts
2527let globalKeyPair: cryptoFramework.KeyPair; // globalKeyPair is an asymmetric key object generated by the asymmetric key generator. The generation process is omitted here.
2528let input1: cryptoFramework.DataBlob;
2529let input2: cryptoFramework.DataBlob;
2530let signMessageBlob: cryptoFramework.DataBlob;// Signed data, which is omitted here.
2531let verifyer = cryptoFramework.createVerify("RSA1024|PKCS1|SHA256");
2532verifyer.init(globalKeyPair.pubKey, (err, data) => {
2533  verifyer.update(input1, (err, data) => {
2534    verifyer.verify(input2, signMessageBlob, (err, data) => {
2535      console.info("verify result is " + data);
2536    })
2537  });
2538})
2539```
2540
2541**Promise示例:**
2542
2543```ts
2544let globalKeyPair: cryptoFramework.KeyPair; // globalKeyPair is an asymmetric key object generated by the asymmetric key generator. The generation process is omitted here.
2545let verifyer = cryptoFramework.createVerify("RSA1024|PKCS1|SHA256");
2546let verifyInitPromise = verifyer.init(globalKeyPair.pubKey);
2547let input1: cryptoFramework.DataBlob;;
2548let input2: cryptoFramework.DataBlob;;
2549let signMessageBlob: cryptoFramework.DataBlob;; // Signed data, which is omitted here.
2550verifyInitPromise.then((): Promise<void> => {
2551  return verifyer.update(input1);
2552}).then(() => {
2553  return verifyer.verify(input2, signMessageBlob);
2554}).then(res => {
2555  console.log("Verify result is " + res);
2556});
2557```
2558
2559### setVerifySpec<sup>10+</sup>
2560
2561setVerifySpec(itemType: SignSpecItem, itemValue: number): void
2562
2563设置验签参数。常用的签名参数可以直接通过[createVerify](#cryptoframeworkcreateverify) 来指定,剩余参数可以通过本接口指定。当前只支持RSA算法。
2564
2565验签的参数应当与签名的参数保持一致。
2566
2567**系统能力:** SystemCapability.Security.CryptoFramework
2568
2569**参数:**
2570
2571| 参数名   | 类型                 | 必填 | 说明       |
2572| -------- | -------------------- | ---- | ---------- |
2573| itemType     | [SignSpecItem](#signspecitem10)              | 是   | 用于指定需要设置的验签参数。 |
2574| itemValue | number | 是   | 用于指定验签参数的具体值。 |
2575
2576**错误码:**
2577以下错误码的详细介绍请参见[crypto framework错误码](../errorcodes/errorcode-crypto-framework.md)
2578
2579| 错误码ID | 错误信息               |
2580| -------- | ---------------------- |
2581| 401 | invalid parameters.          |
2582| 801 | this operation is not supported.          |
2583| 17620001 | memory error.          |
2584| 17630001 | crypto operation error. |
2585
2586**示例:**
2587
2588```ts
2589let verifyer: cryptoFramework.Verify; //The process of generating the Verify instance is omitted here.
2590let setN = 20;
2591verifyer.setVerifySpec(cryptoFramework.SignSpecItem.PSS_SALT_LEN_NUM, setN);
2592```
2593
2594### getVerifySpec<sup>10+</sup>
2595
2596getVerifySpec(itemType: SignSpecItem): string | number
2597
2598获取验签参数。当前只支持RSA算法。
2599
2600验签的参数应当与签名的参数保持一致。
2601
2602**系统能力:** SystemCapability.Security.CryptoFramework
2603
2604**参数:**
2605
2606| 参数名 | 类型     | 必填 | 说明       |
2607| ------ | -------- | ---- | ---------- |
2608| itemType   | [SignSpecItem](#signspecitem10)  | 是   | 用于指定需要获取的验签参数。 |
2609
2610**返回值:**
2611
2612| 类型           | 说明        |
2613| -------------- | ----------- |
2614| string\|number | 获取的验签参数的具体值。 |
2615
2616**错误码:**
2617以下错误码的详细介绍请参见[crypto framework错误码](../errorcodes/errorcode-crypto-framework.md)
2618
2619| 错误码ID | 错误信息               |
2620| -------- | ---------------------- |
2621| 401 | invalid parameters.          |
2622| 801 | this operation is not supported.          |
2623| 17620001 | memory error.          |
2624| 17630001 | crypto operation error. |
2625
2626**示例:**
2627
2628```ts
2629let verifyer: cryptoFramework.Verify; //The process of generating the Verify instance is omitted here.
2630let saltLen = verifyer.getVerifySpec(cryptoFramework.SignSpecItem.PSS_SALT_LEN_NUM);
2631```
2632
2633## cryptoFramework.createKeyAgreement
2634
2635createKeyAgreement(algName: string): KeyAgreement
2636
2637KeyAgreement实例生成。
2638
2639支持的规格详见框架概述“[密钥协商规格](../../security/cryptoFramework-overview.md#密钥协商规格)”一节。
2640
2641**系统能力:** SystemCapability.Security.CryptoFramework
2642
2643**参数:**
2644
2645| 参数名  | 类型   | 必填 | 说明                              |
2646| ------- | ------ | ---- | --------------------------------- |
2647| algName | string | 是   | 指定密钥协商算法:目前仅支持ECC。 |
2648
2649**返回值**:
2650
2651| 类型         | 说明                                       |
2652| ------------ | ------------------------------------------ |
2653| KeyAgreement | 返回由输入算法指定生成的KeyAgreement对象。 |
2654
2655**错误码:**
2656以下错误码的详细介绍请参见[crypto framework错误码](../errorcodes/errorcode-crypto-framework.md)
2657
2658| 错误码ID | 错误信息               |
2659| -------- | ---------------------- |
2660| 401 | invalid parameters.          |
2661| 801 | this operation is not supported.          |
2662| 17620001 | memory error.          |
2663
2664**示例:**
2665
2666```ts
2667let keyAgreement = cryptoFramework.createKeyAgreement("ECC256");
2668
2669```
2670
2671## KeyAgreement
2672
2673KeyAgreement类,使用密钥协商方法之前需要创建该类的实例进行操作,通过[createKeyAgreement(algName: string): KeyAgreement](#cryptoframeworkcreatekeyagreement)方法构造此实例。
2674
2675### 属性
2676
2677**系统能力:** SystemCapability.Security.CryptoFramework
2678
2679| 名称    | 类型   | 可读 | 可写 | 说明                         |
2680| ------- | ------ | ---- | ---- | ---------------------------- |
2681| algName | string | 是   | 否   | 密钥协商指定的算法名称。 |
2682
2683### generateSecret
2684
2685generateSecret(priKey: PriKey, pubKey: PubKey, callback: AsyncCallback\<DataBlob>): void
2686
2687基于传入的私钥与公钥进行密钥协商,通过注册回调函数返回共享秘密。
2688
2689**系统能力:** SystemCapability.Security.CryptoFramework
2690
2691**参数:**
2692
2693| 参数名   | 类型                     | 必填 | 说明                   |
2694| -------- | ------------------------ | ---- | ---------------------- |
2695| priKey   | [PriKey](#prikey)        | 是   | 设置密钥协商的私钥输入。 |
2696| pubKey   | [PubKey](#pubkey)        | 是   | 设置密钥协商的公钥输入。 |
2697| callback | AsyncCallback\<[DataBlob](#datablob)> | 是   | 异步接受共享秘密的回调。 |
2698
2699**错误码:**
2700以下错误码的详细介绍请参见[crypto framework错误码](../errorcodes/errorcode-crypto-framework.md)
2701
2702| 错误码ID | 错误信息               |
2703| -------- | ---------------------- |
2704| 401 | invalid parameters.          |
2705| 17620001 | memory error.          |
2706| 17620002 | runtime error.          |
2707| 17630001 | crypto operation error. |
2708
2709### generateSecret
2710
2711generateSecret(priKey: PriKey, pubKey: PubKey): Promise\<DataBlob>
2712
2713基于传入的私钥与公钥进行密钥协商,通过Promise返回共享秘密。
2714
2715**系统能力:** SystemCapability.Security.CryptoFramework
2716
2717**参数:**
2718
2719| 参数名 | 类型   | 必填 | 说明                   |
2720| ------ | ------ | ---- | ---------------------- |
2721| priKey | [PriKey](#prikey) | 是   | 设置密钥协商的私钥输入。 |
2722| pubKey | [PubKey](#pubkey) | 是   | 设置密钥协商的公钥输入。 |
2723
2724**返回值:**
2725
2726| 类型               | 说明     |
2727| ------------------ | -------- |
2728| Promise\<[DataBlob](#datablob)> | 共享秘密。 |
2729
2730**错误码:**
2731以下错误码的详细介绍请参见[crypto framework错误码](../errorcodes/errorcode-crypto-framework.md)
2732
2733| 错误码ID | 错误信息               |
2734| -------- | ---------------------- |
2735| 401 | invalid parameters.          |
2736| 17620001 | memory error.          |
2737| 17620002 | runtime error.          |
2738| 17630001 | crypto operation error. |
2739
2740**callback示例:**
2741
2742```ts
2743import { BusinessError } from '@ohos.base';
2744
2745let globalKeyPair: cryptoFramework.KeyPair; // globalKeyPair is an asymmetric key object generated by the asymmetric key generator. The generation process is omitted here.
2746let keyAgreement = cryptoFramework.createKeyAgreement("ECC256");
2747keyAgreement.generateSecret(globalKeyPair.priKey, globalKeyPair.pubKey, (err, secret) => {
2748  if (err) {
2749    console.error("keyAgreement error.");
2750    return;
2751  }
2752  console.info("keyAgreement output is " + secret.data);
2753});
2754```
2755
2756**Promise示例:**
2757
2758```ts
2759import { BusinessError } from '@ohos.base';
2760
2761let globalKeyPair: cryptoFramework.KeyPair; // globalKeyPair is an asymmetric key object generated by the asymmetric key generator. The generation process is omitted here.
2762let keyAgreement = cryptoFramework.createKeyAgreement("ECC256");
2763let keyAgreementPromise = keyAgreement.generateSecret(globalKeyPair.priKey, globalKeyPair.pubKey);
2764keyAgreementPromise.then((secret) => {
2765  console.info("keyAgreement output is " + secret.data);
2766}).catch((error: BusinessError) => {
2767  console.error("keyAgreement error.");
2768});
2769```
2770
2771## cryptoFramework.createMd
2772
2773createMd(algName: string): Md
2774
2775生成Md实例,用于进行消息摘要的计算与操作。
2776
2777支持的规格详见框架概述“[MD消息摘要算法规格](../../security/cryptoFramework-overview.md#md消息摘要算法规格)”一节。
2778
2779**系统能力:** SystemCapability.Security.CryptoFramework
2780
2781**参数:**
2782
2783| 参数名  | 类型   | 必填 | 说明                                                         |
2784| ------- | ------ | ---- | ------------------------------------------------------------ |
2785| algName | string | 是   | 指定摘要算法,支持算法请参考“[MD算法支持范围](../../security/cryptoFramework-overview.md#md消息摘要算法规格)”一节。 |
2786
2787**返回值**:
2788
2789| 类型 | 说明                                    |
2790| ---- | --------------------------------------- |
2791| Md   | 返回由输入算法指定生成的[Md](#md)对象。 |
2792
2793**错误码:**
2794以下错误码的详细介绍请参见[crypto framework错误码](../errorcodes/errorcode-crypto-framework.md)
2795
2796| 错误码ID | 错误信息           |
2797| -------- | ------------------ |
2798| 401 | invalid parameters.       |
2799| 17620001 | memory error.       |
2800
2801**示例:**
2802
2803```ts
2804import { BusinessError } from '@ohos.base';
2805
2806try {
2807  // Set algName based on the algorithm supported.
2808  let md = cryptoFramework.createMd("SHA256");
2809} catch (error) {
2810  let e: BusinessError = error as BusinessError;
2811  console.error(`sync error, ${e.code}, ${e.message}`);
2812}
2813```
2814
2815## Md
2816
2817Md类,调用Md方法可以进行MD(Message Digest)摘要计算。调用前,需要通过[createMd](#cryptoframeworkcreatemd)构造Md实例。
2818
2819### 属性
2820
2821**系统能力:** SystemCapability.Security.CryptoFramework
2822
2823| 名称    | 类型   | 可读 | 可写 | 说明                   |
2824| ------- | ------ | ---- | ---- | ---------------------- |
2825| algName | string | 是   | 否   | 代表指定的摘要算法名。 |
2826
2827### update
2828
2829update(input: DataBlob, callback: AsyncCallback\<void>): void
2830
2831传入消息进行Md更新计算,通过注册回调函数更新。
2832
2833> **说明:**
2834>
2835> Md算法多次调用update更新的代码示例详见开发指导“[使用摘要操作](../../security/cryptoFramework-guidelines.md#使用摘要操作)”。
2836
2837**系统能力:** SystemCapability.Security.CryptoFramework
2838
2839**参数:**
2840
2841| 参数名   | 类型                  | 必填 | 说明         |
2842| -------- | --------------------- | ---- | ------------ |
2843| input    | [DataBlob](#datablob) | 是   | 传入的消息。 |
2844| callback | AsyncCallback\<void>  | 是   | 回调函数。当摘要更新成功,err为undefined,否则为错误对象。 |
2845
2846**错误码:**
2847以下错误码的详细介绍请参见[crypto framework错误码](../errorcodes/errorcode-crypto-framework.md)
2848
2849| 错误码ID | 错误信息               |
2850| -------- | ---------------------- |
2851| 401 | invalid parameters.       |
2852| 17630001 | crypto operation error. |
2853
2854**示例:**
2855
2856```ts
2857import { BusinessError } from '@ohos.base';
2858
2859let md = cryptoFramework.createMd("SHA256");
2860console.info("Md algName is: " + md.algName);
2861
2862let blob: cryptoFramework.DataBlob;
2863md.update(blob, (err,) => {
2864  if (err) {
2865    console.error("[Callback] err: " + err.code);
2866  }
2867});
2868```
2869
2870### update
2871
2872update(input: DataBlob): Promise\<void>
2873
2874传入消息进行Md更新计算,通过Promise更新。
2875
2876> **说明:**
2877>
2878> Md算法多次调用update更新的代码示例详见开发指导“[使用摘要操作](../../security/cryptoFramework-guidelines.md#使用摘要操作)”。
2879
2880**系统能力:** SystemCapability.Security.CryptoFramework
2881
2882| 参数名 | 类型     | 必填 | 说明         |
2883| ------ | -------- | ---- | ------------ |
2884| input  | DataBlob | 是   | 传入的消息。 |
2885
2886**返回值:**
2887
2888| 类型           | 说明          |
2889| -------------- | ------------- |
2890| Promise\<void> | 无返回结果的Promise对象。 |
2891
2892**错误码:**
2893以下错误码的详细介绍请参见[crypto framework错误码](../errorcodes/errorcode-crypto-framework.md)
2894
2895| 错误码ID | 错误信息               |
2896| -------- | ---------------------- |
2897| 401 | invalid parameters.       |
2898| 17630001 | crypto operation error. |
2899
2900**示例:**
2901
2902```ts
2903import { BusinessError } from '@ohos.base';
2904
2905let md = cryptoFramework.createMd("SHA256");
2906console.info("Md algName is: " + md.algName);
2907
2908let blob: cryptoFramework.DataBlob;
2909let promiseMdUpdate = md.update(blob);
2910promiseMdUpdate.then(() => {
2911  // do something
2912}).catch((error: BusinessError) => {
2913  console.error("[Promise]: error: " + error.message);
2914});
2915```
2916
2917### digest
2918
2919digest(callback: AsyncCallback\<DataBlob>): void
2920
2921通过注册回调函数返回Md的计算结果。
2922
2923**系统能力:** SystemCapability.Security.CryptoFramework
2924
2925| 参数名   | 类型                     | 必填 | 说明       |
2926| -------- | ------------------------ | ---- | ---------- |
2927| callback | AsyncCallback\<[DataBlob](#datablob)> | 是   | 回调函数,用于获取DataBlob数据。 |
2928
2929**错误码:**
2930以下错误码的详细介绍请参见[crypto framework错误码](../errorcodes/errorcode-crypto-framework.md)
2931
2932| 错误码ID | 错误信息               |
2933| -------- | ---------------------- |
2934| 17620001 | memory error.           |
2935| 17630001 | crypto operation error. |
2936
2937**示例:**
2938
2939```ts
2940import { BusinessError } from '@ohos.base';
2941
2942let md = cryptoFramework.createMd("SHA256");
2943console.info("Md algName is: " + md.algName);
2944
2945let blob: cryptoFramework.DataBlob;
2946md.update(blob, (err,) => {
2947  if (err) {
2948    console.error("[Callback] err: " + err.code);
2949  }
2950  md.digest((err1, mdOutput) => {
2951    if (err1) {
2952      console.error("[Callback] err: " + err1.code);
2953    } else {
2954      console.error("[Callback]: MD result: " + mdOutput);
2955    }
2956  });
2957});
2958```
2959
2960### digest
2961
2962digest(): Promise\<DataBlob>
2963
2964通过Promise返回Md的计算结果。
2965
2966**系统能力:** SystemCapability.Security.CryptoFramework
2967
2968**返回值:**
2969
2970| 类型               | 说明        |
2971| ------------------ | ----------- |
2972| Promise\<[DataBlob](#datablob)> | Promise对象。 |
2973
2974**错误码:**
2975以下错误码的详细介绍请参见[crypto framework错误码](../errorcodes/errorcode-crypto-framework.md)
2976
2977| 错误码ID | 错误信息               |
2978| -------- | ---------------------- |
2979| 17620001 | memory error.           |
2980| 17630001 | crypto operation error. |
2981
2982**示例:**
2983
2984```ts
2985import { BusinessError } from '@ohos.base';
2986
2987let md = cryptoFramework.createMd("SHA256");
2988console.info("Md algName is: " + md.algName);
2989
2990let blob: cryptoFramework.DataBlob;
2991let promiseMdUpdate = md.update(blob);
2992promiseMdUpdate.then(() => {
2993  let promiseMdDigest = md.digest();
2994  return promiseMdDigest;
2995}).then(mdOutput => {
2996  console.error("[Promise]: MD result: " + mdOutput.data);
2997}).catch((error: BusinessError) => {
2998  console.error("[Promise]: error: " + error.message);
2999});
3000```
3001
3002### getMdLength
3003
3004getMdLength(): number
3005
3006获取Md消息摘要长度(字节数)。
3007
3008**系统能力:** SystemCapability.Security.CryptoFramework
3009
3010**返回值:**
3011
3012| 类型   | 说明                       |
3013| ------ | -------------------------- |
3014| number | 返回md计算结果的字节长度。 |
3015
3016**错误码:**
3017以下错误码的详细介绍请参见[crypto framework错误码](../errorcodes/errorcode-crypto-framework.md)
3018
3019| 错误码ID | 错误信息               |
3020| -------- | ---------------------- |
3021| 17630001 | crypto operation error. |
3022
3023**示例:**
3024
3025```ts
3026import { BusinessError } from '@ohos.base';
3027
3028let md = cryptoFramework.createMd("SHA256");
3029console.info("Md algName is: " + md.algName);
3030
3031let blob: cryptoFramework.DataBlob;
3032let promiseMdUpdate = md.update(blob);
3033promiseMdUpdate.then(() => {
3034  let promiseMdDigest = md.digest();
3035  return promiseMdDigest;
3036}).then(mdOutput => {
3037  console.error("[Promise]: MD result: " + mdOutput.data);
3038  let mdLen = md.getMdLength();
3039  console.error("MD len: " + mdLen);
3040}).catch((error: BusinessError) => {
3041  console.error("[Promise]: error: " + error.message);
3042});
3043```
3044
3045## cryptoFramework.createMac
3046
3047createMac(algName: string): Mac
3048
3049生成Mac实例,用于进行消息认证码的计算与操作。
3050
3051支持的规格详见框架概述“[HMAC消息认证码算法规格](../../security/cryptoFramework-overview.md#hmac消息认证码算法规格)”一节。
3052
3053**系统能力:** SystemCapability.Security.CryptoFramework
3054
3055**参数:**
3056
3057| 参数名  | 类型   | 必填 | 说明                                                         |
3058| ------- | ------ | ---- | ------------------------------------------------------------ |
3059| algName | string | 是   | 指定摘要算法,支持算法请参考“[HMAC算法支持范围](../../security/cryptoFramework-overview.md#hmac消息认证码算法规格)”一节。 |
3060
3061**返回值**:
3062
3063| 类型 | 说明                                      |
3064| ---- | ----------------------------------------- |
3065| Mac  | 返回由输入算法指定生成的[Mac](#mac)对象。 |
3066
3067**错误码:**
3068以下错误码的详细介绍请参见[crypto framework错误码](../errorcodes/errorcode-crypto-framework.md)
3069
3070| 错误码ID | 错误信息           |
3071| -------- | ------------------ |
3072| 401 | invalid parameters.       |
3073| 17620001 | memory error.       |
3074
3075**示例:**
3076
3077```ts
3078import { BusinessError } from '@ohos.base';
3079
3080try {
3081  // Set algName based on the algorithm supported.
3082  let mac = cryptoFramework.createMac("SHA256");
3083} catch (error) {
3084  let e: BusinessError = error as BusinessError;
3085  console.error(`sync error, ${e.code}, ${e.message}`);
3086}
3087```
3088
3089## Mac
3090
3091Mac类,调用Mac方法可以进行MAC(Message Authentication Code)加密计算。调用前,需要通过[createMac](#cryptoframeworkcreatemac)构造Mac实例。
3092
3093### 属性
3094
3095**系统能力:** SystemCapability.Security.CryptoFramework
3096
3097| 名称    | 类型   | 可读 | 可写 | 说明                   |
3098| ------- | ------ | ---- | ---- | ---------------------- |
3099| algName | string | 是   | 否   | 代表指定的摘要算法名。 |
3100
3101### init
3102
3103init(key: SymKey, callback: AsyncCallback\<void>): void
3104
3105使用对称密钥初始化Mac计算,通过注册回调函数获取结果。
3106
3107**系统能力:** SystemCapability.Security.CryptoFramework
3108
3109**参数:**
3110
3111| 参数名   | 类型                 | 必填 | 说明           |
3112| -------- | -------------------- | ---- | -------------- |
3113| key      | [SymKey](#symkey)    | 是   | 共享对称密钥。 |
3114| callback | AsyncCallback\<void> | 是   | 回调函数。当HMAC初始化成功,err为undefined,否则为错误对象。 |
3115
3116**错误码:**
3117以下错误码的详细介绍请参见[crypto framework错误码](../errorcodes/errorcode-crypto-framework.md)
3118
3119| 错误码ID | 错误信息               |
3120| -------- | ---------------------- |
3121| 401 | invalid parameters.       |
3122| 17630001 | crypto operation error. |
3123
3124**示例:**
3125
3126```ts
3127import { BusinessError } from '@ohos.base';
3128
3129let mac = cryptoFramework.createMac("SHA256");
3130let keyBlob: cryptoFramework.DataBlob;
3131let symKeyGenerator = cryptoFramework.createSymKeyGenerator("AES128");
3132symKeyGenerator.convertKey(keyBlob, (err, symKey) => {
3133  if (err) {
3134    console.error("[Callback] err: " + err.code);
3135  }
3136  mac.init(symKey, (err1, ) => {
3137    if (err1) {
3138      console.error("[Callback] err: " + err1.code);
3139    }
3140  });
3141});
3142```
3143
3144### init
3145
3146init(key: SymKey): Promise\<void>
3147
3148使用对称密钥初始化Mac计算,通过Promise获取结果。
3149
3150**系统能力:** SystemCapability.Security.CryptoFramework
3151
3152**参数:**
3153
3154| 参数名 | 类型   | 必填 | 说明         |
3155| ------ | ------ | ---- | ------------ |
3156| key    | [SymKey](#symkey) | 是   | 共享对称密钥。 |
3157
3158**返回值:**
3159
3160| 类型           | 说明          |
3161| -------------- | ------------- |
3162| Promise\<void> | 无返回结果的Promise对象。 |
3163
3164**错误码:**
3165以下错误码的详细介绍请参见[crypto framework错误码](../errorcodes/errorcode-crypto-framework.md)
3166
3167| 错误码ID | 错误信息               |
3168| -------- | ---------------------- |
3169| 401 | invalid parameters.       |
3170| 17630001 | crypto operation error. |
3171
3172**示例:**
3173
3174```ts
3175import { BusinessError } from '@ohos.base';
3176
3177let mac = cryptoFramework.createMac("SHA256");
3178console.info("Mac algName is: " + mac.algName);
3179
3180let keyBlob: cryptoFramework.DataBlob;
3181let symKeyGenerator = cryptoFramework.createSymKeyGenerator("AES128");
3182let promiseConvertKey = symKeyGenerator.convertKey(keyBlob);
3183promiseConvertKey.then(symKey => {
3184  let promiseMacInit = mac.init(symKey);
3185  return promiseMacInit;
3186}).catch((error: BusinessError) => {
3187  console.error("[Promise]: error: " + error.message);
3188});
3189
3190```
3191
3192### update
3193
3194update(input: DataBlob, callback: AsyncCallback\<void>): void
3195
3196传入消息进行Mac更新计算,通过注册回调函数获取结果。
3197
3198> **说明:**
3199>
3200> Hmac算法多次调用update更新的代码示例详见开发指导“[使用消息认证码操作](../../security/cryptoFramework-guidelines.md#使用消息认证码操作)”。
3201
3202**系统能力:** SystemCapability.Security.CryptoFramework
3203
3204**参数:**
3205
3206| 参数名   | 类型                  | 必填 | 说明         |
3207| -------- | --------------------- | ---- | ------------ |
3208| input    | [DataBlob](#datablob) | 是   | 传入的消息。 |
3209| callback | AsyncCallback\<void>  | 是   | 回调函数。当HMAC更新成功,err为undefined,否则为错误对象。 |
3210
3211**错误码:**
3212以下错误码的详细介绍请参见[crypto framework错误码](../errorcodes/errorcode-crypto-framework.md)
3213
3214| 错误码ID | 错误信息               |
3215| -------- | ---------------------- |
3216| 401 | invalid parameters.       |
3217| 17630001 | crypto operation error. |
3218
3219**示例:**
3220
3221```ts
3222import { BusinessError } from '@ohos.base';
3223
3224let keyBlob: cryptoFramework.DataBlob;
3225let mac = cryptoFramework.createMac("SHA256");
3226let symKeyGenerator = cryptoFramework.createSymKeyGenerator("AES128");
3227symKeyGenerator.convertKey(keyBlob, (err, symKey) => {
3228  if (err) {
3229    console.error("[Callback] err: " + err.code);
3230  }
3231  mac.init(symKey, (err1, ) => {
3232    if (err1) {
3233      console.error("[Callback] err: " + err1.code);
3234    }
3235    let blob: cryptoFramework.DataBlob;
3236    mac.update(blob, (err2, data) => {
3237      if (err2) {
3238        console.error("[Callback] err: " + err2.code);
3239      }
3240    });
3241  });
3242});
3243```
3244
3245### update
3246
3247update(input: DataBlob): Promise\<void>
3248
3249传入消息进行Mac更新计算,通过Promise获取结果。
3250
3251> **说明:**
3252>
3253> Hmac算法多次调用update更新的代码示例详见开发指导“[使用消息认证码操作](../../security/cryptoFramework-guidelines.md#使用消息认证码操作)”。
3254
3255**系统能力:** SystemCapability.Security.CryptoFramework
3256
3257**参数:**
3258
3259| 参数名 | 类型     | 必填 | 说明       |
3260| ------ | -------- | ---- | ---------- |
3261| input  | [DataBlob](#datablob) | 是   | 传入的消息。 |
3262
3263**返回值:**
3264
3265| 类型           | 说明          |
3266| -------------- | ------------- |
3267| Promise\<void> | 无返回结果的Promise对象。 |
3268
3269**错误码:**
3270以下错误码的详细介绍请参见[crypto framework错误码](../errorcodes/errorcode-crypto-framework.md)
3271
3272| 错误码ID | 错误信息               |
3273| -------- | ---------------------- |
3274| 401 | invalid parameters.       |
3275| 17630001 | crypto operation error. |
3276
3277**示例:**
3278
3279```ts
3280import { BusinessError } from '@ohos.base';
3281
3282let mac = cryptoFramework.createMac("SHA256");
3283console.info("Mac algName is: " + mac.algName);
3284
3285let keyBlob: cryptoFramework.DataBlob;
3286let symKeyGenerator = cryptoFramework.createSymKeyGenerator("AES128");
3287let promiseConvertKey = symKeyGenerator.convertKey(keyBlob);
3288promiseConvertKey.then(symKey => {
3289  let promiseMacInit = mac.init(symKey);
3290  return promiseMacInit;
3291}).then(() => {
3292  let blob: cryptoFramework.DataBlob;
3293  let promiseMacUpdate = mac.update(blob);
3294  return promiseMacUpdate;
3295}).catch((error: BusinessError) => {
3296  console.error("[Promise]: error: " + error.message);
3297});
3298
3299```
3300
3301### doFinal
3302
3303doFinal(callback: AsyncCallback\<DataBlob>): void
3304
3305通过注册回调函数返回Mac的计算结果。
3306
3307**系统能力:** SystemCapability.Security.CryptoFramework
3308
3309**参数:**
3310
3311| 参数名   | 类型                     | 必填 | 说明     |
3312| -------- | ------------------------ | ---- | -------- |
3313| callback | AsyncCallback\<[DataBlob](#datablob)> | 是   | 回调函数,用于获取DataBlob数据。 |
3314
3315**错误码:**
3316以下错误码的详细介绍请参见[crypto framework错误码](../errorcodes/errorcode-crypto-framework.md)
3317
3318| 错误码ID | 错误信息               |
3319| -------- | ---------------------- |
3320| 17620001 | memory error.           |
3321| 17630001 | crypto operation error. |
3322
3323**示例:**
3324
3325```ts
3326import { BusinessError } from '@ohos.base';
3327
3328let keyBlob: cryptoFramework.DataBlob;
3329let mac = cryptoFramework.createMac("SHA256");
3330let symKeyGenerator = cryptoFramework.createSymKeyGenerator("AES128");
3331symKeyGenerator.convertKey(keyBlob, (err, symKey) => {
3332  if (err) {
3333    console.error("[Callback] err: " + err.code);
3334  }
3335  mac.init(symKey, (err1, ) => {
3336    if (err1) {
3337      console.error("[Callback] err: " + err1.code);
3338    }
3339    let blob: cryptoFramework.DataBlob;
3340    mac.update(blob, (err2, ) => {
3341      if (err2) {
3342        console.error("[Callback] err: " + err2.code);
3343      }
3344      mac.doFinal((err3, macOutput) => {
3345        if (err3) {
3346          console.error("[Callback] err: " + err3.code);
3347        } else {
3348          console.error("[Promise]: HMAC result: " + macOutput);
3349        }
3350      });
3351    });
3352  });
3353});
3354```
3355
3356### doFinal
3357
3358doFinal(): Promise\<DataBlob>
3359
3360通过Promise返回Mac的计算结果。
3361
3362**系统能力:** SystemCapability.Security.CryptoFramework
3363
3364**返回值:**
3365
3366| 类型               | 说明        |
3367| ------------------ | ----------- |
3368| Promise\<[DataBlob](#datablob)> | Promise对象。 |
3369
3370**错误码:**
3371以下错误码的详细介绍请参见[crypto framework错误码](../errorcodes/errorcode-crypto-framework.md)
3372
3373| 错误码ID | 错误信息               |
3374| -------- | ---------------------- |
3375| 17620001 | memory error.           |
3376| 17630001 | crypto operation error. |
3377
3378**示例:**
3379
3380```ts
3381import { BusinessError } from '@ohos.base';
3382
3383let mac = cryptoFramework.createMac("SHA256");
3384console.info("Mac algName is: " + mac.algName);
3385let keyBlob: cryptoFramework.DataBlob;
3386let symKeyGenerator = cryptoFramework.createSymKeyGenerator("AES128");
3387let promiseConvertKey = symKeyGenerator.convertKey(keyBlob);
3388promiseConvertKey.then(symKey => {
3389  let promiseMacInit = mac.init(symKey);
3390  return promiseMacInit;
3391}).then(() => {
3392  let blob: cryptoFramework.DataBlob;
3393  let promiseMacUpdate = mac.update(blob);
3394  return promiseMacUpdate;
3395}).then(() => {
3396  let promiseMacDoFinal = mac.doFinal();
3397  return promiseMacDoFinal;
3398}).then(macOutput => {
3399  console.error("[Promise]: HMAC result: " + macOutput.data);
3400}).catch((error: BusinessError) => {
3401  console.error("[Promise]: error: " + error.message);
3402});
3403```
3404
3405### getMacLength
3406
3407getMacLength(): number
3408
3409获取Mac消息认证码的长度(字节数)。
3410
3411**系统能力:** SystemCapability.Security.CryptoFramework
3412
3413**返回值:**
3414
3415| 类型   | 说明                        |
3416| ------ | --------------------------- |
3417| number | 返回mac计算结果的字节长度。 |
3418
3419**错误码:**
3420以下错误码的详细介绍请参见[crypto framework错误码](../errorcodes/errorcode-crypto-framework.md)
3421
3422| 错误码ID | 错误信息               |
3423| -------- | ---------------------- |
3424| 17630001 | crypto operation error. |
3425
3426**示例:**
3427
3428```ts
3429import { BusinessError } from '@ohos.base';
3430
3431let mac = cryptoFramework.createMac("SHA256");
3432console.info("Mac algName is: " + mac.algName);
3433let keyBlob: cryptoFramework.DataBlob;
3434let symKeyGenerator = cryptoFramework.createSymKeyGenerator("AES128");
3435let promiseConvertKey = symKeyGenerator.convertKey(keyBlob);
3436promiseConvertKey.then(symKey => {
3437  let promiseMacInit = mac.init(symKey);
3438  return promiseMacInit;
3439}).then(() => {
3440  let blob: cryptoFramework.DataBlob;
3441  let promiseMacUpdate = mac.update(blob);
3442  return promiseMacUpdate;
3443}).then(() => {
3444  let promiseMacDoFinal = mac.doFinal();
3445  return promiseMacDoFinal;
3446}).then(macOutput => {
3447  console.error("[Promise]: HMAC result: " + macOutput.data);
3448  let macLen = mac.getMacLength();
3449  console.error("MAC len: " + macLen);
3450}).catch((error: BusinessError) => {
3451  console.error("[Promise]: error: " + error.message);
3452});
3453```
3454
3455## cryptoFramework.createRandom
3456
3457createRandom(): Random
3458
3459生成Random实例,用于进行随机数的计算与设置种子。
3460
3461支持的规格详见框架概述“[随机数算法规格](../../security/cryptoFramework-overview.md#随机数)”一节。
3462
3463**系统能力:** SystemCapability.Security.CryptoFramework
3464
3465**返回值**:
3466
3467| 类型   | 说明                                            |
3468| ------ | ----------------------------------------------- |
3469| Random | 返回由输入算法指定生成的[Random](#random)对象。 |
3470
3471**错误码:**
3472以下错误码的详细介绍请参见[crypto framework错误码](../errorcodes/errorcode-crypto-framework.md)
3473
3474| 错误码ID | 错误信息     |
3475| -------- | ------------ |
3476| 17620001 | memory error. |
3477
3478**示例:**
3479
3480```ts
3481import { BusinessError } from '@ohos.base';
3482
3483try {
3484  let rand = cryptoFramework.createRandom();
3485} catch (error) {
3486  let e: BusinessError = error as BusinessError;
3487  console.error(`sync error, ${e.code}, ${e.message}`);
3488}
3489```
3490
3491## Random
3492
3493Random类,调用Random方法可以进行随机数计算。调用前,需要通过[createRandom](#cryptoframeworkcreaterandom)构造Random实例。
3494
3495### 属性
3496
3497**系统能力:** SystemCapability.Security.CryptoFramework
3498
3499| 名称    | 类型   | 可读 | 可写 | 说明                 |
3500| ------- | ------ | ---- | ---- | -------------------- |
3501| algName<sup>10+</sup> | string | 是   | 否   | 代表当前使用的随机数生成算法,目前只支持“CTR_DRBG"。 |
3502
3503### generateRandom
3504
3505generateRandom(len: number, callback: AsyncCallback\<DataBlob>): void
3506
3507异步生成指定长度的随机数,通过注册回调函数返回。
3508
3509**系统能力:** SystemCapability.Security.CryptoFramework
3510
3511**参数:**
3512
3513| 参数名   | 类型                     | 必填 | 说明                 |
3514| -------- | ------------------------ | ---- | -------------------- |
3515| len      | number                   | 是   | 表示生成随机数的长度,单位为byte,范围在[1, INT_MAX]。 |
3516| callback | AsyncCallback\<[DataBlob](#datablob)> | 是   | 回调函数,用于获取DataBlob数据。 |
3517
3518**错误码:**
3519以下错误码的详细介绍请参见[crypto framework错误码](../errorcodes/errorcode-crypto-framework.md)
3520
3521| 错误码ID | 错误信息               |
3522| -------- | ---------------------- |
3523| 401 | invalid parameters.          |
3524| 17620001 | memory error.          |
3525| 17630001 | crypto operation error. |
3526
3527**示例:**
3528
3529```ts
3530import { BusinessError } from '@ohos.base';
3531
3532let rand = cryptoFramework.createRandom();
3533rand.generateRandom(12, (err, randData) => {
3534  if (err) {
3535    console.error("[Callback] err: " + err.code);
3536  } else {
3537    console.error("[Callback]: generate random result: " + randData.data);
3538  }
3539});
3540```
3541
3542### generateRandom
3543
3544generateRandom(len: number): Promise\<DataBlob>
3545
3546异步生成指定长度的随机数,通过Promise返回。
3547
3548**系统能力:** SystemCapability.Security.CryptoFramework
3549
3550**参数:**
3551
3552| 参数名 | 类型   | 必填 | 说明                                                   |
3553| ------ | ------ | ---- | ------------------------------------------------------ |
3554| len    | number | 是   | 表示生成随机数的长度,单位为byte,范围在[1, INT_MAX]。 |
3555
3556**返回值:**
3557
3558| 类型               | 说明        |
3559| ------------------ | ----------- |
3560| Promise\<[DataBlob](#datablob)> | Promise对象。 |
3561
3562**错误码:**
3563以下错误码的详细介绍请参见[crypto framework错误码](../errorcodes/errorcode-crypto-framework.md)
3564
3565| 错误码ID | 错误信息               |
3566| -------- | ---------------------- |
3567| 401 | invalid parameters.          |
3568| 17620001 | memory error.           |
3569| 17630001 | crypto operation error. |
3570
3571**示例:**
3572
3573```ts
3574import { BusinessError } from '@ohos.base';
3575
3576let rand = cryptoFramework.createRandom();
3577let promiseGenerateRand = rand.generateRandom(12);
3578promiseGenerateRand.then(randData => {
3579  console.error("[Promise]: rand result: " + randData.data);
3580}).catch((error: BusinessError) => {
3581  console.error("[Promise]: error: " + error.message);
3582});
3583```
3584
3585### generateRandomSync<sup>10+</sup>
3586
3587generateRandomSync(len: number): DataBlob
3588
3589同步生成指定长度的随机数。
3590
3591**系统能力:** SystemCapability.Security.CryptoFramework
3592
3593**参数:**
3594
3595| 参数名 | 类型   | 必填 | 说明                 |
3596| ------ | ------ | ---- | -------------------- |
3597| len    | number | 是   | 表示生成随机数的长度,单位为byte,范围在[1, INT_MAX]。 |
3598
3599**返回值:**
3600
3601| 类型               | 说明        |
3602| ------------------ | ----------- |
3603|[DataBlob](#datablob) | 表示生成的随机数。 |
3604
3605**错误码:**
3606以下错误码的详细介绍请参见[crypto framework错误码](../errorcodes/errorcode-crypto-framework.md)
3607
3608| 错误码ID | 错误信息               |
3609| -------- | ---------------------- |
3610| 401 | invalid parameters.          |
3611| 17620001 | memory error.           |
3612| 17630001 | crypto operation error. |
3613
3614**示例:**
3615
3616```ts
3617import { BusinessError } from '@ohos.base';
3618
3619let rand = cryptoFramework.createRandom();
3620try {
3621  let randData = rand.generateRandomSync(12);
3622  if (randData != null) {
3623    console.info("[Sync]: rand result: " + randData.data);
3624  } else {
3625    console.error("[Sync]: get rand result fail!");
3626  }
3627} catch (error) {
3628  let e: BusinessError = error as BusinessError;
3629  console.error(`sync error, ${e.code}, ${e.message}`);
3630}
3631```
3632
3633### setSeed
3634
3635setSeed(seed: DataBlob): void
3636
3637设置指定的种子。
3638
3639**系统能力:** SystemCapability.Security.CryptoFramework
3640
3641| 参数名 | 类型     | 必填 | 说明         |
3642| ------ | -------- | ---- | ------------ |
3643| seed   | DataBlob | 是   | 设置的种子。 |
3644
3645**错误码:**
3646以下错误码的详细介绍请参见[crypto framework错误码](../errorcodes/errorcode-crypto-framework.md)
3647
3648| 错误码ID | 错误信息           |
3649| -------- | ----------------- |
3650| 17620001 | memory error.      |
3651
3652**示例:**
3653
3654```ts
3655import { BusinessError } from '@ohos.base';
3656
3657let rand = cryptoFramework.createRandom();
3658rand.generateRandom(12, (err, randData) => {
3659  if (err) {
3660    console.error("[Callback] err: " + err.code);
3661  } else {
3662    console.info("[Callback]: generate random result: " + randData.data);
3663    try {
3664      rand.setSeed(randData);
3665    } catch (error) {
3666      let e: BusinessError = error as BusinessError;
3667      console.error(`sync error, ${e.code}, ${e.message}`);
3668    }
3669  }
3670});
3671```
3672