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