• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1# @ohos.security.cryptoFramework (Crypto Framework)
2
3The **cryptoFramework** module shields underlying hardware and algorithm libraries and provides unified APIs for cryptographic operations.
4
5> **NOTE**
6>
7> The initial APIs of this module are supported since API version 9. Newly added APIs will be marked with a superscript to indicate their earliest API version.
8
9## Modules to Import
10
11```ts
12import cryptoFramework from "@ohos.security.cryptoFramework";
13```
14
15## Result
16
17 Enumerates the operation results.
18
19 **System capability**: SystemCapability.Security.CryptoFramework
20
21| Name                                 |    Value  |   Description                        |
22| ------------------------------------- | -------- | ---------------------------- |
23| INVALID_PARAMS                        | 401      | Invalid parameter.                  |
24| NOT_SUPPORT                           | 801      | Unsupported operation.                |
25| ERR_OUT_OF_MEMORY                     | 17620001 | Memory error.                  |
26| ERR_RUNTIME_ERROR                     | 17620002 | Runtime error.            |
27| ERR_CRYPTO_OPERATION                  | 17630001 | Cryptographic operation error.    |
28
29## DataBlob
30
31Defines a buffer array of the Binary Large Object (BLOB) type.
32
33 **System capability**: SystemCapability.Security.CryptoFramework
34
35| Name| Type      | Readable| Writable| Description  |
36| ---- | ---------- | ---- | ---- | ------ |
37| data | Uint8Array | Yes  | Yes  | Binary data array.|
38
39## ParamsSpec
40
41Encapsulates the parameters used for encryption or decryption. You need to construct its child class object and pass it to [init()](#init-2) for symmetric encryption or decryption.
42
43It applies to the symmetric cipher modes that require parameters such as the initialization vector (IV). If the IV is not required (for example, the ECB mode), pass in **null** to [init()](#init-2).
44
45**System capability**: SystemCapability.Security.CryptoFramework
46
47| Name   | Type  | Readable| Writable| Description                                                        |
48| ------- | ------ | ---- | ---- | ------------------------------------------------------------ |
49| algName | string | Yes  | Yes  | Algorithm for symmetric encryption or decryption. Options:<br>- **IvParamsSpec**: applicable to the CBC, CTR, OFB, and CFB modes.<br>- **GcmParamsSpec**: applicable to the GCM mode.<br>- **CcmParamsSpec**: applicable to the CCM mode.|
50
51> **NOTE**
52>
53> The **params** parameter in [init()](#init-2) is of the **ParamsSpec** type (parent class). However, a child class object (such as **IvParamsSpec**) needs to be passed in. When constructing the child class object, you need to set **algName** for its parent class **ParamsSpec** to specify the child class object to be passed to **init()**.
54
55## IvParamsSpec
56
57Defines the child class of [ParamsSpec](#paramsspec). It is a parameter of [init()](#init-2) for symmetric encryption or decryption.
58
59**IvParamsSpec** applies to the cipher modes such as CBC, CTR, OFB, and CFB, which use only the IV.
60
61**System capability**: SystemCapability.Security.CryptoFramework
62
63| Name| Type                 | Readable| Writable| Description                                                        |
64| ---- | --------------------- | ---- | ---- | ------------------------------------------------------------ |
65| iv   | [DataBlob](#datablob) | Yes  | Yes  | IV for encryption or decryption. Options:<br>- AES CBC, CTR, OFB, or CFB mode: 16-byte IV<br>- 3DES CBC, OFB, or CFB mode: 8-byte IV<br>- SM4<sup>10+</sup> CBC, CTR, OFB, or CFB mode: 16-byte IV|
66
67> **NOTE**
68>
69> Before passing **IvParamsSpec** to [init()](#init-2), specify **algName** for its parent class [ParamsSpec](#paramsspec).
70
71## GcmParamsSpec
72
73Defines the child class of [ParamsSpec](#paramsspec). It is a parameter of [init()](#init-2) for symmetric encryption or decryption.
74
75**GcmParamsSpec** applies to the GCM mode.
76
77**System capability**: SystemCapability.Security.CryptoFramework
78
79| Name   | Type                 | Readable| Writable| Description                                                        |
80| ------- | --------------------- | ---- | ---- | ------------------------------------------------------------ |
81| iv      | [DataBlob](#datablob) | Yes  | Yes  | IV, which is of 1 to 16 bytes. A 12-byte IV is commonly used.                            |
82| aad     | [DataBlob](#datablob) | Yes  | Yes  | Additional authentication data (AAD), which is of 0 to INT_MAX bytes. A 16-byte AAD is commonly used.                            |
83| authTag | [DataBlob](#datablob) | Yes  | Yes  | Authentication tag, which is of 16 bytes.<br>When the GCM mode is used for encryption, the last 16 bytes of [DataBlob](#datablob) output by [doFinal()](#dofinal-2) are used as **authTag** in [GcmParamsSpec](#gcmparamsspec) of [init()](#init-2).|
84
85> **NOTE**
86>
87> 1. Before passing **GcmParamsSpec** to [init()](#init-2), specify **algName** for its parent class [ParamsSpec](#paramsspec).
88> 2. The IV to use is not length bound. However, the operation result depends on whether the underlying OpenSSL supports the IV.
89> 3. If **aad** is not required or the length of **aad** is **0**, you can set **aad** to an empty Uint8Array, that is, **aad: { data: new Uint8Array() }**.
90
91## CcmParamsSpec
92
93Defines the child class of [ParamsSpec](#paramsspec). It is a parameter of [init()](#init-2) for symmetric encryption or decryption.
94
95**CcmParamsSpec** applies to the CCM mode.
96
97**System capability**: SystemCapability.Security.CryptoFramework
98
99| Name   | Type                 | Readable| Writable| Description                                                        |
100| ------- | --------------------- | ---- | ---- | ------------------------------------------------------------ |
101| iv      | [DataBlob](#datablob) | Yes  | Yes  | IV, which is of 7 bytes.                             |
102| aad     | [DataBlob](#datablob) | Yes  | Yes  | AAD, which is of 8 bytes.                            |
103| authTag | [DataBlob](#datablob) | Yes  | Yes  | Authentication tag, which is of 12 bytes.<br>When the CCM mode is used for encryption, the last 12 bytes of [DataBlob](#datablob) output by [doFinal()](#dofinal-2) are used as **authTag** in [CcmParamsSpec](#ccmparamsspec) of [init()](#init-2).|
104
105> **NOTE**
106>
107> Before passing **CcmParamsSpec** to [init()](#init-2), specify **algName** for its parent class [ParamsSpec](#paramsspec).
108
109## CryptoMode
110
111Enumerates the cryptographic operations.
112
113**System capability**: SystemCapability.Security.CryptoFramework
114
115| Name        | Value  | Description              |
116| ------------ | ---- | ------------------ |
117| ENCRYPT_MODE | 0    | Encryption.|
118| DECRYPT_MODE | 1    | Decryption.|
119
120## AsyKeySpecItem<sup>10+</sup>
121
122Enumerates the asymmetric key parameters.
123
124**System capability**: SystemCapability.Security.CryptoFramework
125
126| Name        | Value  | Description            |
127| ------------ | ---- | ---------------- |
128| DSA_P_BN | 101 | Prime modulus **p** in the DSA algorithm.|
129| DSA_Q_BN | 102 | Parameter **q**, prime factor of (p – 1) in the DSA algorithm.|
130| DSA_G_BN | 103 | Parameter **g** in the DSA algorithm.|
131| DSA_SK_BN | 104 | Private key **sk** in the DSA algorithm.|
132| DSA_PK_BN | 105 | Public key **pk** in the DSA algorithm.|
133| ECC_FP_P_BN | 201 | Prime number **p** in the **Fp** fields of the elliptic curve in the DSA algorithm.|
134| ECC_A_BN | 202 | First coefficient **a** of the elliptic curve in the DSA algorithm.|
135| ECC_B_BN | 203 | Second coefficient **b** of the elliptic curve in the DSA algorithm.|
136| ECC_G_X_BN | 204 | X coordinate of the base point **g** in the ECC algorithm.|
137| ECC_G_Y_BN | 205 | Y coordinate of the base point **g** in the ECC algorithm.|
138| ECC_N_BN | 206 | Order **n** of the base point **g** in the ECC algorithm.|
139| ECC_H_NUM | 207 | Cofactor **h** in the ECC algorithm.|
140| ECC_SK_BN | 208 | Private key **sk** in the ECC algorithm.|
141| ECC_PK_X_BN | 209 | X coordinate of the public key **pk** (a point on the elliptic curve) in the ECC algorithm.|
142| ECC_PK_Y_BN | 210 | Y coordinate of the public key **pk** (a point on the elliptic curve) in the ECC algorithm.|
143| ECC_FIELD_TYPE_STR | 211 | Elliptic curve field type in the ECC algorithm. Currently, only the **Fp** field is supported.|
144| ECC_FIELD_SIZE_NUM | 212 | Size of the field in the ECC algorithm, in bits.<br>**NOTE**<br>The size of the **Fp** field is the length of the prime **p**, in bits.|
145| ECC_CURVE_NAME_STR | 213 | Standards for Efficient Cryptography Group (SECG) curve name in the ECC algorithm.|
146| RSA_N_BN | 301 | Modulus **n** in the RSA algorithm.|
147| RSA_SK_BN | 302 | Private key **sk** (private key exponent **d**) in the RSA algorithm.|
148| RSA_PK_BN | 303 | Public key **pk** (public key exponent **e**) in the RSA algorithm.|
149| DH_P_BN<sup>11+</sup> | 401 | Prime **p** in the DH algorithm.|
150| DH_G_BN<sup>11+</sup> | 402 | Parameter **g** in the DH algorithm.|
151| DH_L_NUM<sup>11+</sup> | 403 | Length of the private key in the DH algorithm, in bits.|
152| DH_SK_BN<sup>11+</sup> | 404 | Private key **sk** in the DH algorithm.|
153| DH_PK_BN<sup>11+</sup> | 405 | Public key **pk** in the DH algorithm.|
154| ED25519_SK_BN<sup>11+</sup> | 501 | Private key **sk** in the Ed25519 algorithm.|
155| ED25519_PK_BN<sup>11+</sup> | 502 | Public key **pk** in the Ed25519 algorithm.|
156| X25519_SK_BN<sup>11+</sup> | 601 | Private key **sk** in the X25519 algorithm.|
157| X25519_PK_BN<sup>11+</sup> | 602 | Public key **pk** in the X25519 algorithm.|
158
159## AsyKeySpecType<sup>10+</sup>
160
161Enumerates the key parameter types.
162
163**System capability**: SystemCapability.Security.CryptoFramework
164
165| Name        | Value  | Description            |
166| ------------ | ---- | ---------------- |
167| COMMON_PARAMS_SPEC | 0 | Common parameter of the public and private keys. You can use [generateKeyPair()](#generatekeypair-2) to randomly generate a key pair based on the parameters of this type.|
168| PRIVATE_KEY_SPEC | 1 | Parameter of the private key. You can use [generatePriKey()](#generateprikey) to generate a private key based on the parameters of this type.|
169| PUBLIC_KEY_SPEC | 2 | Parameter of the public key. You can use [generatePubKey()](#generatepubkey) to generate a public key based on the parameters of this type.|
170| KEY_PAIR_SPEC | 3 | Full parameters of the public and private keys. You can use [generateKeyPair](#generatekeypair-2) to generate a key pair based on the parameters of this type.|
171
172## CipherSpecItem<sup>10+</sup>
173
174Enumerates the cipher parameters. You can use [setCipherSpec](#setcipherspec10) to set cipher parameters, and use [getCipherSpec](#getcipherspec10) to obtain cipher parameters.
175
176Currently, only RSA and SM2 are supported. Since API version 11, the **SM2_MD_NAME_STR** parameter is supported. For details, see [Asymmetric Key Encryption and Decryption Algorithm Specifications](../../security/CryptoArchitectureKit/crypto-asym-encrypt-decrypt-spec.md).
177
178**System capability**: SystemCapability.Security.CryptoFramework
179
180| Name        | Value  | Description            |
181| ------------ | ---- | ---------------- |
182| OAEP_MD_NAME_STR | 100 | Message digest (MD) algorithm used with the PKCS1_OAEP padding mode in RSA.|
183| OAEP_MGF_NAME_STR | 101 | Mask generation algorithm used with the PKCS1_OAEP padding mode in RSA. Currently, only MGF1 is supported.|
184| OAEP_MGF1_MD_STR | 102 | MD algorithm for the MGF1 mask generation used with the PKCS1_OAEP padding mode in RSA.|
185| OAEP_MGF1_PSRC_UINT8ARR | 103 | **pSource** byte stream used with the PKCS1_OAEP padding mode in RSA.|
186| SM2_MD_NAME_STR<sup>11+</sup> | 104 | MD algorithm used in SM2.|
187
188## SignSpecItem<sup>10+</sup>
189
190Enumerates the parameters for signing and signature verification. You can use [setSignSpec](#setsignspec10) and [setVerifySpec](#setverifyspec10) to set these parameters, and use [getSignSpec](#getsignspec10) and [getVerifySpec](#getverifyspec10) to obtain the parameters.
191
192Currently, only RSA and SM2 are supported. Since API version 11, the **SM2_USER_ID_UINT8ARR** parameter is supported. For details, see [Signing and Signature Verification Overview and Algorithm Specifications](../../security/CryptoArchitectureKit/crypto-sign-sig-verify-overview.md).
193
194**System capability**: SystemCapability.Security.CryptoFramework
195
196| Name        | Value  | Description            |
197| ------------ | ---- | ---------------- |
198| PSS_MD_NAME_STR | 100 | MD algorithm used with the PSS padding mode in RSA.|
199| PSS_MGF_NAME_STR | 101 | Mask generation algorithm used with the PSS padding mode in RSA. Currently, only MGF1 is supported.|
200| PSS_MGF1_MD_STR | 102 | MD parameters for the MGF1 mask generation used with the PSS padding mode in RSA.|
201| PSS_SALT_LEN_NUM | 103 | Length of the salt in bytes used with the PSS padding mode in RSA.|
202| PSS_TRAILER_FIELD_NUM | 104 | Trailer field used in the encoding operation when PSS padding mode is used in RSA. The value is **1**.|
203| SM2_USER_ID_UINT8ARR<sup>11+</sup> | 105 | User ID field in SM2.|
204
205## AsyKeySpec<sup>10+</sup>
206
207Defines the asymmetric key parameters for creating a key generator. You need to construct a child class object and pass it to [createAsyKeyGeneratorBySpec()](#cryptoframeworkcreateasykeygeneratorbyspec10) to create a key generator. When constructing the child class object, all the parameters of the bigint type must be positive numbers in big-endian format.
208
209**System capability**: SystemCapability.Security.CryptoFramework
210
211| Name   | Type  | Readable| Writable| Description                                                        |
212| ------- | ------ | ---- | ---- | ------------------------------------------------------------ |
213| algName | string | Yes  | Yes  | Asymmetric key algorithm, for example, **RSA**, **DSA**, **ECC**, **SM2**, **Ed25519**, **X25519**, or **DH**.|
214| specType | [AsyKeySpecType](#asykeyspectype10) | Yes  | Yes| Key parameter type, which is used to distinguish public and private key parameters.|
215
216## DSACommonParamsSpec<sup>10+</sup>
217
218Defines a child class of [AsyKeySpec](#asykeyspec10) used to specify the common parameters of the public and private keys in the DSA algorithm. It can be used to randomly generate a public or private key.
219
220To generate a key based on key parameters, pass it to [createAsyKeyGeneratorBySpec()](#cryptoframeworkcreateasykeygeneratorbyspec10) to create a key generator.
221
222**System capability**: SystemCapability.Security.CryptoFramework
223
224| Name   | Type  | Readable| Writable| Description                                                        |
225| ------- | ------ | ---- | ---- | ------------------------------------------------------------ |
226| p | bigint | Yes  | Yes  | Prime modulus **p** in the DSA algorithm.|
227| q | bigint | Yes  | Yes  | Parameter **q**, prime factor of (**p** – 1) in the DSA algorithm.|
228| g | bigint | Yes  | Yes  | Parameter **g** in the DSA algorithm.|
229
230## DSAPubKeySpec<sup>10+</sup>
231
232Defines a child class of [AsyKeySpec](#asykeyspec10) used to specify the parameters of the public key in the DSA algorithm.
233
234To generate a key based on key parameters, pass it to [createAsyKeyGeneratorBySpec()](#cryptoframeworkcreateasykeygeneratorbyspec10) to create a key generator.
235
236**System capability**: SystemCapability.Security.CryptoFramework
237
238| Name   | Type  | Readable| Writable| Description                                                        |
239| ------- | ------ | ---- | ---- | ------------------------------------------------------------ |
240| params | [DSACommonParamsSpec](#dsacommonparamsspec10) | Yes  | Yes  | Common parameters of the public and private keys in the DSA algorithm.|
241| pk | bigint | Yes  | Yes  | Public key in the DSA algorithm.|
242
243## DSAKeyPairSpec<sup>10+</sup>
244
245Defines a child class of [AsyKeySpec](#asykeyspec10) used to specify full parameters of the public and private keys in the DSA algorithm.
246
247To generate a key based on key parameters, pass it to [createAsyKeyGeneratorBySpec()](#cryptoframeworkcreateasykeygeneratorbyspec10) to create a key generator.
248
249**System capability**: SystemCapability.Security.CryptoFramework
250
251| Name   | Type  | Readable| Writable| Description                                                        |
252| ------- | ------ | ---- | ---- | ------------------------------------------------------------ |
253| params | [DSACommonParamsSpec](#dsacommonparamsspec10) | Yes  | Yes  | Common parameters of the public and private keys in the DSA algorithm.|
254| sk | bigint | Yes  | Yes  | Private key **sk** in the DSA algorithm.|
255| pk | bigint | Yes  | Yes  | Public key **pk** in the DSA algorithm.|
256
257## ECField<sup>10+</sup>
258
259Defines an elliptic curve field. Currently, only the **Fp** field is supported.
260
261**System capability**: SystemCapability.Security.CryptoFramework
262
263| Name   | Type  | Readable| Writable| Description                                                        |
264| ------- | ------ | ---- | ---- | ------------------------------------------------------------ |
265| fieldType | string | Yes  | Yes  | Type of the elliptic curve field. Currently, only **Fp** is supported.|
266
267## ECFieldFp<sup>10+</sup>
268
269Defines the prime field of the elliptic curve. It is a child class of [ECField](#ecfield10).
270
271**System capability**: SystemCapability.Security.CryptoFramework
272
273| Name   | Type  | Readable| Writable| Description                                                        |
274| ------- | ------ | ---- | ---- | ------------------------------------------------------------ |
275| p | bigint | Yes  | Yes  | Prime **p**.|
276
277## Point<sup>10+</sup>
278
279Defines a point on the elliptic curve.
280
281**System capability**: SystemCapability.Security.CryptoFramework
282
283| Name   | Type  | Readable| Writable| Description                                                        |
284| ------- | ------ | ---- | ---- | ------------------------------------------------------------ |
285| x | bigint | Yes  | Yes  | X coordinate of the point on an elliptic curve.|
286| y | bigint | Yes  | Yes  | Y coordinate of the point on an elliptic curve.|
287
288## ECCCommonParamsSpec<sup>10+</sup>
289
290Defines a child class of [AsyKeySpec](#asykeyspec10) used to specify the common parameters of the public and private keys in the ECC algorithm. It can be used to randomly generate a public or private key.
291
292To generate a key based on key parameters, pass it to [createAsyKeyGeneratorBySpec()](#cryptoframeworkcreateasykeygeneratorbyspec10) to create a key generator.
293
294**System capability**: SystemCapability.Security.CryptoFramework
295
296| Name   | Type  | Readable| Writable| Description                                                        |
297| ------- | ------ | ---- | ---- | ------------------------------------------------------------ |
298| field | [ECField](#ecfield10) | Yes  | Yes  | Field of the elliptic curve. Currently, only **Fp** is supported.|
299| a | bigint | Yes  | Yes  | First coefficient **a** of the elliptic curve.|
300| b | bigint | Yes  | Yes  | Second coefficient **b** of the elliptic curve.|
301| g | [Point](#point10) | Yes  | Yes  | Base point g.|
302| n | bigint | Yes  | Yes  | Order **n** of the base point **g**.|
303| h | number | Yes  | Yes  | Cofactor **h**.|
304
305## ECCPriKeySpec<sup>10+</sup>
306
307Defines a child class of [AsyKeySpec](#asykeyspec10) used to specify the parameters of the private key in the ECC algorithm.
308
309To generate a key based on key parameters, pass it to [createAsyKeyGeneratorBySpec()](#cryptoframeworkcreateasykeygeneratorbyspec10) to create a key generator.
310
311**System capability**: SystemCapability.Security.CryptoFramework
312
313| Name   | Type  | Readable| Writable| Description                                                        |
314| ------- | ------ | ---- | ---- | ------------------------------------------------------------ |
315| params | [ECCCommonParamsSpec](#ecccommonparamsspec10) | Yes  | Yes  | Common parameters of the public and private keys in the ECC algorithm.|
316| sk | bigint | Yes  | Yes  | Private key **sk** in the ECC algorithm.|
317
318## ECCPubKeySpec<sup>10+</sup>
319
320Defines a child class of [AsyKeySpec](#asykeyspec10) used to specify the parameters of the public key in the ECC algorithm.
321
322To generate a key based on key parameters, pass it to [createAsyKeyGeneratorBySpec()](#cryptoframeworkcreateasykeygeneratorbyspec10) to create a key generator.
323
324**System capability**: SystemCapability.Security.CryptoFramework
325
326| Name   | Type  | Readable| Writable| Description                                                        |
327| ------- | ------ | ---- | ---- | ------------------------------------------------------------ |
328| params | [ECCCommonParamsSpec](#ecccommonparamsspec10) | Yes  | Yes  | Common parameters of the public and private keys in the ECC algorithm.|
329| pk | [Point](#point10) | Yes  | Yes  | Public key **pk** in the ECC algorithm.|
330
331## ECCKeyPairSpec<sup>10+</sup>
332
333Defines a child class of [AsyKeySpec](#asykeyspec10) used to specify full parameters of the public and private keys in the ECC algorithm.
334
335To generate a key based on key parameters, pass it to [createAsyKeyGeneratorBySpec()](#cryptoframeworkcreateasykeygeneratorbyspec10) to create a key generator.
336
337**System capability**: SystemCapability.Security.CryptoFramework
338
339| Name   | Type  | Readable| Writable| Description                                                        |
340| ------- | ------ | ---- | ---- | ------------------------------------------------------------ |
341| params | [ECCCommonParamsSpec](#ecccommonparamsspec10) | Yes  | Yes  | Common parameters of the public and private keys in the ECC algorithm.|
342| sk | bigint | Yes  | Yes  | Private key **sk** in the ECC algorithm.|
343| pk | [Point](#point10) | Yes  | Yes  | Public key **pk** in the ECC algorithm.|
344
345## RSACommonParamsSpec<sup>10+</sup>
346
347Defines a child class of [AsyKeySpec](#asykeyspec10) used to specify the common parameters of the public and private keys in the RSA algorithm. It can be used to randomly generate a public or private key.
348
349To generate a key based on key parameters, pass it to [createAsyKeyGeneratorBySpec()](#cryptoframeworkcreateasykeygeneratorbyspec10) to create a key generator.
350
351**System capability**: SystemCapability.Security.CryptoFramework
352
353| Name   | Type  | Readable| Writable| Description                                                        |
354| ------- | ------ | ---- | ---- | ------------------------------------------------------------ |
355| n | bigint | Yes  | Yes  | Modulus **n**.|
356
357## RSAPubKeySpec<sup>10+</sup>
358
359Defines a child class of [AsyKeySpec](#asykeyspec10) used to specify the parameters of the public key in the RSA algorithm.
360
361To generate a key based on key parameters, pass it to [createAsyKeyGeneratorBySpec()](#cryptoframeworkcreateasykeygeneratorbyspec10) to create a key generator.
362
363**System capability**: SystemCapability.Security.CryptoFramework
364
365| Name   | Type  | Readable| Writable| Description                                                        |
366| ------- | ------ | ---- | ---- | ------------------------------------------------------------ |
367| params | [RSACommonParamsSpec](#rsacommonparamsspec10) | Yes  | Yes  | Common parameters of the public and private keys in the RSA algorithm.|
368| pk | bigint | Yes  | Yes  | Public key **pk** in the RSA algorithm.|
369
370## RSAKeyPairSpec<sup>10+</sup>
371
372Defines a child class of [AsyKeySpec](#asykeyspec10) used to specify full parameters of the public and private keys in the RSA algorithm.
373
374To generate a key based on key parameters, pass it to [createAsyKeyGeneratorBySpec()](#cryptoframeworkcreateasykeygeneratorbyspec10) to create a key generator.
375
376**System capability**: SystemCapability.Security.CryptoFramework
377
378| Name   | Type  | Readable| Writable| Description                                                        |
379| ------- | ------ | ---- | ---- | ------------------------------------------------------------ |
380| params | [RSACommonParamsSpec](#rsacommonparamsspec10) | Yes  | Yes  | Common parameters of the public and private keys in the RSA algorithm.|
381| sk | bigint | Yes  | Yes  | Private key **sk** in the RSA algorithm.|
382| pk | bigint | Yes  | Yes  | Public key **pk** in the RSA algorithm.|
383
384## ED25519PriKeySpec<sup>11+</sup>
385
386Defines a child class of [AsyKeySpec](#asykeyspec10) used to specify the parameters of the private key in the Ed25519 algorithm.
387
388To generate a key based on key parameters, pass it to [createAsyKeyGeneratorBySpec()](#cryptoframeworkcreateasykeygeneratorbyspec10) to create a key generator.
389
390**System capability**: SystemCapability.Security.CryptoFramework
391
392| Name| Type  | Readable| Writable| Description                     |
393| ---- | ------ | ---- | ---- | ------------------------- |
394| sk   | bigint | Yes  | Yes  | Private key **sk** in the Ed25519 algorithm.|
395
396## ED25519PubKeySpec<sup>11+</sup>
397
398Defines a child class of [AsyKeySpec](#asykeyspec10) used to specify the parameters of the public key in the Ed25519 algorithm.
399
400To generate a key based on key parameters, pass it to [createAsyKeyGeneratorBySpec()](#cryptoframeworkcreateasykeygeneratorbyspec10) to create a key generator.
401
402**System capability**: SystemCapability.Security.CryptoFramework
403
404| Name| Type  | Readable| Writable| Description                     |
405| ---- | ------ | ---- | ---- | ------------------------- |
406| pk   | bigint | Yes  | Yes  | Public key **pk** in the Ed25519 algorithm.|
407
408## ED25519KeyPairSpec<sup>11+</sup>
409
410Defines a child class of [AsyKeySpec](#asykeyspec10) used to specify full parameters of the public and private keys in the Ed25519 algorithm.
411
412To generate a key based on key parameters, pass it to [createAsyKeyGeneratorBySpec()](#cryptoframeworkcreateasykeygeneratorbyspec10) to create a key generator.
413
414**System capability**: SystemCapability.Security.CryptoFramework
415
416| Name| Type  | Readable| Writable| Description                     |
417| ---- | ------ | ---- | ---- | ------------------------- |
418| sk   | bigint | Yes  | Yes  | Private key **sk** in the Ed25519 algorithm.|
419| pk   | bigint | Yes  | Yes  | Public key **pk** in the Ed25519 algorithm.|
420
421## X25519PriKeySpec<sup>11+</sup>
422
423Defines a child class of [AsyKeySpec](#asykeyspec10) used to specify the parameters of the private key in the X25519 algorithm.
424
425To generate a key based on key parameters, pass it to [createAsyKeyGeneratorBySpec()](#cryptoframeworkcreateasykeygeneratorbyspec10) to create a key generator.
426
427**System capability**: SystemCapability.Security.CryptoFramework
428
429| Name| Type  | Readable| Writable| Description                    |
430| ---- | ------ | ---- | ---- | ------------------------ |
431| sk   | bigint | Yes  | Yes  | Private key **sk** in the X25519 algorithm.|
432
433## X25519PubKeySpec<sup>11+</sup>
434
435Defines a child class of [AsyKeySpec](#asykeyspec10) used to specify the parameters of the public key in the X25519 algorithm.
436
437To generate a key based on key parameters, pass it to [createAsyKeyGeneratorBySpec()](#cryptoframeworkcreateasykeygeneratorbyspec10) to create a key generator.
438
439**System capability**: SystemCapability.Security.CryptoFramework
440
441| Name| Type  | Readable| Writable| Description                    |
442| ---- | ------ | ---- | ---- | ------------------------ |
443| pk   | bigint | Yes  | Yes  | Public key **pk** in the X25519 algorithm.|
444
445## X25519KeyPairSpec<sup>11+</sup>
446
447Defines a child class of [AsyKeySpec](#asykeyspec10) used to specify full parameters of the public and private keys in the X25519 algorithm.
448
449To generate a key based on key parameters, pass it to [createAsyKeyGeneratorBySpec()](#cryptoframeworkcreateasykeygeneratorbyspec10) to create a key generator.
450
451**System capability**: SystemCapability.Security.CryptoFramework
452
453| Name| Type  | Readable| Writable| Description                    |
454| ---- | ------ | ---- | ---- | ------------------------ |
455| sk   | bigint | Yes  | Yes  | Private key **sk** in the X25519 algorithm.|
456| pk   | bigint | Yes  | Yes  | Public key **pk** in the X25519 algorithm.|
457
458## DHCommonParamsSpec<sup>11+</sup>
459
460Defines a child class of [AsyKeySpec](#asykeyspec10) used to specify the parameters of the public and private keys in the DH algorithm.
461
462To generate a key based on key parameters, pass it to [createAsyKeyGeneratorBySpec()](#cryptoframeworkcreateasykeygeneratorbyspec10) to create a key generator.
463
464**System capability**: SystemCapability.Security.CryptoFramework
465
466| Name| Type  | Readable| Writable| Description                               |
467| ---- | ------ | ---- | ---- | ----------------------------------- |
468| p    | bigint | Yes  | Yes  | Large prime **p** in the DH algorithm.              |
469| g    | bigint | Yes  | Yes  | Parameter **g** in the DH algorithm.                |
470| l    | number | Yes  | Yes  | Length of the private key in the DH algorithm, in bits.|
471
472## DHPriKeySpec<sup>11+</sup>
473
474Defines a child class of [AsyKeySpec](#asykeyspec10) used to specify the parameters of the private key in the DH algorithm.
475
476To generate a key based on key parameters, pass it to [createAsyKeyGeneratorBySpec()](#cryptoframeworkcreateasykeygeneratorbyspec10) to create a key generator.
477
478**System capability**: SystemCapability.Security.CryptoFramework
479
480| Name  | Type              | Readable| Writable| Description                                |
481| ------ | ------------------ | ---- | ---- | ------------------------------------ |
482| params | [DHCommonParamsSpec](#dhcommonparamsspec11) | Yes  | Yes  | Common parameters of the public and private keys in the DH algorithm.|
483| sk     | bigint             | Yes  | Yes  | Private key **sk** in the DH algorithm.                |
484
485## DHPubKeySpec<sup>11+</sup>
486
487Defines a child class of [AsyKeySpec](#asykeyspec10) used to specify the parameters of the public key in the DH algorithm.
488
489To generate a key based on key parameters, pass it to [createAsyKeyGeneratorBySpec()](#cryptoframeworkcreateasykeygeneratorbyspec10) to create a key generator.
490
491**System capability**: SystemCapability.Security.CryptoFramework
492
493| Name  | Type              | Readable| Writable| Description                                |
494| ------ | ------------------ | ---- | ---- | ------------------------------------ |
495| params | [DHCommonParamsSpec](#dhcommonparamsspec11) | Yes  | Yes  | Common parameters of the public and private keys in the DH algorithm.|
496| pk     | bigint             | Yes  | Yes  | Public key **pk** in the DH algorithm.                |
497
498## DHKeyPairSpec<sup>11+</sup>
499
500Defines a child class of [AsyKeySpec](#asykeyspec10) used to specify all parameters of the public and private keys in the DH algorithm.
501
502To generate a key based on key parameters, pass it to [createAsyKeyGeneratorBySpec()](#cryptoframeworkcreateasykeygeneratorbyspec10) to create a key generator.
503
504**System capability**: SystemCapability.Security.CryptoFramework
505
506| Name  | Type              | Readable| Writable| Description                                |
507| ------ | ------------------ | ---- | ---- | ------------------------------------ |
508| params | [DHCommonParamsSpec](#dhcommonparamsspec11) | Yes  | Yes  | Common parameters of the public and private keys in the DH algorithm.|
509| sk     | bigint             | Yes  | Yes  | Private key **sk** in the DH algorithm.                |
510| pk     | bigint             | Yes  | Yes  | Public key **pk** in the DH algorithm.                |
511
512## KdfSpec<sup>11+</sup>
513
514Defines the parameters of the key derivation function. When the key derivation function is used to derive a key, you need to construct and pass in a child class object of **KdfSpec**.
515
516**System capability**: SystemCapability.Security.CryptoFramework
517
518| Name   | Type  | Readable| Writable| Description                                                        |
519| ------- | ------ | ---- | ---- | ------------------------------------------------------------ |
520| algName | string | Yes  | Yes  | Algorithm of the key derivation function, for example, **PBKDF2**.|
521
522## PBKDF2Spec<sup>11+</sup>
523
524Defines the child class of [KdfSpec](#kdfspec11). It is used as an input of the PBKDF2 key derivation function.
525
526**System capability**: SystemCapability.Security.CryptoFramework
527
528| Name   | Type  | Readable| Writable| Description                                                        |
529| ------- | ------ | ---- | ---- | ------------------------------------------------------------ |
530| password | string \| Uint8Array | Yes  | Yes  | Original password entered by the user. |
531| salt | Uint8Array | Yes  | Yes  | Salt value.|
532| iterations | number | Yes  | Yes  | Number of iterations. The value must be a positive integer.|
533| keySize | number | Yes  | Yes  | Length of the derived key, in bytes.|
534
535> **NOTE**
536>
537> **password** specifies the original password. If **password** is of the string type, pass in the data used for key derivation rather than a string of the HexString or Base64 type. In addition, the string must be in utf-8 format. Otherwise, the key derived may be different from the one expected.
538
539## Key
540
541Provides APIs for key operations. Before performing cryptographic operations (such as encryption and decryption), you need to construct a child class object of **Key** and pass it to [init()](#init-2) of the [Cipher](#cipher) instance.
542
543Keys can be generated by a key generator.
544
545### Attributes
546
547**System capability**: SystemCapability.Security.CryptoFramework
548
549| Name   | Type  | Readable| Writable| Description                        |
550| ------- | ------ | ---- | ---- | ---------------------------- |
551| format  | string | Yes  | No  | Format of the key.                |
552| algName | string | Yes  | No  | Algorithm name (including the key length).|
553
554### getEncoded
555
556getEncoded(): DataBlob
557
558Obtains the byte stream of the key data. This API returns the result synchronously. The key can be a symmetric key, public key, or private key. The public key must be in DER encoding format and comply with the ASN.1 syntax and X.509 specifications. The private key must be in DER encoding format and comply with the ASN.1 syntax and PKCS#8 specifications.
559
560> **NOTE**
561>
562> When a key parameter is used to generate an RSA private key, the private key object does not support **getEncoded()**.
563
564**System capability**: SystemCapability.Security.CryptoFramework
565
566**Return value**
567
568| Type                 | Description                    |
569| --------------------- | ------------------------ |
570| [DataBlob](#datablob) | Key obtained.|
571
572**Error codes**
573For details about the error codes, see [Crypto Framework Error Codes](../errorcodes/errorcode-crypto-framework.md).
574
575| ID| Error Message              |
576| -------- | ---------------------- |
577| 801 | this operation is not supported. |
578| 17620001 | memory error. |
579| 17630001 | crypto operation error. |
580
581**Example**
582
583```ts
584import cryptoFramework from '@ohos.security.cryptoFramework';
585
586async function testGenerateAesKey() {
587  let symKeyGenerator = cryptoFramework.createSymKeyGenerator('AES256');
588  let symKey = await symKeyGenerator.generateSymKey();
589  let encodedKey = symKey.getEncoded();
590  console.info('key hex:' + encodedKey.data);
591}
592```
593
594## SymKey
595
596Provides APIs for symmetric key operations. It is a child class of [Key](#key). Its objects need to be passed to [init()](#init-2) of the [Cipher](#cipher) instance in symmetric encryption and decryption.
597
598Symmetric keys can be generated by a [SymKeyGenerator](#symkeygenerator).
599
600### clearMem
601
602clearMem(): void
603
604Clears the keys in the memory. This API returns the result synchronously. You are advised to use this API when symmetric key instances are no longer used.
605
606**System capability**: SystemCapability.Security.CryptoFramework
607
608**Example**
609
610```ts
611let key: cryptoFramework.SymKey;    // The key is generated by a symKeyGenerator. The generation process is omitted here.
612let encodedKey = key.getEncoded();
613console.info('key blob: '+ encodedKey.data);    // Display key content.
614key.clearMem();
615encodedKey = key.getEncoded();
616console.info('key blob: ' + encodedKey.data);  // Display all 0s.
617```
618
619## PubKey
620
621Provides APIs for public key operations. **PubKey** is a child class of [Key](#key). It needs to be passed in during asymmetric encryption and decryption, signature verification, and key agreement.
622
623The public key can be generated by using the asymmetric key generator [AsyKeyGenerator](#asykeygenerator) or [AsyKeyGeneratorBySpec](#asykeygeneratorbyspec10).
624
625### getAsyKeySpec<sup>10+</sup>
626
627getAsyKeySpec(itemType: AsyKeySpecItem): bigint | string | number
628
629Obtains a key parameter. This API returns the result synchronously.
630
631**System capability**: SystemCapability.Security.CryptoFramework
632
633**Parameters**
634
635| Name| Type                 | Mandatory| Description                |
636| ---- | --------------------- | ---- | -------------------- |
637| item  | [AsyKeySpecItem](#asykeyspecitem10) | Yes  | Key parameter to obtain.|
638
639**Return value**
640
641| Type                       | Description                             |
642| --------------------------- | --------------------------------- |
643| bigint\|string\|number | Content of the key parameter obtained.|
644
645**Error codes**
646For details about the error codes, see [Crypto Framework Error Codes](../errorcodes/errorcode-crypto-framework.md).
647
648| ID| Error Message              |
649| -------- | ---------------------- |
650| 401 | invalid parameters. |
651| 17620001 | memory error. |
652| 17630001 | crypto operation error. |
653
654**Example**
655
656```ts
657let key: cryptoFramework.PubKey; // key is a public key object. The generation process is omitted here.
658let p = key.getAsyKeySpec(cryptoFramework.AsyKeySpecItem.ECC_FP_P_BN);
659console.info('ecc item --- p: ' + p.toString(16));
660```
661
662## PriKey
663
664Provides APIs for private key operations. **PriKey** is a child class of [Key](#key). It needs to be passed in during asymmetric encryption and decryption, signing, and key agreement.
665
666The private key can be generated by using the asymmetric key generator [AsyKeyGenerator](#asykeygenerator) or [AsyKeyGeneratorBySpec](#asykeygeneratorbyspec10).
667
668### clearMem
669
670clearMem(): void
671
672Clears the keys in the memory. This API returns the result synchronously.
673
674**System capability**: SystemCapability.Security.CryptoFramework
675
676**Example**
677
678```ts
679let key: cryptoFramework.PriKey; // The key is a private key generated by the asymmetric key generator. The generation process is omitted here.
680key.clearMem(); // For the asymmetric private key, clearMem() releases the internal key struct. After clearMem is executed, getEncoded() is not supported.
681```
682
683### getAsyKeySpec<sup>10+</sup>
684
685getAsyKeySpec(itemType: AsyKeySpecItem): bigint | string | number
686
687Obtains a key parameter. This API returns the result synchronously.
688
689**System capability**: SystemCapability.Security.CryptoFramework
690
691**Parameters**
692
693| Name| Type                 | Mandatory| Description                |
694| ---- | --------------------- | ---- | -------------------- |
695| item  | [AsyKeySpecItem](#asykeyspecitem10) | Yes  | Key parameter to obtain.|
696
697**Return value**
698
699| Type                       | Description                             |
700| --------------------------- | --------------------------------- |
701| bigint\|string\|number | Content of the key parameter obtained.|
702
703**Error codes**
704For details about the error codes, see [Crypto Framework Error Codes](../errorcodes/errorcode-crypto-framework.md).
705
706| ID| Error Message              |
707| -------- | ---------------------- |
708| 401 | invalid parameters. |
709| 17620001 | memory error. |
710| 17630001 | crypto operation error. |
711
712**Example**
713
714```ts
715let key: cryptoFramework.PriKey; // key is a private key object. The generation process is omitted here.
716let p = key.getAsyKeySpec(cryptoFramework.AsyKeySpecItem.ECC_FP_P_BN);
717console.info('ecc item --- p: ' + p.toString(16));
718```
719
720## KeyPair
721
722Defines an asymmetric key pair, which includes a public key and a private key.
723
724The asymmetric key pair can be generated by using the asymmetric key generator [AsyKeyGenerator](#asykeygenerator) or [AsyKeyGeneratorBySpec](#asykeygeneratorbyspec10).
725
726> **NOTE**
727>
728> The **pubKey** and **priKey** objects in the **KeyPair** object exist as one parameter in the **KeyPair** object. When **KeyPair** leaves the scope, its internal objects can be destructed.
729>
730> The service must reference the **KeyPair** object instead of the internal **pubKey** or **priKey** object.
731
732### Attributes
733
734**System capability**: SystemCapability.Security.CryptoFramework
735
736| Name   | Type  | Readable| Writable| Description          |
737| ------- | ------ | ---- | ---- | ------------ |
738| priKey  | [PriKey](#prikey) | Yes  | No  | Private key.     |
739| pubKey | [PubKey](#pubkey) | Yes  | No  | Public key.      |
740
741## cryptoFramework.createSymKeyGenerator
742
743createSymKeyGenerator(algName: string): SymKeyGenerator
744
745Creates a **symKeyGenerator** instance based on the specified algorithm.
746
747For details about the supported specifications, see [Symmetric Key Generation and Conversion Specifications](../../security/CryptoArchitectureKit/crypto-sym-key-generation-conversion-spec.md).
748
749**System capability**: SystemCapability.Security.CryptoFramework
750
751**Parameters**
752
753| Name | Type  | Mandatory| Description                                                        |
754| ------- | ------ | ---- | ------------------------------------------------------------ |
755| algName | string | Yes  | Algorithm used to create the **symKeyGenerator** instance.<br>For details, see "String Parameter" in [Symmetric Key Generation and Conversion Specifications] (../../security/CryptoArchitectureKit/crypto-sym-key-generation-conversion-spec.md).|
756
757**Return value**
758
759| Type                               | Description                      |
760| ----------------------------------- | -------------------------- |
761| [SymKeyGenerator](#symkeygenerator) | **symKeyGenerator** instance created.|
762
763For details about the error codes, see [Crypto Framework Error Codes](../errorcodes/errorcode-crypto-framework.md).
764| ID| Error Message              |
765| -------- | ---------------------- |
766| 401 | invalid parameters. |
767| 801 | this operation is not supported. |
768
769**Example**
770
771```ts
772let symKeyGenerator = cryptoFramework.createSymKeyGenerator('3DES192');
773```
774
775## SymKeyGenerator
776
777Provides APIs for using the **symKeyGenerator**.
778
779Before using any API of the **SymKeyGenerator** class, you must create a **symKeyGenerator** instance by using [createSymKeyGenerator](#cryptoframeworkcreatesymkeygenerator).
780
781### Attributes
782
783**System capability**: SystemCapability.Security.CryptoFramework
784
785| Name   | Type  | Readable| Writable| Description                          |
786| ------- | ------ | ---- | ---- | ------------------------------ |
787| algName | string | Yes  | No  | Algorithm used by the **symKeyGenerator**.|
788
789### generateSymKey
790
791generateSymKey(callback: AsyncCallback\<SymKey>): void
792
793Generates a key randomly. This API uses an asynchronous callback to return the result.
794
795This API can be used only after a **symKeyGenerator** instance is created by using [createSymKeyGenerator](#cryptoframeworkcreatesymkeygenerator).
796
797**RAND_priv_bytes()** of OpenSSL can be used to generate random keys.
798
799> **NOTE**
800>
801> For the symmetric key used in the hash-based message authentication code (HMAC) algorithm, if the hash algorithm (for example, **HMAC|SHA256**) is specified when the symmetric key generator is created, a binary key with the same length as the hash value will be randomly generated. For example, if **HMAC|SHA256** is specified, a 256-bit key will be randomly generated. <br>If no hash algorithm is specified when the symmetric key generator is created (for example, only HMAC is specified), symmetric key data cannot be randomly generated. In this case, you can use [convertKey](#convertkey) to generate symmetric key data.
802
803**System capability**: SystemCapability.Security.CryptoFramework
804
805**Parameters**
806
807| Name    | Type                             | Mandatory| Description                                                        |
808| -------- | --------------------------------- | ---- | ------------------------------------------------------------ |
809| callback | AsyncCallback\<[SymKey](#symkey)> | Yes  | Callback invoked to return the result. If the operation is successful, **err** is **undefined** and **data** is the symmetric key generated. Otherwise, **err** is an error object.|
810
811**Error codes**
812For details about the error codes, see [Crypto Framework Error Codes](../errorcodes/errorcode-crypto-framework.md).
813
814| ID| Error Message     |
815| -------- | ------------- |
816| 17620001 | memory error. |
817
818**Example**
819
820```ts
821import cryptoFramework from '@ohos.security.cryptoFramework';
822
823let symKeyGenerator = cryptoFramework.createSymKeyGenerator('3DES192');
824  symKeyGenerator.generateSymKey((err, symKey) => {
825    console.info('Generate symKey success, algName: ' + symKey.algName);
826  });
827```
828
829### generateSymKey
830
831generateSymKey(): Promise\<SymKey>
832
833Generates a key randomly. This API uses a promise to return the result.
834
835This API can be used only after a **symKeyGenerator** instance is created by using [createSymKeyGenerator](#cryptoframeworkcreatesymkeygenerator).
836
837**RAND_priv_bytes()** of OpenSSL can be used to generate random keys.
838
839**System capability**: SystemCapability.Security.CryptoFramework
840
841**Return value**
842
843| Type                       | Description                             |
844| --------------------------- | --------------------------------- |
845| Promise\<[SymKey](#symkey)> | Promise used to return the symmetric key generated.|
846
847**Error codes**
848For details about the error codes, see [Crypto Framework Error Codes](../errorcodes/errorcode-crypto-framework.md).
849
850| ID| Error Message     |
851| -------- | ------------- |
852| 17620001 | memory error. |
853
854**Example**
855
856```ts
857import cryptoFramework from '@ohos.security.cryptoFramework';
858import { BusinessError } from '@ohos.base';
859
860let symKeyGenerator = cryptoFramework.createSymKeyGenerator('AES128');
861  symKeyGenerator.generateSymKey()
862    .then(symKey => {
863      console.info('Generate symKey success, algName: ' + symKey.algName);
864    }, (error: BusinessError) => {
865      console.error(`Generate symKey failed, ${error.code}, ${error.message}`);
866    });
867```
868
869### convertKey
870
871convertKey(key: DataBlob, callback: AsyncCallback\<SymKey>): void
872
873Converts data into a symmetric key. This API uses an asynchronous callback to return the result.
874
875This API can be used only after a **symKeyGenerator** instance is created by using [createSymKeyGenerator](#cryptoframeworkcreatesymkeygenerator).
876
877> **NOTE**
878>
879> For the symmetric key used in the HMAC algorithm, if the hash algorithm (for example, **HMAC|SHA256**) is specified when the symmetric key generator is created, the binary key data to be passed in must be of the same length as the hash. For example, if **HMAC|SHA256** is specified, a 256-bit key must be passed in. <br>If no hash algorithm is specified when the symmetric key generator is created (for example, only HMAC is specified), the length of the binary key data is in the range of [1,4096], in bytes.
880
881**System capability**: SystemCapability.Security.CryptoFramework
882
883**Parameters**
884
885| Name    | Type         | Mandatory| Description                      |
886| -------- | ------------------- | ---- | ---------------------|
887| key      | [DataBlob](#datablob)             | Yes  | Data to convert.                                        |
888| callback | AsyncCallback\<[SymKey](#symkey)> | Yes  | Callback invoked to return the result. If the operation is successful, **err** is **undefined** and **data** is the symmetric key generated. Otherwise, **err** is an error object.|
889
890**Error codes**
891For details about the error codes, see [Crypto Framework Error Codes](../errorcodes/errorcode-crypto-framework.md).
892
893| ID| Error Message                                              |
894| -------- | --------------------------------------------------- |
895| 401 | invalid parameters.          |
896| 17620001 | memory error.                                       |
897
898**Example**
899
900```ts
901import cryptoFramework from '@ohos.security.cryptoFramework';
902
903function genKeyMaterialBlob(): cryptoFramework.DataBlob {
904  let arr = [
905    0xba, 0x3d, 0xc2, 0x71, 0x21, 0x1e, 0x30, 0x56,
906    0xad, 0x47, 0xfc, 0x5a, 0x46, 0x39, 0xee, 0x7c,
907    0xba, 0x3b, 0xc2, 0x71, 0xab, 0xa0, 0x30, 0x72]; // keyLen = 192 (24 bytes)
908  let keyMaterial = new Uint8Array(arr);
909  return { data: keyMaterial };
910}
911
912function testConvertKey() {
913  let symKeyGenerator = cryptoFramework.createSymKeyGenerator('3DES192');
914  let keyMaterialBlob = genKeyMaterialBlob();
915  symKeyGenerator.convertKey(keyMaterialBlob, (err, symKey) => {
916    console.info('Convert symKey success, algName: ' + symKey.algName);
917  });
918}
919```
920
921### convertKey
922
923convertKey(key: DataBlob): Promise\<SymKey>
924
925Converts data into a symmetric key. This API uses a promise to return the result.
926
927This API can be used only after a **symKeyGenerator** instance is created by using [createSymKeyGenerator](#cryptoframeworkcreatesymkeygenerator).
928
929**System capability**: SystemCapability.Security.CryptoFramework
930
931**Parameters**
932
933| Name| Type                 | Mandatory| Description                |
934| ---- | --------------------- | ---- | -------------------- |
935| key  | [DataBlob](#datablob) | Yes  | Data to convert.|
936
937**Return value**
938
939| Type                       | Description                             |
940| --------------------------- | --------------------------------- |
941| Promise\<[SymKey](#symkey)> | Promise used to return the symmetric key generated.|
942
943**Error codes**
944For details about the error codes, see [Crypto Framework Error Codes](../errorcodes/errorcode-crypto-framework.md).
945
946| ID| Error Message                                         |
947| -------- | --------------------------------------------- |
948| 401 | invalid parameters.          |
949| 17620001 | memory error.                                |
950
951**Example**
952
953```ts
954import cryptoFramework from '@ohos.security.cryptoFramework';
955import { BusinessError } from '@ohos.base';
956
957function genKeyMaterialBlob(): cryptoFramework.DataBlob {
958  let arr = [
959    0xba, 0x3d, 0xc2, 0x71, 0x21, 0x1e, 0x30, 0x56,
960    0xad, 0x47, 0xfc, 0x5a, 0x46, 0x39, 0xee, 0x7c,
961    0xba, 0x3b, 0xc2, 0x71, 0xab, 0xa0, 0x30, 0x72]; // keyLen = 192 (24 bytes)
962  let keyMaterial = new Uint8Array(arr);
963  return { data: keyMaterial };
964}
965
966function testConvertKey() {
967  let symKeyGenerator = cryptoFramework.createSymKeyGenerator('3DES192');
968  let keyMaterialBlob = genKeyMaterialBlob();
969  symKeyGenerator.convertKey(keyMaterialBlob)
970    .then(symKey => {
971      console.info('Convert symKey success, algName: ' + symKey.algName);
972    }, (error: BusinessError) => {
973      console.error(`Convert symKey failed, ${error.code}, ${error.message}`);
974    });
975}
976```
977
978## cryptoFramework.createAsyKeyGenerator
979
980createAsyKeyGenerator(algName: string): AsyKeyGenerator
981
982Creates an **AsyKeyGenerator** instance based on the specified algorithm.
983
984For details about the supported specifications, see [Asymmetric Key Generation and Conversion Specifications](../../security/CryptoArchitectureKit/crypto-sym-key-generation-conversion-spec.md).
985
986**System capability**: SystemCapability.Security.CryptoFramework
987
988**Parameters**
989
990| Name | Type  | Mandatory| Description                            |
991| ------- | ------ | ---- | -------------------------------- |
992| algName | string | Yes  | Algorithm used to create the **symkeyGenerator**.|
993
994**Return value**
995
996| Type           | Description                        |
997| --------------- | ---------------------------- |
998| [AsyKeyGenerator](#asykeygenerator) | **AsyKeyGenerator** instance created.|
999
1000**Error codes**
1001For details about the error codes, see [Crypto Framework Error Codes](../errorcodes/errorcode-crypto-framework.md).
1002
1003| ID| Error Message              |
1004| -------- | ---------------------- |
1005| 401 | invalid parameters. |
1006| 801 | this operation is not supported. |
1007| 17620001 | memory error. |
1008
1009**Example**
1010
1011```ts
1012let asyKeyGenerator = cryptoFramework.createAsyKeyGenerator('ECC256');
1013```
1014
1015## AsyKeyGenerator
1016
1017Provides APIs for using the **AsKeyGenerator**. Before using any API of the **AsKeyGenerator** class, you must create an **AsyKeyGenerator** instance by using **createAsyKeyGenerator()**.
1018
1019### Attributes
1020
1021**System capability**: SystemCapability.Security.CryptoFramework
1022
1023| Name   | Type  | Readable| Writable| Description                            |
1024| ------- | ------ | ---- | ---- | -------------------------------- |
1025| algName | string | Yes  | No  | Algorithm used by the **AsKeyGenerator**.|
1026
1027### generateKeyPair
1028
1029generateKeyPair(callback: AsyncCallback\<KeyPair>): void
1030
1031Generates a key pair randomly. This API uses an asynchronous callback to return the result.
1032
1033**System capability**: SystemCapability.Security.CryptoFramework
1034
1035**Parameters**
1036
1037| Name    | Type                   | Mandatory| Description                          |
1038| -------- | ----------------------- | ---- | ------------------------------ |
1039| callback | AsyncCallback\<[KeyPair](#keypair)> | Yes  | Callback invoked to return the key pair obtained.|
1040
1041**Error codes**
1042For details about the error codes, see [Crypto Framework Error Codes](../errorcodes/errorcode-crypto-framework.md).
1043
1044| ID| Error Message              |
1045| -------- | ---------------------- |
1046| 401 | invalid parameters.          |
1047| 17620001 | memory error.          |
1048| 17630001 | crypto operation error.          |
1049
1050**Example**
1051
1052```ts
1053import cryptoFramework from '@ohos.security.cryptoFramework';
1054
1055let asyKeyGenerator = cryptoFramework.createAsyKeyGenerator('ECC256');
1056asyKeyGenerator.generateKeyPair((err, keyPair) => {
1057  if (err) {
1058    console.error("generateKeyPair: error.");
1059    return;
1060  }
1061  console.info('generateKeyPair: success.');
1062})
1063```
1064
1065### generateKeyPair
1066
1067generateKeyPair(): Promise\<KeyPair>
1068
1069Generates a key pair randomly. This API uses a promise to return the result.
1070
1071**System capability**: SystemCapability.Security.CryptoFramework
1072
1073**Return value**
1074
1075| Type             | Description                             |
1076| ----------------- | --------------------------------- |
1077| Promise\<[KeyPair](#keypair)> | Promise used to return the key pair generated.|
1078
1079**Error codes**
1080For details about the error codes, see [Crypto Framework Error Codes](../errorcodes/errorcode-crypto-framework.md).
1081
1082| ID| Error Message              |
1083| -------- | ---------------------- |
1084| 401 | invalid parameters.          |
1085| 17620001 | memory error.          |
1086| 17630001 | crypto operation error.          |
1087
1088**Example**
1089
1090```ts
1091import { BusinessError } from '@ohos.base';
1092
1093let asyKeyGenerator = cryptoFramework.createAsyKeyGenerator('ECC256');
1094let keyGenPromise = asyKeyGenerator.generateKeyPair();
1095keyGenPromise.then(keyPair => {
1096  console.info('generateKeyPair success.');
1097}).catch((error: BusinessError) => {
1098  console.error("generateKeyPair error.");
1099});
1100```
1101
1102### convertKey
1103
1104convertKey(pubKey: DataBlob | null, priKey: DataBlob | null, callback: AsyncCallback\<KeyPair\>): void
1105
1106Converts data into an asymmetric key. This API uses an asynchronous callback to return the result. For details, see **Key Conversion**.
1107
1108**System capability**: SystemCapability.Security.CryptoFramework
1109
1110**Parameters**
1111
1112| Name    | Type      | Mandatory| Description                          |
1113| -------- | ----------- | ---- | ------------------------------ |
1114| pubKey   | [DataBlob](#datablob) \| null<sup>10+</sup>    | Yes  | Public key material to convert. If no public key is required, set this parameter to **null**. In versions earlier than API version 10, only **DataBlob** is supported. Since API version 10, **null** is also supported.       |
1115| priKey   | [DataBlob](#datablob) \| null<sup>10+</sup>   | Yes  | Private key material to convert. If no private key is required, set this parameter to **null**. In versions earlier than API version 10, only **DataBlob** is supported. Since API version 10, **null** is also supported.       |
1116| callback | AsyncCallback\<[KeyPair](#keypair)> | Yes  | Callback invoked to return the key pair obtained.|
1117
1118**Error codes**
1119For details about the error codes, see [Crypto Framework Error Codes](../errorcodes/errorcode-crypto-framework.md).
1120
1121| ID| Error Message              |
1122| -------- | ---------------------- |
1123| 401 | invalid parameters.          |
1124| 17620001 | memory error.          |
1125| 17630001 | crypto operation error.          |
1126
1127**Example**
1128
1129```ts
1130import cryptoFramework from '@ohos.security.cryptoFramework';
1131
1132let 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]);
1133let 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]);
1134let pubKeyBlob: cryptoFramework.DataBlob = { data: pubKeyArray }; // Binary data of the public key.
1135let priKeyBlob: cryptoFramework.DataBlob = { data: priKeyArray }; // Binary data of the private key.
1136let asyKeyGenerator = cryptoFramework.createAsyKeyGenerator('ECC256');
1137asyKeyGenerator.convertKey(pubKeyBlob, priKeyBlob, (err, keyPair) => {
1138  if (err) {
1139    console.error("convertKey: error.");
1140    return;
1141  }
1142  console.info('convertKey: success.');
1143});
1144```
1145
1146### convertKey
1147
1148convertKey(pubKey: DataBlob | null, priKey: DataBlob | null): Promise\<KeyPair>
1149
1150Converts data into an asymmetric key. This API uses a promise to return the result. For details, see **Key Conversion**.
1151
1152**System capability**: SystemCapability.Security.CryptoFramework
1153
1154**Parameters**
1155
1156| Name  | Type   | Mandatory| Description            |
1157| ------ | -------- | ---- | ---------------- |
1158| pubKey | [DataBlob](#datablob) \| null<sup>10+</sup> | Yes  | Public key material to convert. If no public key is required, set this parameter to **null**. In versions earlier than API version 10, only **DataBlob** is supported. Since API version 10, **null** is also supported.|
1159| priKey | [DataBlob](#datablob) \| null<sup>10+</sup> | Yes  | Private key material to convert. If no private key is required, set this parameter to **null**. In versions earlier than API version 10, only **DataBlob** is supported. Since API version 10, **null** is also supported.|
1160
1161**Return value**
1162
1163| Type             | Description                             |
1164| ----------------- | --------------------------------- |
1165| Promise\<[KeyPair](#keypair)> | Promise used to return the key pair generated.|
1166
1167**Error codes**
1168For details about the error codes, see [Crypto Framework Error Codes](../errorcodes/errorcode-crypto-framework.md).
1169
1170| ID| Error Message              |
1171| -------- | ---------------------- |
1172| 401 | invalid parameters.          |
1173| 17620001 | memory error.          |
1174| 17630001 | crypto operation error.          |
1175
1176**Example**
1177
1178```ts
1179import { BusinessError } from '@ohos.base';
1180
1181let 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]);
1182let 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]);
1183let pubKeyBlob: cryptoFramework.DataBlob = { data: pubKeyArray }; // Binary data of the public key.
1184let priKeyBlob: cryptoFramework.DataBlob = { data: priKeyArray }; // Binary data of the private key.
1185let asyKeyGenerator = cryptoFramework.createAsyKeyGenerator('ECC256');
1186let keyGenPromise = asyKeyGenerator.convertKey(pubKeyBlob, priKeyBlob);
1187keyGenPromise.then(keyPair => {
1188  console.info('convertKey success.');
1189}).catch((error: BusinessError) => {
1190  console.error("convertKey error.");
1191});
1192```
1193
1194**Key Conversion**
1195
11961. After **getEncoded()** is called for the asymmetric (RSA, ECC, or DSA) public and private keys, binary data in X.509 format and binary data in PKCS #8 format are returned, respectively. The binary data can be used for cross-application transfer or persistent storage.
11972. The public key returned by **convertKey()** must comply with the ASN.1 syntax, X.509 specifications, and DER encoding format, and the private key must comply with the ASN.1 syntax, PKCS #8 specifications, and DER encoding format.
11983. In **convertKey()**, you can pass in either **pubKey** or **priKey**, or both of them. If one of them is passed in, the returned **KeyPair** instance contains only the key converted from the data you passed in.
1199
1200## cryptoFramework.createAsyKeyGeneratorBySpec<sup>10+</sup>
1201
1202createAsyKeyGeneratorBySpec(asyKeySpec: AsyKeySpec): AsyKeyGeneratorBySpec
1203
1204Creates an **AsyKeyGenerator** instance based on the specified key parameter.
1205
1206For details about the supported specifications, see [Asymmetric Key Generation and Conversion Specifications](../../security/CryptoArchitectureKit/crypto-sym-key-generation-conversion-spec.md).
1207
1208**System capability**: SystemCapability.Security.CryptoFramework
1209
1210**Parameters**
1211
1212| Name | Type  | Mandatory| Description                            |
1213| ------- | ------ | ---- | -------------------------------- |
1214| asyKeySpec | [AsyKeySpec](#asykeyspec10) | Yes  | Key parameters. The **AsyKeyGenerator** generates the public/private key based on the specified parameters.|
1215
1216**Return value**
1217
1218| Type                                           | Description                      |
1219| ----------------------------------------------- | -------------------------- |
1220| [AsyKeyGeneratorBySpec](#asykeygeneratorbyspec10) | Returns the **AsyKeyGenerator** instance created.|
1221
1222**Error codes**
1223For details about the error codes, see [Crypto Framework Error Codes](../errorcodes/errorcode-crypto-framework.md).
1224
1225| ID| Error Message              |
1226| -------- | ---------------------- |
1227| 401 | invalid parameters. |
1228| 801 | this operation is not supported. |
1229| 17620001 | memory error. |
1230
1231**Example**
1232
1233```ts
1234// Set the common parameters of the DSA1024 public and private keys.
1235function genDsa1024CommonSpecBigE() {
1236  let dsaCommonSpec: cryptoFramework.DSACommonParamsSpec = {
1237    algName: "DSA",
1238    specType: cryptoFramework.AsyKeySpecType.COMMON_PARAMS_SPEC,
1239    p: BigInt("0xed1501551b8ab3547f6355ffdc2913856ddeca198833dbd04f020e5f25e47c50e0b3894f7690a0d2ea5ed3a7be25c54292a698e1f086eb3a97deb4dbf04fcad2dafd94a9f35c3ae338ab35477e16981ded6a5b13d5ff20bf55f1b262303ad3a80af71aa6aa2354d20e9c82647664bdb6b333b7bea0a5f49d55ca40bc312a1729"),
1240    q: BigInt("0xd23304044019d5d382cfeabf351636c7ab219694ac845051f60b047b"),
1241    g: BigInt("0x2cc266d8bd33c3009bd67f285a257ba74f0c3a7e12b722864632a0ac3f2c17c91c2f3f67eb2d57071ef47aaa8f8e17a21ad2c1072ee1ce281362aad01dcbcd3876455cd17e1dd55d4ed36fa011db40f0bbb8cba01d066f392b5eaa9404bfcb775f2196a6bc20eeec3db32d54e94d87ecdb7a0310a5a017c5cdb8ac78597778bd"),
1242  }
1243  return dsaCommonSpec;
1244}
1245
1246// Set full parameters of the DSA1024 key pair.
1247function genDsa1024KeyPairSpecBigE() {
1248  let dsaCommonSpec = genDsa1024CommonSpecBigE();
1249  let dsaKeyPairSpec: cryptoFramework.DSAKeyPairSpec = {
1250    algName: "DSA",
1251    specType: cryptoFramework.AsyKeySpecType.KEY_PAIR_SPEC,
1252    params: dsaCommonSpec,
1253    sk: BigInt("0xa2dd2adb2d11392c2541930f61f1165c370aabd2d78d00342e0a2fd9"),
1254    pk: BigInt("0xae6b5d5042e758f3fc9a02d009d896df115811a75b5f7b382d8526270dbb3c029403fafb8573ba4ef0314ea86f09d01e82a14d1ebb67b0c331f41049bd6b1842658b0592e706a5e4d20c14b67977e17df7bdd464cce14b5f13bae6607760fcdf394e0b73ac70aaf141fa4dafd736bd0364b1d6e6c0d7683a5de6b9221e7f2d6b"),
1255  }
1256  return dsaKeyPairSpec;
1257}
1258
1259let asyKeyPairSpec = genDsa1024KeyPairSpecBigE(); // The JS input must be a positive number in big-endian format.
1260let asyKeyGeneratorBySpec = cryptoFramework.createAsyKeyGeneratorBySpec(asyKeyPairSpec);
1261```
1262
1263## AsyKeyGeneratorBySpec<sup>10+</sup>
1264
1265Provides APIs for using the **AsKeyGenerator**. Before using the APIs of this class, you need to use [createAsyKeyGeneratorBySpec()](#cryptoframeworkcreateasykeygeneratorbyspec10) to create an **AsyKeyGeneratorBySpec** instance.
1266
1267### Attributes
1268
1269**System capability**: SystemCapability.Security.CryptoFramework
1270
1271| Name   | Type  | Readable| Writable| Description                      |
1272| ------- | ------ | ---- | ---- | -------------------------- |
1273| algName | string | Yes  | No  | Algorithm used by the asymmetric key generator.|
1274
1275### generateKeyPair
1276
1277generateKeyPair(callback: AsyncCallback\<KeyPair>): void
1278
1279Generates an asymmetric key pair. This API uses an asynchronous callback to return the result.
1280
1281If a key parameter of the [COMMON_PARAMS_SPEC](#asykeyspectype10) type is used to create the key generator, a key pair will be randomly generated. If a key parameter of the [KEY_PAIR_SPEC](#asykeyspectype10) type is used to create the key generator, you can obtain a key pair that is consistent with the specified key parameters.
1282
1283**System capability**: SystemCapability.Security.CryptoFramework
1284
1285**Parameters**
1286
1287| Name    | Type                   | Mandatory| Description                          |
1288| -------- | ----------------------- | ---- | ------------------------------ |
1289| callback | AsyncCallback\<[KeyPair](#keypair)> | Yes  | Callback invoked to return the key pair obtained.|
1290
1291**Error codes**
1292For details about the error codes, see [Crypto Framework Error Codes](../errorcodes/errorcode-crypto-framework.md).
1293
1294| ID| Error Message               |
1295| -------- | ----------------------- |
1296| 401 | invalid parameters.          |
1297| 17620001 | memory error.           |
1298| 17630001 | crypto operation error. |
1299
1300**Example**
1301
1302```ts
1303let asyKeyPairSpec: cryptoFramework.DSAKeyPairSpec; // Use DSA as an example. asyKeyPairSpec specifies full parameters of the private and public keys. The generation process is omitted here.
1304let asyKeyGeneratorBySpec = cryptoFramework.createAsyKeyGeneratorBySpec(asyKeyPairSpec);
1305asyKeyGeneratorBySpec.generateKeyPair((err, keyPair) => {
1306  if (err) {
1307    console.error("generateKeyPair: error.");
1308    return;
1309  }
1310  console.info('generateKeyPair: success.');
1311})
1312```
1313
1314### generateKeyPair
1315
1316generateKeyPair(): Promise\<KeyPair>
1317
1318Generates an asymmetric key pair. This API uses a promise to return the result.
1319
1320If a key parameter of the [COMMON_PARAMS_SPEC](#asykeyspectype10) type is used to create the key generator, a key pair will be randomly generated. If a key parameter of the [KEY_PAIR_SPEC](#asykeyspectype10) type is used to create the key generator, you can obtain a key pair that is consistent with the specified key parameters.
1321
1322**System capability**: SystemCapability.Security.CryptoFramework
1323
1324**Return value**
1325
1326| Type             | Description                             |
1327| ----------------- | --------------------------------- |
1328| Promise\<[KeyPair](#keypair)> | Promise used to return the key pair generated.|
1329
1330**Error codes**
1331For details about the error codes, see [Crypto Framework Error Codes](../errorcodes/errorcode-crypto-framework.md).
1332
1333| ID| Error Message              |
1334| -------- | ---------------------- |
1335| 401 | invalid parameters.          |
1336| 17620001 | memory error.          |
1337| 17630001 | crypto operation error. |
1338
1339**Example**
1340
1341```ts
1342import { BusinessError } from '@ohos.base';
1343
1344let asyKeyPairSpec: cryptoFramework.DSAKeyPairSpec; // Use DSA as an example. asyKeyPairSpec specifies full parameters of the private and public keys. The generation process is omitted here.
1345let asyKeyGeneratorBySpec = cryptoFramework.createAsyKeyGeneratorBySpec(asyKeyPairSpec);
1346let keyGenPromise = asyKeyGeneratorBySpec.generateKeyPair();
1347keyGenPromise.then(keyPair => {
1348  console.info('generateKeyPair success.');
1349}).catch((error: BusinessError) => {
1350  console.error("generateKeyPair error.");
1351});
1352```
1353
1354### generatePriKey
1355
1356generatePriKey(callback: AsyncCallback\<PriKey>): void
1357
1358Generates an asymmetric key pair. This API uses an asynchronous callback to return the result.
1359
1360If a key parameter of the [PRIVATE_KEY_SPEC](#asykeyspectype10) type is used to create the key generator, the specified private key can be obtained. If a key parameter of the [KEY_PAIR_SPEC](#asykeyspectype10) type is used to create the key generator, you can obtain the specified private key from the key pair generated.
1361
1362**System capability**: SystemCapability.Security.CryptoFramework
1363
1364**Parameters**
1365
1366| Name    | Type                   | Mandatory| Description                          |
1367| -------- | ----------------------- | ---- | ------------------------------ |
1368| callback | AsyncCallback\<[PriKey](#prikey)> | Yes  | Callback invoked to return the key pair obtained.|
1369
1370**Error codes**
1371For details about the error codes, see [Crypto Framework Error Codes](../errorcodes/errorcode-crypto-framework.md).
1372
1373| ID| Error Message              |
1374| -------- | ---------------------- |
1375| 401 | invalid parameters.          |
1376| 17620001 | memory error.          |
1377| 17630001 | crypto operation error. |
1378
1379**Example**
1380
1381```ts
1382let asyKeyPairSpec: cryptoFramework.DSAKeyPairSpec; // Use DSA as an example. asyKeyPairSpec specifies full parameters of the private and public keys. The generation process is omitted here.
1383let asyKeyGeneratorBySpec = cryptoFramework.createAsyKeyGeneratorBySpec(asyKeyPairSpec);
1384asyKeyGeneratorBySpec.generatePriKey((err, prikey) => {
1385  if (err) {
1386    console.error("generatePriKey: error.");
1387    return;
1388  }
1389  console.info('generatePriKey: success.');
1390})
1391```
1392
1393### generatePriKey
1394
1395generatePriKey(): Promise\<PriKey>
1396
1397Generates an asymmetric key pair. This API uses a promise to return the result.
1398
1399If a key parameter of the [PRIVATE_KEY_SPEC](#asykeyspectype10) type is used to create the key generator, the specified private key can be obtained. If a key parameter of the [KEY_PAIR_SPEC](#asykeyspectype10) type is used to create the key generator, you can obtain the specified private key from the key pair generated.
1400
1401**System capability**: SystemCapability.Security.CryptoFramework
1402
1403**Return value**
1404
1405| Type             | Description                             |
1406| ----------------- | --------------------------------- |
1407| Promise\<[PriKey](#prikey)> | Promise used to return the key pair generated.|
1408
1409**Error codes**
1410For details about the error codes, see [Crypto Framework Error Codes](../errorcodes/errorcode-crypto-framework.md).
1411
1412| ID| Error Message              |
1413| -------- | ---------------------- |
1414| 401 | invalid parameters.          |
1415| 17620001 | memory error.          |
1416| 17630001 | crypto operation error. |
1417
1418**Example**
1419
1420```ts
1421import { BusinessError } from '@ohos.base';
1422
1423let asyKeyPairSpec: cryptoFramework.DSAKeyPairSpec; // Use DSA as an example. asyKeyPairSpec specifies full parameters of the private and public keys. The generation process is omitted here.
1424let asyKeyGeneratorBySpec = cryptoFramework.createAsyKeyGeneratorBySpec(asyKeyPairSpec);
1425let keyGenPromise = asyKeyGeneratorBySpec.generatePriKey();
1426keyGenPromise.then(priKey => {
1427  console.info('generatePriKey success.');
1428}).catch((error: BusinessError) => {
1429  console.error("generatePriKey error.");
1430});
1431```
1432
1433### generatePubKey
1434
1435generatePubKey(callback: AsyncCallback\<PubKey>): void
1436
1437Generates an asymmetric key pair. This API uses an asynchronous callback to return the result.
1438
1439If a key parameter of the [PUBLIC_KEY_SPEC](#asykeyspectype10) type is used to create the key generator, the specified public key can be obtained. If a key parameter of the [KEY_PAIR_SPEC](#asykeyspectype10) type is used to create the key generator, you can obtain the specified public key from the key pair generated.
1440
1441**System capability**: SystemCapability.Security.CryptoFramework
1442
1443**Parameters**
1444
1445| Name    | Type                   | Mandatory| Description                          |
1446| -------- | ----------------------- | ---- | ------------------------------ |
1447| callback | AsyncCallback\<[PubKey](#pubkey)> | Yes  | Callback invoked to return the key pair obtained.|
1448
1449**Error codes**
1450For details about the error codes, see [Crypto Framework Error Codes](../errorcodes/errorcode-crypto-framework.md).
1451
1452| ID| Error Message              |
1453| -------- | ---------------------- |
1454| 401 | invalid parameters.          |
1455| 17620001 | memory error.          |
1456| 17630001 | crypto operation error. |
1457
1458**Example**
1459
1460```ts
1461let asyKeyPairSpec: cryptoFramework.DSAKeyPairSpec; // Use DSA as an example. asyKeyPairSpec specifies full parameters of the private and public keys. The generation process is omitted here.
1462let asyKeyGeneratorBySpec = cryptoFramework.createAsyKeyGeneratorBySpec(asyKeyPairSpec);
1463asyKeyGeneratorBySpec.generatePubKey((err, pubKey) => {
1464  if (err) {
1465    console.error("generatePubKey: error.");
1466    return;
1467  }
1468  console.info('generatePubKey: success.');
1469})
1470```
1471
1472### generatePubKey
1473
1474generatePubKey(): Promise\<PubKey>
1475
1476Generates an asymmetric key pair. This API uses a promise to return the result.
1477
1478If a key parameter of the [PUBLIC_KEY_SPEC](#asykeyspectype10) type is used to create the key generator, the specified public key can be obtained. If a key parameter of the [KEY_PAIR_SPEC](#asykeyspectype10) type is used to create the key generator, you can obtain the specified public key from the key pair generated.
1479
1480**System capability**: SystemCapability.Security.CryptoFramework
1481
1482**Return value**
1483
1484| Type             | Description                             |
1485| ----------------- | --------------------------------- |
1486| Promise\<[PubKey](#pubkey)> | Promise used to return the key pair generated.|
1487
1488**Error codes**
1489For details about the error codes, see [Crypto Framework Error Codes](../errorcodes/errorcode-crypto-framework.md).
1490
1491| ID| Error Message              |
1492| -------- | ---------------------- |
1493| 401 | invalid parameters.          |
1494| 17620001 | memory error.          |
1495| 17630001 | crypto operation error. |
1496
1497**Example**
1498
1499```ts
1500import { BusinessError } from '@ohos.base';
1501
1502let asyKeyPairSpec: cryptoFramework.DSAKeyPairSpec; // Use DSA as an example. asyKeyPairSpec specifies full parameters of the private and public keys. The generation process is omitted here.
1503let asyKeyGeneratorBySpec = cryptoFramework.createAsyKeyGeneratorBySpec(asyKeyPairSpec);
1504let keyGenPromise = asyKeyGeneratorBySpec.generatePubKey();
1505keyGenPromise.then(pubKey => {
1506  console.info('generatePubKey success.');
1507}).catch((error: BusinessError) => {
1508  console.error("generatePubKey error.");
1509});
1510```
1511
1512## ECCKeyUtil<sup>11+</sup>
1513
1514Provides APIs for generating common parameters for an asymmetric key pair based on the elliptic curve name.
1515
1516### genECCCommonParamsSpec<sup>11+</sup>
1517
1518static genECCCommonParamsSpec(curveName: string): ECCCommonParamsSpec
1519
1520Generates common parameters for an asymmetric key pair based on the specified name identifier (NID) of an elliptic curve. For details, see [ECC](../../security/CryptoArchitectureKit/crypto-asym-key-generation-conversion-spec.md#ecc) and [SM2](../../security/CryptoArchitectureKit/crypto-asym-key-generation-conversion-spec.md#sm2).
1521
1522**System capability**: SystemCapability.Security.CryptoFramework
1523
1524**Parameters**
1525
1526| Name | Type  | Mandatory| Description                                          |
1527| ------- | ------ | ---- | ---------------------------------------------- |
1528| algName | string | Yes  | NID of the elliptic curve.|
1529
1530**Return value**
1531
1532| Type             | Description                             |
1533| ----------------- | --------------------------------- |
1534| [ECCCommonParamsSpec](#ecccommonparamsspec10) | ECC common parameters generated.|
1535
1536**Error codes**
1537For details about the error codes, see [Crypto Framework Error Codes](../errorcodes/errorcode-crypto-framework.md).
1538
1539| ID| Error Message                        |
1540| -------- | -------------------------------- |
1541| 401      | invalid parameters.              |
1542| 801      | this operation is not supported. |
1543| 17620001 | memory error.                    |
1544
1545**Example**
1546
1547```ts
1548import cryptoFramework from "@ohos.security.cryptoFramework";
1549import { BusinessError } from '@ohos.base';
1550try {
1551    let ECCCommonParamsSpec = cryptoFramework.ECCKeyUtil.genECCCommonParamsSpec('NID_brainpoolP160r1');
1552    console.info('genECCCommonParamsSpec success');
1553} catch (err) {
1554    let e: BusinessError = err as BusinessError;
1555    console.error(`genECCCommonParamsSpec error, ${e.code}, ${e.message}`);
1556}
1557```
1558
1559## DHKeyUtil<sup>11+</sup>
1560
1561Provides APIs for generating common parameters for a DH key based on the prime **p** length and the private key length.
1562
1563### genDHCommonParamsSpec<sup>11+</sup>
1564
1565static genDHCommonParamsSpec(pLen: number, skLen?: number): DHCommonParamsSpec
1566
1567Generates common parameters for a DH key based on the prime **p** length and the private key length. For details, see [DH](../../security/CryptoArchitectureKit/crypto-asym-key-generation-conversion-spec.md#dh).
1568
1569**System capability**: SystemCapability.Security.CryptoFramework
1570
1571**Parameters**
1572
1573| Name| Type  | Mandatory| Description                                            |
1574| ------ | ------ | ---- | ------------------------------------------------ |
1575| pLen   | number | Yes  | Length of the prime **p**, in bits.|
1576| skLen  | number | No  | Length of the private key, in bits. |
1577
1578**Return value**
1579
1580| Type             | Description                             |
1581| ----------------- | --------------------------------- |
1582| [DHCommonParamsSpec](#dhcommonparamsspec11) | DH common parameters generated.|
1583
1584**Error codes**
1585For details about the error codes, see [Crypto Framework Error Codes](../errorcodes/errorcode-crypto-framework.md).
1586
1587| ID| Error Message                        |
1588| -------- | -------------------------------- |
1589| 401      | invalid parameters.              |
1590| 801      | this operation is not supported. |
1591| 17620001 | memory error.                    |
1592| 17630001 | crypto operation error.          |
1593
1594**Example**
1595
1596```ts
1597import cryptoFramework from "@ohos.security.cryptoFramework";
1598import { BusinessError } from '@ohos.base';
1599try {
1600    let DHCommonParamsSpec = cryptoFramework.DHKeyUtil.genDHCommonParamsSpec(2048);
1601    console.info('genDHCommonParamsSpec success');
1602} catch (err) {
1603    let e: BusinessError = err as BusinessError;
1604    console.error(`genDHCommonParamsSpec error, ${e.code}, ${e.message}`);
1605}
1606```
1607
1608## cryptoFramework.createCipher
1609
1610createCipher(transformation: string): Cipher
1611
1612Creates a [Cipher](#cipher) instance based on the specified algorithm.
1613
1614For details about the supported specifications, see [Symmetric Key Encryption and Decryption Algorithm Specifications](../../security/CryptoArchitectureKit/crypto-sym-encrypt-decrypt-spec.md) and [Asymmetric Key Encryption and Decryption Algorithm Specifications](../../security/CryptoArchitectureKit/crypto-asym-encrypt-decrypt-spec.md).
1615
1616**System capability**: SystemCapability.Security.CryptoFramework
1617
1618**Parameters**
1619
1620| Name        | Type  | Mandatory| Description                                                        |
1621| -------------- | ------ | ---- | ------------------------------------------------------------ |
1622| transformation | string | Yes  | Combination of the algorithm name (including the key length), encryption mode, and padding algorithm of the **Cipher** instance to create.|
1623
1624> **NOTE**
1625>
1626> 1. In symmetric encryption and decryption, the implementation of PKCS #5 is the same as that of PKCS #7. PKCS #5 and PKCS #7 use the same padding length and block length. That is, data is padded with 8 bytes in 3DES and 16 bytes in AES. **noPadding** indicates that no padding is performed.
1627> <br>You need to understand the differences between different block cipher modes and use the correct parameter specifications. For example, padding is required for ECB and CBC. Otherwise, ensure that the plaintext length is an integer multiple of the block size. No padding is recommended for other modes. In this case, the ciphertext length is the same as the plaintext length.
1628> 2. When RSA or SM2 is used for asymmetric encryption and decryption, create a **Cipher** instance for encryption and decryption respectively. Do not use the same **Cipher** instance for encryption and decryption. For symmetric encryption and decryption, one **cipher** object can be used to perform both encryption and decryption as long as the algorithm specifications are the same.
1629
1630**Return value**
1631
1632| Type             | Description                    |
1633| ----------------- | ------------------------ |
1634| [Cipher](#cipher) | [Cipher](#cipher) instance created.|
1635
1636**Error codes**
1637For details about the error codes, see [Crypto Framework Error Codes](../errorcodes/errorcode-crypto-framework.md).
1638
1639| ID| Error Message              |
1640| -------- | ---------------------- |
1641| 401 | invalid parameters.          |
1642| 801 | this operation is not supported. |
1643| 17620001 | memory error.          |
1644
1645**Example**
1646
1647```ts
1648import { BusinessError } from '@ohos.base';
1649
1650let cipherAlgName = '3DES192|ECB|PKCS7';
1651try {
1652  let cipher = cryptoFramework.createCipher(cipherAlgName);
1653  console.info('cipher algName: ' + cipher.algName);
1654} catch (error) {
1655  let e: BusinessError = error as BusinessError;
1656  console.error(`sync error, ${e.code}, ${e.message}`);
1657}
1658```
1659
1660## Cipher
1661
1662Provides APIs for cipher operations. The [init()](#init-1), [update()](#update), and [doFinal()](#dofinal) APIs in this class are called in sequence to implement symmetric encryption or decryption and asymmetric encryption or decryption.
1663
1664For details about the encryption and decryption process, see [Encryption and Decryption Overview] (../../security/CryptoArchitectureKit/crypto-encryption-decryption-overview.md).
1665
1666A complete symmetric encryption/decryption process is slightly different from the asymmetric encryption/decryption process.
1667
1668- Symmetric encryption and decryption: **init()** and **doFinal()** are mandatory. **update()** is optional and can be called multiple times to encrypt or decrypt big data. After **doFinal()** is called to complete an encryption or decryption operation, **init()** can be called to start a new encryption or decryption operation.
1669- RSA or SM2 asymmetric encryption and decryption: **init()** and **doFinal()** are mandatory, and **update()** is not supported. **doFinal()** can be called multiple times to encrypt or decrypt big data. **init()** cannot be called repeatedly. If the encryption/decryption mode or padding mode is changed, a new **Cipher** object must be created.
1670
1671### Attributes
1672
1673**System capability**: SystemCapability.Security.CryptoFramework
1674
1675| Name   | Type  | Readable| Writable| Description                        |
1676| ------- | ------ | ---- | ---- | ---------------------------- |
1677| algName | string | Yes  | No  | Algorithm.|
1678
1679### init
1680
1681init(opMode: CryptoMode, key: Key, params: ParamsSpec | null, callback: AsyncCallback\<void>): void
1682
1683Initializes a [cipher](#cipher) instance. This API uses an asynchronous callback to return the result. **init**, **update**, and **doFinal** must be used together. **init** and **doFinal** are mandatory, and **update** is optional.
1684
1685This API can be used only after a [Cipher](#cipher) instance is created by using [createCipher](#cryptoframeworkcreatecipher).
1686
1687**System capability**: SystemCapability.Security.CryptoFramework
1688
1689**Parameters**
1690
1691| Name    | Type                     | Mandatory| Description                                                        |
1692| -------- | ------------------------- | ---- | ------------------------------------------------------------ |
1693| opMode   | [CryptoMode](#cryptomode) | Yes  | Operation (encryption or decryption) to perform.                                          |
1694| key      | [Key](#key)               | Yes  | Key for encryption or decryption.                                      |
1695| params   | [ParamsSpec](#paramsspec) \| null<sup>10+</sup> | Yes  | Parameters for encryption or decryption. For algorithm modes without parameters (such as ECB), **null** can be passed in. In versions earlier than API version 10, only **ParamsSpec** is supported. Since API version 10, **null** is also supported.|
1696| callback | AsyncCallback\<void>      | Yes  | Callback invoked to return the result. If the operation is successful, **err** is **undefined**. Otherwise, **err** is an error object.    |
1697
1698**Error codes**
1699For details about the error codes, see [Crypto Framework Error Codes](../errorcodes/errorcode-crypto-framework.md).
1700
1701| ID| Error Message                                                |
1702| -------- | --------------------------------------------------------- |
1703| 401 | invalid parameters.          |
1704| 17620001 | memory error.                                            |
1705| 17620002 | runtime error.                                           |
1706| 17630001 | crypto operation error.|
1707
1708### init
1709
1710init(opMode: CryptoMode, key: Key, params: ParamsSpec | null): Promise\<void>
1711
1712Initializes a [cipher](#cipher) instance. This API uses a promise to return the result. **init**, **update**, and **doFinal** must be used together. **init** and **doFinal** are mandatory, and **update** is optional.
1713
1714This API can be used only after a [Cipher](#cipher) instance is created by using [createCipher](#cryptoframeworkcreatecipher).
1715
1716**System capability**: SystemCapability.Security.CryptoFramework
1717
1718**Parameters**
1719
1720| Name  | Type                     | Mandatory| Description                                                        |
1721| ------ | ------------------------- | ---- | ------------------------------------------------------------ |
1722| opMode | [CryptoMode](#cryptomode) | Yes  | Operation (encryption or decryption) to perform.                                          |
1723| key    | [Key](#key)               | Yes  | Key for encryption or decryption.                                      |
1724| params | [ParamsSpec](#paramsspec) \| null<sup>10+</sup> | Yes  | Parameters for encryption or decryption. For algorithm modes without parameters (such as ECB), **null** can be passed in. In versions earlier than API version 10, only **ParamsSpec** is supported. Since API version 10, **null** is also supported.|
1725
1726**Return value**
1727
1728| Type          | Description                                  |
1729| -------------- | -------------------------------------- |
1730| Promise\<void> | Promise that returns no value.|
1731
1732**Error codes**
1733For details about the error codes, see [Crypto Framework Error Codes](../errorcodes/errorcode-crypto-framework.md).
1734
1735| ID| Error Message                                         |
1736| -------- | ------------------------------------------------- |
1737| 401 | invalid parameters.          |
1738| 17620001 | memory error.                                     |
1739| 17620002 | runtime error.                                    |
1740| 17630001 | crypto operation error.|
1741
1742### update
1743
1744update(data: DataBlob, callback: AsyncCallback\<DataBlob>): void
1745
1746Updates the data to encrypt or decrypt by segment. This API uses an asynchronous callback to return the encrypted or decrypted data.
1747
1748This API can be called only after the [Cipher](#cipher) instance is initialized by using [init()](init-1).
1749
1750> **NOTE**
1751>
1752> 1. The **update** and **doFinal** operation results vary with the block mode used. If you are not familiar with the block modes for symmetric encryption and decryption, add a judgment to determine whether the result of each **update** and **doFinal** is null. If the result is not null, obtain the data to concatenate the complete ciphertext or plaintext.  <br>For example, in ECB and CBC modes, data is encrypted or decrypted by block no matter whether the data passed in by **update()** is an integer multiple of the block length, and the encryption/decryption block result generated by this **update()** is output.<br>That is, encrypted/decrypted data is returned as long as the data passed in by **update()** reaches the size of a block. Otherwise, **null** is returned and the data will be retained until a block is formed in the next **update()**/**doFinal()**.<br>When **doFinal()** is called, the data that has not been encrypted or decrypted will be padded based on the padding mode set in [createCipher](#cryptoframeworkcreatecipher) to an integer multiple of the block length, and then encrypted or decrypted.<br>For a mode in which a block cipher can be converted into a stream cipher, the length of the ciphertext may be the same as that of the plaintext.
1753> 2. You can use **update()** multiple times or do not use it (use **doFinal()** after **init()**), depending on the size of the data.<br>
1754>    The data to be passed in **updated()** (once or accumulatively) is not size bound. For symmetric encryption and decryption of a large amount of data, you are advised to call **update()** multiple times to pass in the data by segment.<br>
1755>    For details about the sample code for calling **update** multiple times, see [Encryption and Decryption by Segment with an AES Symmetric Key (GCM Mode)](../../security/CryptoArchitectureKit/crypto-aes-sym-encrypt-decrypt-gcm-by-segment.md).
1756> 3. RSA or SM2 asymmetric encryption and decryption do not support **update()**.
1757
1758**System capability**: SystemCapability.Security.CryptoFramework
1759
1760**Parameters**
1761
1762| Name    | Type                                 | Mandatory| Description                                                        |
1763| -------- | ------------------------------------- | ---- | ------------------------------------------------------------ |
1764| data     | [DataBlob](#datablob)                 | Yes  | Data to encrypt or decrypt. It cannot be **null** or {data:Uint8Array (empty)}.          |
1765| callback | AsyncCallback\<[DataBlob](#datablob)> | Yes  | Callback invoked to return the result. If the operation is successful, **err** is **undefined**, and **data** is **DataBlob** (containing the encrypted or decrypted data). Otherwise, **err** is an error object.|
1766
1767**Error codes**
1768For details about the error codes, see [Crypto Framework Error Codes](../errorcodes/errorcode-crypto-framework.md).
1769
1770| ID| Error Message                                   |
1771| -------- | ------------------------------------------- |
1772| 401 | invalid parameters.          |
1773| 17620001 | memory error.                               |
1774| 17620002 | runtime error.                              |
1775| 17630001 | crypto operation error.                     |
1776
1777### update
1778
1779update(data: DataBlob): Promise\<DataBlob>
1780
1781Updates the data to encrypt or decrypt by segment. This API uses a promise to return the encrypted or decrypted data.
1782
1783This API can be called only after the [Cipher](#cipher) instance is initialized by using [init()](init-2).
1784
1785> **NOTE**
1786>
1787> 1. The **update** and **doFinal** operation results vary with the block mode used. If you are not familiar with the block modes for symmetric encryption and decryption, add a judgment to determine whether the result of each **update** and **doFinal** is null. If the result is not null, obtain the data to concatenate the complete ciphertext or plaintext.  <br>For example, in ECB and CBC modes, data is encrypted or decrypted by block no matter whether the data passed in by **update()** is an integer multiple of the block length, and the encryption/decryption block result generated by this **update()** is output.<br>That is, encrypted/decrypted data is returned as long as the data passed in by **update()** reaches the size of a block. Otherwise, **null** is returned and the data will be retained until a block is formed in the next **update()**/**doFinal()**.<br>When **doFinal()** is called, the data that has not been encrypted or decrypted will be padded based on the padding mode set in [createCipher](#cryptoframeworkcreatecipher) to an integer multiple of the block length, and then encrypted or decrypted.<br>For a mode in which a block cipher can be converted into a stream cipher, the length of the ciphertext may be the same as that of the plaintext.
1788> 2. You can use **update()** multiple times or do not use it (use **doFinal()** after **init()**), depending on the size of the data.<br>
1789> The data to be passed in **updated()** (once or accumulatively) is not size bound. For symmetric encryption and decryption of a large amount of data, you are advised to call **update()** multiple times to pass in the data by segment.<br>
1790>    For details about the sample code for calling **update** multiple times, see [Encryption and Decryption by Segment with an AES Symmetric Key (GCM Mode)](../../security/CryptoArchitectureKit/crypto-aes-sym-encrypt-decrypt-gcm-by-segment.md).
1791>    3. RSA or SM2 asymmetric encryption and decryption do not support **update()**.
1792
1793**System capability**: SystemCapability.Security.CryptoFramework
1794
1795**Parameters**
1796
1797| Name| Type                 | Mandatory| Description                |
1798| ---- | --------------------- | ---- | -------------------- |
1799| data | [DataBlob](#datablob) | Yes  | Data to encrypt or decrypt. It cannot be **null** or {data:Uint8Array (empty)}.|
1800
1801**Return value**
1802
1803| Type                           | Description                                            |
1804| ------------------------------- | ------------------------------------------------ |
1805| Promise\<[DataBlob](#datablob)> | Promise used to return the **DataBlob** (containing the encrypted or decrypted data).|
1806
1807**Error codes**
1808For details about the error codes, see [Crypto Framework Error Codes](../errorcodes/errorcode-crypto-framework.md).
1809
1810| ID| Error Message                                    |
1811| -------- | -------------------------------------------- |
1812| 401 | invalid parameters.          |
1813| 17620001 | memory error.                                |
1814| 17620002 | runtime error.                               |
1815| 17630001 | crypto operation error.                      |
1816
1817### doFinal
1818
1819doFinal(data: DataBlob | null, callback: AsyncCallback\<DataBlob>): void
1820
1821(1) Encrypts or decrypts the remaining data (generated by the block cipher mode) and the data passed in by **doFinal()** to finalize the symmetric encryption or decryption. This API uses an asynchronous callback to return the encrypted or decrypted data.<br>If a small amount of data needs to be encrypted or decrypted, you can use **doFinal()** to pass in data without using **update()**. If all the data has been passed in by [update()](#update-4), you can pass in **null** in **data** of **doFinal()**.
1822
1823The output of **doFinal()** varies with the symmetric encryption/decryption mode in use.
1824
1825- Symmetric encryption in GCM and CCM mode: The result consists of the ciphertext and **authTag** (the last 16 bytes for GCM and the last 12 bytes for CCM). If **data** in **doFinal** is null, the result of **doFinal** is **authTag**.<br>Set **authTag** to [GcmParamsSpec](#gcmparamsspec) or [CcmParamsSpec](#ccmparamsspec) for decryption. The ciphertext is used as the input parameter **data** for decryption.
1826- Symmetric encryption and decryption in other modes and symmetric decryption in GCM and CCM modes: The result is the complete plaintext/ciphertext.
1827
1828(2) Encrypts or decrypts the input data for RSA or SM2 asymmetric encryption/decryption. This API uses an asynchronous callback to return the result. If a large amount of data needs to be encrypted/decrypted, call **doFinal()** multiple times and concatenate the result of each **doFinal()** to obtain the complete plaintext/ciphertext.
1829
1830> **NOTE**
1831>
1832>  1. In symmetric encryption and decryption, after **doFinal** is called, the encryption and decryption process is complete and the [Cipher](#cipher) instance is cleared. When a new encryption and decryption process is started, **init()** must be called with a complete parameter list for initialization.<br>Even if the same symmetric key is used to encrypt and decrypt the same **Cipher** instance, the **params** parameter must be set when **init** is called during decryption.
1833>  2. If a decryption fails, check whether the data to be encrypted and decrypted matches the parameters in **init()**. For the GCM mode, check whether the **authTag** obtained after encryption is obtained from the **GcmParamsSpec** for decryption.
1834>  3. The result of **doFinal()** may be **null**. To avoid exceptions, determine whether the result is **null** before using the **.data** field to access the **doFinal()** result.
1835>  4. For details about the sample code for calling **doFinal** multiple times in asymmetric encryption and decryption, see [Encryption and Decryption by Segment with an RSA Asymmetric Key Pair](../../security/CryptoArchitectureKit/crypto-rsa-asym-encrypt-decrypt-by-segment.md). The operations are similar for SM2 and RSA.
1836
1837**System capability**: SystemCapability.Security.CryptoFramework
1838
1839**Parameters**
1840
1841| Name    | Type                                 | Mandatory| Description                                                        |
1842| -------- | ------------------------------------- | ---- | ------------------------------------------------------------ |
1843| data     | [DataBlob](#datablob) \| null<sup>10+</sup>                 | Yes  | Data to encrypt or decrypt. It can be **null** in symmetric encryption or decryption, but cannot be {data:Uint8Array(empty)}. In versions earlier than API version 10, only **DataBlob** is supported. Since API version 10, **null** is also supported.      |
1844| callback | AsyncCallback\<[DataBlob](#datablob)> | Yes  | Callback invoked to return the result. If the data is successfully encrypted or decrypted, **err** is **undefined**, and **data** is the **DataBlob** (encryption or decryption result of the remaining data). Otherwise, **err** is an error object.|
1845
1846**Error codes**
1847For details about the error codes, see [Crypto Framework Error Codes](../errorcodes/errorcode-crypto-framework.md).
1848
1849| ID| Error Message               |
1850| -------- | ----------------------- |
1851| 401 | invalid parameters.          |
1852| 17620001 | memory error.           |
1853| 17620002 | runtime error.          |
1854| 17630001 | crypto operation error. |
1855
1856**Encryption with AES GCM (example)**
1857
1858For more encryption and decryption examples, see Encryption and Decryption with an AES Symmetric Key (GCM Mode)(../../security/CryptoArchitectureKit/crypto-aes-sym-encrypt-decrypt-gcm.md).
1859
1860```ts
1861import cryptoFramework from '@ohos.security.cryptoFramework';
1862import buffer from '@ohos.buffer';
1863
1864function genGcmParamsSpec() {
1865  let arr = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0];
1866  let dataIv = new Uint8Array(arr);
1867  let ivBlob: cryptoFramework.DataBlob = { data: dataIv };
1868  arr = [0, 0, 0, 0, 0, 0, 0, 0];
1869  let dataAad = new Uint8Array(arr);
1870  let aadBlob: cryptoFramework.DataBlob = { data: dataAad };
1871  arr = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0];
1872  let dataTag = new Uint8Array(arr);
1873  let tagBlob: cryptoFramework.DataBlob = {
1874    data: dataTag
1875  };
1876  let gcmParamsSpec: cryptoFramework.GcmParamsSpec = {
1877    iv: ivBlob,
1878    aad: aadBlob,
1879    authTag: tagBlob,
1880    algName: "GcmParamsSpec"
1881  };
1882  return gcmParamsSpec;
1883}
1884
1885function cipherByCallback() {
1886  let gcmParams = genGcmParamsSpec();
1887  let symKeyGenerator = cryptoFramework.createSymKeyGenerator('AES128');
1888  let cipher = cryptoFramework.createCipher('AES128|GCM|PKCS7');
1889  symKeyGenerator.generateSymKey((err, symKey) => {
1890    cipher.init(cryptoFramework.CryptoMode.ENCRYPT_MODE, symKey, gcmParams, (err,) => {
1891      let message = "This is a test";
1892      let plainText: cryptoFramework.DataBlob = { data: new Uint8Array(buffer.from(message, 'utf-8').buffer) };
1893      cipher.update(plainText, (err, encryptUpdate) => {
1894        cipher.doFinal(null, (err, tag) => {
1895          gcmParams.authTag = tag;
1896          console.info('encryptUpdate plainText: ' + encryptUpdate.data);
1897        });
1898      });
1899    });
1900  });
1901}
1902```
1903
1904### doFinal
1905
1906doFinal(data: DataBlob | null): Promise\<DataBlob>
1907
1908(1) Encrypts or decrypts the remaining data (generated by the block cipher mode) and the data passed in by **doFinal()** to finalize the symmetric encryption or decryption. This API uses a promise to return the encrypted or decrypted data.<br>If a small amount of data needs to be encrypted or decrypted, you can use **doFinal()** to pass in data without using **update()**. If all the data has been passed in by **update()**, you can pass in **null** in **data** of **doFinal()**.<br>The output of **doFinal()** varies with the symmetric encryption/decryption mode in use.
1909
1910- Symmetric encryption in GCM and CCM mode: The result consists of the ciphertext and **authTag** (the last 16 bytes for GCM and the last 12 bytes for CCM). If **data** in **doFinal** is null, the result of **doFinal** is **authTag**.<br>Set **authTag** to [GcmParamsSpec](#gcmparamsspec) or [CcmParamsSpec](#ccmparamsspec) for decryption. The ciphertext is used as the input parameter **data** for decryption.
1911- Symmetric encryption and decryption in other modes and symmetric decryption in GCM and CCM modes: The result is the complete plaintext/ciphertext.
1912
1913(2) Encrypts or decrypts the input data for RSA or SM2 asymmetric encryption/decryption. This API uses a promise to return the result. If a large amount of data needs to be encrypted/decrypted, call **doFinal()** multiple times and concatenate the result of each **doFinal()** to obtain the complete plaintext/ciphertext.
1914
1915> **NOTE**
1916>
1917>  1. In symmetric encryption and decryption, after **doFinal** is called, the encryption and decryption process is complete and the [Cipher](#cipher) instance is cleared. When a new encryption and decryption process is started, **init()** must be called with a complete parameter list for initialization.<br>Even if the same symmetric key is used to encrypt and decrypt the same **Cipher** instance, the **params** parameter must be set when **init** is called during decryption.
1918>  2. If a decryption fails, check whether the data to be encrypted and decrypted matches the parameters in **init()**. For the GCM mode, check whether the **authTag** obtained after encryption is obtained from the **GcmParamsSpec** for decryption.
1919>  3. The result of **doFinal()** may be **null**. To avoid exceptions, determine whether the result is **null** before using the **.data** field to access the **doFinal()** result.
1920>  4. For details about the sample code for calling **doFinal** multiple times in asymmetric encryption and decryption, see [Encryption and Decryption by Segment with an RSA Asymmetric Key Pair](../../security/CryptoArchitectureKit/crypto-rsa-asym-encrypt-decrypt-by-segment.md). The operations are similar for SM2 and RSA.
1921
1922**System capability**: SystemCapability.Security.CryptoFramework
1923
1924**Parameters**
1925
1926| Name| Type                 | Mandatory| Description                |
1927| ---- | --------------------- | ---- | -------------------- |
1928| data | [DataBlob](#datablob) \| null<sup>10+</sup> | Yes  | Data to encrypt or decrypt. It can be **null**, but cannot be {data:Uint8Array(empty)}. In versions earlier than API version 10, only **DataBlob** is supported. Since API version 10, **null** is also supported.|
1929
1930**Return value**
1931
1932| Type                           | Description                                            |
1933| ------------------------------- | ------------------------------------------------ |
1934| Promise\<[DataBlob](#datablob)> | Promise used to return the **DataBlob**, which is the encryption or decryption result of the remaining data.|
1935
1936**Error codes**
1937For details about the error codes, see [Crypto Framework Error Codes](../errorcodes/errorcode-crypto-framework.md).
1938
1939| ID| Error Message                                    |
1940| -------- | -------------------------------------------- |
1941| 401 | invalid parameters.          |
1942| 17620001 | memory error.                                |
1943| 17620002 | runtime error.                               |
1944| 17630001 | crypto operation error.                      |
1945
1946**Encryption with AES GCM (example)**
1947
1948For more encryption and decryption examples, see Encryption and Decryption with an AES Symmetric Key (GCM Mode)(../../security/CryptoArchitectureKit/crypto-aes-sym-encrypt-decrypt-gcm.md).
1949
1950```ts
1951import cryptoFramework from '@ohos.security.cryptoFramework';
1952import buffer from '@ohos.buffer';
1953
1954function genGcmParamsSpec() {
1955  let arr = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0];
1956  let dataIv = new Uint8Array(arr);
1957  let ivBlob: cryptoFramework.DataBlob = { data: dataIv };
1958  arr = [0, 0, 0, 0, 0, 0, 0, 0];
1959  let dataAad = new Uint8Array(arr);
1960  let aadBlob: cryptoFramework.DataBlob = { data: dataAad };
1961  arr = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0];
1962  let dataTag = new Uint8Array(arr);
1963  let tagBlob: cryptoFramework.DataBlob = {
1964    data: dataTag
1965  };
1966  let gcmParamsSpec: cryptoFramework.GcmParamsSpec = {
1967    iv: ivBlob,
1968    aad: aadBlob,
1969    authTag: tagBlob,
1970    algName: "GcmParamsSpec"
1971  };
1972  return gcmParamsSpec;
1973}
1974
1975async function cipherByPromise() {
1976  let gcmParams = genGcmParamsSpec();
1977  let symKeyGenerator = cryptoFramework.createSymKeyGenerator('AES128');
1978  let cipher = cryptoFramework.createCipher('AES128|GCM|PKCS7');
1979  let symKey = await symKeyGenerator.generateSymKey();
1980  await cipher.init(cryptoFramework.CryptoMode.ENCRYPT_MODE, symKey, gcmParams);
1981  let message = "This is a test";
1982  let plainText: cryptoFramework.DataBlob = { data: new Uint8Array(buffer.from(message, 'utf-8').buffer) };
1983  let encryptUpdate = await cipher.update(plainText);
1984  gcmParams.authTag = await cipher.doFinal(null);
1985  console.info('encryptUpdate plainText: ' + encryptUpdate.data);
1986}
1987```
1988
1989### setCipherSpec<sup>10+</sup>
1990
1991setCipherSpec(itemType: CipherSpecItem, itemValue: Uint8Array): void
1992
1993Sets cipher specifications. You can use this API to set cipher specifications that cannot be set by [createCipher](#cryptoframeworkcreatecipher). Currently, only RSA is supported.
1994
1995**System capability**: SystemCapability.Security.CryptoFramework
1996
1997**Parameters**
1998
1999| Name  | Type                | Mandatory| Description      |
2000| -------- | -------------------- | ---- | ---------- |
2001| itemType     | [CipherSpecItem](#cipherspecitem10)           | Yes  | Cipher parameter to set.|
2002| itemValue | Uint8Array | Yes  | Value of the parameter to set.|
2003
2004**Error codes**
2005For details about the error codes, see [Crypto Framework Error Codes](../errorcodes/errorcode-crypto-framework.md).
2006
2007| ID| Error Message              |
2008| -------- | ---------------------- |
2009| 401 | invalid parameters.          |
2010| 801 | this operation is not supported.          |
2011| 17620001 | memory error.          |
2012| 17630001 | crypto operation error. |
2013
2014**Example**
2015
2016```ts
2017let cipher: cryptoFramework.Cipher; // The process of generating the Cipher instance is omitted here.
2018let pSource = new Uint8Array([1,2,3,4]);
2019cipher.setCipherSpec(cryptoFramework.CipherSpecItem.OAEP_MGF1_PSRC_UINT8ARR, pSource);
2020```
2021
2022### getCipherSpec<sup>10+</sup>
2023
2024getCipherSpec(itemType: CipherSpecItem): string | Uint8Array
2025
2026Obtains cipher specifications. Currently, only RSA and SM2 (available since API version 11) are supported.
2027
2028**System capability**: SystemCapability.Security.CryptoFramework
2029
2030**Parameters**
2031
2032| Name| Type    | Mandatory| Description      |
2033| ------ | -------- | ---- | ---------- |
2034| itemType   | [CipherSpecItem](#cipherspecitem10) | Yes  | Cipher parameter to obtain.|
2035
2036**Return value**
2037
2038| Type          | Description       |
2039| -------------- | ----------- |
2040| string\|Uint8Array | Returns the value of the cipher parameter obtained.|
2041
2042**Error codes**
2043For details about the error codes, see [Crypto Framework Error Codes](../errorcodes/errorcode-crypto-framework.md).
2044
2045| ID| Error Message              |
2046| -------- | ---------------------- |
2047| 401 | invalid parameters.          |
2048| 801 | this operation is not supported.          |
2049| 17620001 | memory error.          |
2050| 17630001 | crypto operation error. |
2051
2052**Example**
2053
2054```ts
2055let cipher: cryptoFramework.Cipher; // The process of generating the Cipher instance is omitted here.
2056let mdName = cipher.getCipherSpec(cryptoFramework.CipherSpecItem.OAEP_MD_NAME_STR);
2057```
2058
2059## cryptoFramework.createSign
2060
2061createSign(algName: string): Sign
2062
2063Creates a **Sign** instance.
2064
2065For details about the supported specifications, see [Signing and Signature Verification Overview and Algorithm Specifications](../../security/CryptoArchitectureKit/crypto-sign-sig-verify-overview.md).
2066
2067**System capability**: SystemCapability.Security.CryptoFramework
2068
2069**Parameters**
2070
2071| Name | Type  | Mandatory| Description                                                        |
2072| ------- | ------ | ---- | ------------------------------------------------------------ |
2073| algName | string | Yes  | Signing algorithm to use. Currently, RSA, ECC, DSA, SM2<sup>10+</sup> and Ed25519<sup>11+</sup> are supported. <br>If the RSA PKCS1 mode is used, you need to set the digest. If the RSA PSS mode is used, you need to set the digest and mask digest.|
2074
2075**Return value**
2076
2077| Type| Description                              |
2078| ---- | ---------------------------------- |
2079| Sign | Returns the **Sign** instance created.|
2080
2081**Error codes**
2082For details about the error codes, see [Crypto Framework Error Codes](../errorcodes/errorcode-crypto-framework.md).
2083
2084| ID| Error Message              |
2085| -------- | ---------------------- |
2086| 401 | invalid parameters.          |
2087| 801 | this operation is not supported.          |
2088| 17620001 | memory error.          |
2089
2090**Example**
2091
2092```ts
2093let signer1 = cryptoFramework.createSign('RSA1024|PKCS1|SHA256');
2094
2095let signer2 = cryptoFramework.createSign('RSA1024|PSS|SHA256|MGF1_SHA256');
2096
2097let signer3 = cryptoFramework.createSign('ECC224|SHA256');
2098
2099let signer4 = cryptoFramework.createSign('DSA2048|SHA256');
2100```
2101
2102## Sign
2103
2104Provides APIs for signing. Before using any API of the **Sign** class, you must create a **Sign** instance by using [createSign(algName: string): Sign](#cryptoframeworkcreatesign). Invoke **init()**, **update()**, and **sign()** in this class in sequence to complete the signing operation. For details about the sample code, see [Signing and Signature Verification with an RSA Key Pair (PKCS1 Mode)](../../security/CryptoArchitectureKit/crypto-rsa-sign-sig-verify-pkcs1.md).
2105
2106The **Sign** class does not support repeated initialization. When a new key is used for signing, you must create a new **Sign** instance and call **init()** for initialization.
2107
2108The signing mode is determined in **createSign()**, and the key is set by **init()**.
2109
2110If the data to be signed is short, you can directly call **sign()** to pass in the original data for signing after **init()**. That is, you do not need to use **update()**.
2111
2112If the data to be signed is long, you can use **update()** to pass in the data by segment, and then use **sign()** to sign the entire data.
2113
2114When **update()** is used, the **sign()** API supports only **DataBlob** in versions earlier than API version 10 and starts to support **null** since API version 10. After all the data is passed in by using **update()**, **sign()** can be called to sign the data.
2115
2116### Attributes
2117
2118**System capability**: SystemCapability.Security.CryptoFramework
2119
2120| Name   | Type  | Readable| Writable| Description                        |
2121| ------- | ------ | ---- | ---- | ---------------------------- |
2122| algName | string | Yes  | No  | Algorithm to use.|
2123
2124### init
2125
2126init(priKey: PriKey, callback: AsyncCallback\<void>): void
2127
2128Initializes the **Sign** instance with a private key. This API uses an asynchronous callback to return the result. **init**, **update**, and **sign** must be used together. **init** and **sign** are mandatory, and **update** is optional.
2129
2130The **Sign** class does not support repeated use of **init()**.
2131
2132**System capability**: SystemCapability.Security.CryptoFramework
2133
2134**Parameters**
2135
2136| Name  | Type                | Mandatory| Description            |
2137| -------- | -------------------- | ---- | ---------------- |
2138| priKey   | [PriKey](#prikey)    | Yes  | Private key used for the initialization.|
2139| callback | AsyncCallback\<void> | Yes  | Callback invoked to return the result. If the operation is successful, **err** is **undefined**. Otherwise, **err** is an error object.|
2140
2141**Error codes**
2142For details about the error codes, see [Crypto Framework Error Codes](../errorcodes/errorcode-crypto-framework.md).
2143
2144| ID| Error Message              |
2145| -------- | ---------------------- |
2146| 401 | invalid parameters.          |
2147| 17620001 | memory error.          |
2148| 17620002 | runtime error.          |
2149| 17630001 | crypto operation error. |
2150
2151### init
2152
2153init(priKey: PriKey): Promise\<void>
2154
2155Initializes the **Sign** instance with a private key. This API uses a promise to return the result. **init**, **update**, and **sign** must be used together. **init** and **sign** are mandatory, and **update** is optional.
2156
2157The **Sign** class does not support repeated use of **init()**.
2158
2159**System capability**: SystemCapability.Security.CryptoFramework
2160
2161**Parameters**
2162
2163| Name| Type| Mandatory| Description            |
2164| ------ | ---- | ---- | ---------------- |
2165| priKey | [PriKey](#prikey)  | Yes  | Private key used for the initialization.|
2166
2167**Return value**
2168
2169| Type          | Description         |
2170| -------------- | ------------- |
2171| Promise\<void> | Promise that returns no value.|
2172
2173**Error codes**
2174For details about the error codes, see [Crypto Framework Error Codes](../errorcodes/errorcode-crypto-framework.md).
2175
2176| ID| Error Message              |
2177| -------- | ---------------------- |
2178| 401 | invalid parameters.          |
2179| 17620001 | memory error.          |
2180| 17620002 | runtime error.          |
2181| 17630001 | crypto operation error. |
2182
2183### update
2184
2185update(data: DataBlob, callback: AsyncCallback\<void>): void
2186
2187Updates the data to be signed. This API uses an asynchronous callback to return the result.
2188
2189This API can be called only after the [Sign](#sign) instance is initialized by using [init()](init-2).
2190
2191> **NOTE**
2192>
2193> You can call **update** multiple times or do not use **update** (call [sign](#sign-1) after [init](#init-2)), depending on the size of the data.<br>
2194> The data to be passed in **updated()** (once or accumulatively) is not size bound. If a large amount of data needs to be signed, you are advised to use **update** multiple times to pass in data. This can prevent too much memory from being requested at a time.<br>
2195> For details about the sample code for calling **update** multiple times in signing, see [Signing and Signature Verification by Segment with an RSA Key Pair (PKCS1 Mode)](../../security/CryptoArchitectureKit/crypto-rsa-sign-sig-verify-pkcs1-by-segment.md). The operations of other algorithms are similar.
2196
2197**System capability**: SystemCapability.Security.CryptoFramework
2198
2199**Parameters**
2200
2201| Name  | Type                 | Mandatory| Description        |
2202| -------- | --------------------- | ---- | ------------ |
2203| data     | [DataBlob](#datablob) | Yes  | Data to pass in.|
2204| callback | AsyncCallback\<void>  | Yes  | Callback invoked to return the result. If the operation is successful, **err** is **undefined**. Otherwise, **err** is an error object.|
2205
2206**Error codes**
2207For details about the error codes, see [Crypto Framework Error Codes](../errorcodes/errorcode-crypto-framework.md).
2208
2209| ID| Error Message              |
2210| -------- | ---------------------- |
2211| 401 | invalid parameters.          |
2212| 17620001 | memory error.          |
2213| 17620002 | runtime error.          |
2214| 17630001 | crypto operation error. |
2215
2216### update
2217
2218update(data: DataBlob): Promise\<void>
2219
2220Updates the data to be signed. This API uses a promise to return the result.
2221
2222This API can be called only after the [Sign](#sign) instance is initialized by using [init()](#init-3).
2223
2224> **NOTE**
2225>
2226> You can call **update** multiple times or do not use **update** (call [sign](#sign-2) after [init](#init-3)), depending on the size of the data.<br>
2227> The data to be passed in **updated()** (once or accumulatively) is not size bound. If a large amount of data needs to be signed, you are advised to use **update** multiple times to pass in data. This can prevent too much memory from being requested at a time.<br>
2228> For details about the sample code for calling **update** multiple times in signing, see [Signing and Signature Verification by Segment with an RSA Key Pair (PKCS1 Mode)](../../security/CryptoArchitectureKit/crypto-rsa-sign-sig-verify-pkcs1-by-segment.md). The operations of other algorithms are similar.
2229
2230**System capability**: SystemCapability.Security.CryptoFramework
2231
2232**Parameters**
2233
2234| Name| Type    | Mandatory| Description      |
2235| ------ | -------- | ---- | ---------- |
2236| data   | [DataBlob](#datablob)  | Yes  | Data to pass in.|
2237
2238**Return value**
2239
2240| Type          | Description         |
2241| -------------- | ------------- |
2242| Promise\<void> | Promise that returns no value.|
2243
2244**Error codes**
2245For details about the error codes, see [Crypto Framework Error Codes](../errorcodes/errorcode-crypto-framework.md).
2246
2247| ID| Error Message              |
2248| -------- | ---------------------- |
2249| 401 | invalid parameters.          |
2250| 17620001 | memory error.          |
2251| 17620002 | runtime error.          |
2252| 17630001 | crypto operation error. |
2253
2254### sign
2255
2256sign(data: DataBlob | null, callback: AsyncCallback\<DataBlob>): void
2257
2258Signs the data. This API uses an asynchronous callback to return the result.
2259
2260**System capability**: SystemCapability.Security.CryptoFramework
2261
2262**Parameters**
2263
2264| Name  | Type                | Mandatory| Description      |
2265| -------- | -------------------- | ---- | ---------- |
2266| data     | [DataBlob](#datablob) \| null<sup>10+</sup>              | Yes  | Data to pass in. In versions earlier than API version 10, only **DataBlob** is supported. Since API version 10, **null** is also supported.|
2267| callback | AsyncCallback\<[DataBlob](#datablob)> | Yes  | Callback invoked to return a **DataBlob** object.|
2268
2269**Error codes**
2270For details about the error codes, see [Crypto Framework Error Codes](../errorcodes/errorcode-crypto-framework.md).
2271
2272| ID| Error Message              |
2273| -------- | ---------------------- |
2274| 401 | invalid parameters.          |
2275| 17620001 | memory error.          |
2276| 17620002 | runtime error.          |
2277| 17630001 | crypto operation error. |
2278
2279### sign
2280
2281sign(data: DataBlob | null): Promise\<DataBlob>
2282
2283Signs the data. This API uses a promise to return the result.
2284
2285**System capability**: SystemCapability.Security.CryptoFramework
2286
2287**Parameters**
2288
2289| Name| Type    | Mandatory| Description      |
2290| ------ | -------- | ---- | ---------- |
2291| data   | [DataBlob](#datablob) \| null<sup>10+</sup>  | Yes  | Data to pass in.|
2292
2293**Return value**
2294
2295| Type          | Description         |
2296| -------------- | ------------- |
2297| Promise\<void> | Promise that returns no value.|
2298
2299**Error codes**
2300For details about the error codes, see [Crypto Framework Error Codes](../errorcodes/errorcode-crypto-framework.md).
2301
2302| ID| Error Message              |
2303| -------- | ---------------------- |
2304| 401 | invalid parameters.          |
2305| 17620001 | memory error.          |
2306| 17620002 | runtime error.          |
2307| 17630001 | crypto operation error. |
2308
2309**Callback example**:
2310
2311For more examples of signing and signature verification, see [Signing and Signature Verification with an RSA Key Pair (PKCS1 Mode)](../../security/CryptoArchitectureKit/crypto-rsa-sign-sig-verify-pkcs1.md).
2312
2313```ts
2314import cryptoFramework from '@ohos.security.cryptoFramework';
2315import buffer from '@ohos.buffer';
2316
2317function signByCallback() {
2318  let inputUpdate: cryptoFramework.DataBlob = { data: new Uint8Array(buffer.from("This is Sign test plan1", 'utf-8').buffer) };
2319  let inputVerify: cryptoFramework.DataBlob = { data: new Uint8Array(buffer.from("This is Sign test plan2", 'utf-8').buffer) };
2320  let pkData = new Uint8Array([48, 129, 159, 48, 13, 6, 9, 42, 134, 72, 134, 247, 13, 1, 1, 1, 5, 0, 3, 129, 141, 0, 48, 129, 137, 2, 129, 129, 0, 214, 179, 23, 198, 183, 139, 148, 8, 173, 74, 56, 160, 15, 248, 244, 166, 209, 250, 142, 74, 216, 58, 117, 215, 178, 247, 254, 39, 180, 227, 85, 201, 59, 133, 209, 221, 26, 9, 116, 31, 172, 151, 252, 185, 123, 20, 25, 7, 92, 129, 5, 196, 239, 214, 126, 254, 154, 188, 239, 144, 161, 171, 65, 42, 31, 214, 93, 115, 247, 69, 94, 143, 54, 51, 25, 49, 146, 204, 205, 165, 20, 120, 35, 184, 190, 65, 106, 12, 214, 176, 57, 125, 235, 51, 88, 135, 76, 73, 109, 112, 147, 138, 198, 252, 5, 20, 245, 51, 7, 32, 108, 89, 125, 204, 50, 189, 88, 254, 255, 146, 244, 244, 149, 79, 54, 216, 45, 89, 2, 3, 1, 0, 1]);
2321  let skData = new Uint8Array([48, 130, 2, 120, 2, 1, 0, 48, 13, 6, 9, 42, 134, 72, 134, 247, 13, 1, 1, 1, 5, 0, 4, 130, 2, 98, 48, 130, 2, 94, 2, 1, 0, 2, 129, 129, 0, 214, 179, 23, 198, 183, 139, 148, 8, 173, 74, 56, 160, 15, 248, 244, 166, 209, 250, 142, 74, 216, 58, 117, 215, 178, 247, 254, 39, 180, 227, 85, 201, 59, 133, 209, 221, 26, 9, 116, 31, 172, 151, 252, 185, 123, 20, 25, 7, 92, 129, 5, 196, 239, 214, 126, 254, 154, 188, 239, 144, 161, 171, 65, 42, 31, 214, 93, 115, 247, 69, 94, 143, 54, 51, 25, 49, 146, 204, 205, 165, 20, 120, 35, 184, 190, 65, 106, 12, 214, 176, 57, 125, 235, 51, 88, 135, 76, 73, 109, 112, 147, 138, 198, 252, 5, 20, 245, 51, 7, 32, 108, 89, 125, 204, 50, 189, 88, 254, 255, 146, 244, 244, 149, 79, 54, 216, 45, 89, 2, 3, 1, 0, 1, 2, 129, 129, 0, 152, 111, 145, 203, 10, 88, 116, 163, 112, 126, 9, 20, 68, 34, 235, 121, 98, 14, 182, 102, 151, 125, 114, 91, 210, 122, 215, 29, 212, 5, 176, 203, 238, 146, 5, 190, 41, 21, 91, 56, 125, 239, 111, 133, 53, 200, 192, 56, 132, 202, 42, 145, 120, 3, 224, 40, 223, 46, 148, 29, 41, 92, 17, 40, 12, 72, 165, 69, 192, 211, 142, 233, 81, 202, 177, 235, 156, 27, 179, 48, 18, 85, 154, 101, 193, 45, 218, 91, 24, 143, 196, 248, 16, 83, 177, 198, 136, 77, 111, 134, 60, 219, 95, 246, 23, 5, 45, 14, 83, 29, 137, 248, 159, 28, 132, 142, 205, 99, 226, 213, 84, 232, 57, 130, 156, 81, 191, 237, 2, 65, 0, 255, 158, 212, 13, 43, 132, 244, 135, 148, 161, 232, 219, 20, 81, 196, 102, 103, 44, 110, 71, 100, 62, 73, 200, 32, 138, 114, 209, 171, 150, 179, 92, 198, 5, 190, 218, 79, 227, 227, 37, 32, 57, 159, 252, 107, 211, 139, 198, 202, 248, 137, 143, 186, 205, 106, 81, 85, 207, 134, 148, 110, 204, 243, 27, 2, 65, 0, 215, 4, 181, 121, 57, 224, 170, 168, 183, 159, 152, 8, 74, 233, 80, 244, 146, 81, 48, 159, 194, 199, 36, 187, 6, 181, 182, 223, 115, 133, 151, 171, 78, 219, 90, 161, 248, 69, 6, 207, 173, 3, 81, 161, 2, 60, 238, 204, 177, 12, 138, 17, 220, 179, 71, 113, 200, 248, 159, 153, 252, 150, 180, 155, 2, 65, 0, 190, 202, 185, 211, 170, 171, 238, 40, 84, 84, 21, 13, 144, 57, 7, 178, 183, 71, 126, 120, 98, 229, 235, 4, 40, 229, 173, 149, 185, 209, 29, 199, 29, 54, 164, 161, 38, 8, 30, 62, 83, 179, 47, 42, 165, 0, 156, 207, 160, 39, 169, 229, 81, 180, 136, 170, 116, 182, 20, 233, 45, 90, 100, 9, 2, 65, 0, 152, 255, 47, 198, 15, 201, 238, 133, 89, 11, 133, 153, 184, 252, 37, 239, 177, 65, 118, 80, 231, 190, 222, 66, 250, 118, 72, 166, 221, 67, 156, 245, 119, 138, 28, 6, 142, 107, 71, 122, 116, 200, 156, 199, 237, 152, 191, 239, 4, 184, 64, 114, 143, 81, 62, 48, 23, 233, 217, 95, 47, 221, 104, 171, 2, 64, 30, 219, 1, 230, 241, 70, 246, 243, 121, 174, 67, 66, 11, 99, 202, 17, 52, 234, 78, 29, 3, 57, 51, 123, 149, 86, 64, 192, 73, 199, 108, 101, 55, 232, 41, 114, 153, 237, 253, 52, 205, 148, 45, 86, 186, 241, 182, 183, 42, 77, 252, 195, 29, 158, 173, 3, 182, 207, 254, 61, 71, 184, 167, 184]);
2322  let pubKeyBlob: cryptoFramework.DataBlob = { data: pkData };
2323  let priKeyBlob: cryptoFramework.DataBlob = { data: skData };
2324  let rsaGenerator = cryptoFramework.createAsyKeyGenerator('RSA1024');
2325  let signer = cryptoFramework.createSign('RSA1024|PKCS1|SHA256');
2326  rsaGenerator.convertKey(pubKeyBlob, priKeyBlob, (err, keyPair) => {
2327    signer.init(keyPair.priKey, err => {
2328      signer.update(inputUpdate, err => {
2329        signer.sign(inputVerify, (err, signData) => {
2330          console.info('sign output is ' + signData.data);
2331        });
2332      });
2333    });
2334  });
2335}
2336```
2337
2338**Example (promise)**
2339
2340For more examples of signing and signature verification, see [Signing and Signature Verification with an RSA Key Pair (PKCS1 Mode)](../../security/CryptoArchitectureKit/crypto-rsa-sign-sig-verify-pkcs1.md).
2341
2342```ts
2343import cryptoFramework from '@ohos.security.cryptoFramework';
2344import buffer from '@ohos.buffer';
2345
2346async function genKeyPairByData(pubKeyData: Uint8Array, priKeyData: Uint8Array) {
2347  let pubKeyBlob: cryptoFramework.DataBlob = { data: pubKeyData };
2348  let priKeyBlob: cryptoFramework.DataBlob = { data: priKeyData };
2349  let rsaGenerator = cryptoFramework.createAsyKeyGenerator('RSA1024');
2350  let keyPair = await rsaGenerator.convertKey(pubKeyBlob, priKeyBlob);
2351  console.info('convertKey success');
2352  return keyPair;
2353}
2354
2355async function signByPromise() {
2356  let pkData = new Uint8Array([48, 129, 159, 48, 13, 6, 9, 42, 134, 72, 134, 247, 13, 1, 1, 1, 5, 0, 3, 129, 141, 0, 48, 129, 137, 2, 129, 129, 0, 214, 179, 23, 198, 183, 139, 148, 8, 173, 74, 56, 160, 15, 248, 244, 166, 209, 250, 142, 74, 216, 58, 117, 215, 178, 247, 254, 39, 180, 227, 85, 201, 59, 133, 209, 221, 26, 9, 116, 31, 172, 151, 252, 185, 123, 20, 25, 7, 92, 129, 5, 196, 239, 214, 126, 254, 154, 188, 239, 144, 161, 171, 65, 42, 31, 214, 93, 115, 247, 69, 94, 143, 54, 51, 25, 49, 146, 204, 205, 165, 20, 120, 35, 184, 190, 65, 106, 12, 214, 176, 57, 125, 235, 51, 88, 135, 76, 73, 109, 112, 147, 138, 198, 252, 5, 20, 245, 51, 7, 32, 108, 89, 125, 204, 50, 189, 88, 254, 255, 146, 244, 244, 149, 79, 54, 216, 45, 89, 2, 3, 1, 0, 1]);
2357  let skData = new Uint8Array([48, 130, 2, 120, 2, 1, 0, 48, 13, 6, 9, 42, 134, 72, 134, 247, 13, 1, 1, 1, 5, 0, 4, 130, 2, 98, 48, 130, 2, 94, 2, 1, 0, 2, 129, 129, 0, 214, 179, 23, 198, 183, 139, 148, 8, 173, 74, 56, 160, 15, 248, 244, 166, 209, 250, 142, 74, 216, 58, 117, 215, 178, 247, 254, 39, 180, 227, 85, 201, 59, 133, 209, 221, 26, 9, 116, 31, 172, 151, 252, 185, 123, 20, 25, 7, 92, 129, 5, 196, 239, 214, 126, 254, 154, 188, 239, 144, 161, 171, 65, 42, 31, 214, 93, 115, 247, 69, 94, 143, 54, 51, 25, 49, 146, 204, 205, 165, 20, 120, 35, 184, 190, 65, 106, 12, 214, 176, 57, 125, 235, 51, 88, 135, 76, 73, 109, 112, 147, 138, 198, 252, 5, 20, 245, 51, 7, 32, 108, 89, 125, 204, 50, 189, 88, 254, 255, 146, 244, 244, 149, 79, 54, 216, 45, 89, 2, 3, 1, 0, 1, 2, 129, 129, 0, 152, 111, 145, 203, 10, 88, 116, 163, 112, 126, 9, 20, 68, 34, 235, 121, 98, 14, 182, 102, 151, 125, 114, 91, 210, 122, 215, 29, 212, 5, 176, 203, 238, 146, 5, 190, 41, 21, 91, 56, 125, 239, 111, 133, 53, 200, 192, 56, 132, 202, 42, 145, 120, 3, 224, 40, 223, 46, 148, 29, 41, 92, 17, 40, 12, 72, 165, 69, 192, 211, 142, 233, 81, 202, 177, 235, 156, 27, 179, 48, 18, 85, 154, 101, 193, 45, 218, 91, 24, 143, 196, 248, 16, 83, 177, 198, 136, 77, 111, 134, 60, 219, 95, 246, 23, 5, 45, 14, 83, 29, 137, 248, 159, 28, 132, 142, 205, 99, 226, 213, 84, 232, 57, 130, 156, 81, 191, 237, 2, 65, 0, 255, 158, 212, 13, 43, 132, 244, 135, 148, 161, 232, 219, 20, 81, 196, 102, 103, 44, 110, 71, 100, 62, 73, 200, 32, 138, 114, 209, 171, 150, 179, 92, 198, 5, 190, 218, 79, 227, 227, 37, 32, 57, 159, 252, 107, 211, 139, 198, 202, 248, 137, 143, 186, 205, 106, 81, 85, 207, 134, 148, 110, 204, 243, 27, 2, 65, 0, 215, 4, 181, 121, 57, 224, 170, 168, 183, 159, 152, 8, 74, 233, 80, 244, 146, 81, 48, 159, 194, 199, 36, 187, 6, 181, 182, 223, 115, 133, 151, 171, 78, 219, 90, 161, 248, 69, 6, 207, 173, 3, 81, 161, 2, 60, 238, 204, 177, 12, 138, 17, 220, 179, 71, 113, 200, 248, 159, 153, 252, 150, 180, 155, 2, 65, 0, 190, 202, 185, 211, 170, 171, 238, 40, 84, 84, 21, 13, 144, 57, 7, 178, 183, 71, 126, 120, 98, 229, 235, 4, 40, 229, 173, 149, 185, 209, 29, 199, 29, 54, 164, 161, 38, 8, 30, 62, 83, 179, 47, 42, 165, 0, 156, 207, 160, 39, 169, 229, 81, 180, 136, 170, 116, 182, 20, 233, 45, 90, 100, 9, 2, 65, 0, 152, 255, 47, 198, 15, 201, 238, 133, 89, 11, 133, 153, 184, 252, 37, 239, 177, 65, 118, 80, 231, 190, 222, 66, 250, 118, 72, 166, 221, 67, 156, 245, 119, 138, 28, 6, 142, 107, 71, 122, 116, 200, 156, 199, 237, 152, 191, 239, 4, 184, 64, 114, 143, 81, 62, 48, 23, 233, 217, 95, 47, 221, 104, 171, 2, 64, 30, 219, 1, 230, 241, 70, 246, 243, 121, 174, 67, 66, 11, 99, 202, 17, 52, 234, 78, 29, 3, 57, 51, 123, 149, 86, 64, 192, 73, 199, 108, 101, 55, 232, 41, 114, 153, 237, 253, 52, 205, 148, 45, 86, 186, 241, 182, 183, 42, 77, 252, 195, 29, 158, 173, 3, 182, 207, 254, 61, 71, 184, 167, 184]);
2358  let keyPair = await genKeyPairByData(pkData, skData);
2359  let inputUpdate: cryptoFramework.DataBlob = { data: new Uint8Array(buffer.from("This is Sign test plan1", 'utf-8').buffer) };
2360  let inputSign: cryptoFramework.DataBlob = { data: new Uint8Array(buffer.from("This is Sign test plan2", 'utf-8').buffer) };
2361  let signer = cryptoFramework.createSign('RSA1024|PKCS1|SHA256');
2362  await signer.init(keyPair.priKey);
2363  await signer.update(inputUpdate);
2364  let signData = await signer.sign(inputSign);
2365  console.info('signData result: ' + signData.data);
2366}
2367```
2368
2369### setSignSpec<sup>10+</sup>
2370
2371setSignSpec(itemType: SignSpecItem, itemValue: number): void
2372
2373setSignSpec(itemType: SignSpecItem, itemValue: number\|Uint8Array): void
2374
2375Sets signing specifications. You can use this API to set signing parameters that cannot be set by [createSign](#cryptoframeworkcreatesign).
2376
2377Currently, only RSA and SM2 are supported. Since API version 11, signature parameters can be set for the SM2 algorithm.
2378
2379**System capability**: SystemCapability.Security.CryptoFramework
2380
2381**Parameters**
2382
2383| Name  | Type                | Mandatory| Description      |
2384| -------- | -------------------- | ---- | ---------- |
2385| itemType     | [SignSpecItem](#signspecitem10)              | Yes  | Signing parameter to set.|
2386| itemValue | number\|Uint8Array<sup>11+</sup> | Yes  | Value of the signing parameter to set.|
2387
2388**Error codes**
2389For details about the error codes, see [Crypto Framework Error Codes](../errorcodes/errorcode-crypto-framework.md).
2390
2391| ID| Error Message              |
2392| -------- | ---------------------- |
2393| 401 | invalid parameters.          |
2394| 801 | this operation is not supported.          |
2395| 17620001 | memory error.          |
2396| 17630001 | crypto operation error. |
2397
2398**Example**
2399
2400```ts
2401let signer: cryptoFramework.Sign; // The process of generating the Sign instance is omitted here.
2402let setN = 20;
2403signer.setSignSpec(cryptoFramework.SignSpecItem.PSS_SALT_LEN_NUM, setN);
2404```
2405
2406### getSignSpec<sup>10+</sup>
2407
2408getSignSpec(itemType: SignSpecItem): string | number
2409
2410Obtains signing specifications. Currently, only RSA is supported.
2411
2412**System capability**: SystemCapability.Security.CryptoFramework
2413
2414**Parameters**
2415
2416| Name| Type    | Mandatory| Description      |
2417| ------ | -------- | ---- | ---------- |
2418| itemType | [SignSpecItem](#signspecitem10)  | Yes  | Signing parameter to obtain.|
2419
2420**Return value**
2421
2422| Type          | Description       |
2423| -------------- | ----------- |
2424| string\|number | Returns the value of the signing parameter obtained.|
2425
2426**Error codes**
2427For details about the error codes, see [Crypto Framework Error Codes](../errorcodes/errorcode-crypto-framework.md).
2428
2429| ID| Error Message              |
2430| -------- | ---------------------- |
2431| 401 | invalid parameters.          |
2432| 801 | this operation is not supported.          |
2433| 17620001 | memory error.          |
2434| 17630001 | crypto operation error. |
2435
2436**Example**
2437
2438```ts
2439let signer: cryptoFramework.Sign; // The process of generating the Sign instance is omitted here.
2440let saltLen = signer.getSignSpec(cryptoFramework.SignSpecItem.PSS_SALT_LEN_NUM);
2441```
2442
2443## cryptoFramework.createVerify
2444
2445createVerify(algName: string): Verify
2446
2447Creates a **Verify** instance.
2448
2449For details about the supported specifications, see [Signing and Signature Verification Overview and Algorithm Specifications](../../security/CryptoArchitectureKit/crypto-sign-sig-verify-overview.md).
2450
2451**System capability**: SystemCapability.Security.CryptoFramework
2452
2453**Parameters**
2454
2455| Name | Type  | Mandatory| Description                                                        |
2456| ------- | ------ | ---- | ------------------------------------------------------------ |
2457| algName | string | Yes  | Signing algorithm to use. Currently, RSA, ECC, DSA, SM2<sup>10+</sup> and Ed25519<sup>11+</sup> are supported. <br>If the RSA PKCS1 mode is used, you need to set the digest. If the RSA PSS mode is used, you need to set the digest and mask digest.|
2458
2459**Return value**
2460
2461| Type  | Description                                |
2462| ------ | ------------------------------------ |
2463| Verify | Returns the **Verify** instance created.|
2464
2465**Error codes**
2466For details about the error codes, see [Crypto Framework Error Codes](../errorcodes/errorcode-crypto-framework.md).
2467
2468| ID| Error Message              |
2469| -------- | ---------------------- |
2470| 401 | invalid parameters.          |
2471| 801 | this operation is not supported.          |
2472| 17620001 | memory error.          |
2473
2474**Example**
2475
2476```ts
2477let verifyer1 = cryptoFramework.createVerify('RSA1024|PKCS1|SHA256');
2478
2479let verifyer2 = cryptoFramework.createVerify('RSA1024|PSS|SHA256|MGF1_SHA256');
2480```
2481
2482## Verify
2483
2484Provides APIs for signature verification. Before using any API of the **Verify** class, you must create a **Verify** instance by using [createVerify(algName: string): Verify](#cryptoframeworkcreateverify). Invoke **init()**, **update()**, and **sign()** in this class in sequence to complete the signature verification. For details about the sample code, see [Signing and Signature Verification with an RSA Key Pair (PKCS1 Mode)](../../security/CryptoArchitectureKit/crypto-rsa-sign-sig-verify-pkcs1.md).
2485
2486The **Verify** class does not support repeated initialization. When a new key is used for signature verification, you must create a new **Verify** instance and call **init()** for initialization.
2487
2488The signature verification mode is determined in **createVerify()**, and key is set by **init()**.
2489
2490If the signed message is short, you can call **verify()** to pass in the signed message and signature (**signatureData**) for signature verification after **init()**. That is, you do not need to use **update()**.
2491
2492If the signed message is too long, you can call **update()** multiple times to pass in the signed message by segment, and then call **verify()** to verify the full text of the message. In versions earlier than API version 10, the input parameter **data** of **verify()** supports only **DataBlob**. Since API version 10, **data** also supports **null**. After all the data is passed in by using **update()**, **verify()** can be called to verify the signature data.
2493
2494### Attributes
2495
2496**System capability**: SystemCapability.Security.CryptoFramework
2497
2498| Name   | Type  | Readable| Writable| Description                        |
2499| ------- | ------ | ---- | ---- | ---------------------------- |
2500| algName | string | Yes  | No  | Algorithm to be used for signature verification.|
2501
2502### init
2503
2504init(pubKey: PubKey, callback: AsyncCallback\<void>): void
2505
2506Initializes the **Verify** instance with a public key. This API uses an asynchronous callback to return the result. **init**, **update**, and **verify** must be used together. **init** and **verify** are mandatory, and **update** is optional.
2507
2508**System capability**: SystemCapability.Security.CryptoFramework
2509
2510**Parameters**
2511
2512| Name  | Type                | Mandatory| Description                          |
2513| -------- | -------------------- | ---- | ------------------------------ |
2514| pubKey   | [PubKey](#pubkey)    | Yes  | Public key used to initialize the **Verify** instance.|
2515| callback | AsyncCallback\<void> | Yes  | Callback invoked to return the result. If the operation is successful, **err** is **undefined**. Otherwise, **err** is an error object. |
2516
2517**Error codes**
2518For details about the error codes, see [Crypto Framework Error Codes](../errorcodes/errorcode-crypto-framework.md).
2519
2520| ID| Error Message              |
2521| -------- | ---------------------- |
2522| 401 | invalid parameters.          |
2523| 17620001 | memory error.          |
2524| 17620002 | runtime error.          |
2525| 17630001 | crypto operation error. |
2526
2527### init
2528
2529init(pubKey: PubKey): Promise\<void>
2530
2531Initializes the **Verify** instance with a public key. This API uses a promise to return the result. **init**, **update**, and **verify** must be used together. **init** and **verify** are mandatory, and **update** is optional.
2532
2533**System capability**: SystemCapability.Security.CryptoFramework
2534
2535**Parameters**
2536
2537| Name| Type| Mandatory| Description                        |
2538| ------ | ---- | ---- | ---------------------------- |
2539| pubKey | [PubKey](#pubkey)  | Yes  | Public key used to initialize the **Verify** instance.|
2540
2541**Return value**
2542
2543| Type          | Description         |
2544| -------------- | ------------- |
2545| Promise\<void> | Promise that returns no value.|
2546
2547**Error codes**
2548For details about the error codes, see [Crypto Framework Error Codes](../errorcodes/errorcode-crypto-framework.md).
2549
2550| ID| Error Message              |
2551| -------- | ---------------------- |
2552| 401 | invalid parameters.          |
2553| 17620001 | memory error.          |
2554| 17620002 | runtime error.          |
2555| 17630001 | crypto operation error. |
2556
2557### update
2558
2559update(data: DataBlob, callback: AsyncCallback\<void>): void
2560
2561Updates the data for signature verification. This API uses an asynchronous callback to return the result.
2562
2563This API can be called only after the [Verify](#verify) instance is initialized using [init()](#init-4).
2564
2565> **NOTE**
2566>
2567> You can call **update** multiple times or do not use **update** (call [verify](#verify-1) after [init](#init-4)), depending on the size of the data.<br>
2568> The data to be passed in **update** (once or accumulatively) is not size bound. If the data is considerably long, you are advised to use **update()** multiple times to pass in data by segment. This prevents too much memory from being requested at a time.<br>
2569> For details about the sample code for calling **update** multiple times in signature verification, see [Signing and Signature Verification by Segment with an RSA Key Pair (PKCS1 Mode)](../../security/CryptoArchitectureKit/crypto-rsa-sign-sig-verify-pkcs1-by-segment.md). The operations of other algorithms are similar.
2570
2571**System capability**: SystemCapability.Security.CryptoFramework
2572
2573**Parameters**
2574
2575| Name  | Type                 | Mandatory| Description        |
2576| -------- | --------------------- | ---- | ------------ |
2577| data     | [DataBlob](#datablob) | Yes  | Data to pass in.|
2578| callback | AsyncCallback\<void>  | Yes  | Callback invoked to return the result. If the operation is successful, **err** is **undefined**. Otherwise, **err** is an error object.|
2579
2580**Error codes**
2581For details about the error codes, see [Crypto Framework Error Codes](../errorcodes/errorcode-crypto-framework.md).
2582
2583| ID| Error Message              |
2584| -------- | ---------------------- |
2585| 401 | invalid parameters.          |
2586| 17620001 | memory error.          |
2587| 17620002 | runtime error.          |
2588| 17630001 | crypto operation error. |
2589
2590### update
2591
2592update(data: DataBlob): Promise\<void>
2593
2594Updates the data for signature verifications. This API uses a promise to return the result.
2595
2596This API can be called only after the [Verify](#verify) instance is initialized using [init()](#init-5).
2597
2598> **NOTE**
2599>
2600> You can call **update()** multiple times or do not use **update** (call [verify](#verify-2) after [init](#init-5)), depending on the size of the data.<br>
2601> The data to be passed in **update** (once or accumulatively) is not size bound. If the data is considerably long, you are advised to use **update()** multiple times to pass in data by segment. This prevents too much memory from being requested at a time.<br>
2602> For details about the sample code for calling **update** multiple times in signature verification, see [Signing and Signature Verification by Segment with an RSA Key Pair (PKCS1 Mode)](../../security/CryptoArchitectureKit/crypto-rsa-sign-sig-verify-pkcs1-by-segment.md). The operations of other algorithms are similar.
2603
2604**System capability**: SystemCapability.Security.CryptoFramework
2605
2606**Parameters**
2607
2608| Name| Type    | Mandatory| Description      |
2609| ------ | -------- | ---- | ---------- |
2610| data   | [DataBlob](#datablob)  | Yes  | Data to pass in.|
2611
2612**Return value**
2613
2614| Type          | Description         |
2615| -------------- | ------------- |
2616| Promise\<void> | Promise that returns no value.|
2617
2618**Error codes**
2619For details about the error codes, see [Crypto Framework Error Codes](../errorcodes/errorcode-crypto-framework.md).
2620
2621| ID| Error Message              |
2622| -------- | ---------------------- |
2623| 401 | invalid parameters.          |
2624| 17620001 | memory error.          |
2625| 17620002 | runtime error.          |
2626| 17630001 | crypto operation error. |
2627
2628### verify
2629
2630verify(data: DataBlob | null, signatureData: DataBlob, callback: AsyncCallback\<boolean>): void
2631
2632Verifies the signature. This API uses an asynchronous callback to return the result.
2633
2634**System capability**: SystemCapability.Security.CryptoFramework
2635
2636**Parameters**
2637
2638| Name       | Type                | Mandatory| Description      |
2639| ------------- | -------------------- | ---- | ---------- |
2640| data          | [DataBlob](#datablob) \| null<sup>10+</sup>             | Yes  | Data to pass in. In versions earlier than API version 10, only **DataBlob** is supported. Since API version 10, **null** is also supported.|
2641| signatureData | [DataBlob](#datablob)              | Yes  | Signature data. |
2642| callback      | AsyncCallback\<boolean> | Yes  | Callback invoked to return the signature verification result.|
2643
2644**Error codes**
2645For details about the error codes, see [Crypto Framework Error Codes](../errorcodes/errorcode-crypto-framework.md).
2646
2647| ID| Error Message              |
2648| -------- | ---------------------- |
2649| 401 | invalid parameters.          |
2650| 17620001 | memory error.          |
2651| 17620002 | runtime error.          |
2652| 17630001 | crypto operation error. |
2653
2654### verify
2655
2656verify(data: DataBlob | null, signatureData: DataBlob): Promise\<boolean>
2657
2658Verifies the signature. This API uses a promise to return the result.
2659
2660**System capability**: SystemCapability.Security.CryptoFramework
2661
2662**Parameters**
2663
2664| Name       | Type    | Mandatory| Description      |
2665| ------------- | -------- | ---- | ---------- |
2666| data          | [DataBlob](#datablob) \| null<sup>10+</sup>  | Yes  | Data to pass in. In versions earlier than API version 10, only **DataBlob** is supported. Since API version 10, **null** is also supported.|
2667| signatureData | [DataBlob](#datablob)  | Yes  | Signature data. |
2668
2669**Return value**
2670
2671| Type             | Description                          |
2672| ----------------- | ------------------------------ |
2673| Promise\<boolean> | Promise used to return the result.|
2674
2675**Error codes**
2676For details about the error codes, see [Crypto Framework Error Codes](../errorcodes/errorcode-crypto-framework.md).
2677
2678| ID| Error Message              |
2679| -------- | ---------------------- |
2680| 401 | invalid parameters.          |
2681| 17620001 | memory error.          |
2682| 17620002 | runtime error.          |
2683| 17630001 | crypto operation error. |
2684
2685**Callback example**:
2686
2687For more examples of signing and signature verification, see [Signing and Signature Verification with an RSA Key Pair (PKCS1 Mode)](../../security/CryptoArchitectureKit/crypto-rsa-sign-sig-verify-pkcs1.md).
2688
2689```ts
2690import cryptoFramework from '@ohos.security.cryptoFramework';
2691import buffer from '@ohos.buffer';
2692
2693function verifyByCallback() {
2694  let inputUpdate: cryptoFramework.DataBlob = { data: new Uint8Array(buffer.from("This is Sign test plan1", 'utf-8').buffer) };
2695  let inputVerify: cryptoFramework.DataBlob = { data: new Uint8Array(buffer.from("This is Sign test plan2", 'utf-8').buffer) };
2696  // Key generated based on the key data and input data for signature verification. If the data in verify() is the same as that in sign(), the signature verification is successful.
2697  let pkData = new Uint8Array([48, 129, 159, 48, 13, 6, 9, 42, 134, 72, 134, 247, 13, 1, 1, 1, 5, 0, 3, 129, 141, 0, 48, 129, 137, 2, 129, 129, 0, 214, 179, 23, 198, 183, 139, 148, 8, 173, 74, 56, 160, 15, 248, 244, 166, 209, 250, 142, 74, 216, 58, 117, 215, 178, 247, 254, 39, 180, 227, 85, 201, 59, 133, 209, 221, 26, 9, 116, 31, 172, 151, 252, 185, 123, 20, 25, 7, 92, 129, 5, 196, 239, 214, 126, 254, 154, 188, 239, 144, 161, 171, 65, 42, 31, 214, 93, 115, 247, 69, 94, 143, 54, 51, 25, 49, 146, 204, 205, 165, 20, 120, 35, 184, 190, 65, 106, 12, 214, 176, 57, 125, 235, 51, 88, 135, 76, 73, 109, 112, 147, 138, 198, 252, 5, 20, 245, 51, 7, 32, 108, 89, 125, 204, 50, 189, 88, 254, 255, 146, 244, 244, 149, 79, 54, 216, 45, 89, 2, 3, 1, 0, 1]);
2698  let skData = new Uint8Array([48, 130, 2, 120, 2, 1, 0, 48, 13, 6, 9, 42, 134, 72, 134, 247, 13, 1, 1, 1, 5, 0, 4, 130, 2, 98, 48, 130, 2, 94, 2, 1, 0, 2, 129, 129, 0, 214, 179, 23, 198, 183, 139, 148, 8, 173, 74, 56, 160, 15, 248, 244, 166, 209, 250, 142, 74, 216, 58, 117, 215, 178, 247, 254, 39, 180, 227, 85, 201, 59, 133, 209, 221, 26, 9, 116, 31, 172, 151, 252, 185, 123, 20, 25, 7, 92, 129, 5, 196, 239, 214, 126, 254, 154, 188, 239, 144, 161, 171, 65, 42, 31, 214, 93, 115, 247, 69, 94, 143, 54, 51, 25, 49, 146, 204, 205, 165, 20, 120, 35, 184, 190, 65, 106, 12, 214, 176, 57, 125, 235, 51, 88, 135, 76, 73, 109, 112, 147, 138, 198, 252, 5, 20, 245, 51, 7, 32, 108, 89, 125, 204, 50, 189, 88, 254, 255, 146, 244, 244, 149, 79, 54, 216, 45, 89, 2, 3, 1, 0, 1, 2, 129, 129, 0, 152, 111, 145, 203, 10, 88, 116, 163, 112, 126, 9, 20, 68, 34, 235, 121, 98, 14, 182, 102, 151, 125, 114, 91, 210, 122, 215, 29, 212, 5, 176, 203, 238, 146, 5, 190, 41, 21, 91, 56, 125, 239, 111, 133, 53, 200, 192, 56, 132, 202, 42, 145, 120, 3, 224, 40, 223, 46, 148, 29, 41, 92, 17, 40, 12, 72, 165, 69, 192, 211, 142, 233, 81, 202, 177, 235, 156, 27, 179, 48, 18, 85, 154, 101, 193, 45, 218, 91, 24, 143, 196, 248, 16, 83, 177, 198, 136, 77, 111, 134, 60, 219, 95, 246, 23, 5, 45, 14, 83, 29, 137, 248, 159, 28, 132, 142, 205, 99, 226, 213, 84, 232, 57, 130, 156, 81, 191, 237, 2, 65, 0, 255, 158, 212, 13, 43, 132, 244, 135, 148, 161, 232, 219, 20, 81, 196, 102, 103, 44, 110, 71, 100, 62, 73, 200, 32, 138, 114, 209, 171, 150, 179, 92, 198, 5, 190, 218, 79, 227, 227, 37, 32, 57, 159, 252, 107, 211, 139, 198, 202, 248, 137, 143, 186, 205, 106, 81, 85, 207, 134, 148, 110, 204, 243, 27, 2, 65, 0, 215, 4, 181, 121, 57, 224, 170, 168, 183, 159, 152, 8, 74, 233, 80, 244, 146, 81, 48, 159, 194, 199, 36, 187, 6, 181, 182, 223, 115, 133, 151, 171, 78, 219, 90, 161, 248, 69, 6, 207, 173, 3, 81, 161, 2, 60, 238, 204, 177, 12, 138, 17, 220, 179, 71, 113, 200, 248, 159, 153, 252, 150, 180, 155, 2, 65, 0, 190, 202, 185, 211, 170, 171, 238, 40, 84, 84, 21, 13, 144, 57, 7, 178, 183, 71, 126, 120, 98, 229, 235, 4, 40, 229, 173, 149, 185, 209, 29, 199, 29, 54, 164, 161, 38, 8, 30, 62, 83, 179, 47, 42, 165, 0, 156, 207, 160, 39, 169, 229, 81, 180, 136, 170, 116, 182, 20, 233, 45, 90, 100, 9, 2, 65, 0, 152, 255, 47, 198, 15, 201, 238, 133, 89, 11, 133, 153, 184, 252, 37, 239, 177, 65, 118, 80, 231, 190, 222, 66, 250, 118, 72, 166, 221, 67, 156, 245, 119, 138, 28, 6, 142, 107, 71, 122, 116, 200, 156, 199, 237, 152, 191, 239, 4, 184, 64, 114, 143, 81, 62, 48, 23, 233, 217, 95, 47, 221, 104, 171, 2, 64, 30, 219, 1, 230, 241, 70, 246, 243, 121, 174, 67, 66, 11, 99, 202, 17, 52, 234, 78, 29, 3, 57, 51, 123, 149, 86, 64, 192, 73, 199, 108, 101, 55, 232, 41, 114, 153, 237, 253, 52, 205, 148, 45, 86, 186, 241, 182, 183, 42, 77, 252, 195, 29, 158, 173, 3, 182, 207, 254, 61, 71, 184, 167, 184]);
2699  let pubKeyBlob: cryptoFramework.DataBlob = { data: pkData };
2700  let priKeyBlob: cryptoFramework.DataBlob = { data: skData };
2701  // The data is signData.data in Sign().
2702  let signMessageBlob: cryptoFramework.DataBlob = { data: new Uint8Array([9, 68, 164, 161, 230, 155, 255, 153, 10, 12, 14, 22, 146, 115, 209, 167, 223, 133, 89, 173, 50, 249, 176, 104, 10, 251, 219, 104, 117, 196, 105, 65, 249, 139, 119, 41, 15, 171, 191, 11, 177, 177, 1, 119, 130, 142, 87, 183, 32, 220, 226, 28, 38, 73, 222, 172, 153, 26, 87, 58, 188, 42, 150, 67, 94, 214, 147, 64, 202, 87, 155, 125, 254, 112, 95, 176, 255, 207, 106, 43, 228, 153, 131, 240, 120, 88, 253, 179, 207, 207, 110, 223, 173, 15, 113, 11, 183, 122, 237, 205, 206, 123, 246, 33, 167, 169, 251, 237, 199, 26, 220, 152, 190, 117, 131, 74, 232, 50, 39, 172, 232, 178, 112, 73, 251, 235, 131, 209]) }
2703  let rsaGenerator = cryptoFramework.createAsyKeyGenerator('RSA1024');
2704  let verifyer = cryptoFramework.createVerify('RSA1024|PKCS1|SHA256');
2705  rsaGenerator.convertKey(pubKeyBlob, priKeyBlob, (err, keyPair) => {
2706    verifyer.init(keyPair.pubKey, err => {
2707      verifyer.update(inputUpdate, err => {
2708        verifyer.verify(inputVerify, signMessageBlob, (err, res) => {
2709          console.info('verify result is ' + res);
2710        });
2711      });
2712    });
2713  });
2714}
2715```
2716
2717**Example (promise)**
2718
2719For more examples of signing and signature verification, see [Signing and Signature Verification with an RSA Key Pair (PKCS1 Mode)](../../security/CryptoArchitectureKit/crypto-rsa-sign-sig-verify-pkcs1.md).
2720
2721```ts
2722import cryptoFramework from '@ohos.security.cryptoFramework';
2723import buffer from '@ohos.buffer';
2724
2725async function genKeyPairByData(pubKeyData: Uint8Array, priKeyData: Uint8Array) {
2726  let pubKeyBlob: cryptoFramework.DataBlob = { data: pubKeyData };
2727  let priKeyBlob: cryptoFramework.DataBlob = { data: priKeyData };
2728  let rsaGenerator = cryptoFramework.createAsyKeyGenerator('RSA1024');
2729  let keyPair = await rsaGenerator.convertKey(pubKeyBlob, priKeyBlob);
2730  console.info('convertKey success');
2731  return keyPair;
2732}
2733
2734async function verifyByPromise() {
2735  // Key generated based on the key data and input data for signature verification. If the data in verify() is the same as that in sign(), the signature verification is successful.
2736  let pkData = new Uint8Array([48, 129, 159, 48, 13, 6, 9, 42, 134, 72, 134, 247, 13, 1, 1, 1, 5, 0, 3, 129, 141, 0, 48, 129, 137, 2, 129, 129, 0, 214, 179, 23, 198, 183, 139, 148, 8, 173, 74, 56, 160, 15, 248, 244, 166, 209, 250, 142, 74, 216, 58, 117, 215, 178, 247, 254, 39, 180, 227, 85, 201, 59, 133, 209, 221, 26, 9, 116, 31, 172, 151, 252, 185, 123, 20, 25, 7, 92, 129, 5, 196, 239, 214, 126, 254, 154, 188, 239, 144, 161, 171, 65, 42, 31, 214, 93, 115, 247, 69, 94, 143, 54, 51, 25, 49, 146, 204, 205, 165, 20, 120, 35, 184, 190, 65, 106, 12, 214, 176, 57, 125, 235, 51, 88, 135, 76, 73, 109, 112, 147, 138, 198, 252, 5, 20, 245, 51, 7, 32, 108, 89, 125, 204, 50, 189, 88, 254, 255, 146, 244, 244, 149, 79, 54, 216, 45, 89, 2, 3, 1, 0, 1]);
2737  let skData = new Uint8Array([48, 130, 2, 120, 2, 1, 0, 48, 13, 6, 9, 42, 134, 72, 134, 247, 13, 1, 1, 1, 5, 0, 4, 130, 2, 98, 48, 130, 2, 94, 2, 1, 0, 2, 129, 129, 0, 214, 179, 23, 198, 183, 139, 148, 8, 173, 74, 56, 160, 15, 248, 244, 166, 209, 250, 142, 74, 216, 58, 117, 215, 178, 247, 254, 39, 180, 227, 85, 201, 59, 133, 209, 221, 26, 9, 116, 31, 172, 151, 252, 185, 123, 20, 25, 7, 92, 129, 5, 196, 239, 214, 126, 254, 154, 188, 239, 144, 161, 171, 65, 42, 31, 214, 93, 115, 247, 69, 94, 143, 54, 51, 25, 49, 146, 204, 205, 165, 20, 120, 35, 184, 190, 65, 106, 12, 214, 176, 57, 125, 235, 51, 88, 135, 76, 73, 109, 112, 147, 138, 198, 252, 5, 20, 245, 51, 7, 32, 108, 89, 125, 204, 50, 189, 88, 254, 255, 146, 244, 244, 149, 79, 54, 216, 45, 89, 2, 3, 1, 0, 1, 2, 129, 129, 0, 152, 111, 145, 203, 10, 88, 116, 163, 112, 126, 9, 20, 68, 34, 235, 121, 98, 14, 182, 102, 151, 125, 114, 91, 210, 122, 215, 29, 212, 5, 176, 203, 238, 146, 5, 190, 41, 21, 91, 56, 125, 239, 111, 133, 53, 200, 192, 56, 132, 202, 42, 145, 120, 3, 224, 40, 223, 46, 148, 29, 41, 92, 17, 40, 12, 72, 165, 69, 192, 211, 142, 233, 81, 202, 177, 235, 156, 27, 179, 48, 18, 85, 154, 101, 193, 45, 218, 91, 24, 143, 196, 248, 16, 83, 177, 198, 136, 77, 111, 134, 60, 219, 95, 246, 23, 5, 45, 14, 83, 29, 137, 248, 159, 28, 132, 142, 205, 99, 226, 213, 84, 232, 57, 130, 156, 81, 191, 237, 2, 65, 0, 255, 158, 212, 13, 43, 132, 244, 135, 148, 161, 232, 219, 20, 81, 196, 102, 103, 44, 110, 71, 100, 62, 73, 200, 32, 138, 114, 209, 171, 150, 179, 92, 198, 5, 190, 218, 79, 227, 227, 37, 32, 57, 159, 252, 107, 211, 139, 198, 202, 248, 137, 143, 186, 205, 106, 81, 85, 207, 134, 148, 110, 204, 243, 27, 2, 65, 0, 215, 4, 181, 121, 57, 224, 170, 168, 183, 159, 152, 8, 74, 233, 80, 244, 146, 81, 48, 159, 194, 199, 36, 187, 6, 181, 182, 223, 115, 133, 151, 171, 78, 219, 90, 161, 248, 69, 6, 207, 173, 3, 81, 161, 2, 60, 238, 204, 177, 12, 138, 17, 220, 179, 71, 113, 200, 248, 159, 153, 252, 150, 180, 155, 2, 65, 0, 190, 202, 185, 211, 170, 171, 238, 40, 84, 84, 21, 13, 144, 57, 7, 178, 183, 71, 126, 120, 98, 229, 235, 4, 40, 229, 173, 149, 185, 209, 29, 199, 29, 54, 164, 161, 38, 8, 30, 62, 83, 179, 47, 42, 165, 0, 156, 207, 160, 39, 169, 229, 81, 180, 136, 170, 116, 182, 20, 233, 45, 90, 100, 9, 2, 65, 0, 152, 255, 47, 198, 15, 201, 238, 133, 89, 11, 133, 153, 184, 252, 37, 239, 177, 65, 118, 80, 231, 190, 222, 66, 250, 118, 72, 166, 221, 67, 156, 245, 119, 138, 28, 6, 142, 107, 71, 122, 116, 200, 156, 199, 237, 152, 191, 239, 4, 184, 64, 114, 143, 81, 62, 48, 23, 233, 217, 95, 47, 221, 104, 171, 2, 64, 30, 219, 1, 230, 241, 70, 246, 243, 121, 174, 67, 66, 11, 99, 202, 17, 52, 234, 78, 29, 3, 57, 51, 123, 149, 86, 64, 192, 73, 199, 108, 101, 55, 232, 41, 114, 153, 237, 253, 52, 205, 148, 45, 86, 186, 241, 182, 183, 42, 77, 252, 195, 29, 158, 173, 3, 182, 207, 254, 61, 71, 184, 167, 184]);
2738  let keyPair = await genKeyPairByData(pkData, skData);
2739  let inputUpdate: cryptoFramework.DataBlob = { data: new Uint8Array(buffer.from("This is Sign test plan1", 'utf-8').buffer) };
2740  let inputVerify: cryptoFramework.DataBlob = { data: new Uint8Array(buffer.from("This is Sign test plan2", 'utf-8').buffer) };
2741  // The data is signData.data in Sign().
2742  let signMessageBlob: cryptoFramework.DataBlob = { data: new Uint8Array([9, 68, 164, 161, 230, 155, 255, 153, 10, 12, 14, 22, 146, 115, 209, 167, 223, 133, 89, 173, 50, 249, 176, 104, 10, 251, 219, 104, 117, 196, 105, 65, 249, 139, 119, 41, 15, 171, 191, 11, 177, 177, 1, 119, 130, 142, 87, 183, 32, 220, 226, 28, 38, 73, 222, 172, 153, 26, 87, 58, 188, 42, 150, 67, 94, 214, 147, 64, 202, 87, 155, 125, 254, 112, 95, 176, 255, 207, 106, 43, 228, 153, 131, 240, 120, 88, 253, 179, 207, 207, 110, 223, 173, 15, 113, 11, 183, 122, 237, 205, 206, 123, 246, 33, 167, 169, 251, 237, 199, 26, 220, 152, 190, 117, 131, 74, 232, 50, 39, 172, 232, 178, 112, 73, 251, 235, 131, 209]) };
2743  let verifier = cryptoFramework.createVerify('RSA1024|PKCS1|SHA256');
2744  await verifier.init(keyPair.pubKey);
2745  await verifier.update(inputUpdate);
2746  let res = await verifier.verify(inputVerify, signMessageBlob);
2747  console.info('signData result: ' + res);
2748}
2749```
2750
2751### setVerifySpec<sup>10+</sup>
2752
2753setVerifySpec(itemType: SignSpecItem, itemValue: number): void
2754
2755setVerifySpec(itemType: SignSpecItem, itemValue: number\|Uint8Array): void
2756
2757Sets signature verification specifications. You can use this API to set signature verification parameters that cannot be set by [createVerify](#cryptoframeworkcreateverify).
2758
2759Currently, only RSA and SM2 (available since API version 11) are supported.
2760
2761The parameters for signature verification must be the same as those for signing.
2762
2763**System capability**: SystemCapability.Security.CryptoFramework
2764
2765**Parameters**
2766
2767| Name  | Type                | Mandatory| Description      |
2768| -------- | -------------------- | ---- | ---------- |
2769| itemType     | [SignSpecItem](#signspecitem10)              | Yes  | Signature verification parameter to set.|
2770| itemValue | number\|Uint8Array<sup>11+</sup> | Yes  | Value of the signature verification parameter to set.|
2771
2772**Error codes**
2773For details about the error codes, see [Crypto Framework Error Codes](../errorcodes/errorcode-crypto-framework.md).
2774
2775| ID| Error Message              |
2776| -------- | ---------------------- |
2777| 401 | invalid parameters.          |
2778| 801 | this operation is not supported.          |
2779| 17620001 | memory error.          |
2780| 17630001 | crypto operation error. |
2781
2782**Example**
2783
2784```ts
2785let verifyer: cryptoFramework.Verify; // The process of generating the Verify instance is omitted here.
2786let setN = 20;
2787verifyer.setVerifySpec(cryptoFramework.SignSpecItem.PSS_SALT_LEN_NUM, setN);
2788```
2789
2790### getVerifySpec<sup>10+</sup>
2791
2792getVerifySpec(itemType: SignSpecItem): string | number
2793
2794Obtains signature verification specifications. Currently, only RSA is supported.
2795
2796The parameters for signature verification must be the same as those for signing.
2797
2798**System capability**: SystemCapability.Security.CryptoFramework
2799
2800**Parameters**
2801
2802| Name| Type    | Mandatory| Description      |
2803| ------ | -------- | ---- | ---------- |
2804| itemType   | [SignSpecItem](#signspecitem10)  | Yes  | Signature verification parameter to obtain.|
2805
2806**Return value**
2807
2808| Type          | Description       |
2809| -------------- | ----------- |
2810| string\|number | Returns the value of the parameter obtained.|
2811
2812**Error codes**
2813For details about the error codes, see [Crypto Framework Error Codes](../errorcodes/errorcode-crypto-framework.md).
2814
2815| ID| Error Message              |
2816| -------- | ---------------------- |
2817| 401 | invalid parameters.          |
2818| 801 | this operation is not supported.          |
2819| 17620001 | memory error.          |
2820| 17630001 | crypto operation error. |
2821
2822**Example**
2823
2824```ts
2825let verifyer: cryptoFramework.Verify; // The process of generating the Verify instance is omitted here.
2826let saltLen = verifyer.getVerifySpec(cryptoFramework.SignSpecItem.PSS_SALT_LEN_NUM);
2827```
2828
2829## cryptoFramework.createKeyAgreement
2830
2831createKeyAgreement(algName: string): KeyAgreement
2832
2833Creates a **KeyAgreement** instance.
2834
2835For details about the supported specifications, see [Key Agreement Overview and Algorithm Specifications](../../security/CryptoArchitectureKit/crypto-key-agreement-overview.md).
2836
2837**System capability**: SystemCapability.Security.CryptoFramework
2838
2839**Parameters**
2840
2841| Name | Type  | Mandatory| Description                                                        |
2842| ------- | ------ | ---- | ------------------------------------------------------------ |
2843| algName | string | Yes  | Key agreement algorithm to use. In addition to ECC, X25519 and DH are supported since API version 11.|
2844
2845**Return value**
2846
2847| Type        | Description                                      |
2848| ------------ | ------------------------------------------ |
2849| KeyAgreement | Returns the **KeyAgreement** instance created.|
2850
2851**Error codes**
2852For details about the error codes, see [Crypto Framework Error Codes](../errorcodes/errorcode-crypto-framework.md).
2853
2854| ID| Error Message              |
2855| -------- | ---------------------- |
2856| 401 | invalid parameters.          |
2857| 801 | this operation is not supported.          |
2858| 17620001 | memory error.          |
2859
2860**Example**
2861
2862```ts
2863let keyAgreement = cryptoFramework.createKeyAgreement('ECC256');
2864
2865```
2866
2867## KeyAgreement
2868
2869Provides APIs for key agreement operations. Before using any API of the **KeyAgreement** class, you must create a **KeyAgreement** instance by using [createKeyAgreement(algName: string): KeyAgreement](#cryptoframeworkcreatekeyagreement).
2870
2871### Attributes
2872
2873**System capability**: SystemCapability.Security.CryptoFramework
2874
2875| Name   | Type  | Readable| Writable| Description                        |
2876| ------- | ------ | ---- | ---- | ---------------------------- |
2877| algName | string | Yes  | No  | Algorithm used for key agreement.|
2878
2879### generateSecret
2880
2881generateSecret(priKey: PriKey, pubKey: PubKey, callback: AsyncCallback\<DataBlob>): void
2882
2883Performs key agreement based on a private key and a public key. This API uses an asynchronous callback to return the shared secret generated.
2884
2885**System capability**: SystemCapability.Security.CryptoFramework
2886
2887**Parameters**
2888
2889| Name  | Type                    | Mandatory| Description                  |
2890| -------- | ------------------------ | ---- | ---------------------- |
2891| priKey   | [PriKey](#prikey)        | Yes  | Private key used for key agreement.|
2892| pubKey   | [PubKey](#pubkey)        | Yes  | Public key used for key agreement.|
2893| callback | AsyncCallback\<[DataBlob](#datablob)> | Yes  | Callback invoked to return the shared secret.|
2894
2895**Error codes**
2896For details about the error codes, see [Crypto Framework Error Codes](../errorcodes/errorcode-crypto-framework.md).
2897
2898| ID| Error Message              |
2899| -------- | ---------------------- |
2900| 401 | invalid parameters.          |
2901| 17620001 | memory error.          |
2902| 17620002 | runtime error.          |
2903| 17630001 | crypto operation error. |
2904
2905### generateSecret
2906
2907generateSecret(priKey: PriKey, pubKey: PubKey): Promise\<DataBlob>
2908
2909Performs key agreement based on a private key and a public key. This API uses a promise to return the shared secret generated.
2910
2911**System capability**: SystemCapability.Security.CryptoFramework
2912
2913**Parameters**
2914
2915| Name| Type  | Mandatory| Description                  |
2916| ------ | ------ | ---- | ---------------------- |
2917| priKey | [PriKey](#prikey) | Yes  | Private key used for key agreement.|
2918| pubKey | [PubKey](#pubkey) | Yes  | Public key used for key agreement.|
2919
2920**Return value**
2921
2922| Type              | Description    |
2923| ------------------ | -------- |
2924| Promise\<[DataBlob](#datablob)> | Promise used to return the shared secret.|
2925
2926**Error codes**
2927For details about the error codes, see [Crypto Framework Error Codes](../errorcodes/errorcode-crypto-framework.md).
2928
2929| ID| Error Message              |
2930| -------- | ---------------------- |
2931| 401 | invalid parameters.          |
2932| 17620001 | memory error.          |
2933| 17620002 | runtime error.          |
2934| 17630001 | crypto operation error. |
2935
2936**Callback example**:
2937
2938```ts
2939import { BusinessError } from '@ohos.base';
2940
2941let globalKeyPair: cryptoFramework.KeyPair; // globalKeyPair is an asymmetric key object generated by the asymmetric key generator. The generation process is omitted here.
2942let keyAgreement = cryptoFramework.createKeyAgreement('ECC256');
2943keyAgreement.generateSecret(globalKeyPair.priKey, globalKeyPair.pubKey, (err, secret) => {
2944  if (err) {
2945    console.error("keyAgreement error.");
2946    return;
2947  }
2948  console.info('keyAgreement output is ' + secret.data);
2949});
2950```
2951
2952**Example (promise)**
2953
2954```ts
2955import { BusinessError } from '@ohos.base';
2956
2957let globalKeyPair: cryptoFramework.KeyPair; // globalKeyPair is an asymmetric key object generated by the asymmetric key generator. The generation process is omitted here.
2958let keyAgreement = cryptoFramework.createKeyAgreement('ECC256');
2959let keyAgreementPromise = keyAgreement.generateSecret(globalKeyPair.priKey, globalKeyPair.pubKey);
2960keyAgreementPromise.then(secret => {
2961  console.info('keyAgreement output is ' + secret.data);
2962}).catch((error: BusinessError) => {
2963  console.error("keyAgreement error.");
2964});
2965```
2966
2967## cryptoFramework.createMd
2968
2969createMd(algName: string): Md
2970
2971Creates an **Md** instance for MD operations.
2972
2973For details about the supported specifications, see [Supported Algorithms and Specifications](../../security/CryptoArchitectureKit/crypto-generate-message-digest.md#supported-algorithms-and-specifications).
2974
2975**System capability**: SystemCapability.Security.CryptoFramework
2976
2977**Parameters**
2978
2979| Name | Type  | Mandatory| Description                                                        |
2980| ------- | ------ | ---- | ------------------------------------------------------------ |
2981| algName | string | Yes  | MD algorithm to use. For details about the supported algorithms, see [Supported Algorithms and Specifications](../../security/CryptoArchitectureKit/crypto-generate-message-digest.md#supported-algorithms-and-specifications).|
2982
2983**Return value**
2984
2985| Type| Description                                   |
2986| ---- | --------------------------------------- |
2987| Md   | Returns the [Md](#md) instance created.|
2988
2989**Error codes**
2990For details about the error codes, see [Crypto Framework Error Codes](../errorcodes/errorcode-crypto-framework.md).
2991
2992| ID| Error Message          |
2993| -------- | ------------------ |
2994| 401 | invalid parameters.       |
2995| 17620001 | memory error.       |
2996
2997**Example**
2998
2999```ts
3000import { BusinessError } from '@ohos.base';
3001
3002try {
3003  // Set algName based on the algorithm supported.
3004  let md = cryptoFramework.createMd('SHA256');
3005} catch (error) {
3006  let e: BusinessError = error as BusinessError;
3007  console.error(`sync error, ${e.code}, ${e.message}`);
3008}
3009```
3010
3011## Md
3012
3013Provides APIs for MD operations. Before using any API of the **Md** class, you must create an **Md** instance by using [createMd](#cryptoframeworkcreatemd).
3014
3015### Attributes
3016
3017**System capability**: SystemCapability.Security.CryptoFramework
3018
3019| Name   | Type  | Readable| Writable| Description                  |
3020| ------- | ------ | ---- | ---- | ---------------------- |
3021| algName | string | Yes  | No  | Digest algorithm.|
3022
3023### update
3024
3025update(input: DataBlob, callback: AsyncCallback\<void>): void
3026
3027Updates the message for MD operations. This API uses an asynchronous callback to return the result. **update** and **digest** must be used together. **digest** is mandatory, and **update** is optional.
3028
3029> **NOTE**
3030>
3031> For details about the code for calling **update** multiple times in an MD operation, see [MD (Passing In Data by Segment)](../../security/CryptoArchitectureKit/crypto-generate-message-digest.md#md-passing-in-data-by-segment).
3032
3033**System capability**: SystemCapability.Security.CryptoFramework
3034
3035**Parameters**
3036
3037| Name  | Type                 | Mandatory| Description        |
3038| -------- | --------------------- | ---- | ------------ |
3039| input    | [DataBlob](#datablob) | Yes  | Data to pass in.|
3040| callback | AsyncCallback\<void>  | Yes  | Callback invoked to return the result. If the operation is successful, **err** is **undefined**. Otherwise, **err** is an error object. |
3041
3042**Error codes**
3043For details about the error codes, see [Crypto Framework Error Codes](../errorcodes/errorcode-crypto-framework.md).
3044
3045| ID| Error Message              |
3046| -------- | ---------------------- |
3047| 401 | invalid parameters.       |
3048| 17630001 | crypto operation error. |
3049
3050### update
3051
3052update(input: DataBlob): Promise\<void>
3053
3054Updates the message for MD operations. This API uses a promise to return the result. **update** and **digest** must be used together. **digest** is mandatory, and **update** is optional.
3055
3056> **NOTE**
3057>
3058> For details about the code for calling **update** multiple times in an MD operation, see [MD (Passing In Data by Segment)](../../security/CryptoArchitectureKit/crypto-generate-message-digest.md#md-passing-in-data-by-segment).
3059
3060**System capability**: SystemCapability.Security.CryptoFramework
3061
3062| Name| Type    | Mandatory| Description        |
3063| ------ | -------- | ---- | ------------ |
3064| input  | DataBlob | Yes  | Data to pass in.|
3065
3066**Return value**
3067
3068| Type          | Description         |
3069| -------------- | ------------- |
3070| Promise\<void> | Promise that returns no value.|
3071
3072**Error codes**
3073For details about the error codes, see [Crypto Framework Error Codes](../errorcodes/errorcode-crypto-framework.md).
3074
3075| ID| Error Message              |
3076| -------- | ---------------------- |
3077| 401 | invalid parameters.       |
3078| 17630001 | crypto operation error. |
3079
3080### digest
3081
3082digest(callback: AsyncCallback\<DataBlob>): void
3083
3084Generates an MD. This API uses an asynchronous callback to return the result.
3085
3086**System capability**: SystemCapability.Security.CryptoFramework
3087
3088| Name  | Type                    | Mandatory| Description      |
3089| -------- | ------------------------ | ---- | ---------- |
3090| callback | AsyncCallback\<[DataBlob](#datablob)> | Yes  | Callback invoked to return a **DataBlob** object.|
3091
3092**Error codes**
3093For details about the error codes, see [Crypto Framework Error Codes](../errorcodes/errorcode-crypto-framework.md).
3094
3095| ID| Error Message              |
3096| -------- | ---------------------- |
3097| 17620001 | memory error.           |
3098| 17630001 | crypto operation error. |
3099
3100**Example**
3101
3102```ts
3103import cryptoFramework from '@ohos.security.cryptoFramework';
3104import buffer from '@ohos.buffer';
3105
3106function mdByCallback() {
3107  let md = cryptoFramework.createMd('SHA256');
3108  md.update({ data: new Uint8Array(buffer.from("mdTestMessage", 'utf-8').buffer) }, (err,) => {
3109    md.digest((err, digestOutput) => {
3110      console.info('[Callback]: MD result: ' + digestOutput.data);
3111      console.info('[Callback]: MD len: ' + md.getMdLength());
3112    });
3113  });
3114}
3115```
3116
3117### digest
3118
3119digest(): Promise\<DataBlob>
3120
3121Generates an MD. This API uses a promise to return the result.
3122
3123**System capability**: SystemCapability.Security.CryptoFramework
3124
3125**Return value**
3126
3127| Type              | Description       |
3128| ------------------ | ----------- |
3129| Promise\<[DataBlob](#datablob)> | Promise used to return the result.|
3130
3131**Error codes**
3132For details about the error codes, see [Crypto Framework Error Codes](../errorcodes/errorcode-crypto-framework.md).
3133
3134| ID| Error Message              |
3135| -------- | ---------------------- |
3136| 17620001 | memory error.           |
3137| 17630001 | crypto operation error. |
3138
3139**Example**
3140
3141```ts
3142import cryptoFramework from '@ohos.security.cryptoFramework';
3143import buffer from '@ohos.buffer';
3144
3145async function mdByPromise() {
3146  let md = cryptoFramework.createMd('SHA256');
3147  await md.update({ data: new Uint8Array(buffer.from("mdTestMessage", 'utf-8').buffer) });
3148  let mdOutput = await md.digest();
3149  console.info('[Promise]: MD result: ' + mdOutput.data);
3150  console.info('[Promise]: MD len: ' + md.getMdLength());
3151}
3152```
3153
3154### getMdLength
3155
3156getMdLength(): number
3157
3158Obtains the MD length, in bytes.
3159
3160**System capability**: SystemCapability.Security.CryptoFramework
3161
3162**Return value**
3163
3164| Type  | Description                      |
3165| ------ | -------------------------- |
3166| number | MD length obtained.|
3167
3168**Error codes**
3169For details about the error codes, see [Crypto Framework Error Codes](../errorcodes/errorcode-crypto-framework.md).
3170
3171| ID| Error Message              |
3172| -------- | ---------------------- |
3173| 17630001 | crypto operation error. |
3174
3175**Example**
3176
3177```ts
3178import cryptoFramework from '@ohos.security.cryptoFramework';
3179
3180function getLength() {
3181  let md = cryptoFramework.createMd('SHA256');
3182  console.info('[Promise]: MD len: ' + md.getMdLength());
3183}
3184```
3185
3186## cryptoFramework.createMac
3187
3188createMac(algName: string): Mac
3189
3190Creates a **Mac** instance for message authentication code (MAC) operations.
3191
3192For details about the supported specifications, see [Supported Algorithms and Specifications](../../security/CryptoArchitectureKit/crypto-compute-mac.md#supported-algorithms-and-specifications).
3193
3194**System capability**: SystemCapability.Security.CryptoFramework
3195
3196**Parameters**
3197
3198| Name | Type  | Mandatory| Description                                                        |
3199| ------- | ------ | ---- | ------------------------------------------------------------ |
3200| algName | string | Yes  | MD algorithm to use. For details about the supported algorithms, see [Supported Algorithms and Specifications](../../security/CryptoArchitectureKit/crypto-compute-mac.md#supported-algorithms-and-specifications).|
3201
3202**Return value**
3203
3204| Type| Description                                     |
3205| ---- | ----------------------------------------- |
3206| Mac  | Returns the [Mac](#mac) instance created.|
3207
3208**Error codes**
3209For details about the error codes, see [Crypto Framework Error Codes](../errorcodes/errorcode-crypto-framework.md).
3210
3211| ID| Error Message          |
3212| -------- | ------------------ |
3213| 401 | invalid parameters.       |
3214| 17620001 | memory error.       |
3215
3216**Example**
3217
3218```ts
3219import { BusinessError } from '@ohos.base';
3220
3221try {
3222  // Set algName based on the algorithm supported.
3223  let mac = cryptoFramework.createMac('SHA256');
3224} catch (error) {
3225  let e: BusinessError = error as BusinessError;
3226  console.error(`sync error, ${e.code}, ${e.message}`);
3227}
3228```
3229
3230## Mac
3231
3232Provides APIs for MAC operations. Before using any API of the **Mac** class, you must create a **Mac** instance by using [createMac](#cryptoframeworkcreatemac).
3233
3234### Attributes
3235
3236**System capability**: SystemCapability.Security.CryptoFramework
3237
3238| Name   | Type  | Readable| Writable| Description                  |
3239| ------- | ------ | ---- | ---- | ---------------------- |
3240| algName | string | Yes  | No  | Digest algorithm.|
3241
3242### init
3243
3244init(key: SymKey, callback: AsyncCallback\<void>): void
3245
3246Initializes the MAC computation with a symmetric key. This API uses an asynchronous callback to return the result. **init**, **update**, and **doFinal** must be used together. **init** and **doFinal** are mandatory, and **update** is optional.
3247
3248  > **NOTE**
3249  >
3250  > You are advised to create a symmetric key generator based on the [HMAC key generation specifications](../../security/CryptoArchitectureKit/crypto-sym-key-generation-conversion-spec.md#hmac) and use [generateSymKey](#generatesymkey) to randomly generate a symmetric key or use [convertKey](#convertkey) to convert the binary data (whose length is the same as the key specifications) into a key.<br>If **HMAC** is specified to generate the symmetric key generator, only [convertKey](#convertkey) can be called to pass in a binary key of 1 to 4096 bytes.
3251
3252**System capability**: SystemCapability.Security.CryptoFramework
3253
3254**Parameters**
3255
3256| Name  | Type                | Mandatory| Description          |
3257| -------- | -------------------- | ---- | -------------- |
3258| key      | [SymKey](#symkey)    | Yes  | Shared symmetric key.|
3259| callback | AsyncCallback\<void> | Yes  | Callback invoked to return the result. If the operation is successful, **err** is **undefined**. Otherwise, **err** is an error object. |
3260
3261**Error codes**
3262For details about the error codes, see [Crypto Framework Error Codes](../errorcodes/errorcode-crypto-framework.md).
3263
3264| ID| Error Message              |
3265| -------- | ---------------------- |
3266| 401 | invalid parameters.       |
3267| 17630001 | crypto operation error. |
3268
3269### init
3270
3271init(key: SymKey): Promise\<void>
3272
3273Initializes the MAC computation with a symmetric key. This API uses a promise to return the result. **init**, **update**, and **doFinal** must be used together. **init** and **doFinal** are mandatory, and **update** is optional.
3274
3275**System capability**: SystemCapability.Security.CryptoFramework
3276
3277**Parameters**
3278
3279| Name| Type  | Mandatory| Description        |
3280| ------ | ------ | ---- | ------------ |
3281| key    | [SymKey](#symkey) | Yes  | Shared symmetric key.|
3282
3283**Return value**
3284
3285| Type          | Description         |
3286| -------------- | ------------- |
3287| Promise\<void> | Promise that returns no value.|
3288
3289**Error codes**
3290For details about the error codes, see [Crypto Framework Error Codes](../errorcodes/errorcode-crypto-framework.md).
3291
3292| ID| Error Message              |
3293| -------- | ---------------------- |
3294| 401 | invalid parameters.       |
3295| 17630001 | crypto operation error. |
3296
3297### update
3298
3299update(input: DataBlob, callback: AsyncCallback\<void>): void
3300
3301Updates the message for MAC computation. This API uses an asynchronous callback to return the result.
3302
3303> **NOTE**
3304>
3305> For details about the code for calling **update** multiple times in an HMAC operation, see [HMAC (Passing In Full Data)](../../security/CryptoArchitectureKit/crypto-compute-mac.md#hmac-passing-in-full-data).
3306
3307**System capability**: SystemCapability.Security.CryptoFramework
3308
3309**Parameters**
3310
3311| Name  | Type                 | Mandatory| Description        |
3312| -------- | --------------------- | ---- | ------------ |
3313| input    | [DataBlob](#datablob) | Yes  | Data to pass in.|
3314| callback | AsyncCallback\<void>  | Yes  | Callback invoked to return the result. If the operation is successful, **err** is **undefined**. Otherwise, **err** is an error object.|
3315
3316**Error codes**
3317For details about the error codes, see [Crypto Framework Error Codes](../errorcodes/errorcode-crypto-framework.md).
3318
3319| ID| Error Message              |
3320| -------- | ---------------------- |
3321| 401 | invalid parameters.       |
3322| 17630001 | crypto operation error. |
3323
3324### update
3325
3326update(input: DataBlob): Promise\<void>
3327
3328Updates the message for MAC computation. This API uses a promise to return the result.
3329
3330> **NOTE**
3331>
3332> For details about the code for calling **update** multiple times in an HMAC operation, see [HMAC (Passing In Full Data)](../../security/CryptoArchitectureKit/crypto-compute-mac.md#hmac-passing-in-full-data).
3333
3334**System capability**: SystemCapability.Security.CryptoFramework
3335
3336**Parameters**
3337
3338| Name| Type    | Mandatory| Description      |
3339| ------ | -------- | ---- | ---------- |
3340| input  | [DataBlob](#datablob) | Yes  | Data to pass in.|
3341
3342**Return value**
3343
3344| Type          | Description         |
3345| -------------- | ------------- |
3346| Promise\<void> | Promise that returns no value.|
3347
3348**Error codes**
3349For details about the error codes, see [Crypto Framework Error Codes](../errorcodes/errorcode-crypto-framework.md).
3350
3351| ID| Error Message              |
3352| -------- | ---------------------- |
3353| 401 | invalid parameters.       |
3354| 17630001 | crypto operation error. |
3355
3356### doFinal
3357
3358doFinal(callback: AsyncCallback\<DataBlob>): void
3359
3360Finishes the MAC computation. This API uses an asynchronous callback to return the result.
3361
3362**System capability**: SystemCapability.Security.CryptoFramework
3363
3364**Parameters**
3365
3366| Name  | Type                    | Mandatory| Description    |
3367| -------- | ------------------------ | ---- | -------- |
3368| callback | AsyncCallback\<[DataBlob](#datablob)> | Yes  | Callback invoked to return a **DataBlob** object.|
3369
3370**Error codes**
3371For details about the error codes, see [Crypto Framework Error Codes](../errorcodes/errorcode-crypto-framework.md).
3372
3373| ID| Error Message              |
3374| -------- | ---------------------- |
3375| 17620001 | memory error.           |
3376| 17630001 | crypto operation error. |
3377
3378**Example**
3379
3380For more HMAC operation examples, see [MAC Operation](../../security/CryptoArchitectureKit/crypto-compute-mac.md).
3381
3382```ts
3383import cryptoFramework from '@ohos.security.cryptoFramework';
3384import buffer from '@ohos.buffer';
3385
3386function hmacByCallback() {
3387  let mac = cryptoFramework.createMac('SHA256');
3388  let keyBlob: cryptoFramework.DataBlob = { data: new Uint8Array(buffer.from("12345678abcdefgh", 'utf-8').buffer) };
3389  let symKeyGenerator = cryptoFramework.createSymKeyGenerator('AES128');
3390  symKeyGenerator.convertKey(keyBlob, (err, symKey) => {
3391    mac.init(symKey, (err,) => {
3392      mac.update({ data: new Uint8Array(buffer.from("hmacTestMessage", 'utf-8').buffer) }, (err,) => {
3393        mac.doFinal((err, output) => {
3394          console.info('[Callback]: HMAC result: ' + output.data);
3395          console.info('[Callback]: MAC len: ' + mac.getMacLength());
3396        });
3397      });
3398    });
3399  });
3400}
3401```
3402
3403### doFinal
3404
3405doFinal(): Promise\<DataBlob>
3406
3407Finishes the MAC computation. This API uses a promise to return the result.
3408
3409**System capability**: SystemCapability.Security.CryptoFramework
3410
3411**Return value**
3412
3413| Type              | Description       |
3414| ------------------ | ----------- |
3415| Promise\<[DataBlob](#datablob)> | Promise used to return the result.|
3416
3417**Error codes**
3418For details about the error codes, see [Crypto Framework Error Codes](../errorcodes/errorcode-crypto-framework.md).
3419
3420| ID| Error Message              |
3421| -------- | ---------------------- |
3422| 17620001 | memory error.           |
3423| 17630001 | crypto operation error. |
3424
3425**Example**
3426
3427For more HMAC operation examples, see [MAC Operation](../../security/CryptoArchitectureKit/crypto-compute-mac.md).
3428
3429```ts
3430import cryptoFramework from '@ohos.security.cryptoFramework';
3431import buffer from '@ohos.buffer';
3432
3433async function hmacByPromise() {
3434  let mac = cryptoFramework.createMac('SHA256');
3435  let keyBlob: cryptoFramework.DataBlob = { data: new Uint8Array(buffer.from("12345678abcdefgh", 'utf-8').buffer) };
3436  let symKeyGenerator = cryptoFramework.createSymKeyGenerator('AES128');
3437  let symKey = await symKeyGenerator.convertKey(keyBlob);
3438  await mac.init(symKey);
3439  await mac.update({ data: new Uint8Array(buffer.from("hmacTestMessage", 'utf-8').buffer) });
3440  let macOutput = await mac.doFinal();
3441  console.info('[Promise]: HMAC result: ' + macOutput.data);
3442  console.info('[Promise]: MAC len: ' + mac.getMacLength());
3443}
3444```
3445
3446### getMacLength
3447
3448getMacLength(): number
3449
3450Obtains the MAC length, in bytes.
3451
3452**System capability**: SystemCapability.Security.CryptoFramework
3453
3454**Return value**
3455
3456| Type  | Description                       |
3457| ------ | --------------------------- |
3458| number | Returns the MAC length obtained.|
3459
3460**Error codes**
3461For details about the error codes, see [Crypto Framework Error Codes](../errorcodes/errorcode-crypto-framework.md).
3462
3463| ID| Error Message              |
3464| -------- | ---------------------- |
3465| 17630001 | crypto operation error. |
3466
3467**Example**
3468
3469```ts
3470import cryptoFramework from '@ohos.security.cryptoFramework';
3471import { BusinessError } from '@ohos.base';
3472
3473let mac = cryptoFramework.createMac('SHA256');
3474console.info('Mac algName is: ' + mac.algName);
3475let keyBlob: cryptoFramework.DataBlob;  // The generation process is omitted here.
3476let symKeyGenerator = cryptoFramework.createSymKeyGenerator('AES128');
3477let promiseConvertKey = symKeyGenerator.convertKey(keyBlob);
3478promiseConvertKey.then(symKey => {
3479  let promiseMacInit = mac.init(symKey);
3480  return promiseMacInit;
3481}).then(() => {
3482  let blob: cryptoFramework.DataBlob;  // The generation process is omitted here.
3483  let promiseMacUpdate = mac.update(blob);
3484  return promiseMacUpdate;
3485}).then(() => {
3486  let promiseMacDoFinal = mac.doFinal();
3487  return promiseMacDoFinal;
3488}).then(macOutput => {
3489  console.info('[Promise]: HMAC result: ' + macOutput.data);
3490  let macLen = mac.getMacLength();
3491  console.info('MAC len: ' + macLen);
3492}).catch((error: BusinessError) => {
3493  console.error("[Promise]: error: " + error.message);
3494});
3495```
3496
3497## cryptoFramework.createRandom
3498
3499createRandom(): Random
3500
3501Creates a **Random** instance for generating random numbers and setting seeds.
3502
3503For details about the supported specifications, see [Supported Algorithms and Specifications](../../security/CryptoArchitectureKit/crypto-generate-random-number.md#supported-algorithms-and-specifications).
3504
3505**System capability**: SystemCapability.Security.CryptoFramework
3506
3507**Return value**
3508
3509| Type  | Description                                           |
3510| ------ | ----------------------------------------------- |
3511| Random | Returns the [Random](#random) instance created.|
3512
3513**Error codes**
3514For details about the error codes, see [Crypto Framework Error Codes](../errorcodes/errorcode-crypto-framework.md).
3515
3516| ID| Error Message    |
3517| -------- | ------------ |
3518| 17620001 | memory error. |
3519
3520**Example**
3521
3522```ts
3523import { BusinessError } from '@ohos.base';
3524
3525try {
3526  let rand = cryptoFramework.createRandom();
3527} catch (error) {
3528  let e: BusinessError = error as BusinessError;
3529  console.error(`sync error, ${e.code}, ${e.message}`);
3530}
3531```
3532
3533## Random
3534
3535Provides APIs for computing random numbers and setting seeds. Before using any API of the **Random** class, you must create a **Random** instance by using [createRandom](#cryptoframeworkcreaterandom).
3536
3537### Attributes
3538
3539**System capability**: SystemCapability.Security.CryptoFramework
3540
3541| Name   | Type  | Readable| Writable| Description                |
3542| ------- | ------ | ---- | ---- | -------------------- |
3543| algName<sup>10+</sup> | string | Yes  | No  | Algorithm used to generate the random number. Currently, only **CTR_DRBG** is supported.|
3544
3545### generateRandom
3546
3547generateRandom(len: number, callback: AsyncCallback\<DataBlob>): void
3548
3549Generates a random number of the specified length. This API uses an asynchronous callback to return the result.
3550
3551**System capability**: SystemCapability.Security.CryptoFramework
3552
3553**Parameters**
3554
3555| Name  | Type                    | Mandatory| Description                |
3556| -------- | ------------------------ | ---- | -------------------- |
3557| len      | number                   | Yes  | Length of the random number to generate, in bytes. The value range is [1, INT_MAX].|
3558| callback | AsyncCallback\<[DataBlob](#datablob)> | Yes  | Callback invoked to return a **DataBlob** object.|
3559
3560**Error codes**
3561For details about the error codes, see [Crypto Framework Error Codes](../errorcodes/errorcode-crypto-framework.md).
3562
3563| ID| Error Message              |
3564| -------- | ---------------------- |
3565| 401 | invalid parameters.          |
3566| 17620001 | memory error.          |
3567| 17630001 | crypto operation error. |
3568
3569**Example**
3570
3571```ts
3572import { BusinessError } from '@ohos.base';
3573
3574let rand = cryptoFramework.createRandom();
3575rand.generateRandom(12, (err, randData) => {
3576  if (err) {
3577    console.error("[Callback] err: " + err.code);
3578  } else {
3579    console.info('[Callback]: generate random result: ' + randData.data);
3580  }
3581});
3582```
3583
3584### generateRandom
3585
3586generateRandom(len: number): Promise\<DataBlob>
3587
3588Generates a random number of the specified length. This API uses a promise to return the result.
3589
3590**System capability**: SystemCapability.Security.CryptoFramework
3591
3592**Parameters**
3593
3594| Name| Type  | Mandatory| Description                                                  |
3595| ------ | ------ | ---- | ------------------------------------------------------ |
3596| len    | number | Yes  | Length of the random number to generate, in bytes. The value range is [1, INT_MAX].|
3597
3598**Return value**
3599
3600| Type              | Description       |
3601| ------------------ | ----------- |
3602| Promise\<[DataBlob](#datablob)> | Promise used to return the result.|
3603
3604**Error codes**
3605For details about the error codes, see [Crypto Framework Error Codes](../errorcodes/errorcode-crypto-framework.md).
3606
3607| ID| Error Message              |
3608| -------- | ---------------------- |
3609| 401 | invalid parameters.          |
3610| 17620001 | memory error.           |
3611| 17630001 | crypto operation error. |
3612
3613**Example**
3614
3615```ts
3616import { BusinessError } from '@ohos.base';
3617
3618let rand = cryptoFramework.createRandom();
3619let promiseGenerateRand = rand.generateRandom(12);
3620promiseGenerateRand.then(randData => {
3621  console.info('[Promise]: rand result: ' + randData.data);
3622}).catch((error: BusinessError) => {
3623  console.error("[Promise]: error: " + error.message);
3624});
3625```
3626
3627### generateRandomSync<sup>10+</sup>
3628
3629generateRandomSync(len: number): DataBlob
3630
3631Generates a random number of the specified length. This API returns the result synchronously.
3632
3633**System capability**: SystemCapability.Security.CryptoFramework
3634
3635**Parameters**
3636
3637| Name| Type  | Mandatory| Description                |
3638| ------ | ------ | ---- | -------------------- |
3639| len    | number | Yes  | Length of the random number to generate, in bytes. The value range is [1, INT_MAX].|
3640
3641**Return value**
3642
3643| Type              | Description       |
3644| ------------------ | ----------- |
3645|[DataBlob](#datablob) | Returns the generated random number.|
3646
3647**Error codes**
3648For details about the error codes, see [Crypto Framework Error Codes](../errorcodes/errorcode-crypto-framework.md).
3649
3650| ID| Error Message              |
3651| -------- | ---------------------- |
3652| 401 | invalid parameters.          |
3653| 17620001 | memory error.           |
3654| 17630001 | crypto operation error. |
3655
3656**Example**
3657
3658```ts
3659import { BusinessError } from '@ohos.base';
3660
3661let rand = cryptoFramework.createRandom();
3662try {
3663  let randData = rand.generateRandomSync(12);
3664  if (randData != null) {
3665    console.info('[Sync]: rand result: ' + randData.data);
3666  } else {
3667    console.error("[Sync]: get rand result fail!");
3668  }
3669} catch (error) {
3670  let e: BusinessError = error as BusinessError;
3671  console.error(`sync error, ${e.code}, ${e.message}`);
3672}
3673```
3674
3675### setSeed
3676
3677setSeed(seed: DataBlob): void
3678
3679Sets a seed.
3680
3681**System capability**: SystemCapability.Security.CryptoFramework
3682
3683| Name| Type    | Mandatory| Description        |
3684| ------ | -------- | ---- | ------------ |
3685| seed   | DataBlob | Yes  | Seed to set.|
3686
3687**Error codes**
3688For details about the error codes, see [Crypto Framework Error Codes](../errorcodes/errorcode-crypto-framework.md).
3689
3690| ID| Error Message          |
3691| -------- | ----------------- |
3692| 17620001 | memory error.      |
3693
3694**Example**
3695
3696```ts
3697import { BusinessError } from '@ohos.base';
3698
3699let rand = cryptoFramework.createRandom();
3700rand.generateRandom(12, (err, randData) => {
3701  if (err) {
3702    console.error("[Callback] err: " + err.code);
3703  } else {
3704    console.info('[Callback]: generate random result: ' + randData.data);
3705    try {
3706      rand.setSeed(randData);
3707    } catch (error) {
3708      let e: BusinessError = error as BusinessError;
3709      console.error(`sync error, ${e.code}, ${e.message}`);
3710    }
3711  }
3712});
3713```
3714
3715## cryptoFramework.createKdf<sup>11+</sup>
3716
3717createKdf(algName: string): Kdf
3718
3719Creates a key derivation function instance.<br>For details about the supported specifications, see [Supported Algorithms and Specifications](../../security/CryptoArchitectureKit/crypto-key-derivation.md#supported-algorithms-and-specifications).
3720
3721**System capability**: SystemCapability.Security.CryptoFramework
3722
3723**Parameters**
3724
3725| Name | Type  | Mandatory| Description                             |
3726| ------- | ------ | ---- | --------------------------------- |
3727| algName | string | Yes  | Key derivation algorithm (including the hash function for the HMAC). Currently, only the PBKDF2 algorithm is supported. For example, **PBKDF2\|SHA1**.| |
3728
3729**Return value**
3730
3731| Type        | Description                                      |
3732| ------------ | ------------------------------------------ |
3733| [Kdf](#kdf11) | Key derivation function instance created.|
3734
3735**Error codes**
3736For details about the error codes, see [Crypto Framework Error Codes](../errorcodes/errorcode-crypto-framework.md).
3737
3738| ID| Error Message              |
3739| -------- | ---------------------- |
3740| 401 | invalid parameters.          |
3741| 801 | this operation is not supported.          |
3742| 17620001 | memory error.          |
3743
3744**Example**
3745
3746```ts
3747let kdf = cryptoFramework.createKdf('PBKDF2|SHA1');
3748
3749```
3750
3751## Kdf<sup>11+</sup>
3752
3753Defines the key derivation function class. Before using APIs of this class, you need to create an instance of this class by using **createKdf(algName: string): Kdf**.
3754
3755### Attributes
3756
3757**System capability**: SystemCapability.Security.CryptoFramework
3758
3759| Name   | Type  | Readable| Writable| Description                        |
3760| ------- | ------ | ---- | ---- | ---------------------------- |
3761| algName | string | Yes  | No  | Algorithm of the key derivation function.|
3762
3763### generateSecret
3764
3765generateSecret(params: KdfSpec, callback: AsyncCallback\<DataBlob>): void
3766
3767Generates a key based on the specified key derivation parameters. This API uses an asynchronous callback to return the result.
3768
3769**System capability**: SystemCapability.Security.CryptoFramework
3770
3771**Parameters**
3772
3773| Name  | Type                    | Mandatory| Description                  |
3774| -------- | ------------------------ | ---- | ---------------------- |
3775| spec   | [KdfSpec](#kdfspec11)        | Yes  | Parameters of the key derivation function.|
3776| callback | AsyncCallback\<[DataBlob](#datablob)> | Yes  | Callback invoked to return the derived key generated.|
3777
3778**Error codes**
3779For details about the error codes, see [Crypto Framework Error Codes](../errorcodes/errorcode-crypto-framework.md).
3780
3781| ID| Error Message              |
3782| -------- | ---------------------- |
3783| 401 | invalid parameters.          |
3784| 17620001 | memory error.          |
3785| 17630001 | crypto operation error. |
3786
3787**Example**
3788
3789```ts
3790let spec: cryptoFramework.PBKDF2Spec = {
3791  algName: 'PBKDF2',
3792  password: '123456',
3793  salt: new Uint8Array(16),
3794  iterations: 10000,
3795  keySize: 32
3796};
3797let kdf = cryptoFramework.createKdf('PBKDF2|SHA256');
3798kdf.generateSecret(spec, (err, secret) => {
3799  if (err) {
3800    console.error("key derivation error.");
3801    return;
3802  }
3803  console.info('key derivation output is ' + secret.data);
3804});
3805```
3806
3807### generateSecret
3808
3809generateSecret(params: KdfSpec): Promise\<DataBlob>
3810
3811Generates a key based on the specified key derivation parameters. This API uses a promise to return the result.
3812
3813**System capability**: SystemCapability.Security.CryptoFramework
3814
3815**Parameters**
3816
3817| Name| Type  | Mandatory| Description                  |
3818| ------ | ------ | ---- | ---------------------- |
3819| spec   | [KdfSpec](#kdfspec11)        | Yes  | Parameters of the key derivation function.|
3820
3821**Return value**
3822
3823| Type              | Description    |
3824| ------------------ | -------- |
3825| Promise\<[DataBlob](#datablob)> | Promise used to return the derived key generated.|
3826
3827**Error codes**
3828For details about the error codes, see [Crypto Framework Error Codes](../errorcodes/errorcode-crypto-framework.md).
3829
3830| ID| Error Message              |
3831| -------- | ---------------------- |
3832| 401 | invalid parameters.          |
3833| 17620001 | memory error.          |
3834| 17630001 | crypto operation error. |
3835
3836**Example**
3837
3838```ts
3839import { BusinessError } from '@ohos.base';
3840
3841let spec: cryptoFramework.PBKDF2Spec = {
3842  algName: 'PBKDF2',
3843  password: '123456',
3844  salt: new Uint8Array(16),
3845  iterations: 10000,
3846  keySize: 32
3847};
3848let kdf = cryptoFramework.createKdf('PBKDF2|SHA256');
3849let kdfPromise = kdf.generateSecret(spec);
3850kdfPromise.then(secret => {
3851  console.info('key derivation output is ' + secret.data);
3852}).catch((error: BusinessError) => {
3853  console.error("key derivation error.");
3854});
3855```
3856